akm-cli
Version:
akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur
153 lines • 55.5 kB
Markdown
# Persisted-Data Compatibility Contract
akm persists state in twelve-odd formats across releases: config, three SQLite
databases, task and workflow documents, native scheduler rows, and a few smaller JSON/text payloads. Each has grown its own
versioning and its own failure behavior. This document is the one place that
states what a reader owes data an earlier release wrote, and inventories how
close each format is to that contract today.
## The contract
**Version floor (0.10, #1091): 0.9.15.** A 0.10 reader owes data written by
0.9.15 or later, and nothing older. An install on an earlier release runs
`akm migrate apply` under akm 0.9.x first, then upgrades. A reader that meets a
shape older than the floor does not convert it: it refuses, with one message
naming `akm migrate apply` under akm 0.9.x (config: the retired
`stashDir`/`sources[]`/`installed[]` keys). A shape that 0.9.15 or later still wrote stays
readable; the rows below say which those are.
Above the floor, a reader must tolerate anything an earlier release wrote: convert the old
shape in memory, warn once, and name `akm migrate apply` as the on-disk
cleanup path — the migrator is where an explicit, backed-up rewrite happens,
never a precondition for reading. The only refusal a reader is allowed is data
written by a release *newer* than itself, and that refusal must name the
remedy (upgrade akm). One format is a named exception: task sources
(`tasks/*.yml`) are read only in the current grammar, and an older file is
refused on its own, naming `akm migrate apply` (#987; see the Task source
row). Bundle content is never rewritten just to make it
readable again by an older or current binary. Every format-version bump must
ship with its old shape covered by the upgrade rehearsal gate
(`tests/integration/upgrade-rehearsal/`). No config object is strict: an unknown key at any depth is kept in memory
and named once, round-trips through ordinary writes, and is dropped by
`akm migrate apply`.
## Formats
| Format | Where written | Version marker | Older data | Newer data | Gate |
| --- | --- | --- | --- | --- | --- |
| `config.json` | `src/core/config/config.ts` | `configVersion` field | `configVersion` is read, never gated on (`readConfigVersion`, `src/core/config/config.ts`): a missing field or `"0.9.0"` — the only value akm has shipped — loads silently, and any other value is named once and read as `0.9.0`. Below the 0.9.15 floor the file is refused, not converted: the retired `stashDir`/`sources[]`/`installed[]` layout fails validation (`AkmConfigSchema`, `src/core/config/config-schema.ts`), telling the user to run `akm migrate apply` under akm 0.9.x. The `engines` / `defaults` form 0.9.15 and later wrote (with the user's `models.json` as an overlay, and an `AKM_ENGINE_<NAME>_API_KEY` or `AKM_LLM_API_KEY` set in the environment read as the connection's `$VAR` key) is read in memory as `connections` / `harnesses` by `convertEngineConfig` (`src/core/config/convert-engines.ts`, called from `readRetiredEngines`), with one warning that names `akm migrate apply`; a connection or harness its own schema rejects is dropped from what is read, with one warning (`dropUnusableEntries`). A bundle's `components` map (`bundles.<name>.components.<id>`, one entry, holding `adapter`, `root` and `writable`) is read in memory as those keys on the bundle by `convertBundleComponents` (`src/core/config/convert-bundle-components.ts`, called from `readRetiredBundleComponents`), with one warning naming `akm migrate apply`: the bundle's own `adapter` and `root` win when it has them, the component's `writable` wins over the bundle's own because that is what 0.9 honoured, a `root` of `.` is the default and is dropped, and a map of more than one entry is refused. An ordinary write (`mutateConfig`, `mutateConfigWithPrecommit`) edits the file's own document (`editedConfigFile`), so the retired forms (an edit to a bundle's `writable` also reaches its component's, so the old value does not come back), a literal `apiKey` and the entries the reader dropped stay in the file as written, and removing a value only the retired form supplies is refused until the file is migrated. A config with no `scheduler.enabled` (0.9.15 wrote none) is read as "keep what is installed": `akm task sync` adopts the akm-written scheduler rows as the list (`tests/integration/upgrade-rehearsal/`'s 0.9.15 origin). 0.9.16's `{kind, ref, sourceId}` `scheduler.enabled` entries are still read, as their `ref`, and written back as plain refs. A `secret://<name>` credential (`engines.*.apiKey`, `embedding.apiKey`, a git bundle's `credential`, any config string) is retired: the reader (`readRetiredSecretRefs`, `src/core/config/config.ts`) takes it as `${<name>}` when `<name>` is already a full ref, else `${secrets/<name>}`, naming the key once. `akm migrate apply`'s `configFile` step (`normalizeConfigFile`) persists all of it — `configVersion: "0.9.0"`, `secret://` rewritten, the retired `engines` form converted, the retired `components` map lifted onto its bundle, unknown keys dropped — to the file once, under a backup: the keys the new form does not read from config (an engine's `apiKeyFile`, a literal or `${secrets/...}` `apiKey`, and the same on a connection or `embedding`) are filed in `credentials.json` first (`planKeyMoves`), `models.json` is folded in and moved, and a dropped connection or harness is kept as written, each with a note | Same as older: the value is named once and the file is read as `0.9.0`; there is no `UNSUPPORTED_CONFIG_VERSION` refusal. `akm health`'s `binary-config-skew` advisory (`src/commands/health/config-skew.ts`) is what says "a newer akm wrote this config, upgrade this install" | Upgrade rehearsal gate (`tests/integration/upgrade-rehearsal/`); `tests/integration/config-v09.test.ts` (including the `secret://` read and rewrite); `tests/integration/config-convert-engines.test.ts` (the in-memory conversion and ordinary writes); `tests/integration/migrate/config-file.test.ts` (the migrator step); `tests/integration/config-bundle-components.test.ts` (the `components` conversion, its warning, the migrator rewrite); `tests/integration/previous-release-corpus.test.ts` (a `components` config read as converted) |
| `credentials.json` | `src/core/config/credentials.ts` (`writeCredential`, written atomically and 0600; the directory is made 0700 only when akm creates it, so an existing config directory keeps its mode); filled by `akm setup` (a key typed at its masked prompt) and by `akm migrate apply` | No marker: `{ "connections": { "<name>": { "key", "endpoint" } }, "services": { "embedding": { "key", "endpoint" } } }` | New in 0.10, so no release wrote an older shape. The flat `{ "<name>": "<key>" }` form some pre-release builds wrote names no endpoint, so the reader does not use it: it is named once and ignored, and `akm migrate apply` files it under the endpoint the config file itself gives that block (`fileFlatCredentials`), leaving an entry it cannot place as it is, with a note. A file that cannot be read or is not a JSON object is named once and ignored when reading, and never overwritten when writing (`readStore`, `writableStore`): a migration that cannot store a key stops before it removes the key from `config.json`. An entry that is not `{ key, endpoint }` is named once and ignored. A key is read only for the endpoint it was stored for, and only for a connection this host's own `config.json` names: one that only an `extends` base defines (`isInheritedConnection`) never uses a stored key | Keys are looked up by slot and every other entry is kept, so a file with more entries than this release knows is read as it is | `tests/integration/credentials.test.ts`; `tests/integration/inherited-connection-credentials.test.ts`; `tests/integration/migrate/config-file.test.ts` |
| Migrator's remembered engine names (`<akm data dir>/migrate/engine-targets.json`) | `src/core/config/retired-engines.ts` owns it. The config step (`normalizeConfigFile`) writes it, with the rewrite of the `engines` form, from its `engineTargets`: a JSON object from each old engine name to `{ "connection": "<name>" }` or `{ "harness": "<name>" }`. The asset step (`scripts/akm-migrate/engine-key-migrate.ts`) removes it, and in that run adds one note (`assetEngineKeys.notes`) naming each renamed engine and the flag that now reaches it. The resolver of an `engine:` selector (`retiredEngineTargets`) reads it, so a selector in a file the migration has not rewritten keeps its meaning | No marker | New in 0.10. A file that is not such an object reads as empty, and an entry that is not a target is ignored | Removed once the asset step, re-reading the files after its rewrite, finds no `engine:` key that still names an old engine (a skipped file, or a block of a rewritten file in a style the step does not write). The step reads every command, agent, workflow and task file the runtime reads, whatever its size, in each enabled bundle and in the working stash no bundle names (`bundleRoots`, `scripts/akm-migrate/bundle-roots.ts`), by the adapter that reads it: an `akm` stash's `commands/`, `agents/`, `workflows/` and `tasks/`; every workflow or task file under an `akm-workflow` or `akm-task` bundle's root; and a `claude` or `opencode` bundle's `commands/` and `agents/`, where the runtime reads `akm.engine` and no top-level key. A file that is a symbolic link is read through and never rewritten, so its key is listed as skipped and keeps the map (a link to a directory is not descended, as the runtime does not descend one). A file that is still there is read as it is | `tests/integration/migrate/asset-engine-keys.test.ts` |
| akm's OpenCode database (`<akm data dir>/opencode-runtime/data/opencode/opencode.db`, with its `-wal`/`-shm` files) | The OpenCode 2 binary akm's own runtime runs as a process (`OPENCODE_RUNTIME_VERSION` in `src/integrations/harnesses/opencode/runtime/binary.ts`), with `XDG_DATA_HOME` set to the runtime's `data/` directory; akm's own runtime stores its sessions here | OpenCode's own `migration` table | New in 0.10. OpenCode applies its migrations forward when it opens the file (WAL, 0600); every run is `--standalone`, which keeps the resume sweep off, so a turn an earlier run left open is never resumed. The 0.10 pre-releases that ran OpenCode inside akm's process kept their sessions in `<akm data dir>/opencode.db`; that file is no longer read. History reads (`akm proposal extract --type opencode`, the improve extract gate) open this file, and the user's own OpenCode database, read-only with SQLite, through a private snapshot only for a dry-run gate's listing: they never change the database or its WAL, but like any SQLite reader of a WAL database they create or rewrite the `-shm` (and an empty `-wal` when there is none) | A file written by a newer OpenCode than the pinned binary is opened as it is: OpenCode ignores migration rows it does not know, and akm adds no check. This only arises when an earlier akm is run against a database a later akm wrote | `tests/integration/opencode-runtime-sessions.test.ts` (the sweep and the roots), `tests/integration/opencode-session-store.test.ts` (read-only history) |
| `models.json` (user alias overlay, retired) | `<config dir>/models.json`; no longer written, and akm no longer ships a default table | `{ "version": 1, "aliases": { <alias>: { <column>: <model> } } }` | Read in memory as an overlay (`readModelsFile`), whether the config is in the `engines` form or already in `connections` / `harnesses`: a connection's or harness's own column first, then the `*` column and the flat shorthand, then the engine's own model, never over a model the config already names (`convertEngineConfig`). `akm migrate apply` folds it and moves it to `<cache dir>/config-backups/models.json.<timestamp>` (`retireModelsFile`), naming the aliases that named nothing configured or that the config already names | Not written by this release | `tests/integration/config-convert-engines.test.ts`; `tests/integration/migrate/config-file.test.ts` |
| `state.db` | `src/core/state/migrations.ts` (append-only `MIGRATIONS` registry, applied by `src/storage/sqlite-migrations.ts`) | `schema_migrations` ledger table | 0.10 adds two migrations: the registry ends at `031-bundle-id-columns` (0.9.31 ends at `029-improve-ledger-content-hash`). `akm migrate apply` runs the pending ones in its `stateMigrations` step (`akm migrate status` lists them as `pending`); the state opener also runs them on any open. `030-usage-events-created-at-index` is one `CREATE INDEX IF NOT EXISTS` on `usage_events(datetime(created_at))`, so the time-window reads filter without a table scan; no row is rewritten. **Rows follow a bundle by its name (0.10, §0.2 P8):** `031-bundle-id-columns` renames `stash_dir` to `bundle_id` in `proposals`, `improve_runs` and `improve_ledger` (the list of columns that hold a bundle id is `src/storage/bundle-id-columns.ts`; `proposal_fingerprints` and `proposal_fs_imports` were dropped by 028). A migration cannot read config, so it copies each value as it was, an absolute root, and the state opener then rewrites every root a configured bundle is at to that bundle's id (found by the bundle's resolved root, the one `resolveSourceEntries` gives a directory, git, npm or location bundle; the default bundle first, then in configured order) in one transaction, on the open that finds one and again on later opens, and the config of the command (`--config` sets `AKM_CONFIG_FILE`) is the one it reads. A directory no configured bundle is at keeps its path as its key, as `state.db` always filed it: nothing is shared between unconfigured directories (`~/akm` and `AKM_BUNDLE_DIR=…/akm` stay apart), a bundle configured later at a different directory takes none of the rows, and one configured at that directory takes them on the next open. A bundle id holds no `/`, `\\` or `:`, so a row already converted is never touched. `akm doctor` reports rows filed under a name or directory no configured bundle has (`state-unknown-bundle`, information, exit code unchanged); they stay as they are. Moving a bundle's directory (editing its config `path`) keeps its rows; renaming a bundle by hand in config leaves them under the old name, where `state-unknown-bundle` reports them, and `akm bundle rename` carries them. Two bundles on one directory (an existing config) file rows under the first in configured order, the default first. `openStateDatabase` opens one connection (mkdir, open, standard pragmas), reads the ledger on it, and runs every migration not yet applied forward in one transaction; a missing/empty/table-less file is simply a fresh database. Before a migration that drops schema or that an older akm cannot read past (`018-drop-dead-lane-schema`, `028-improve-ledger`, `031-bundle-id-columns`; `STATE_MIGRATION_SAFETY_BY_ID`) runs against a database that already has migrations applied, the file is copied beside itself to `state.db.pre-<migration id>.bak` via `VACUUM INTO` on the same connection | An older binary opening a `state.db` migrated by a newer akm continues with the schema it knows and warns once (`warnNewerStateLedger`, `src/core/state-db.ts`); it does not refuse; only a ledger that diverges from this akm's registry is refused (`assertMigrationLedger`). **Gap:** after `031-bundle-id-columns` a 0.9.x or earlier 0.10 pre-release akm on the same `state.db` finds no `stash_dir` column, so its proposal queue, improve ledger and improve-run reads and writes fail (owner-accepted, §0.2 A14); there is no guard. The migration keeps `state.db.pre-031-bundle-id-columns.bak` (written before it runs, when the database already had migrations applied; under `<data dir>`): restore it to downgrade, losing what was recorded since | Upgrade rehearsal gate (`tests/integration/upgrade-rehearsal/`) |
| `index.db` | `src/storage/repositories/index-schema.ts` (`ensureSchema`; `index-entry-schema.ts` for the DDL and the layout constant) | `index_meta.version` = `CANONICAL_INDEX_DB_VERSION` (26), a layout marker | Readers (`openExistingDatabase` / `openReadonlyExistingDatabase`) serve it as-is and name `akm index` once (`checkIndexLayout`); the writable opener migrates in place — added columns via `ALTER TABLE`, a one-time FTS rebuild from `entries` for the layout-23 content-copy tables, and for layout 24 the drops of the sqlite-vec mirror `entries_vec` (when sqlite-vec loads; dropping a vec0 table needs it) and `entry_fragments_fts`, with `entries.search_text` hashed into `embed_hash` before the column is dropped so no vector is re-embedded, and for layout 25 the declared links (`asset_links`) derived from each entry's stored `document_json` with no file read (only the directories holding workflows and tasks, whose targets no earlier layout stored, lose their incremental cursor and re-drain on the next `akm index`) — never dropping `embeddings`, `utility_scores*`, or `llm_enrichment_cache`. It drops the lazy-extraction queue `graph_extraction_queue`, retired in 0.9.17, and, on any layout, the LLM entity graph (`graph_meta`, `graph_files`, `graph_file_*`) and its `llm_enrichment_cache` rows, retired in 0.9.17-alpha.9 — an older release's `CREATE TABLE IF NOT EXISTS` recreates the graph tables (empty) if it ever opens this index again. It also deletes `llm_enrichment_cache` rows at the default `cache_variant` — the metadata-enhance pass, retired in 0.9.17-alpha.9 — on any layout; memory inference uses its own named variant and is unaffected. A migration leaves `index_meta.vacuumPending`, and the next `akm index` VACUUMs the freed pages. An `entries` table older than layout 21 has its entries-keyed tables recreated: one that lacks a column this release reads, or that still has a transitional column layout 21 removed (`entry_key`, `dir_path`, `stash_dir`, `entry_json`, `entry_type`), as the table 0.9.1 wrote does, with `document_json` empty on every row. A reader finds such a table unservable (`hasCurrentEntriesTable`), so a read rebuilds it inline. Only `SQLITE_CORRUPT` deletes and rebuilds the file | Refused by readers and the writable opener alike (`INDEX_SCHEMA_INCOMPATIBLE`, "Upgrade akm to use this index.", `newerIndexLayoutError`), leaving the file untouched: a newer layout may lack a column this akm reads, as layout 25 lacks `search_text` | `tests/integration/indexer/index-layout-migration.test.ts` (layout-23 and layout-24 fixtures); `tests/integration/previous-release-corpus.test.ts` (the layout-25 index 0.9.17-alpha.7 wrote, `index-v25.sql`, and the layout-20 index 0.9.1 wrote, `index-v20.sql`); `tests/integration/storage/index-generation-read-boundary.test.ts`; upgrade rehearsal gate (`tests/integration/upgrade-rehearsal/`) |
| `index.db` rows of a bundle that is no directory (`entries.file_path`, `document_json.fileless`) | `src/storage/repositories/index-entry-mapper.ts` (`storedFilePath`); `scripts/akm-migrate/index-rows-migrate.ts` | No marker; rows are keyed by `item_ref` (`UNIQUE`) | A row an earlier akm wrote for a keyring's or vault's entry keyed it under a path inside the bundle's root and marked its document `fileless`. Until `akm migrate apply` runs, every reader takes such a row as a row with no file (`file_path` `''`); `akm index` writes new and re-drained rows as `file_path = ''` with no `fileless`. The migration step (`indexRows`) is one update that changes no column and not the layout (26, through 0.10) | An earlier akm reads the new form without trouble: it prints no path for a keyring or vault entry either way | `tests/integration/indexer/legacy-location-rows.test.ts` |
| `index.db` `index_meta` keys `variant:<bundle id>` and `store-findings:<bundle id>` | `src/storage/repositories/index-meta-repository.ts` (`bundleVariantKey`, `setStoreFindings`), written by `akm index` (`src/indexer/indexer.ts`) | No marker of their own; `index_meta` is a key/value table and the layout stays 26 | `variant:<bundle>` is the freshness variant `akm index` last scanned the bundle under (`<adapter id>@<adapter version>+content<projection version>`). A key that is absent (an index an earlier akm wrote) means nothing is recorded: a type lookup trusts the row, and the next `akm index` describes the bundle's rows again under the current variant. `store-findings:<bundle>` is what `akm index` found wrong with a keyring's or vault's entries, kept for `akm lint`; absent, it reads as no findings until the next `akm index`. No `akm migrate apply` step: both are derived and rewritten by `akm index` | Not checked: an earlier akm does not read these keys | `tests/integration/indexer/legacy-location-rows.test.ts` (an absent `variant:` key) |
| Task source (`tasks/*.yml`) | `src/tasks/source/parse-task-source.ts` | `version: 4` (`TASK_SOURCE_V4_VERSION`), or `version: 5-beta.1` (`TASK_SOURCE_V5_VERSION`, Experimental, read by `src/tasks/v5/source.ts`; a build reads only its own beta) | **The named exception to the contract (#987): the runtime reads only v4 and the one v5 beta.** `version: 2` or `version: 3` throws `TASK_SCHEMA_VERSION_UNSUPPORTED`, and a declared `version: 4` document whose `schedule[]` still carries 0.9.15's retired `enabled` key throws `TASK_SOURCE_INVALID`; both messages name `akm migrate apply`, the one place the conversion happens (`scripts/akm-migrate/migrate/task-files.ts`, planning every v2/v3/v4 file straight to v4 with the pure planner `scripts/akm-migrate/migrate/task-to-v4.ts`, rewriting under a backup; a v4 task or a workflow file named on the command line is converted to v5 by `scripts/akm-migrate/task-migrate.ts`; `akm upgrade` runs it after an install). It covers every stash the runtime reads tasks from: each enabled configured bundle, and the working stash (`AKM_BUNDLE_DIR`, else the default stash when no `defaultBundle` is set; `implicitStashDir`, `src/indexer/search/search-source.ts`) when no bundle names it. The `assetEngineKeys` step reads the same bundles (`bundleRoots`, `scripts/akm-migrate/bundle-roots.ts`), each for the files its adapter holds; the `akm-task` probe still recognizes a root of v2/v3 task files, so one without a recorded adapter is found. Every caller reports the refusal for that one file: `akm task sync` keeps reconciling every other task and leaves the file's installed row as it is | Any other `version` throws `TASK_SCHEMA_VERSION_UNSUPPORTED` naming `akm migrate apply` | Upgrade rehearsal gate (`tests/integration/upgrade-rehearsal/`); `tests/integration/previous-release-corpus.test.ts` (each older shape is refused at runtime and converted by the migrator) |
| Workflow IR (frozen plans) | `src/workflows/freeze/freeze.ts`, read back in `src/workflows/runtime/run-plan.ts` (`readRunPlan`, `decodeWorkflowPlan`) | `irVersion` (`WORKFLOW_PLAN_VERSION`, 8) on the plan and in `plan_ir_version`; `plan_hash` alongside | Every workflow compiles to one plan type. `decodeWorkflowPlan` reads the irVersion 5 shape 0.9.15 and 0.9.16 wrote (its `sourceReadSet` and host-identity fields included) and the irVersion 6 shape (a shell or command target's `cwdIdentity`, an env-ref's `owner`, `keys` and `secretNames`) as well as the current one, and keeps keys it does not know. A frozen `pass_env` (the unit's `passEnv` and its `pass-through` environment descriptor) is read and kept, and it selects nothing: an exec child inherits akm's environment. The irVersion 6 location fields are kept exactly as stored and never read: a v6 run dispatches by ref, finding the bundle root and the env asset again, but the unit `input_hash` and the child invocation key derive from the whole decoded target (an embedded child plan included), so dropping a field would give an interrupted v6 parent a new key after the upgrade and publish a second child (`irVersion` 7 and 8 write none of them, and the inode and path fields left the shell `contentHash` preimage and the unit `input_hash` for new plans only; stored rows keep their hashes). `irVersion` 7 froze an engine where 8 freezes a connection or a harness (a connection runner carries `storedKey: false` when only an `extends` base defines it, so it never uses a key stored on this host; absent means it may), and a command target an earlier irVersion froze is not converted: its request is `schemaVersion` 1 and its runner is `llm`, `agent` or `sdk`, which `decodeResolvedExecutionRequest` and `decodeFrozenRunnerSpec` do not read, so a plan of irVersion 7 or earlier that holds one fails the decode and is abandoned the way any undecodable plan is (below). A plan of those versions with no command target, nested child plans included, still decodes. A command target freezes `cwdIdentity: {}` (`irVersion` 7 did too), which the decoder carries and ignores: akm 0.10.0 and earlier decode a command-only v7 plan (they only warn on a version mismatch, and read `cwdIdentity` loosely) and would run it in the invoking directory, but their dispatch (`prepareWorkflowExecution`) refuses an identity it cannot verify with `PATH_ESCAPE_VIOLATION` before anything is spawned. A v7 shell target or `env:` ref already fails their decode. The hash gates nothing and neither does an older version: a stored plan that decodes runs whatever older `irVersion` froze it, with one warning; one that cannot be decoded is abandoned by `akm workflow run` (status `failed`) with a message naming `akm workflow run <ref>` to start afresh — a status change, never an exception; `list`/`abandon` never read the plan, and `status --units` decodes it, read-only and without a warning, only to describe a failed unit | A plan whose `plan_ir_version` is above this release's is left untouched and refused, whether or not it would decode, with a message naming "Upgrade akm" (`readRunPlan`'s `newer`) | `tests/workflows/run-plan.test.ts`; `tests/integration/workflows/legacy-plan-child-identity.test.ts` (a v6 parent resumed after the upgrade recovers its child); `tests/integration/workflows/frozen-plan.test.ts`; `tests/integration/workflows/frozen-identities.test.ts` (a v6 `plan_json` row dispatches by ref) — the rehearsal builds no workflow run |
| Workflow run rows (`workflow_runs.scope_key`, `workflow_entry_id`) | `src/storage/repositories/workflow-runs-repository.ts` (`insertRun`, `publishChildWorkflowRun`) | No marker; the columns stay in the schema | A row from before 0.10 carries a directory-hash `scope_key` (`dir:v1:…`) and, for a top-level run, an `index.db` `workflow_entry_id`. Neither is read: `list`, `status`, `resume`, `abandon` and the start warning select runs by run id and `workflow_ref` alone, so those rows stay visible from any directory. New rows (0.10, #1239) write NULL in both columns. `bundle rename` rewrites `workflow_ref` on every row naming the old bundle prefix (a legacy unqualified ref is left alone) and lists the renamed bundle's active and blocked runs, whose frozen `plan_json` keeps the old qualified refs | A 0.9.15 binary on the same `state.db` filters runs by `scope_key`, so it does not see runs 0.10 started (owner-accepted, #1239): finish or abandon them before downgrading | `tests/integration/state-db/state-migration-023.test.ts`, `state-migration-024.test.ts` (the column set); `tests/integration/workflows/run-resume-and-new.test.ts` (new rows write NULL) |
| Native scheduler rows (crontab, launchd plists, Task Scheduler) | `src/tasks/backends/cron.ts`, `launchd.ts`, `schtasks.ts`; the invocation grammar in `src/tasks/scheduler-invocation.ts` | The row's own invocation shape: current rows set their environment inline (a cron `VAR=value` prefix, a plist `EnvironmentVariables` entry, a PowerShell `$env:` assignment) — always `AKM_BUNDLE_DIR`, the syncing shell's working stash — and carry no `--scheduler-context`; 0.9.0 – 0.9.17-alpha.6 rows carry `--scheduler-context <descriptor>` holding the same values; older rows carry neither. A task row runs `run <bundle//concept-id> --scheduled` (from 0.10.261135); a row written before that runs `task run <bundle//concept-id> --scheduled` (0.10; §0.2 A11), and one written before that names its task by id, `task run <id> --bundle <bundle> --scheduled`. A cron command over 1,000 bytes runs an akm wrapper script (`sh <log dir>/.akm-cron-wrapper-…sh`) that holds the same line | Every shape is listed and parsed (`parseScheduledInvocationArgv`; a spilled cron row from its wrapper script): a row inside akm's own `# akm:task` markers from before `--scheduler-context`, and a `--scheduler-context` row, which keeps firing (the CLI applies its descriptor, below) until the next plain `akm task sync` rewrites it in place — an update that keeps the row's launcher and schedule, never an add or remove. The primary bundle proves a row by the `AKM_BUNDLE_DIR` it carries, inline or in its descriptor; any other bundle owns rows by name. Rows that still carry the pre-0.9.17 workflow execution-evidence marker (`# akm:workflow-evidence` in the crontab, an `akm-workflow-evidence` plist comment or PowerShell literal) are listed like any other and rewritten once without it. A `task run` row, by ref or by id, is read until 0.11 and fires as before; the row's signature includes its invocation, so the next `akm doctor scheduler sync` / `akm task sync` reports it `updated` and rewrites it in the `run` form (§0.2 P11). A `run <ref> --scheduled` start whose ref cannot be resolved (a config that cannot load, a task that is gone) goes to the task runner, which records it as the scheduled run's failure, as `task run --scheduled` does (`isUnresolvedScheduledRun`, `src/commands/run-cli.ts`). On a downgrade, a binary before 0.10.261135 runs a `run` row as a scheduled task run (its `akm run` resolves the task and passes `--scheduled` on) but cannot parse it, so its next sync lists the task as an add and replaces the row in place by its native id, in the `task run` form. Plain `akm task sync` keeps an installed row's own launcher (`installOptionsFor`, `src/tasks/scheduler-sync.ts`) and recomputes its environment; `akm task sync --rebind` repoints the launcher | A row inside akm's markers, `com.akm.task.` label namespace, or `\akm\` task folder whose argv this binary cannot parse (for example one a newer akm wrote) is not listed: sync leaves it alone unless an enabled source renders a row with the same native id, which then replaces it — the row is derived state and its source is the record. A crontab whose akm markers are malformed is refused unmodified (`parseBlocks`, `cron.ts`) | Upgrade rehearsal gate (`tests/integration/upgrade-rehearsal/`: the previous release's `--scheduler-context` rows fire under the candidate, then `task sync --dry-run` shows them only as updates); `tests/integration/tasks-sync.test.ts` (`--scheduler-context` rows and spilled rows are updates, never adds); `tests/integration/tasks-sync.test.ts` (id-form rows are updates) |
| Dispatch row and `$STATE/scheduler/dispatch-minute` (0.10.261135, Experimental) | `src/commands/tasks/tasks.ts` (`--dispatch`), `src/commands/tasks/dispatch.ts`; the row through the backends above | The row's invocation is `task dispatch`, with no task or bundle, under native id `dispatch`. It sets `AKM_BUNDLE_DIR` only when the syncing process was given one, and its `AKM_CONFIG_DIR` or `AKM_CONFIG_FILE` when not the default, which is how sync tells its installation's row; a row written by an earlier 0.10.261135 build with `AKM_BUNDLE_DIR` and no config is the default config's, and the next sync rewrites it without the variable; the minute file is one decimal number of minutes since the epoch | A host without the row is in per-task mode; a missing or unreadable minute file means "this minute only" | An akm before 0.10.261135 does not parse the row, so its sync neither lists nor removes it and writes per-task rows beside it; if the row's launcher is still a newer akm, both fire. Run `akm doctor scheduler sync --no-dispatch` before going back to an older akm. No guard | `tests/integration/tasks-dispatch.test.ts`; the backend contract (`tests/_helpers/scheduler-backend-conformance.ts`) |
| Scheduler-context descriptor (`$DATA/tasks/context/<sha256>.json`, written by 0.9.0 – 0.9.17-alpha.6) | No longer written: a row carries its own environment. Read by `src/tasks/scheduler-invocation.ts` (`readLegacySchedulerContext`) | `version: 1`; the environment key set | When a row that names one fires, the CLI reads the file as plain JSON and applies its `AKM_*_DIR` keys and, in one written before 0.9.17, `PATH`; nothing else about the file (name, mode, owner, link) is checked. Sync reads its `AKM_BUNDLE_DIR` to attribute the row. A plain `akm task sync` that reconciles the row rewrites it without the argument; a row a sync leaves as it is (its source failed, a `--bundle` sync did not cover it) keeps naming the file | A key this binary does not know is ignored. A file that is gone or is not JSON fails the run with `INVALID_CONFIG_FILE` naming `akm task sync`; sync cannot attribute such a row to the primary bundle and leaves it in place, and `akm task prune` reports it as `invalid-context` | `tests/integration/tasks-scheduler-invocation.test.ts`; `tests/integration/scheduler-context-launcher.test.ts`; upgrade rehearsal gate (`tests/integration/upgrade-rehearsal/`) fires the previous release's rows under the candidate before and after its plain `task sync` |
| Proposal `metadata_json` | `src/storage/repositories/proposals-repository.ts` | No explicit version field; presence/absence of the `changes` key | Rows from before the `changes` key existed decode with an empty change list rather than throwing (`proposals-repository.ts`), and a decision on one never writes an empty `changes` list back: an absent key is that legacy shape, an empty array is refused on read. A pending row whose `ref` is the pre-concept-ID `<type>:<name>` grammar (#1513) decodes with the ref as written and is non-applicable: `akm proposal show` reports a `legacy-ref` finding, `reject` archives it with its ref and content kept, `accept` and `diff` refuse it and the drain leaves it alone; a fragment ref is still skipped (#898). Later releases added metadata that an older reader's `validatePresentMetadata` does not enumerate, so it neither inspects nor rejects it and the row decodes with those keys absent: a consolidate pair-pass `retire` proposal's `changes[0].op: "delete"` (no `after`, already a valid `FileChangeOp`) with its `retirement` / `retiredArchive` / `promotionSource` / `promotionSourceHash` keys and `retirement.continuityRisk` (a person can accept a flagged proposal by id even though bulk accept excludes it); `retirement.judgedScope` optionally records the shared normalized memory scope tuple: `{}` means known unscoped and absence means unknown. Older rows still decode unchanged; acceptance refuses an unknown tuple and asks for rejection or reassessment, rather than inferring judgment from live files, and staged stale decisions use the existing stale-target rejection and ledger retry path. Older readers carry this nested object through but do not enforce it, so do not downgrade before reviewing pending retirements. No format-version bump or database migration is needed for this additive metadata. `review.decidedBy` (`"triage"` is written when the drain accepts or rejects; `"human"` is written when `akmProposalAccept` / `akmProposalReject` runs without the option: CLI accept/reject, bulk adjudicate, UI actions and the feedback manual-fix accept; the field is absent on decisions recorded before this change (#1373), and on system archives (expired retention, asset missing on disk, a failed feedback manual-fix); a revert keeps the accept's `decidedBy`, and one written before this change has none. In every absent case the decider is unknown and is never back-filled; a hand-run `akm proposal drain` still records `triage`), which an older reader carries through whole; `acceptedAt` (ISO, top-level; written at accept and kept through a revert), which an older release drops if it rewrites the row, so readers date a reverted proposal by its revert; `reviewHistory` (the rejections `akm proposal reopen` undid, oldest first, each with its gate verdict), which an older release drops if it rewrites the row; and the quality judge's `scores` and `judgeReason` inside the existing `gateDecision` object, which an older reader carries through whole. An older release counts a pending proposal's age (retention expiry, `--older-than`) from `createdAt`, so after a downgrade a reopened proposal can expire at the next `akm improve` run (a retire proposal never expires), or be swept by a scheduled `--older-than` bulk action or drain **Refs, not files (0.10, §0.2 P5):** a record names assets by ref. `changes` is `[{ ref, op, content? }]` (the primary change's content is the `content` column, as `after` was), `proposedTarget` is `{ source }` (the bundle) and `acceptedTarget` is `{ bundle, ref, contentHash }`. A record an older akm wrote with `changes[].path/after`, `proposedTarget.root` or `acceptedTarget.source/root/path` is read as converted in memory (`src/commands/proposal/legacy-records.ts`): a path becomes a ref through the bundle's adapter (valid when no file holds the asset any more), and a `proposedTarget.source` that names no configured bundle (`stash`, made by `--dir`) is mapped through the stored `root` to the bundle at that root; one that names no asset or whose bundle is gone takes the proposal's own ref. The first such record a command reads makes it warn once: `Proposals in state.db were written by an older akm and are read as converted; run \`akm migrate apply\` to rewrite them.` The state opener never rewrites them. `akm migrate apply` rewrites them in one transaction (`proposalRecords`, dry run `proposal records: <n> to rewrite`) after a copy of the database, `state.db.pre-proposal-records.bak`; a decision on one proposal (accept, reject, revert) writes that row in the current shape too. A retire records its archive as `retiredArchive: { retired: [{ ref, handle }] }` (a handle is the opaque name of the retirement's archive: for a directory bundle its path relative to the bundle root) and its accept intent as `retireAcceptIntent: { backupContent }` (§0.2 P7); a record with `retiredArchive.dirs` or `retireAcceptIntent.assetPath` is read as converted by the same reader (the `ref` of each retirement is the accepted target's, which is the ref the retire accept archived each file under), with the same warning, and rewritten by the same `proposalRecords` step. `akm bundle rename` rewrites the bundle in `changes[].ref`, `acceptedTarget` and `retiredArchive.retired[].ref`. A retirement's tombstone (`.akm/memory-cleanup/archive/<stamp>-<concept id>/cleanup.md`, which is in the bundle) names the refs it holds (`ref`, `parentRef`, `survivorRef`, `successorRefs`) and its directory by concept id, a ref into the bundle without its `bundle//` (§0.2 N11); the tombstone reader qualifies refs and reads an older tombstone's qualified refs as written, so no tombstone is rewritten. A tombstone's keys keep the order they have always been written in, because the file is committed into the bundle: `schemaVersion`, `kind`, `archivedAt`, the caller's note fields, `originalPath`, `archivedPath`, then `proposalId`, `retiredAt` and `successorRefs` (`archiveFile`, `src/core/adapter/directory-archive.ts`). | 0.9.17-alpha.8 and earlier predate the retire proposal shape entirely — they were never taught to read a delete-primary change with no `after`. `akm proposal show` / `diff` / `drain` exit 70 on one, and drain's own nightly pre-pass failing on the first pending retire proposal it meets stops that run's auto-promotion for the whole stash, not just that one proposal. **Downgrade gate:** every pending retire proposal must be accepted or rejected (`akm proposal accept` / `reject`) before downgrading to 0.9.17-alpha.8 or earlier — once decided it is archived, out of the pending set `show`/`diff`/`drain` iterate, and no longer trips this. **Gap** otherwise (no code-level guard; this is operator guidance only). Downgrading also revives the starvation the second review round's B1 fixed forward-only: 0.9.17-alpha.8's `retrieval-scope.ts` counts a `consolidate-pair` ledger row as processed, so the pair pass's own nightly attempts crowd new material back out of every other improve lane's scope, the same way they did before B1 — measured on the real bundle, two alpha.9 nights left only 341 of 2,183 new-only assets still in scope once read under alpha.8. **Gap** here too (the ledger `source` string carries no version of its own; operator guidance only — do not downgrade across a pair-pass run without expecting this). **Gap:** a 0.9.x or earlier 0.10 pre-release `akm` reading a row in the refs shape finds no `changes[].path`, refuses the row ("invalid changes") and skips it with a warning, so `akm proposal list` and the drain stop seeing those proposals; there is no guard (operator guidance only: decide pending proposals before downgrading, or restore `state.db.pre-proposal-records.bak`). | `tests/proposal-repository-pure.test.ts` (codec and validator, `acceptedAt` and `review.decidedBy`), `tests/integration/proposal/proposal-legacy-records.test.ts` (old-shape records: converted read, one warning, never rewritten on open, rewritten by `akm migrate apply`), `tests/integration/proposal/proposal-legacy-ref.test.ts` (pre-concept-ID ref rows), `tests/integration/proposal/proposals.test.ts` (default `human`), `tests/integration/proposal-gate-decision.test.ts` (drain stamps `triage`) — the rehearsal builds no proposal |
| Extraction events and `extract_sessions_seen` outcomes | `src/commands/improve/extract.ts`; `src/storage/repositories/extract-sessions-repository.ts` | Existing event envelope / state.db layout; no format bump | #1212 adds `dryRun`, `previewCount`, `blockedCount`, and `failedCount` to event metadata, and `blockedCount` and `failedCount` to seen-session metadata. #1224 adds `failedRejectedCount` to seen-session metadata only: the writes among `failedCount` that the proposal validator refused (`INVALID_PROPOSAL`). A seen row with a failed write other than a refusal stores a null `content_hash`, so the session is retried; a row whose failed writes were all refusals records its hash. An absent `failedRejectedCount` reads as 0. `blockedCount` also counts candidates skipped because this session's proposal for the ref was already accepted. `candidateCount` counts parsed model candidates; `proposalCount` counts successful proposal creation. Preview events use `candidates_previewed`; zero-write runs use `candidates_blocked` or `proposal_write_failed`. Preview runs never write seen-session rows. Legacy metadata is read unchanged: missing `dryRun` means unknown preview status, and historical `candidates_queued` is not proof of persistence. No historical rewrite is performed | Older readers pass through metadata and outcome text. Older health checks may report an all-write-failed run as active instead of warning. Proposal totals still come from proposal rows. No database migration or queue/content rewrite is needed | `tests/integration/extract-command.test.ts` (accounting replay, legacy records); `tests/integration/health/health-session-extraction-ledger.test.ts` |
| `index_completed` event metadata | `src/indexer/indexer.ts` (`akmIndexReal`) | Existing event envelope; no format bump, no migration | #1371 adds `totalEntries` (library size at index completion) to event metadata. Rows written before #1371 carry only `{mode, totalMs, walkMs, llmMs, embedMs, ftsMs, finalizeMs}`. A missing `totalEntries` means unknown, not 0, and is never back-filled (history is not back-calculated) | Older readers pass the extra keys through; `src/commands/metrics/collect.ts` reads only `totalMs` | `tests/integration/timing-persistence.test.ts` (new field); `tests/integration/metrics-command.test.ts` and `tests/metrics-collect.test.ts` (legacy rows without the field) |
| `search` and `select` event metadata | `src/commands/read/search.ts` (`logSearchEvent`), `src/indexer/usage/show-usage.ts` (`appendShowTrace`) | Existing event envelope; no format bump, no migration | #1374 adds `source` and `searchId` to `search` metadata, and copies both onto the `select` that follows it. Rows written before carry neither: a missing `searchId` means the select cannot be deduped and is counted as recorded, and a missing `source` means all sources. Old rows are never back-filled | Older readers pass the extra keys through; `listSelectEvents` reads `searchId` and `source` and ignores an absent, empty, non-string or malformed value (invalid `metadata_json` decodes as legacy) | `tests/integration/usage/select-attribution.test.ts` (new fields, search without them); `tests/metrics-collect.test.ts` and `tests/integration/metrics-command.test.ts` (dedupe, stored `source`/`searchId` decoding, legacy and malformed rows) |
| `improve_ledger` rows | `src/storage/repositories/improve-ledger-repository.ts` | No version field of its own; the `content_hash` column (migration `029-improve-ledger-content-hash`) | A consolidate promotion row with no `content_hash` is held by its clock alone (`next_eligible_at`). 0.9.19 records `content_hash`, and no `next_eligible_at`, on a consolidate promotion once it is accepted or rejected, and holds the memory until its body hash differs (`isContentDrivenRow`); a promotion decided by an older release has no hash and keeps its old window (an accepted one none, a rejected one 7 days) | An older release reads a row by `next_eligible_at` alone and ignores the hash, so after a downgrade a memory whose promotion 0.9.19 decided is offered to the promote pass again at once, a rejected one sooner than the 7 days the older release would have held it; the hash stays on the row until the older release records its next attempt on that memory, which clears it. **Gap** (no code-level guard; operator guidance only) | `tests/integration/storage/improve-ledger-repository.test.ts` |
| `task_history` metadata | `src/storage/repositories/task-history-repository.ts` | `metadataVersion` (currently `2`) | An absent `metadataVersion` is treated as a legacy row and decoded best-effort; unknown fields are dropped rather than round-tripped (`task-history-repository.ts`). `trigger` (`schedule` or `manual`) is optional within version 2: a row without it, or with another value, reads as not recorded, and an older reader drops it. `bundle` (the bundle the task is in) is optional too: a row without it shows under every bundle filter of `akm doctor log --task` and `akm task history`. A version 5 step entry may carry `agent` (`{ engine, reason? }`, written for a step that dispatched an agent): a row written before it has no dispatch to count in `akm doctor`'s `agentFailureRate` | A `metadataVersion` newer than this binary's `2` is decoded best-effort as version 2 with a warning, rather than rejected (`task-history-repository.ts`) | Upgrade rehearsal gate (`tests/integration/upgrade-rehearsal/`) |
| Lock payloads | `src/core/file-lock.ts` | No version field; payload is a bare numeric pid string, or a JSON object carrying `pid` and optionally `launcherPid` (`extractLockIdentity`, `file-lock.ts`) | Any payload shape parses permissively: extra fields are ignored, a missing or unparseable `launcherPid` is simply absent, and a payload with no parseable `pid` probes as `stale` (`invalid_pid`, `probeLock`) and is reclaimed rather than rejected | Same permissive parse; a payload from a newer akm that adds fields is read the same way | `tests/integration/file-lock.test.ts` (describe "probeLock: launcherPid") — not the rehearsal, which does not contend locks |
| `.akm` residue | Documented in `docs/architecture/internals/storage-locations.md` | No version marker | Stale `.akm` directories or files from a previous layout are inert; nothing in current code reads or interprets them | N/A | none — gap (the closest coverage, `tests/integration/migrate/dead-residue.test.ts`, tests the detection and removal that `akm migrate status` / `akm migrate apply` run, not that ordinary commands tolerate leftover `.akm` residue) |
| Index library markers | `src/indexer/index-persist.ts`, `src/indexer/index-readiness.ts` | No layout bump; `stashDir` / `stashDirs` hold directory roots, and `stashBundles` holds pathless bundle IDs | Recognize `<cache>/index/bundles/<id>` as a legacy marker for that store if no real path is there. The next index write replaces legacy store markers; a build for the same directory library remains incremental and retains the store's rows | An older binary does not recognize the new store markers. It also warns and ignores the entire `sourceOwners` record if any owner has no `sourceRoot`. That alone does not force a full scan: mode depends on the primary library marker and `builtAt`. An incremental run can leave rows for removed bundles because it has no prior owners to compare; a complete full run reconciles them. A complete run rewrites ownership in the older format. Current readers use only owner IDs; real directory roots are still written for older readers. | `tests/integration/previous-release-corpus.test.ts` |
## Adding a format or bumping one
1. Give the format an explicit version marker (a field, a table, a filename
convention) if it does not already have one — "no marker" is not a
compatibility strategy.
2. Write the reader so it converts an older marker in memory and warns once,
per the contract above. Reserve throwing for data from a version this
binary has never heard of, and name `akm migrate apply` (or the specific
rebuild command, e.g. `akm index`) in the error.
3. Add the old shape as a fixture to
`tests/integration/upgrade-rehearsal/` so a real previous-release
binary's output is exercised, not just a hand-written fixture.
4. If the format is `config.json`, nothing more: unknown keys at any depth
are kept and named once by the reader (`unknownConfigKeyPaths`), and
`akm migrate apply` drops them.
5. Add or extend the row in the table above, including a `Gap:` note if the
code does not yet meet the contract — do not leave a mismatch undocumented.
### CLI usage store (since 0.10.261119)
The CLI usage tables live in `metrics.db` in `getDataDir()`, the file 0.11 also
uses for its rollup history (`src/core/metrics-db.ts` at the tag `archive/release-0.11.0`). They
are additive local diagnostic state, independent of learning state, and share
nothing else with 0.11's tables:
- **Names:** `cli_usage_meta`, `cli_usage_invocations` (index
`cli_usage_invocations_ts`) and `cli_usage_aggregates`. 0.11's baseline
migration creates `folded_day`, `improve_runs`, `event_daily`, `llm_daily`,
`usage_daily`, `query_daily`, `feedback_tag_daily`, `select_daily`,
`latency_daily` and `improve_skip_daily`; none collides.
- **Version:** the usage schema version (1) is the `schema` row of
`cli_usage_meta`. 0.10 never sets `PRAGMA user_version` and never creates a
`schema_migrations` table, because 0.11 versions `metrics.db` by that ledger
(an exact ordered prefix of its migration ids; a foreign id would be
"inconsistent"). 0.11 opening a file 0.10 wrote finds no ledger, runs its
baseline migration beside the usage tables, and the usage rows are kept.
**Known gap, to be fixed in 0.11:** until 0.11's first fold migrates the
file, a build of the archived 0.11 branch (`archive/release-0.11.0`) fails `akm health`'s `metrics-db` check
("no such table: folded_day", exit 1) and `withMetricsHistory` warns on
stderr, because the file has no `schema_migrations` ledger and no
`folded_day`. 0.10 cannot pre-create `folded_day`: that would break 0.11's
baseline `CREATE TABLE`. 0.11 must treat a `metrics.db` with no
`schema_migrations` ledger or no `folded_day` table as "no day folded yet"
(not an error) in its `metrics-db` health check
(`src/commands/health/metrics-db-check.ts`) and in `withMetricsHistory`
(`src/storage/repositories/metrics-rollup-repository.ts`).
- **Content:** `cli_usage_meta` holds an opaque instance UUID and the
collection start; `cli_usage_invocations` holds redacted schema-version-1
attempt documents and completion fields; `cli_usage_aggregates` holds UTC
daily dimensional counters. Start and completion update detail and aggregate
in separate atomic transactions; completion's conditional update prevents
duplicates. Detail expires after 30 days and never deletes aggregates. An
aggregate's `outcomes` keys are `<category>:<exit code>:<asset type>`, then
`:<error code>` when there was one, then `:<notes>` (`+`-joined names from
akm's own list) when the command noted any, with an empty error code when it
had none; an older reader takes the first four parts and ignores the notes.
The category `child` (from 0.10.261138) is a program akm ran that exited
non-zero; an older report reader counts it as `failure`.
- **Skew:** readers and collectors refuse a newer `schema` without altering CLI
outcomes, and reports explain the gap. A 0.10.261119 build opening a
`metrics.db` 0.11 created adds only its own tables, which 0.11 ignores. An
unwritable, locked or corrupt file never changes a command's output or exit code.
- **Off and read-only:** `usage.capture: false` and `--read-only` open and write
nothing.
- **Daily usage report:** `report.<surface>.*` rows in `cli_usage_meta`: `last_day`, the UTC day the surface last
tried (the claim that keeps it to one a day); `through`, the last day whose counts the server accepted (CLI only);
`last_outcome` and `last_detail`, what the last try came to. The report sends the store's `instance` UUID as its
install id. A 0.11 that does not send the report leaves the rows alone.
**What 0.11 must do to adopt it:** nothing to the file itself, but its readers must tolerate a `metrics.db` that holds only usage tables (see the known gap above). Its usage capture opens
`metrics.db` in the data directory it resolves (after the location is known),
runs the same `CREATE TABLE IF NOT EXISTS` statements for the three tables,
keeps `cli_usage_meta.schema` as the only usage version (bump it for a new usage
schema, not `user_version` or `schema_migrations`), and reads the instance UUID,
aggregate keys and counts as they are. Its upgrade rehearsal must carry
`metrics.db` across a relocation of the data directory with the instance UUID
and counts intact. The fold and purges of 0.11 must leave `cli_usage_*` alone.
**Tested:** `tests/integration/cli-usage.test.ts` pins the table names, the
absence of `user_version` and `schema_migrations` changes beside a 0.11-shaped
`metrics.db`, retention, redaction and fail-open behaviour.
`tests/integration/upgrade-rehearsal/upgrade-rehearsal.test.ts` (step 11b, gated
behind `AKM_UPGRADE_REHEARSAL=1` and run in CI against the previous release)
asserts that the candidate wrote a `manual` task `trigger`, usage-event `agent`
metadata and CLI usage rows, then that the previous release decodes the
candidate's newest task run (same `startedAt`) and `show` with no "Skipping
unparseable" warning, and leaves the `cli_usage_*` row count unchanged. Not
tested: that the previous release reads the `agent` metadata or the usage
tables (it has no command that shows them), and a real
0.11 build opening this file: by hand, a build of `archive/release-0.11.0` fails its health check on it until the 0.11 fix above lands, and that check belongs to 0.11's rehearsal.