Testing Workflow
This project is a CLI with three risk-heavy areas:
- command behavior across real files, config, and cache directories
- managed-source install/update flows
- binary deployment and self-upgrade behavior
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
- core CLI flows:
setup,index,search,show,info,bundle list,config - asset lifecycle: add assets, re-index, search, show, and incremental refresh
- managed-source lifecycle:
akm bundle add,akm bundle list,akm bundle update,akm bundle remove - binary lifecycle: install, run,
akm upgrade --check,akm upgrade - cross-environment behavior on Ubuntu, Debian, Alpine, and Fedora containers
Test Targets
bun run check runs lint and the typecheck, then both targets in sequence.
bun run test:unit(scripts/test-unit.sh) runs every*.test.tsundertests/excepttests/integration/. That includes the top-leveltests/commands/andtests/workflows/directories; do not confuse them with the separatetests/integration/commands/andtests/integration/workflows/directories.bun run test:integration(scripts/test-integration.sh) runstests/integration/**only.
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:
- starts a process (
spawn,spawnSync,Bun.spawn, a fake binary that akm then runs such aswriteFakeHarnessorwithOpencodeOnPath, or product code that runsgit); - runs a CLI entry, in process or not (
runCliCapture,runCliStatus,main([...])); - opens a server or socket (
Bun.serve,http.createServer); - opens a SQLite file (state, index, logs, registry cache) or builds an index (
akmIndex);":memory:"is fine; - 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:
tests/integration/self-update.test.ts- self-upgrade detection and checksum handlingtests/integration/registry/*.test.ts,tests/provider-registry.test.ts- registry search, index formats, and install resolutiontests/integration/setup-wizard.test.ts,tests/integration/setup-scheduled-tasks.test.ts- setup wizard orchestration and failure handlingtests/integration/install/install-script.test.ts- repeatableinstall.shedge cases and permission paths
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):
-
Do not mutate
AKM_*/XDG_*/HOMEonprocess.envdirectly. Use the helpers intests/_helpers/sandbox.ts:sandboxStashDir,sandboxXdgConfigHome,sandboxXdgDataHome,sandboxXdgCacheHome,sandboxXdgStateHome,sandboxHome— set the env var to an isolated temp dir and return acleanupthat restores the prior value. Chain them and callcleanup()inafterEach.withEnv({ AKM_BUNDLE_DIR }, async () => …)— scoped override that always restores in afinally, 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 towithEnvor a subprocess env object yourself).writeSandboxConfig(partial)— mergespartialinto the sandboxedconfig.json(callsandboxXdgConfigHomefirst).withMockedFetch(run, mock)— swapsglobalThis.fetchfor the duration ofrunand restores it in afinally.
Do not assign
process.env.HOME =, callprocess.chdir(...), or assignglobalThis.fetch =directly. UsewithMockedFetchfor fetch swaps, and restore the cwd in afinallyblock when achdiris unavoidable.The DB path resolves from
XDG_DATA_HOME; if youakmIndexthenakmSearch, both must see the same sandboxedXDG_DATA_HOMEor the search reads a different (empty or stale) DB. Sandbox it inbeforeEach. -
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 adurationMsfield computed from injected fixture timestamps is fine (it is deterministic). -
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'sscoreis rounded for display; when a test asserts ordering, compare the same value the output carries. -
Pass
--timeoutwhen a test spawnsbun test <fixture>. Bun ignoresbunfig.toml'stimeout(see the comment there), so the fixture dies at 5 s under load. -
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:
- At preload time
HOMEand all fourXDG_*_HOMEvariables point at a per-process sandbox directory, theAKM_*_DIRoverrides are cleared, and so areAKM_VERBOSE,AKM_LLM_API_KEYandAKM_EMBED_API_KEY. A test file never reads the developer's real~/.config/akm/or~/.cache/akm/. - Bun's
os.homedir()ignores a runtimeHOMEchange, so the preload cannot redirect a default built from it. Both runner scripts start every shard with its own throwawayHOME, whichos.homedir()does see; under a barebun test <file>it returns the real home. Code that resolves a home directory therefore uses the XDG variables or an override of its own, and a test can never rely onHOMEalone. The preload pointsCODEX_HOMEandCLAUDE_CONFIG_DIRat the sandbox for the Codex and Claude Code session readers, andOPENCODE_TEST_HOMEfor OpenCode. - Before each test it snapshots the harnessed environment (
HARNESSEDin the preload:HOME,CODEX_HOME,CLAUDE_CONFIG_DIR,OPENCODE_TEST_HOME, the fourXDG_*_HOMEvariables,AKM_BUNDLE_DIR,AKM_CONFIG_DIR,AKM_CACHE_DIR,AKM_DATA_DIR,AKM_STATE_DIR,AKM_VERBOSE,AKM_LLM_API_KEY,AKM_EMBED_API_KEY,AKM_REGISTRY_URL,AKM_NPM_REGISTRY),process.cwd()andglobalThis.fetch, and restores them afterwards. - It resets the module-level singletons of production code between tests:
cachedConfig,embedCache,localEmbedder, the quiet and verbose flags and the warn module's log file path.mock.restore()runs after every test. - A tripwire throws when a test leaks an
AKM_*,XDG_*orHOMEvariable that was not there at preload time, leavesprocess.cwd()changed, or leavesglobalThis.fetchreplaced. - A global
afterAllends the run by removing the suite sandbox directory.bun testdoes not emitprocess.on("exit")when a run ends normally, so the preload'sexitlistener does not fire there and every run would leave itsakm-test-suite-*directory behind. Theexitand signal handlers still cover an explicitprocess.exit()and signal-kills. Do not rely onprocess.on("exit")for test-process cleanup. - The preload refuses akm's real OpenCode runtime (
agentRuntime.run): a test that dispatches agent work on a connection installsinstallFakeOpencodeRuntime(tests/_helpers/fake-opencode-runtime.ts), which records what the run was asked and answers it, or callsuseRealOpencodeRuntime()to run the real binary.
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:
index -> search -> show- CLI subprocess execution through
src/cli.ts - config read/write behavior
- registry sources and static-index compatibility
- progressive indexing and re-indexing
- update and upgrade command error paths
- markdown
#fragmentselection and mixed asset discovery
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:
offwhen the user opts out explicitlyautowhen the user wants semantic search enabled
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:
pendingwhen semantic search is enabled but not yet verifiedready-jswhen every entry has a vector (the name is historical; there is no other vector path)blockedwhen semantic search cannot run with the current provider/setup
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
- config stays
offonly when the user disables semantic search intentionally - config stays
autowhen preparation is skipped intentionally - config stays
autowhen preparation fails but runtime status becomesblocked - runtime status becomes
pending,ready-js, orblockedas appropriate - index and info output report readiness state instead of only config intent
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:
- bun-based install: Ubuntu, Debian, Alpine, Fedora
- compiled binary install: Ubuntu, Debian, Fedora
- npm install: Debian on
node:24-slim, which has no compiler, python or make (npm install -g --ignore-scriptsof the packed package, as npm 12 installs by default; the install's exit code and the smoke test are the check)
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:
akm --helpakm bundle createakm indexakm search(including--format jsonand--type skill)akm showakm infoakm bundle list- incremental re-index after adding a new asset
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.
Recommended Workflow
Normal change
Use this for most code changes:
bun run test:unit
bun run test:integration
bun run lint:fix
bunx tsc --noEmit
Install, packaging, or release-related change
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:
AKM_UPGRADE_FROM=<version>— pin thepreviousorigin instead of resolving the highest published stable version below the candidate'spackage.jsonversion.AKM_UPGRADE_REHEARSAL_ORIGIN=<origin>— run only one origin (CI runs each origin as its own job).AKM_CANDIDATE_TARBALL=<path>— use an already-packed candidate tarball instead of runningnpm packon the working tree (which requiresdist/cli.js— runbun run buildfirst).
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:
tests/integration/db/,tests/integration/fts/,tests/integration/indexer/,tests/integration/storage/— database, full-text search, and index behaviortests/search-rrf.test.ts,tests/integration/search-fusion.test.ts— search rankingtests/integration/registry/— registry install, search, and update flowstests/integration/workflows/,tests/integration/tasks/— workflow and task behaviortests/integration/vector-search.test.ts,tests/integration/semantic-search-e2e.test.ts— vectors and embeddingstests/integration/info-command.test.ts,tests/integration/output-baseline.test.ts— CLI output shapingtests/integration/docker-install.test.ts— Docker install validation
When Adding Tests
- prefer focused
bun:testfiles undertests/ - use isolated temp config/cache/stash dirs
- cover the user-visible CLI behavior when the risk is output shaping or command routing
- cover internal units directly when the risk is scoring, metadata extraction, or persistence