akm docs

Indexing

akm index builds and refreshes the local SQLite search index ($DATA/index.db). Metadata is derived from the files themselves (src/indexer/passes/metadata.ts); no LLM runs during indexing. The entry point is akmIndex in src/indexer/indexer.ts.

There is no top-level llm config key: it is an unknown key, named once and ignored. Per-call tuning lives on a named connection under connections.<name>.* (see Configuration).

Pipeline

  1. Preflight. Open state.db (this applies pending migrations), materialize sources not yet on this host (ensureSourceCaches: a git or website source is fetched into $CACHE only if it has never been materialized here; an npm bundle with no lock entry is skipped with a warning naming akm bundle update; nothing refreshes on a timer), resolve the source list, and detect each bundle's adapter. Detected adapter ids are persisted to the config (reported as configUpdated.detectedAdapters).
  2. Walk. scanSourceDirs walks each source (walkStashFlat, src/indexer/walk/walker.ts), groups files by directory, and decides per directory whether it can be skipped. A directory that is drained has each file recognized by its bundle's adapter (adapter.recognize, see Classification).
  3. Persist. persistDirRecords writes every drained directory in one transaction: the entries row, its entries_fts row, its entry_fragments row, and its asset_links rows. A changed embedding input deletes the entry's vector. Rows for files that left a directory are deleted in the same transaction. The same transaction records which library the rows are for (index_meta.stashDir and stashDirs): that is what makes the index usable (see Usable index). It takes the write lock up front (BEGIN IMMEDIATE), so a writer that overlaps it waits out the busy timeout instead of failing at once. Moved files. Before the rows are written, persistDirRecords pairs each entry whose file is gone with the new file of the same content hash (pairMovedFiles, src/indexer/ref-moves.ts), within the bundle or across bundles. A hash held by one vanished and one new file pairs them; a hash held by several pairs the ones whose file names match one to one, and the rest are indexed as new and reported (moves.unpaired). A pair re-keys its entries row in place (repointEntry: the id keeps its vector, links and utility score; the upsert that follows rewrites type, name and text and keeps the vector), moves the llm_enrichment_cache rows to the new path, and after the commit re-keys the ref-keyed state.db rows (rekeyStateRefs, the function the legacy-ref carry-over uses too) and appends a moved event on the new ref with { from }. A file edited as well as moved has another hash and is a new asset.
  4. Reconcile. When every source was scanned completely, rows belonging to removed sources are dropped. With --clean, rows whose file is gone are deleted (--dry-run previews them; unreadable files keep their rows).
  5. Embed. runEmbeddingPass generates vectors for entries without one under the configured model, then verifies semantic search state. When the stored vectors changed, storeLayout groups the embedded entries by meaning, places them in 3D and finds the near-duplicate pairs, and stores them in entry_layout and duplicate_pairs for assets.graph; on 20,000 entries this takes a few seconds, and an unchanged set of vectors skips it.
  6. Finalize. Rebuild entries_fts if its totals are stale, re-link state.db usage events to the new entry ids, recompute utility_scores in one index.db transaction (improve and akm doctor metrics read utility; search ranking does not), clear orphaned llm_enrichment_cache rows, and (after a complete scan) record builtAt and sourceOwners in index_meta. Then VACUUM if due, and append an index_completed event with the phase timings.

The command returns the entry count, per-phase timings, warnings, the --clean result, and a verification block with semanticStatus (disabled, pending, ready-js, or blocked) and the sources it could not scan completely (incompleteSources, recorded in index_meta; akm doctor's index-sources check reads it). The run computes it (verifyIndexState) and records it in index_meta under semanticSearch (unavailable when the local runtime could not be downloaded or loaded), which akm doctor's semantic-search check reads.

When a bundle's adapter skips files in folders another adapter would index, akm index warns once per change of that bundle's skipped set, not on every run: [index] bundle "<id>": <adapter> adapter skipped N files in a/ — set bundles.<id>.components.<name>.adapter to "akm" to index them. The index records each bundle's skipped set in index_meta under adapterSkips, and a removed bundle takes its record with it.

Modes

Walking

walkStashFlat lists files with git ls-files --cached --others --exclude-standard when the source sits inside a git repository (so .gitignore applies), plus a second git ls-files --others --ignored listing for env/ and secrets/ so git-ignored env and secret assets are still indexed, and with a directory walk otherwise. Both skip .git, node_modules, bin, .cache, and dot-directories, unless the adapter asks to see every directory (OKF does). A symlink to a file is indexed like any other file; a symlinked directory is never descended.

Search fields

buildSearchFields (src/indexer/search/search-fields.ts) builds the five entries_fts columns:

Column Contents
name asset name, with - and _ replaced by spaces
description description
tags tags and aliases
hints hints, searchHints, examples, usage, intent text, xrefs, pageKind, whenToUse
content table-of-contents headings, parameter names and descriptions, and the body projection

The body projection is the body text the adapter provides; for native Markdown it is bounded by MARKDOWN_CONTENT_MAX_CHARS (1,000,000 characters) and truncation is reported as a warning. Fenced code contributes only its identifiers, never its literal values (fencedCodeIdentifiers, akm#1260). The projection's version, CONTENT_PROJECTION_VERSION, is part of every directory's index fingerprint, so changing what the projection returns re-projects every directory once on the next akm index. env, session, and secret entries get no native body projection. buildSearchText joins the same fields into the text each entry's vector is made from.

Lexical retrieval is one OR query over the query's tokens (Unicode letters and numbers, NFKC-normalized, lowercased, English stopwords removed; a query of only stopwords keeps them), ranked by BM25 with equal column weights. A query that is a ref prefix (skills/, bundle//) enumerates a subtree and skips FTS. Ranking fuses the lexical and vector lists with reciprocal rank fusion; see the Search Pipeline in Architecture.

Metadata sources

Per file, in priority order: package.json description and keywords from the file's directory; Markdown frontmatter (including params, and $ARGUMENTS, $1-$9, {{named}} placeholders in commands); script @param and header-comment metadata; renderer-specific metadata (workflow parameters, table of contents, wiki fields); then filename-derived description, tags, and aliases as fallbacks. .stash.json files are skipped.

Workflow .md sources compile to source IR version 1. The index stores the ordinary entries row and metadata derived from that IR, not a workflow AST or a plan; starting a run recompiles the source and freezes the plan in state.db.

Two files, one ref

Two files in one source can claim one ref (a skill's references/a.md and knowledge/skills/x/references/a.md are both knowledge/skills/x/references/a). The index holds one row: the file with the smaller path (code-point order) wins, regardless of walk order. akm index lists each pair in warnings. akm show refuses the ref with RESOURCE_ALREADY_EXISTS; search returns the indexed file.

Who builds the index

One function builds the live index: buildIndex (src/indexer/index-build.ts). It takes the rebuild lock, $DATA/index.rebuild.lock (src/indexer/index-rebuild-lock.ts, PID liveness only, a dead holder is reclaimed at once), runs akmIndex, and releases the lock. At most one build runs at a time on a host. When a live process holds the lock, a build does not wait and does not fail: it warns, builds nothing and returns a skipped result naming the holder, and the caller carries on with the index as it is. The next build indexes whatever changed.

Caller When a live process holds the lock
akm index Prints the skip, outputs { ok: true, skipped: { reason: "lock-held", pid, launcherPid, startedAt } } and exits 0.
bundle add, bundle update, bundle remove, source add The change is kept; the response's index field is { skipped: ... } and a warning says the bundle's index was not refreshed.
akm setup Says another build is running and names akm index; setup succeeds.
improve's pre-run index and its reindex after memory cleanup Plans on the entries the index has and adds a warning.

akm upgrade spawns a plain akm index, which skips the same way. Reads never build: see below.

Non-interactive setup builds the index for the library it configured, when that directory exists; a failed build is a one-line warning naming akm index, never a failed setup.

bundle update publishes a new revision and indexes it under the asset mutation lease. It takes the rebuild lock first (withIndexBuildLock, which hands the caller a build that runs under that lock) and holds it across publish and index, so lock order is always the rebuild lock, then the lease. When another process holds the rebuild lock, the update still publishes and its reindex is skipped. If the index step fails after the publish, the update says the bundle was updated and its index not refreshed, then rethrows the original error; akm index or the next scheduled build indexes it.

Usable index

An index is usable for a library when the keyword data for it is persisted: the entries table exists and index_meta.stashDir or stashDirs names the library. The persist transaction writes both with the entries and their FTS rows, so a build that is still embedding, was interrupted after the scan, or had one source fail is usable, and so is an empty library that was indexed (akm#1469). An index an older akm finished has the same two keys, so it is usable with no migration. openUsableIndex (src/indexer/index-readiness.ts) is the one check; search, curate, feedback and write-through all use it.

builtAt is not part of usable. It is the incremental watermark, written when a build completes with a complete scan. A persist for a different library clears it and, in the same transaction, deletes every entry outside the new library's source directories (a bundle whose source did not resolve in that build keeps its last-known-good rows), so the marker never names a library whose index still serves another's rows.

How reads degrade

Reads (search, curate, show, the in-process API, Desktop) never build and never wait. They exit 0 in every case below:

Two refusals are not "no index" and still raise: an index file akm may not read (DATA_DIR_UNREADABLE) and an index laid out by a newer akm (INDEX_SCHEMA_INCOMPATIBLE, exit 78).

Locks

Embedding phase

generateEmbeddingsForDb (src/indexer/materialize-embeddings.ts) embeds each entry's own search text. Fragments are not embedded. Knobs are under embedding.* in Configuration.

Progress output

Text mode shows a spinner. --verbose prints every phase message to stderr. In json, yaml, and jsonl modes, phase messages and the embedding heartbeat (every 15 seconds) still reach stderr; the per-batch Embedded N/M entries. line is verbose-only. Source hydration reports Hydrating source i/n: <name> with a 15-second heartbeat. Each run also writes a log file under $CACHE/logs/index/.

Tables and layout

ensureSchema creates twelve tables (index_meta, entries, entries_fts, entry_fragments, asset_links, embeddings, entry_layout, duplicate_pairs, utility_scores, index_dir_state, llm_enrichment_cache, registry_index_cache); columns are in Storage Locations. usage_events and workflow run state live in state.db.

index_meta.version is the layout number, currently 26. It is a marker, not a gate: