akm docs

Testing Workflow

This project is a CLI with three risk-heavy areas:

The safest way to test it is in layers: fast local checks first, then end-to-end CLI coverage, then Docker-based deployment and upgrade validation. This document covers the automated test workflow and test-authoring guidance.

What To Validate

Test Targets

bun run check runs lint and the typecheck, then both targets in sequence.

Where a test goes. A test file stays in the unit target (tests/, outside tests/integration/) only if none of its tests, directly, through a test helper, or through the src/ code it calls:

  1. starts a process (spawn, spawnSync, Bun.spawn, a fake binary that akm then runs such as writeFakeHarness or withOpencodeOnPath, or product code that runs git);
  2. runs a CLI entry, in process or not (runCliCapture, runCliStatus, main([...]));
  3. opens a server or socket (Bun.serve, http.createServer);
  4. opens a SQLite file (state, index, logs, registry cache) or builds an index (akmIndex); ":memory:" is fine;
  5. creates, writes, renames, chmods or deletes anything on disk: temp dirs (mkdtemp, makeSandboxDir, makeStashDir, withIsolatedAkmStorage), and files written into the sandbox HOME/XDG by the test or by product code (writeSandboxConfig, seedLockEntries, saveConfig, credentials).

Injected doubles (mock(), spyOn, seams, withMockedFetch, a spawn function passed as a parameter), env changes and read-only reads of checked-in files are allowed in unit. There is no "single trivial temp file" exception, and a file moves whole if any one of its tests breaks the rule. The real OpenCode binary and the loopback fake model are integration resources. tests/contracts/test-targets.test.ts fails on a unit-target test that shows one of the unambiguous markers above. Files under tests/fixtures/ are data, not executable specs: scripts/test-unit.sh skips them, and the one .test.ts there (tests/fixtures/bundles/code-project/tests/oauth.test.ts) is sample input that the code-project golden lists by path.

Green by default (principle 6). A test that must be disabled is .skipped in the same change that links its issue; never leave a failure standing and never add an "expected failures" allowlist.

Test Layers In This Repo

1. Fast local correctness

Run these before any release candidate or merge:

bun run test:unit
bun run lint:fix
bunx tsc --noEmit

Use this when you want the shortest full-project signal:

bun run check

Relevant coverage:

Writing deterministic, isolated tests

Both scripts/test-unit.sh (bun run test:unit) and scripts/test-integration.sh (bun run test:integration) shard their target across up to min(nproc, 8) concurrent bun test processes, splitting the file list round-robin — neither runner is a single shared process. Within one shard, every file assigned to that process still runs in one shared process: one process.env, one module-singleton namespace, and (under fake timers) one global clock for every file in that shard. A test that mutates shared state without restoring it, or that asserts on a wall-clock measurement, can pass on one scheduling and fail on another.

Rules (conventions, not statically enforced; src/core/paths.ts throws TEST_ISOLATION_MISSING at runtime when isolation is missing, and the preload tripwire catches leaks):

  1. Do not mutate AKM_* / XDG_* / HOME on process.env directly. Use the helpers in tests/_helpers/sandbox.ts:

    • sandboxStashDir, sandboxXdgConfigHome, sandboxXdgDataHome, sandboxXdgCacheHome, sandboxXdgStateHome, sandboxHome — set the env var to an isolated temp dir and return a cleanup that restores the prior value. Chain them and call cleanup() in afterEach.
    • withEnv({ AKM_BUNDLE_DIR }, async () => …) — scoped override that always restores in a finally, even on throw. Use this for per-call overrides around an in-process CLI invocation.
    • makeStashDir / makeSandboxDir — temp dirs that are not wired into env (pass them to withEnv or a subprocess env object yourself).
    • writeSandboxConfig(partial) — merges partial into the sandboxed config.json (call sandboxXdgConfigHome first).
    • withMockedFetch(run, mock) — swaps globalThis.fetch for the duration of run and restores it in a finally.

    Do not assign process.env.HOME =, call process.chdir(...), or assign globalThis.fetch = directly. Use withMockedFetch for fetch swaps, and restore the cwd in a finally block when a chdir is unavoidable.

    The DB path resolves from XDG_DATA_HOME; if you akmIndex then akmSearch, both must see the same sandboxed XDG_DATA_HOME or the search reads a different (empty or stale) DB. Sandbox it in beforeEach.

  2. Do not assert on a measured wall-clock delta. expect(Date.now() - start) .toBeLessThan(N) races the scheduler. Assert the observable result instead (e.g. result.reason === "timeout"), or drive time deterministically with fake timers and a fetch/spawn stub. Asserting on a durationMs field computed from injected fixture timestamps is fine (it is deterministic).

  3. Assert on the value the user sees. Search orders fused candidates by score and then by itemRef (src/indexer/search/ranking.ts), and a hit's score is rounded for display; when a test asserts ordering, compare the same value the output carries.

  4. Pass --timeout when a test spawns bun test <fixture>. Bun ignores bunfig.toml's timeout (see the comment there), so the fixture dies at 5 s under load.

  5. Keep an index from downloading a model. An index with semanticSearchMode: "auto" and no fake embedder downloads a Hugging Face model mid-test; use the deterministic embedder (AKM_EMBED_DETERMINISTIC) or "off".

The preload

bunfig.toml preloads tests/_preload.ts for every bun test invocation. It owns the process state that crosses test boundaries:

2. End-to-end CLI validation

Run the full integration suite when changing CLI behavior, indexing, search, config, source management, or output shaping:

bun run test:integration

Collectively, these suites (tests/integration/) exercise real flows, including:

Semantic Search States

Semantic search does not behave as a simple on/off feature at runtime. Testing should distinguish between saved-config state and actual readiness.

Config intent

Semantic search intent is saved independently as semanticSearchMode:

Setup should not flip intent from auto back to off because preparation or verification fails transiently.

Runtime readiness

Actual semantic readiness is tracked separately from config intent. Runtime state can be:

These cases are covered by the setup and semantic-status suites (tests/integration/setup-wizard.test.ts, tests/integration/vector-search.test.ts, tests/integration/update-no-op-semantic-status.test.ts).

The real-model gate runs with AKM_SEMANTIC_TESTS=1 bun test tests/integration/semantic-search-e2e.test.ts; its first run downloads Hugging Face models. It honors an explicit HF_HOME and otherwise uses the ignored, repo-local .ci-cache/huggingface directory. That path is outside the preload's disposable test HOME, so a second local run reuses the model without exposing the developer's normal AKM cache. Gated CI sets the same path and restores it from a model/source-identified Actions cache. Candidate tags and manual runs are restore-only; only the scheduled default-branch run may save a cache entry.

The same gate runs real semantic index/search round-trips on onnxruntime-node's binding, asserts the embeddingRuntime the index reports, and compares the embedder's vectors with the Transformers.js reference in tests/fixtures/embedder-reference-vectors.json. The binding and its library are shared across runs the same way as the model: tests/_helpers/onnx-runtime-cache.ts copies the repo-local .ci-cache/akm/onnxruntime/ into each sandbox's akm cache and keeps a folder a run fetched there, and gated CI caches that directory under a key from src/llm/embedders/onnx-runtime.ts, which pins the ONNX Runtime version. Package acceptance separately verifies the ordinary npm package surface.

tests/integration/standalone-semantic.test.ts (the same AKM_SEMANTIC_TESTS=1 gate) builds the host's standalone binary and asserts it embeds no .node file. Where akm offers local embeddings it runs akm setup --yes --embedding local, expects the binding and the library in the cache folder, and indexes a small stash, asserting a ready status, a vector per entry and the native runtime. Everywhere else it asserts the default: setup warns and saves keyword search, an index with semantic search on reports it unavailable for the platform, akm health warns, and search is keyword. Gated CI runs it in the Semantic Search job (Linux) and in the Native Scheduler job on macOS (local embeddings) and Windows (the default), the only places the binary runs on those platforms.

What to test explicitly

3. Docker deployment validation

Run the Docker matrix when changing install, packaging, startup, runtime dependencies, or platform behavior:

AKM_DOCKER_TESTS=1 bun test tests/integration/docker-install.test.ts

Or run the shell orchestrator directly:

./tests/docker/run-docker-tests.sh

This validates three deployment methods across four Linux families:

Binary validation currently excludes Alpine: there is no Dockerfile.alpine-binary, because the compiled Linux binary targets glibc and Alpine is musl-based.

The Docker smoke test in tests/docker/smoke-test.sh verifies:

The Dockerfiles are tests/docker/Dockerfile.{ubuntu,debian,alpine,fedora}-bun, tests/docker/Dockerfile.{ubuntu,debian,fedora}-binary and tests/docker/Dockerfile.debian-npm. Run one variant for a focused repro:

./tests/docker/run-docker-tests.sh ubuntu-binary
./tests/docker/run-docker-tests.sh --bun-only
./tests/docker/run-docker-tests.sh --binary-only

The matrix shows that the CLI starts in minimal Linux images, that runtime dependencies are enough for bundle create, index, search, and show, that bun-linked installs work after building from source, that compiled Linux binaries run when copied into the image, and that an npm install of the packed package works on an image with no compiler. It also exercises the real entrypoint scripts, which can catch shell-level failures that unit and subprocess tests miss. It does not show that the published release artifact matches the local compiled binary, that install.sh works against a real GitHub release, or that self-upgrade can replace the running binary in place; check those by hand in a disposable container after publishing.

4. OpenCode 2 CLI compatibility

The unit tests build the opencode run command line and the stub-program tests check that it reaches a program; only a real OpenCode 2 says what its flags, its permission map, its environment and a signal do to it. The compatibility suite runs the real CLI when a binary is named, and is one skipped test otherwise (the CI workflow does not set the gate):

AKM_TEST_OPENCODE2_BIN=/path/to/opencode bun test --timeout=120000 tests/integration/opencode-cli-compat.test.ts

Every run of the binary is sandboxed: its HOME, XDG and OpenCode directories are temporary directories, every other OPENCODE_* variable the developer has exported is blanked, its only provider is a loopback fake model reached through the @ai-sdk/openai-compatible package bundled in the binary (nothing is downloaded), and no real OpenCode file, login or key is opened. The suite covers what akm relies on at that boundary. Model work, which runs standalone, offers only its reading tools, and an abort or a timeout, during a model request or a tool call, releases OpenCode's claim on the session and leaves no process behind. Agent work is the plain invocation, which OpenCode 2 runs through a background service on one port for every HOME: those cases end the service they start, skip when something else holds the port, and record that a stop ends the opencode command and the service's turn (2.1.4 and 2.2.0) and leaves the service up. A provider defined only in the user's OPENCODE_CONFIG_CONTENT works for agent work and model work alike. Run it when changing the OpenCode builder or the subprocess kill ladder, and against a new OpenCode 2 release.

The suites that run akm's own runtime on the real binary (opencode-runtime-sessions, opencode-runtime-signal-teardown, opencode-session-store and standalone-first-run, all under tests/integration/) need no gate: they fetch the pinned OpenCode once, through akm's own fetch path, into a cache every run shares ($AKM_TEST_OPENCODE_CACHE, else node_modules/.cache/akm-test-opencode), and link it into each test's sandboxed akm cache (tests/_helpers/opencode-binary.ts). When the registry cannot be reached they skip, with a message that says why. Run them against a new OPENCODE_RUNTIME_VERSION before moving it.

5. Benchmark (agent utility)

The LLM-provider-driven, multi-seed agent-utility benchmark (akm-bench) lives in the standalone repo itlackey/akm-bench. Run it from there after any change to src/output/, src/commands/read/show.ts, APPLY directives, or other content that affects what agents see.

For curate/search ranking quality, run the retrieval eval of itlackey/akm-eval (evals/retrieval/run --corpus public, with AKM_BIN naming the build under test). It scores akm search and akm curate against graded judgments and calls no model service. See docs/maintainers/eval.md.

Normal change

Use this for most code changes:

bun run test:unit
bun run test:integration
bun run lint:fix
bunx tsc --noEmit

Use this when touching src/cli.ts, src/commands/sources/self-update.ts, install flows, source management, or Docker assets:

bun run test:unit
bun test tests/integration/self-update.test.ts tests/integration/install/install-script.test.ts
./tests/docker/run-docker-tests.sh
bun run lint:fix
bunx tsc --noEmit

Release gate

Use this before publishing a release:

bun run release:check

If Docker is available, prefer ./tests/docker/run-docker-tests.sh over a single-variant container run so both bun and binary installs are covered.

For a local release gate without Docker, use:

./tests/release-check.sh --skip-docker

That script checks the packaged artifact: bin targets, the migrator and package acceptance. Lint, the typecheck and the test suites are bun run check; the upgrade rehearsal runs in CI.

The Release workflow runs Gated CI (real embeddings, Docker, and the Linux/macOS/Windows schedulers) on the commit it publishes and requires CI to have passed on that commit; see the maintainer release checklist. The weekly scheduled run of Gated CI detects default-branch drift.

Upgrade Regression Coverage

Managed-source updates and CLI self-upgrade are separate implementations. Provider and registry suites cover source add/update/remove/cache behavior; tests/integration/self-update.test.ts covers install-method detection, orchestration, checksum, and failure paths.

Upgrade rehearsal gate

tests/integration/upgrade-rehearsal/ runs once per origin in KNOWN_UPGRADE_ORIGINS (previous-release.ts): previous, the highest stable release below the candidate's package.json version; 0.9.32, which keeps the full engines migration covered after previous advances to 0.10; and 0.9.15, which covers scheduler rows installed before host-local activation was recorded. Each origin installs that release as a real global npm package (a real npm pack / npm install --global into a throwaway prefix, see scripts/package-install.ts). The previous and 0.9.32 origins build a full home — filesystem, git (with an in-bundle symlink at its root), website, and npm bundles, scheduled tasks, a synced native (fake) crontab, and model configuration the release itself writes: native connections/harnesses on 0.10+, or the full 0.9 engines form (an llm engine with an apiKeyFile, agent engines, a models.json, and a command and task that name an engine). The 0.9.15 origin uses a smaller home with one directly installed scheduled task. Each then installs the CANDIDATE build OVER it in the SAME prefix: an in-place swap, the same thing a real npm i -g akm-cli@… or bun add -g upgrade does. It then runs the candidate against that home (migrate status / apply, which converts the engines form, files its key and rewrites the engine: keys, or preserves native connections/harnesses, bundle list, search / show, task sync dry-run and real — plain, no --rebind, as an upgrading user runs it — executing the generated cron command and confirming it ran the candidate, task run, health, improve --dry-run), and finally runs a separate untouched copy of the origin release back against the candidate-written home to check that read-back still works. Plain task sync is clean because the candidate lands inside the same prefix the previous release's scheduler rows already point at; a side-by-side install (a separate prefix) would need --rebind. tests/integration/previous-release-corpus.test.ts covers persisted-data shapes read in isolation; this gate covers the whole CLI surface across two real installed releases.

Run it locally with:

bun run build
AKM_UPGRADE_REHEARSAL=1 TMPDIR=/tmp bun test --timeout=900000 tests/integration/upgrade-rehearsal/

Unset (the default), the suite logs one line and skips. When it is requested, every missing capability (no npm on PATH, no network reachable to resolve or fetch the previous release, no candidate build) throws naming the fix. Env overrides:

Fetched previous-release tarballs are cached under ${TMPDIR:-/tmp}/akm-upgrade-rehearsal/previous-release/<version>/ so repeat runs do not re-hit the network. It is wired into CI as the upgrade-rehearsal job (.github/workflows/ci.yml), which runs on a release pull request (a pull request into main), the gate a stable release merges through.

Quality Measures

On-demand measures of code quality and test strength. They are never part of bun run check, CI on a pull request, or a release, and nothing fails on a number: they exist to compare a change or a branch with its base. Each runs its tool through bunx at an exact version pinned in scripts/quality/, so no dependency is added to package.json or the lockfile. Reports go to reports/quality/<tool>/ (gitignored): the tool's own JSON, a summary.txt, and a flat metrics.json. The same measures run from the manual Quality workflow (.github/workflows/quality.yml, workflow_dispatch), which uploads reports/quality as an artifact.

Command Tool Time What the number means What it does not mean
bun run quality:complexity fta-cli about 1 s Per-file FTA score (size, branching and Halstead volume combined); 60 and above is "Needs improvement". Lower is simpler. Quality. Splitting a file lowers its score and removes no logic. Files under 6 lines are skipped.
bun run quality:duplication jscpd about 1 s Verbatim repeated blocks in src/ TypeScript, as clones and duplicated lines. Every repetition: renamed or reshaped copies are not found, and moving a copy to a shared file may not change the number.
bun run quality:dead-code knip about 5 s Files, exports and types in src/ that nothing reachable from the entry points imports. Entry points are set in scripts/quality/knip.json; dependency checks are not run. Safe to delete. A file loaded by path or spawned by a test, or an export used only by tests, is judged by the entry list, so review each hit.
bun run quality:coverage bun test --coverage about 30 min (one serial process over the whole suite) Line and function coverage of src/ from one process over every test file. src/ files with runtime code that no test loads count at 0% (estimated lines, no functions); type-only files are skipped. A real figure. It is a lower bound: code run only in a child process the test spawns (tests that spawn the CLI) is not counted. A hit line is not an asserted line, bun counts a one-line function as hit when declared, and there is no branch data.
bun run quality:compare -- <base> [<head>=HEAD] [--coverage] the static tools above about 10 s (suites twice with --coverage) Both refs exported with git archive, measured with this checkout's configs, with src/ and tests/ file and line counts; delta is head minus base. A verdict. Read it with the caveats of each tool. --coverage also runs bun install and the full suite on both trees.

Run coverage and --coverage compares one at a time and under a memory cap, for example systemd-run --user --scope -p MemoryMax=8G -p MemorySwapMax=0 bun run quality:coverage.

Coverage Notes

Coverage is broad across the CLI, indexing, registry, workflow, and semantic-search paths. Use these directories as the starting point when extending it:

When Adding Tests