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). An ordinary write (mutateConfig, mutateConfigWithPrecommit) edits the file's own document (editedConfigFile), so the retired form, 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, 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) |
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 one migration: the registry ends at 030-usage-events-created-at-index (0.10.261120; 0.9.31 ends at 029-improve-ledger-content-hash). It 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. 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 (018-drop-dead-lane-schema, 028-improve-ledger; 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) |
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/) |
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 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. 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) |
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 |
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). |
tests/proposal-repository-pure.test.ts (codec and validator, acceptedAt and review.decidedBy), 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) |
Adding a format or bumping one
- 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.
- 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. - 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. - If the format is
config.json, nothing more: unknown keys at any depth are kept and named once by the reader (unknownConfigKeyPaths), andakm migrate applydrops them. - 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 on 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(indexcli_usage_invocations_ts) andcli_usage_aggregates. 0.11's baseline migration createsfolded_day,improve_runs,event_daily,llm_daily,usage_daily,query_daily,feedback_tag_daily,select_daily,latency_dailyandimprove_skip_daily; none collides. - Version: the usage schema version (1) is the
schemarow ofcli_usage_meta. 0.10 never setsPRAGMA user_versionand never creates aschema_migrationstable, because 0.11 versionsmetrics.dbby 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, arelease/0.11.0build'sakm healthfails itsmetrics-dbcheck ("no such table: folded_day", exit 1) andwithMetricsHistorywarns on stderr, because the file has noschema_migrationsledger and nofolded_day. 0.10 cannot pre-createfolded_day: that would break 0.11's baselineCREATE TABLE. 0.11 must treat ametrics.dbwith noschema_migrationsledger or nofolded_daytable as "no day folded yet" (not an error) in itsmetrics-dbhealth check (src/commands/health/metrics-db-check.ts) and inwithMetricsHistory(src/storage/repositories/metrics-rollup-repository.ts). - Content:
cli_usage_metaholds an opaque instance UUID and the collection start;cli_usage_invocationsholds redacted schema-version-1 attempt documents and completion fields;cli_usage_aggregatesholds 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. - Skew: readers and collectors refuse a newer
schemawithout altering CLI outcomes, and reports explain the gap. A 0.10.261119 build opening ametrics.db0.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: falseand--read-onlyopen and write nothing. - Daily usage report:
report.<surface>.*rows incli_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_outcomeandlast_detail, what the last try came to. The report sends the store'sinstanceUUID 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, 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.