small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
albedo robot-docs migrations.md
39 kB · 550 lines
Markdown
at main

Storage migrations #

Storage upgrades run at daemon startup before sessions open. Core and extension migrations have separate owners. The extension runtime exposes migrate for extension data migrations.

Generate typed queries #

Put one query per file in src/<package_namespace>/<owner>/sql/<function>.sql under its owning Gleam project. A directory becomes a Gleam module under src/<package_namespace>/generated/sql/. Its module path mirrors the owner path and ends in _sql. Use named SQLite parameters and check the generated parameter and row types against the query, especially nullable joins and expressions. Check in the generated modules. An extension keeps its SQL, generated modules, schema, and migrations inside its own package and namespace.

Run the generator from the repository root. It selects the pinned Marmot package for the current checkout.

Change Command
Edit queries in one package nix develop -c python3 test/marmot.py extensions/mail
Regenerate the workspace nix develop -c python3 test/marmot.py
Change the production schema nix develop -c python3 test/marmot.py --refresh-schema
Check for drift nix develop -c python3 test/marmot.py --check

Normal generation uses the schema snapshot, so it can rebuild missing bindings before the daemon compiles. For a historical fixture, --schema PATH reads an existing migrated database. Refresh and check use production storage setup to apply core, kernel, and extension migrations. The private bootstrap VM supplies current owner-local SQL for fixed script and column-addition bindings, with includes expanded. Marmot’s bootstrap-manifest command reads those sources and writes the JSON manifest of scripts and column batches. At startup the existing guard applies each batch on its migration’s connection. Refresh infers query types against that database and validates the whole workspace before publishing bindings and the snapshot. Use refresh or --schema PATH when the snapshot is missing. The commit gate checks schema and binding drift first. When those checks pass, the same bootstrap VM seeds sessions and exercises each registered transfer filter through the production exporter. Schema refresh ends the VM after schema capture and skips that probe.

If a schema change needs a new migration function, generate its binding and wire it into startup before refreshing. The refresh compiles the daemon before it runs startup. A source-only edit to an existing fixed script or column batch can refresh that schema and its dependent query bindings together.

Result types and execution #

The emitter patch uses Marmot's inferred parameters and row decoders. A query with several columns or a named -- returns: Row returns Result(List(Row), String). An unannotated query with one column returns a list of the inferred field type. Use a named return for a stable record contract. Statements without rows return Result(Nil, String). The SQLite runtime executes the query and reports SQLite's error message.

Pass the store's connection to generated functions, or pass the generated function as a callback to the existing store API. Keep the transaction, snapshot, and migration order that the operation requires.

Albedo supplies the query runtime. Omit tools.marmot.query_function from package configuration.

When SQLite prepares a statement but Marmot cannot infer its types, add explicit types in leading SQL comments. Use -- albedo: columns busy:INTEGER, log:INTEGER, checkpointed:INTEGER to name and type every result column in SQLite's order. Use -- albedo: binds payload:BLOB?, sender:TEXT? to override only the named binds that need it. A trailing ? accepts NULL. Marmot checks projection width and retains its inferred bind order.

Schema scripts and historical layouts #

For a fixed schema or connection script, start the SQL file with -- albedo: script. The generated function takes the caller's connection, executes the script as written, and returns Result(Nil, String). Scripts accept no bind parameters and must contain at least one statement. Generation rejects unrecognized Albedo directives. During generation and drift checks, the workspace driver uses SQLite to split and prepare each statement with EXPLAIN on a disposable in-memory copy of the current schema or the owner's overlay. This catches SQLite prepare-time syntax errors in historical and lifecycle scripts. The driver reports unknown functions and columns that SQLite detects during preparation. Use a historical schema overlay when the script needs a retired layout. When a preceding migration step supplies a table, put -- albedo: requires table temp.example immediately before the statement that needs it. This permits only SQLite's missing-table error for that name. Validation permits already-present objects such as indexes. An existing index can make SQLite skip the body of CREATE INDEX IF NOT EXISTS. The fresh storage bootstrap exercises initializers before those indexes exist. Each script starts from a fresh copy of its schema. The driver applies ordinary table DDL to the disposable copy so later statements can resolve staging tables. It prepares data changes and CREATE TABLE AS SELECT without running them. Verify historical dependencies and effects in migration tests. Follow the database access rule when migrating runtime-selected tables or operations that depend on SQLite error codes.

For a batch of conditional column additions, put -- albedo: add-columns on the first line. Write one semicolon-terminated ALTER TABLE … ADD COLUMN … per line for the same table. This also covers a single conditional addition. Generation checks the statements in order on a disposable SQLite table with one row, the batch's columns absent, and the other columns available. It skips evaluation of data-dependent CHECK constraints on the synthetic row. The check leaves the schema snapshot alone. The generated function takes the caller's connection and returns Result(List(String), String), with the newly added column names in statement order. At runtime the shared schema guard reads the table once with PRAGMA table_xinfo and skips existing columns, including generated columns, under SQLite's ASCII case rules. Keep the batch and dependent backfills in the caller's transaction.

If a query uses a retired table or column, put the minimal historical DDL in schema.overlay.sql beside its owner's sql/ directory. Generation applies the overlay to a private copy of the schema, including during drift checks. Choose the historical binding only after inspecting the live schema. Keep overlays out of the schema snapshot and runtime migrations.

Shared and dynamic SQL #

To reuse literal SQL within an owner, put it in a name.sql.inc file in the same sql/ directory as its callers. Put -- albedo: include name.sql.inc on its own line where the text belongs. Generation expands it before SQLite prepares the query, so bind order comes from the expanded SQL. Include files contain SQL text without generator directives or further includes.

Put SQL fragments in owner-local files starting with -- albedo: fragment. A filtered row query can use one /* albedo: predicates */ slot before its fixed binds. Use named or anonymous fixed binds after the slot. Explicit ?NNN binds can collide with inserted predicates. Supply only the required generated fragments, in binding order, to retain indexable predicates. For a runtime table name, put a representative table between /* albedo: identifier */ and /* albedo: end identifier */. Marmot prepares the representative query. The generated function accepts a validated SQLite identifier. For schema metadata, use direct PRAGMA reads. Tables can shadow the table-valued forms even in the temporary schema. In a direct PRAGMA identifier slot, the generated function quotes the supplied name as a SQLite identifier, including any embedded double quotes. Use a representative object to check the result shape during generation. A package can provide that object in its scratch schema overlay.

For transfer SQL that needs several pieces of SQL text, put -- albedo: slots name, condition immediately after -- albedo: fragment. Use {{name}} and {{condition}} in the body. Marmot checks that the declared names match the placeholders and generates a labelled builder. Pass names and values through the transfer codec's identifier and binding paths before composing the statement. Transfer row streaming still steps a prepared statement on the caller's connection through the SQLite driver binding.

Use -- albedo: write-template for a write whose SQL structure depends on the installed schema. Before the -- albedo: slots line, give each slot an example with -- albedo: example name: SQL. Marmot analyzes the example statement and generates a write with labelled slot arguments and typed SQLite bindings. Supply slot text only from generated fragments and allowlisted schema identifiers. Keep values in the fixed bind arguments, outside the slots.

Use -- albedo: native errors as the first line when the caller branches on a SQLite code. This emits a sqlight.Error result. Put the script marker on the next line for a native-error script. Other generated operations return the SQLite error message. The emitter uses albedo_sqlite.run_native for a parameterized statement with no returned rows when the native error contract is requested. The string-error effect path uses the same implementation.

Albedo runs generated schema scripts through its own migration phases. Marmot's standalone migration runner opens a separate connection and records successful files in schema_migrations. Albedo checks known breaking names and takes backups before it opens the store. Keep migration declarations and execution with the owning core, kernel, or extension migration.

Startup order #

server.main checks the home's breaking-migration record before anything opens storage. Then server.start calls registry.prepare_storage before serving sessions. Core migrations.run runs image storage, transcript classification, transcript row kinds, session profiles, prompts, prompt context blocks, titles, usage-hour, waiting-input, effort-name, and transcript text upgrades in that order, each declared with its compatibility (see Downgrades). Each result is checked, so an error stops the sequence. The waiting-input upgrade moves inputs from the retired pending_inputs table into the inbox. effort_names renames sessions' saved extra-low effort to minimal, the name types.Effort gives Antigravity's lowest tier; account migration renames a profile's at each startup. The transcript text upgrade creates the text index with every row waiting for it. Startup prints migration <name>: <rows> rows for each core, kernel, and extension migration that rewrote rows.

After the core upgrades, prepare_storage runs the kernel's cell_images upgrade and then the installed extensions' data migrations. session_titles, effort_names and cell_images record their completion in the migrations table so homes that already ran them skip them on later startups. Keep that name if the migration moves again. The kernel's schema is created by the runtime, not by an extension.

Paperclips extension contributes schema migrations alongside its table initializer. Extension-owned schema changes belong with their owner. See extensions and paperclips.

Compatibility and interruption #

session_prompts.run moves older session prompt columns into the prompt table. Each 16-session page copies eligible prompts and clears the populated legacy columns in one transaction. A single guarded update clears each affected session row, including homes with only some of the legacy columns. The migration drops those columns after all pages commit. session_context_blocks.run rewrites saved prompt contexts from rendered inputs to JSON name and body blocks. transcript_classes.run handles older transcript rows. transcript_kinds.run records what each older user row is, in transcript.row_kind. It is the only place that reads the frames earlier daemons wrote for notes, notices, letters and skill activations. Readers ask the row's kind and never match the text. A writer of a user row names its kind. Inspect each migration's transaction and marker logic before changing its restart behavior. These upgrades do not all share one transaction.

Downgrades #

A daemon refuses to start on a home that a newer build upgraded with a breaking migration this build does not know. Additive changes never block a rollback.

Every migration declares a migration.Compatibility:

  • Additive: a build without the migration still reads the home correctly. A new table or index, a nullable or defaulted column, or a backfill of one of those is additive. Nothing is recorded.
  • Breaking: a build without the migration would misread or lose data. Rows moved to another table, a column renamed, dropped, or given a new meaning, and values rewritten into a new format are breaking.

Record #

migration.apply and migration.record write a breaking migration's name to the breaking_migrations table before the migration writes anything. The table is created on first use. A data migration's record commits in its own transaction first, so a run interrupted half way is still recorded. An extension schema migration's record commits in the same transaction as its schema change. Breaking migrations run at every startup and record themselves each time, so the insert is idempotent.

Transfers do not carry breaking_migrations. Each daemon records its own upgrades.

Refusal #

server.main calls registry.check_storage after it takes the home lock and before server.start opens storage. It compares the record with registry.known_migrations: every core and kernel migration name, every migration that the build's declared extensions contain, including quarantined ones, and the retired names. A missing albedo.sqlite is a new home.

The check writes none of the database's files. A read-write connection would checkpoint a crashed daemon's write-ahead log into the database and delete it on close, and plain mode=ro creates missing sidecars or rebuilds the -shm index. migration.unknown picks its options from the files present:

  • No -wal, or an empty one: mode=ro&immutable=1. Everything committed is in the main file. immutable=1 ignores a log, so it is used only when none holds commits. The home lock keeps another daemon from writing one.
  • A -wal with commits and its -shm, as a stopped or crashed daemon leaves them: mode=ro&readonly_shm=1. This reads the log's commits and changes neither file.
  • A -wal with commits but no -shm: SQLite cannot read the log without writing an index. If it stays that way, the check fails and startup stops, rather than miss a record that only the log holds.
  • A -wal that exists but cannot be read: the check fails the same way. Only a -wal that is not there at all (enoent) counts as absent.

The home lock keeps other daemons out, but not every program. Another program's last connection can checkpoint and delete the log after the check picks readonly_shm=1 and before it opens, and the open then fails. When the files then call for other options, the check reads again with those, up to three times. SQLite closes by checkpointing, deleting the -shm and then the log, so for a moment a closing connection leaves a log of commits with no index. The check waits 20 ms and looks again within the same three attempts; only a log still unindexed after them is treated as a crash's.

The read is bounded at 30 seconds. A read that takes longer is killed, and the check fails.

The read closes its connection with albedo_sqlite.close, which is complete when it returns. A read-only connection left open makes SQLite refuse the daemon's own writes to the same file. The read runs in a process of its own so the bound can kill it, and the check returns once that process has exited.

The check reads files that a store closed just before it, as migration_test does. store.close returns once each of its connections is closed. The last of them moves the log into the database and removes the -shm file and then the -wal file. A check that ran between the two removals would find a log with commits but no index, and refuse the home.

migration_test checks that the three files are byte-identical after the check, for a stopped home and for one whose record is only in the log.

When a name is unknown, the daemon prints this line to daemon.log and halts with status 78 through lifecycle.refuse_storage:

This home was upgraded by a newer albedo (<names>); update albedo or restore a backup.

The CLI reports a daemon that exits during startup with the log written since launch, so albedo shows the line. A failure to read the record stops startup too. Current CLI-installed systemd units suppress restarts after this refusal. Older units that exempt only exit 75 need an update. The macOS LaunchAgent retries nonzero exits, including 78. Update Albedo or remove a CLI-owned agent with albedo daemon uninstall to stop those retries. For a declaratively owned service, disable it through its declaration owner. See the daemon lifecycle.

Backups #

The backup the refusal names is taken by the build that runs a breaking migration. When the check passes, registry.check_storage lists the breaking migrations this build declares that the home has not recorded. If there are any and the home already has a record, migration.back_up copies the database whole with VACUUM INTO to backups/albedo-before-breaking-<ms>.sqlite in the home. It then records those names in the same connection. This happens before the runtime opens storage, so the copy predates every write those migrations make. Recording the names with the copy means the next startup does not copy the home again, even when a migration's owner fails to install.

The copy is written as <name>.partial and renamed into place only once it is complete. A failed copy removes its partial file, records nothing, and stops startup. The copy holds secrets such as webhook signing keys, so backups/ is made 0700 and the copy 0600.

After a successful copy, check_storage keeps the newest three finished copies and deletes older ones, along with any .partial file a crash left. Partial files never count toward the three. A home with no record yet is a new home, or one from before the record whose first startup backfills it. Neither is copied.

The storage report counts these copies as migration backups, along with the albedo-before-image-store-<ms>.sqlite copies from the image-store upgrade. Both the daemon's report (storage_report.gleam) and the CLI's offline report and cleanup (storage.go) list a finished copy older than 30 days as an old backup that albedo storage prune --backups may remove, and count newer ones as recent backups. They never list .partial files, which startup removes. Keep the two name rules in step when adding a new kind of backup.

Session byte accounting serves both the daemon and offline reports on their existing SQLite snapshots. The offline report checks required columns and supports older layouts with missing tables or pinned context stored on the session row.

To roll back across a breaking migration, stop the daemon, put the copy in place of albedo.sqlite, and remove albedo.sqlite-wal and albedo.sqlite-shm. Anything the newer build wrote after the copy is lost.

Declare a migration #

  1. Decide whether the change is additive or breaking. Prefer an additive form, such as a new column the old one is copied into, when it keeps the change useful.
  2. Give the migration a name that is unique across the daemon. Prefix an extension's migration with the extension's name. migration_names_test checks uniqueness.
  3. Put a core migration in migrations.steps with its compatibility. Declare an extension migration as extension.SchemaMigration or extension.DataMigration, each with a name and compatibility. See extension migrations.
  4. Put a breaking change in a declared migration. A table initialiser's rewrite is not recorded.

Never rename a migration or reuse a name. Once a home records a name, every later build must know it. When you remove a breaking migration's declaration, move its name to retired in migrations.gleam. This covers a core step, an extension migration, and every breaking migration of an extension that is removed whole. retired is the one list for every owner.

Homes from before the record #

The first build with the record runs every migration at startup, so it records each breaking migration it knows. Homes it upgraded earlier gain those records then. Every build with the check knows those names, so the backfill refuses no build that has the check.

A build from before the record does not check it. Rolling a home back to such a build is not refused, even when a later build recorded a breaking migration. The refusal protects only rollbacks to builds that include it.

Classification #

Migration Owner Compatibility Reason
image_store core Breaking Transcript rows keep references to images moved into images.
transcript_classes core Additive Fills the new row_class column and adds indexes over it.
session_profiles core Additive A new table, filled once and kept by triggers on rows every build writes.
session_prompts core Breaking Moves the prompt columns out of sessions and drops them.
session_titles core Additive Sets auto_title_attempted, which every build with the column reads the same way.
usage_hours core Additive A new table, filled once and kept by a trigger on rows every build writes.
pending_inputs_inbox core Breaking Moves waiting inputs out of pending_inputs, and later inputs never go there.
transcript_text core Additive A new index, kept by triggers on rows every build writes.
cell_images kernel Breaking Cell outputs keep references to images moved into images.
coding_lcm_name coding-lcm Breaking Renames the lcm extension in settings and session choices.
paperclips_title, paperclips_reply, paperclips_resolution, paperclips_revision paperclips Additive Defaulted columns.
paperclips_scope paperclips Additive Drops an index that a build which wants it creates again.
work_cwd work Additive A defaulted column and an index.
rolling_observation rolling Additive Drops a table that cached each request's observation. An older build creates it again, empty.
schedule_revision schedule Additive Defaulted columns.

Two older rewrites run inside table initialisers and are not recorded. Every build with the check includes both. mail_kinds copies the mail table and rewrites event kinds. Startup also repairs remote mail references left pointing to the retired table by older upgrades. The webhooks filed upgrade in the webhook ledger posts inbox letters for deliveries that waited from before the inbox.

downgrade_test.py opens a home this checkout upgraded with the reference build. It also starts this checkout on a home that records an unknown breaking migration and checks the CLI's message and that the database is unchanged.

Foreign-key indexes #

Make each foreign key's child columns the leading columns of an index. For a composite key, the index prefix must contain all child columns. An INTEGER PRIMARY KEY needs no separate index.

Deletion looks up referencing child rows. Without an index, that lookup scans the child table for each deleted parent row and can block the store writer. test_every_foreign_key_column_is_indexed checks this invariant across the schema. Preserve it when adding or changing extension tables as well as core tables.

Persisted terms #

Some stored values are Erlang external terms rather than JSON or columns. Gleam encodes a record as a tuple tagged with its constructor's name, never its module's, so moving or renaming a module keeps the stored bytes readable when three things hold: the constructor names, their field order, and their arity stay the same. Do not change any of them for a type listed below. Add a new layout instead and keep decoding the old one, as each decoder here does.

Every decoder reads with binary_to_term's safe option, which refuses an atom the VM has not created yet. A constructor's atom exists once a module whose code names it is loaded. A daemon preloads most modules first, but a storage migration, a helper VM, or a module rename can leave a decoder ahead of the module that names an atom, and the row then reads as invalid. A decoder whose terms hold another module's constructors calls that module's preload() before it decodes. preload() is a no-op whose call loads the module, so a rename is a compile error at the call rather than a decode failure at run time. Bind its result with let _ =, since Gleam treats the call as pure.

Term and where it is stored Decoder Persisted layouts Constructors from other modules, loaded first Fixture families
turn.Submission, an inbox row's payload turn.decode The record with 7, 8, 9 or 10 fields: before title text, attached files, and a skill load albedo_model (images), letter (mail kinds, stop reasons, input forms), operations (attached files), sdk/skills/catalog (skill loads and scopes) submission
An operation's saved display operations.decode_display {display, ...} with 5 fields and one image as an option, or 5, 6 or 7 fields with an image list None: operations names every tag it holds display
Transcript rows and image fit rows transcript_codec unpack, unpack_fit, unpack_list Version 1, {1, Row}. A user image row holds a list of images, or one before messages held several; a tool output holds 2 fields before tool images. An image is {image, ...} with 6 fields, or {clip, ...} with 7 for a clip with options image_codec (packed images, {stored_data, Hash, Size}, {clip_options, Fps}) transcript, transcript-fit, transcript-list
Kernel cell results and traces cell_codec unpack, unpack_trace Version 1. An outcome holds 9 fields, 8 before timing, or 6 before images; an error is busy, lost, {invalid, _} or {unavailable, _}. Images as in transcript rows image_codec (packed images). cell_codec names the outcome, status and error tags itself cell, cell-trace
The MCP catalogue, mcp_catalogues catalogue.saved Version 2: atom-keyed maps, whose atoms the decoder creates first None mcp
Memory import receipts files.decode_receipt Version 1: {done, Sources} or {pending, Sources, Before, After} None memory
The models.dev index beside the catalog catalog_cache.catalog Version 4, {4, Revision, Index, Providers}, and version 3, which kept the index and providers in a map None: tuples, binaries and the atoms null, index and providers models-index

Three other decoders read terms with no constructor that a move could rename, so they have no fixtures:

  • albedo_file/journal reads the settings recovery record, version 1, {Tag, 1, Files}. It creates the tag atom from the journal's name before it decodes, and the files are a map of binaries.
  • active_output_store reads its byte total, an integer, and each segment's metadata, a map whose keys are atoms the store itself names. It decodes a segment's owner process only after it checks the segment belongs to this VM.
  • extension_cache reads .extensions.etf without safe. It holds function captures, which only the build that wrote them can run. It is keyed on a digest of every application in that build, the SDK's and other packages' included, which the seal writes to .extensions-key, so any other build, or a build whose packages changed, discards it.

Other external-term values are hashed, never decoded: the compaction, capability, skill, instruction, catalog and MCP server fingerprints, the selection digest, and memory import keys. The same three rules keep a saved hash stable. Port messages that kernel/native and signal_helper read, and the certificates trust reads, are not stored.

persisted_terms_test.py decodes each fixture under apps/albedo/test/fixtures/persisted-terms as the first thing a fresh VM does, with no boot list and no daemon, and compares the result with what the same build decoded once every module was loaded. Funs, such as a stored image's reader, compare as equal. The fixtures were recorded on main before any module moved, by record_persisted_terms.gleam and the test's --record. Do not re-record them after a move or rename: a failure there is the incompatibility the test exists to catch. When a move renames a decoder's module, update the decoder's name in the test. When a new persisted layout or term appears, record its fixture on a build from before any rename that affects it, and add a row above.

Migration test inventory #

Keep an upgrade scenario while its old format remains supported. A fresh database does not exercise that path. The normal test gate is described in test execution.

Most upgrades are checked in process on apps/albedo/test/fixtures/reference-store, a store the reference build wrote. Its rows and payloads, including waiting inputs and saved prompts in the form before context blocks, come from that build, never from current code. record_reference_store.py records it. Re-record only when the pin moves, and extend the recorder rather than seeding old rows with current code. migration_fixture_test and reference_store_test take a copy back to the layout a release before each upgrade left, run it, and run it again to check that the second run changes nothing.

e2e/migrations_test.py keeps the scenarios that need the assembled daemon: startup's order before routes serve, image payloads older than the reference build, and the preferences files import.