# Bundling akm

This is for anyone shipping `akm` inside their own product: a Docker image, a
plugin whose `node_modules` carries its own akm, or any other install a human
never runs `akm setup` inside. It says exactly what to call at boot and what
each call's JSON means — nothing about akm's internals you don't need.

## The contract

Three lines cover it:

1. **Pin** an exact `akm-cli` version and install it however you install
   things (npm, the standalone binary, a `node_modules` dependency).
2. **At boot, run `akm migrate apply`** (or `akm upgrade`, which runs it).
   It is offline, idempotent, needs no root, takes its own safety copies,
   prints one JSON plan, and exits `0` unless a file is genuinely blocked.
3. **Read `akm doctor --format json`.** Never grep error text — akm's
   wording is not a stable interface; the JSON fields are.

Everything below is detail in service of those three lines.

## `akm migrate apply`

```sh
akm migrate status        # read-only: what would change
akm migrate apply
```

In order, every run applies (or, under `status`, plans):

1. **config.json in its current shape** (`configFile`): unknown keys dropped,
   `configVersion` set, and the `engines` / `defaults` form converted to
   `connections` / `harnesses`. Config loading already does this in memory;
   this persists it under a backup. The API keys a config still holds in any
   form akm no longer reads move to `credentials.json` (`configFile.credentials`
   lists the entry names, never a value), and a leftover `models.json` is folded
   into the `models` of the connections and harnesses it names. A config older
   than 0.9.15 (the legacy `stashDir`/`sources[]`/`installed` layout) is not
   converted by 0.10: it blocks with a message to run `akm migrate apply` under
   akm 0.9.x first. What each retired key becomes is the table in
   [Configuration](../reference/configuration.md#the-engines-form).
2. **Pending `state.db` migrations** (`stateMigrations`). Any command that opens
   `state.db` applies them; this step does it up front and reports what ran. A
   migration that drops schema first copies the file to
   `state.db.pre-<migrationId>.bak`. See
   [One-way state.db](#one-way-note-statedb-migrations-are-one-way) below.
3. **Task files**: every task file at version 2 or 3, and every version 4
   file still carrying the retired `schedule[].enabled` key, rewritten as
   task source v4 (`taskFiles`) under one backup directory per run. A file
   the planner cannot convert unambiguously is reported `blocked` and left
   alone; the rest still convert.
4. **Asset `engine:` keys** (`assetEngineKeys`): the retired `engine:` key on
   commands, agents, workflows and task sources rewritten to `connection:` or
   `harness:` by what the name is now, under one backup directory per run. A
   bundle akm may not change is skipped.
5. **Content refs** (`assetContentRefs`): refs in the text files akm indexes in writable
   bundles that still use the pre-#1432 spelling (`knowledge/WORK/x`, now
   `WORK/x`), in frontmatter and body, rewritten under one backup directory per
   run. An old spelling that is now another file's ref is listed in `shadowed`
   and left as written.
   The ref scan and rewrite is `src/core/asset/ref-rewrite.ts`, the same code
   `akm lint --fix` uses to rewrite links to a ref that `akm index` recorded as
   moved.
6. **Bundle policy** (`bundlePolicy`): in each writable bundle, `lint_skip:`
   frontmatter is stripped from the assets, and a `.gitignore` carrying the old
   `# akm: intentionally track env and secrets` marker adds
   `"tracked-secrets": ["**"]` to the bundle's `lint.skip`. `.gitignore` is
   never modified. The config is written first, the files then under one
   backup directory per run.
7. **Proposal records** (`proposalRecords`): proposals in `state.db` that an
   older akm recorded with the files they change (`changes[].path`, a target
   directory) are rewritten as the current record, which names assets by ref,
   in one transaction after a copy of the database
   (`state.db.pre-proposal-records.bak`). Until then every command reads them as
   converted and warns once. Dry run: `proposal records: <n> to rewrite`.
8. **Index rows** (`indexRows`): rows of a bundle that is no directory (a
   keyring, a vault) that an earlier akm indexed under a path inside the
   bundle's root are re-keyed to hold no path, in one update that changes no
   column and not the index layout. Until then every command reads them as
   rows with no file. Present only when such rows exist. Dry run:
   `index rows: <n> to re-key`.
9. **Residue sweep**: superseded pre-0.9.0 `.akm` files in the stash and the
   transaction-journal, maintenance-barrier, lock-mutex and version-stamp
   files older releases kept under `$DATA`/`$STATE`/`$CONFIG` (`deadResidue`).

### The plan JSON

One JSON object on stdout, always, with one field per step. A current
install, nothing to do, as `akm migrate status` prints it (under `apply` the
per-step objects carry results instead — `applied`, `removed` — with the
same step names):

```json
{
  "schemaVersion": 1,
  "status": "current",
  "blockers": [],
  "configFile": { "keys": [], "changed": false, "applied": false },
  "stateMigrations": { "pending": [] },
  "taskFiles": { "schemaVersion": 1, "changed": 0, "skipped": 0, "blocked": 0, "files": [] },
  "assetEngineKeys": { "schemaVersion": 1, "changed": 0, "skipped": 0, "files": [] },
  "assetContentRefs": { "schemaVersion": 1, "changed": 0, "skipped": 0, "refs": 0, "files": [], "shadowed": [] },
  "bundlePolicy": { "schemaVersion": 1, "changed": 0, "bundles": [], "notes": [] },
  "proposalRecords": { "schemaVersion": 1, "changed": 0, "message": "proposal records: 0 to rewrite" },
  "deadResidue": { "pending": [] }
}
```

`akm migrate status` against a tree with one blocked task file:

```json
{
  "schemaVersion": 1,
  "status": "blocked",
  "blockers": ["tasks/nightly.yml: with-on-non-command-target"],
  "stateMigrations": { "pending": [] },
  "taskFiles": {
    "schemaVersion": 1,
    "changed": 3,
    "skipped": 1,
    "blocked": 1,
    "files": [
      {
        "filePath": "tasks/nightly.yml",
        "status": "blocked",
        "reason": "with-on-non-command-target",
        "beforeHash": "…"
      }
    ]
  }
}
```

`status` is one of:

- **`current`** — no task-source file needs converting, and no config
  rewrite is pending. A no-op boot.
- **`ready`** — task sources have eligible changes and no config-lift
  conflict; a real `apply` will clear them.
- **`blocked`** — at least one item cannot be applied automatically (a
  genuine authoring problem, e.g. a task file the migrator can't rewrite
  unambiguously, or a config that fails validation). `blockers` names each one. `apply` still applies
  everything it *can*, then reports `blocked` and exits non-zero.

A pending `state.db` migration needs no human decision, so it is never
`blocked`: under `akm migrate status` it reads as
`ready` (the run would change `state.db`) and is listed in
`stateMigrations.pending`; a real `apply` always applies it.

Key fields:

| Field | Meaning |
| --- | --- |
| `stateMigrations` | `{ pending: string[] }` under `status`; `{ applied: string[], safetyCopyPath?: string }` after a real `apply`. `safetyCopyPath` is present only when a historical-destructive migration ran — see below. |
| `taskFiles` | `changed`/`skipped`/`blocked` counts and a `files[]` array with each file's `status` and `reason`. |
| `taskFilesV5` | Present when files were named (`status <file>...`, `apply <file>...`): one entry per named task or workflow file with `filePath`, `status` (`converted`, `skipped`, `blocked`), `reason`, `notes[]` (what version 5 does not keep, to change by hand), `taskFile` (the task a workflow file becomes) and, when blocked, `detail` and `guidance`. `taskFilesV5BackupPath` is the backup directory after a real apply. |
| `workflowFiles` | Present when workflow files remain in enabled, writable bundles: `bundles[]` (`bundle`: the bundle's root, `files[]`) and `message`, the files part of the line `akm doctor` prints for its `workflow-files` advisory. Reported only: a workflow file is converted when it is named, and it does not change `status`. |
| `assetEngineKeys` | `changed`/`skipped` counts and a `files[]` array with each rewritten file's `rewrites` (`at`, `from`, `to`). |
| `assetContentRefs` | `changed`/`skipped` file counts, `refs` (old-spelling refs found), a `files[]` array with each file's `refs`, and `shadowed[]` (`bundleId`, `from`, `to`): old spellings another file holds as its ref, not rewritten; and `reconcile[]`, present after an apply that rewrote files inside a git checkout: the checkout path and how to review, commit or restore the edits. Only asset files, `index.md` and wiki `schema.md` are rewritten. |
| `bundlePolicy` | `changed` (files to rewrite plus bundles whose config gains the skip), `bundles[]` (`bundleId`, `stripped`: assets whose `lint_skip` is removed, `skipTrackedSecrets`), and `notes[]`: a bundle with the marker and no config entry. After a real apply: `applied`, and `backupPath` when files were rewritten. |
| `proposalRecords` | `changed` (records of an older shape to rewrite; after a real apply, how many were rewritten) and `message` (`proposal records: <n> to rewrite`). After a real apply that rewrote records: `applied`, and `backupPath` (the copy of `state.db` taken first). |
| `indexRows` | Present only when the index holds rows of the form before it was keyed by ref: `changed` (rows to re-key; after a real apply, how many were) and `message` (`index rows: <n> to re-key`). After a real apply: `applied`. |
| `backupPath` / `applied` | Present after a real apply that rewrote at least one task file: the run's backup directory and how many files it rewrote. |
| `deadResidue` | `{ pending: [...] }` under a read-only run, `{ removed: [...] }` after apply. Each entry carries `relativePath` and `sizeBytes`; a removal entry adds `removed` (a boolean) and an `error` when the delete failed. A failed delete does not set `status` to `blocked`. |

**Backups and their retention:**

- Task-file backups go to `<dataDir>/backups/tasks/<timestamp>-<uuid>/`,
  one directory per apply run that rewrote a file; nothing prunes them.
- Config backups go to `<cacheDir>/config-backups/config-<ISO-ts>.json`; akm
  keeps the newest **5** and prunes older ones.
- A `state.db` migration that drops schema writes a sibling copy next to
  `state.db` itself: `state.db.pre-<migrationId>.bak`, where `<migrationId>` is
  the first such pending migration. akm does not prune it. It is a rare,
  one-time event, so clean it up yourself once you've confirmed the upgrade, if
  disk space matters to your image.

**Exit codes:**

| Exit | Meaning |
| --- | --- |
| `0` | `current` or `ready`-and-applied — nothing left to do. |
| `1` | `blocked` — at least one item needs a human. |
| anything else | A crash, not a migration outcome: `{"ok":false,"error":"...","code"?:"...","hint"?:"..."}` on stderr, with the exit code from akm's normal error-classification table (`2` usage, `70` internal, `78` config). |

**Idempotency:** re-running `apply` against a `current` database/tree is a
no-op — safe to put in every boot, every time, on every replica.

**Offline, no root:** every step reads and writes files/SQLite it already
owns under your configured `$DATA`/`$CACHE`/bundle directories. Nothing here
touches the network or needs elevated privileges.

## `akm upgrade` in a bundled install

```sh
akm upgrade              # install a newer release if there is one, then migrate
akm upgrade --check      # check for updates only — no install, no migration step
```

`akm upgrade` always runs the migration step after its install step — on
install success, on install failure, and when there was nothing to install.
Its result carries the same plan under `migration`:

```json
{
  "currentVersion": "0.10.261122",
  "newVersion": "0.10.261130",
  "upgraded": false,
  "installMethod": "package-local",
  "message": "akm runs as a dependency of the package at /opt/myapp; upgrade that package to move akm.",
  "migration": { "schemaVersion": 1, "status": "current", "blockers": [], "stateMigrations": { "pending": [] } }
}
```

**`installMethod: "package-local"`** is the detection that matters for a
bundler: an `akm` living inside *another* package's `node_modules` (your
image's `tools/` dependency, a plugin's own `node_modules/akm-cli`) is never
`npm install -g`'d over — that would silently diverge from the copy the
parent package actually executes. akm reports `upgraded: false` and names the
parent package to upgrade instead; **its migrations still run**, exactly as
in every other install method. `installMethod` is one of `"binary"`,
`"bun"`, `"npm"`, `"pnpm"`, `"package-local"`, or `"unknown"`.

**Exit code:** `akm upgrade` exits `1` when `migration.status` is `"blocked"`
or `"failed"`, even if the install itself succeeded — an upgrade whose
migration didn't finish is not done. This makes plain `akm upgrade` (no
flags) a safe, idempotent container entrypoint step on every boot: on an
already-current install with nothing pending it is a fast no-op that exits 0.

After the install step it also updates the akm plugin of each agent harness
present in the image (Claude Code, Codex, OpenCode), reported under `plugins`;
see [`akm upgrade`](../reference/cli.md#upgrade) for the rules and the Codex hook-trust entries a headless image needs.

**`--check`** skips the migration step entirely — it only compares versions
and reports `updateAvailable` (plus the pending per-harness plugin updates). Use it for a version-drift alert, not as your
boot check.

## `akm doctor`

```sh
akm doctor --format json
```

Read the JSON. Never parse the human-readable text or grep for a phrase —
that wording is not a stable interface.

**Exit codes:** `0` (`status: "pass"`), `4` (`status: "warn"`), `1`
(`status: "fail"`).

The check that replaces grepping akm's refusal text is a **hard check**
named `state-db-migrations`. Every `state.db` open applies pending migrations
(copying the file to `state.db.pre-<id>.bak` first when one drops schema), so
after an upgrade the check passes and names what health's own open applied:

```json
{
  "name": "state-db-migrations",
  "status": "pass",
  "message": "Applied 11 pending state.db migration(s) on open (018-drop-dead-lane-schema … 028-improve-ledger); the pre-migration copy is /data/akm/state.db.pre-018-drop-dead-lane-schema.bak.",
  "evidence": {
    "path": "/data/akm/state.db",
    "pending": [],
    "applied": ["018-drop-dead-lane-schema", "…", "028-improve-ledger"],
    "backupPath": "/data/akm/state.db.pre-018-drop-dead-lane-schema.bak"
  }
}
```

It is `fail` only when a pending migration could not be applied; `evidence.pending`
then names what is still pending. Watch this row's `status`, not error text.

## The `akm-migrate` executable

`akm-migrate` is the second `bin` entry the `akm-cli` npm package installs
(`akm` and `akm-migrate` side by side), and it is also embedded directly in
the compiled standalone binary — a release binary re-execs itself internally
to reach it, so it needs no separate download. Same surface either way:

```sh
akm-migrate status
akm-migrate apply --dry-run
akm-migrate apply
```

`akm migrate status`/`apply` (under the `akm` CLI) are a thin wrapper over
this same executable — same plan, same exit codes. Reach for `akm-migrate`
directly when you don't want `akm`'s `--format`/`--detail` output
handling in the way, e.g. a shell script that just wants the raw JSON line
on stdout and a plain exit code.

## Container entrypoint sketch

```sh
#!/bin/sh
set -e
akm --version                 # optional: confirm the pinned version actually landed
akm migrate apply             # offline, idempotent — exits 1 only if genuinely blocked
akm doctor scheduler sync --rebind        # only if you schedule akm tasks inside this image
akm doctor --format json      # read this JSON; act on ok/status, never on message text
```

### Environment variables

A bundler that controls the filesystem layout should set these explicitly
rather than rely on `$HOME`-derived defaults:

| Variable | What it points at |
| --- | --- |
| `AKM_BUNDLE_DIR` | The content bundle (`$STASH`) — assets akm indexes and serves. |
| `AKM_CONFIG_DIR` | `config.json`'s directory. |
| `AKM_DATA_DIR` | Durable, non-regenerable data: **`index.db` and `state.db` live here.** This is the directory a migration snapshot's safety copy sits beside. |
| `AKM_CACHE_DIR` | Regenerable cache: installed git, npm and website bundles, config backups, task logs. If it is discarded, `akm bundle update --all` restores the bundles. |
| `AKM_STATE_DIR` | **Not** where `state.db` lives, despite the name — this is the XDG "state" directory. Holds the scheduler lock and, per bundle, `akm improve`'s whole-run lock (`locks/`) — see [Storage locations](../architecture/internals/storage-locations.md). Set it too, so those locks sit on the same persistent volume as the rest of akm's state rather than under `$HOME/.local/state/akm`. |

Set all five to paths that persist across container restarts (a mounted
volume), or `akm migrate apply` will see an empty `state.db` on every boot
and never actually converge.

## Cold starts: carrying embedding vectors (Experimental)

A host with no persistent disk starts with an empty index, and nearly all of a
cold start is embedding. To carry the vectors over: at a checkpoint on a host
with a built index, run `akm index --export-vectors vectors.db`; copy
`vectors.db` to the fresh host; there run `akm index --import-vectors vectors.db`.
The keyword index is rebuilt as usual, and each entry whose embedded text is
unchanged takes its vector from the file instead of the embedder. The file holds
hashes and vectors only, no document text or paths. A different embedding model
or edited content is simply a miss and is embedded normally; a missing or
unusable file warns and indexes normally.

## One-way note: `state.db` migrations are one-way

Once a migration has run against `state.db`, there is no downgrade path. An
**older** akm that later opens the same file continues with the schema it knows
and warns once that the database is newer; upgrade akm if its output looks
incomplete. If you need the ability to roll back a bundled akm version, take
your own backup of the whole data directory (`$AKM_DATA_DIR`) before running
`akm upgrade`/`akm migrate apply`. The `state.db.pre-<migrationId>.bak` copy
described above covers the one schema-dropping step, not a general rollback.
