# Tests

Scope: tests, fakes and the test gate. Read before adding or changing a test or fake under `test/` or `src/adapters/conformance/`, or editing `scripts/check.sh`, `scripts/hang-watch.sh`, `scripts/progress-tee.sh`, `scripts/seeded-check.ts`, `scripts/seeds.json`, `scripts/lib/ts-ast.ts`, `scripts/changed-tests.mjs`, `scripts/check-closing-refs.mjs`, `.github/workflows/closing-refs.yml`, `scripts/release-prepare.ts`, `scripts/release-tag.ts` or `scripts/lib/release-plan.ts`.

- A fake's gated action that never sees its gate skips the action; never fall through to a late, unsynchronized action. Owned-group tests inject `AcpOwnedGroupPorts`; a test never signals a process group it did not spawn.
- When a production closure gains a dependency, find its VM fixtures by the closure and its callers as well as the new dependency name. Bind every transitive host port and actual imported policy helper, including asynchronous read paths, and run each affected extracted closure. When changing question-tool observer exclusions in `src/hub/daemon.ts`, bind the actual `QUESTION_TOOLS` import in `test/review-privacy-wiring.test.ts` and run that test alongside the question tests. Keep native identity checks on real unstarted instances; never replace a policy predicate with an always-true stub or weaken existing assertions to accommodate a moved dependency.
- On Bun 1.4.2 and 1.4.4 (rechecked 2026-11-14, hub task 940: after `expect(value).toMatchObject({ text: expect.stringContaining("x") })` the fields read back as matcher objects), preserve original fields before `toMatchObject` with asymmetric matchers, or assert primitive fields and strings separately; never use a matcher-mutated value for a later content/canary assertion. Recheck this restriction when upgrading Bun.
- A daemon fixture that routes write-class work (`implement`, `bulk_edit`) to a hub-sandboxed peer (Pi, `local`) runs in a throwaway repository made with `gitProject()` (`test/fakes/git-project.ts`), never in `ROOT`: the agent-hub checkout carries the machine's git config (a hosted runner's checkout has an `includeIf` credentials entry the hub refuses), so such a test passes on one machine and fails on another, and it would make a hub worktree and `task/*` branch inside the checkout under test (#1129). Before calling a hosted-only failure a flake, reproduce the runner's condition in a scratch clone.
- A fixture that walks a policy table (a `COMPAT` entry list, a registry) derives its per-entry values from the table, never a fixed list of keys or versions a planned entry is not in: the compat watch test builds every served version and the ahead/unknown row from `COMPAT[id]`, so an added entry (`pi`, #843 AC2) is covered without editing the test.
- Tests that are not about batching build the bus with `batchMs: 0`; with the default 15 s window a lone status envelope looks like a lost message.
- A test that writes an executable shim and then times a product call through it (a `git` wrapper on `PATH`, as `test/memory-code-head-684.test.ts` does) runs the shim once by absolute path first, outside the measured region: the first exec of a newly written executable costs about 250 ms on macOS (#519). Never widen the product's bound or weaken the assertion for it.
- A test timeout that fires while `Bun.spawnSync` runs can start the next test inside spawnSync's own event loop (Bun 1.3.14 and 1.4.2; not rechecked on 1.4.4; background: README). `scripts/check.sh` runs tests with a 20 s timeout and under `scripts/hang-watch.sh`; a test that spawns and reads the process table gets a timeout of its own, never above 20 s: an explicit larger timeout overrides the gate's `--timeout 20000`, so shorten the scenario instead. Narrow exception (person's ruling 2026-11-20, #1577): a test that must keep a real multi-second process may set its own timeout above 20 s only when its body has a deadline, every cleanup wait is bounded, and the body deadline plus the cleanup bounds stay below the test timeout, so the timeout can never fire inside a `spawnSync`. The instances are `test/conductor-recovery-process.test.ts` (60 s: 30 s body deadline, post-receipt waits of 6 s each, cleanup waits of 3 s each) and `test/staged-project-isolation.test.ts` (90 s: 45 s body deadline, cleanup waits of 6 s each; its body keeps two real daemons and a real upgrade CLI child and took 14.7 s in a green macOS shard run, so the gate's 20 s left no room for a slower one).
- Sandboxed commands and the MLX server get a fixed environment (`PATH`, `HOME` and their own keys), so test knobs for their fakes travel in a wrapper script or argv, not in `process.env`. Daemon-owned peer children use `peerChildEnv`, which drops `ORCA_*` and replaces agent identity markers; a person-owned native launch preserves only its own pane's `ORCA_*` context while dropping inherited agent identity.
- Bind agent identity markers explicitly in native/CLI fixture children. The full gate starts the test runner without inherited agent markers (including `AGENTHUB_DELIVERY_ONLY`) and without an `ahub claude` session's hub variables (`AGENTHUB_PROJECT_DIR`, `AGENTHUB_STATE_DIR`, `AGENTHUB_INSTANCE_ID`, `AGENTHUB_LAUNCH_ID`); a new variable a native session exports and a fixture child reads joins that `env -u` list in `scripts/check.sh`. Never weaken production marker detection to make them pass.
- A fixture that spawns the real channel plugin (`src/adapters/claude-channel.ts` or `plugins/agent-hub/server.js`) to act as a peer runs it with `cwd` at the hub's project root, made with `realPath` (the macOS temp dir is a symlink). The plugin chooses its hub through `channelProject` (rule: `daemon.md`), so from another cwd it joins the wrong hub, joins as a distinct session or connects nowhere. Only tools mode with both `AGENTHUB_STATE_DIR` and `AGENTHUB_PROJECT_DIR` set skips that check. A fixture whose plugin must push as a channel (not fall back to tools mode) injects the parent row with `syntheticClaudeParentEvidenceSetup()` (`test/fakes/claude-channel-parent.ts`, #1171), which replaces only `claudeParentCommandPort.read`; the production marker and classifier still run, so never stub `classifyClaudeParentCommand` or skip the evidence check. For an unchanged published bundle with an inlined observer port, use the published-leg raw port-fact injection in `test/published-protocol-compat.test.ts`: bootstrap its import with Bun's built-in `mock.module` only for `child_process` and `node:child_process`, export the real functions and replace only `spawnSync` for `/bin/ps -ww -p <direct-parent-pid> -o command=`. Return `SYNTHETIC_CLAUDE_PARENT_COMMAND` from the same fixture helper and delegate every other call. Preserve the bundle bytes, classifier, inherited marker, parent-identity check, assertions and timeouts. This synthetic host observation is not native-launch acceptance. A second opted-in session attached while a fixture owner holds the peer stays a standby (#1174): close the owner and wait for offline before attaching the session under test (`test/channel-inbox-daemon.test.ts`).
- Orca environment (#613, #1048): the `test/hub-home.ts` preload also deletes every inherited `ORCA_*` variable, and `scripts/check.sh` unsets them before `bun test`. A run from an Orca pane otherwise reaches the person's Orca through `ORCA_WORKTREE_ID`, `ORCA_TERMINAL_HANDLE` and `ORCA_CLI_COMMAND` (the launcher's four names are `ORCA_LAUNCHER_ENV` in `src/hub/orca-env.ts`, the one list; `personEnv` drops the whole prefix) and opens real tabs and agents there. A test that needs one sets it itself after the preload and restores it; a test of the launcher uses a stub `ORCA_CLI_COMMAND` and never the real one. `test/orca-env-guard.test.ts` runs a real `ahub up` with fake values and a recording stub and must see zero calls.
- `bunfig.toml` preloads `test/hub-home.ts`, which first clears inherited `AMEM_HOME`, gives every test run (the gate and `bun test <file>` alike) a temp `AGENTHUB_HOME` unless one is set, and always replaces `KIMI_CODE_HOME` with a temp dir, an inherited value included (#285); scoped tests may set their own `AMEM_HOME` or `KIMI_CODE_HOME` after preload. Hub memory (#258) is on with any project config, and no test may write the person's `~/.agenthub`. Do not remove it; a test that needs its own home sets and restores the variable. The preload keeps an inherited `AGENTHUB_HOME`, which an agent shell exports as the person's hub home and `scripts/check.sh` does not unset: run `bun test` and the gate with `env -u AGENTHUB_HOME`.
- `test/registry-guard.test.ts` statically scans `src/` against the committed `test/registry-guard.baseline.json` (#451); a test never writes, regenerates or repairs that baseline, and a failing guard is fixed in the source by moving the policy into a definition (rule: `docs/agent-notes/adapters.md`); the baseline stays `[]`. Scanner behavior is pinned on inline sources in `test/registry-guard-fixtures.test.ts`, never on edits to real files. A new table, hint or flag list in generic code that names a peer (`"pi"`, `isJcodePeer`) is a new group: derive it from the definitions instead (`ADAPTERS.filter(...)`, a port such as `statusNotice`). Missed twice on 2026-11-02 (PR #1093 `jcodeTuiHint`, PR #1100 `INIT_SETTINGS`), both found only by CI's shard 3; run `scripts/check.sh --changed` or `bun test --timeout 20000 test/registry-guard.test.ts` before pushing a new peer-shaped table (a bare `bun test` times out at 5 s on this file).
- A daemon fixture whose `cwd` is the repository root sees this checkout's own design specs (`docs/design/`): a test that is not about specs sets `specs: { ...DEFAULT_CONFIG.specs, enabled: false }`, or runs in a temp project, so a new spec never changes its output; it also passes `sdlc: sdlcConfig(undefined)` (`DaemonOptions.sdlc`, #1411), because the checkout tracks `.agenthub/sdlc.toml` and its mode would otherwise run in the fixture; never absorb a `Specs covering` line into an unrelated expectation (#1117). The committed `AGENT_HUB_SPECS` block in AGENTS.md is pinned to `specsBlock('', true)` by test/repository-specs-block.test.ts; regenerate it with `ahub init --specs`, never edit it by hand (#1119).
- A fixture that needs a port takes it from a free-port probe, never a fixed number, which collides with whatever holds it on a shared runner (#548). The probe binds `127.0.0.1`, matching the loopback server that takes the port (#232).
- `ahub upgrade` without `--to` asks the registry (`npm view`) and hands a target newer than the CLI to `bun x` (#272): a test that reaches either puts a fake `npm` first on `PATH` and a recording stand-in for `process.execPath`, as `test/upgrade-cli.test.ts` does. The interactive screens are tested through a scripted `ScreenIO`; a CLI test that needs them marks `process.stdin` and `process.stdout` as terminals in a wrapper script.
- Cross-process fixtures wait for the consuming client to process its handshake (the channel connected diagnostic), not merely the daemon's attached/idle state. Deadline-routing fixtures hold and release responses at the fallback decision; do not place a fixed sleep between deadline fractions and assume scheduler headroom (#287). Receipt-order fixtures use the normal watchdog for ordinary I/O, trigger expiry after observed native acceptance, and await a consumed transport barrier before asserting on late results.
- Companion tests moved with the companions to STAIxBWLB/ahub-orca, ahub-herdr and ahub-claude (#1387); read their `AGENTS.md` there. What stays here is `test/companion-contract.test.ts`, which holds ahub to `docs/contracts/companion-cli-v1.json`: a daemon fixture with positive and absent optional fields, the `shellQuote` vectors, the needs and `pausedNote` producer cases and the guard that ahub names no companion.
- A bounded polling wait must assert its condition after the last attempt, or document why giving up is intentional. Bound it by time (a deadline with short sleeps), never by a count of event-loop turns (`setImmediate`), which a loaded runner spends before a socket frame or child output arrives (#1163, `untilSeen` in `test/control-client.test.ts`). Append-only event histories wait for a correlated closing event, not removal of the opening event. Before changing a slow wait, identify the unreached state and repair its cause (#296).
- A test of turn or notice behavior that is not about the snapshot budget yields an I/O turn (`await new Promise(r => setImmediate(r))`) between captures: captures in one synchronous burst share the 250 ms budget and may correctly record unknown evidence. A daemon test whose assertion needs a turn's snapshot or end evidence passes `snapshotClock: () => 0` (`DaemonOptions.snapshotClock`, #661) so a slow runner cannot spend that budget; never lengthen the budget instead (#550). A wait on concurrent-edit evidence correlates the expected turn ids and paths (#617).
- Holding the snapshot budget clock (`snapshotClock`, #661) holds the deadline and, since #554, the git child's wall-clock timeout (the 10 s ceiling instead of the remaining budget). The rule lives in the pure `childTimeoutMs` (`src/hub/snapshots.ts`: production keeps min(10000, remaining), only a budget carrying `now` gets the ceiling). Reproduce a slow git with a deliberately slow `git` first on PATH (`slowGit` in `test/snapshots.test.ts`), never with host-wide load, and never run a high-parallel loop while another gate shares the dgx02 host.
- The macOS CI leg uses four shards and the Ubuntu leg six (#548, #1490): `check (ubuntu-latest) shard i/6` and `check (macos-latest) shard i/4` run `AHUB_CHECK_SHARD=i/n scripts/check.sh` (`bun test --shard --timings=scripts/test-timings.json`), and each stable job name `check (ubuntu-latest)` / `check (macos-latest)` is the aggregator over its OS shards; `scripts/ci-gates.mjs`, branch protection and the reuse proof read that name, so never rename it or turn it back into a matrix job without reading them. `gateJob()` in `scripts/ci-gates.mjs` counts the shard names (`check (ubuntu-latest) shard i/N` and `check (macos-latest) shard i/N`) as gate jobs, so a run with either OS and the seeded shards done and only the other OS shards running reads as a launched full gate and not as unknown scope (`test/ci-reuse.test.ts` pins every mid-run window). A new test file needs no timing entry (it gets the median), but a shard that grows past about 15 minutes means the timings are stale: regenerate them with `scripts/make-test-timings.ts`. A shard starts the suite cold, so `scripts/check.sh` execs the system git once (`AHUB_CHECK_WARM_GIT`, default `/usr/bin/git`) before the tests, because tests that give it `PATH=/usr/bin:/bin` and a 1000 ms timeout (`read-only-shell-proof`, `task-shell-default`) are killed by a cold first exec; a failing or absent warm-up never fails the shard. `check.sh` unsets `AHUB_CHECK_SHARD` after building the test arguments, so the runner and every scratch `check.sh` a test spawns (`test/check-lock.test.ts` copies `process.env`) see an unsharded environment; keep that unset. A test must not depend on running in the same process as another file (shards split files across machines), and anything that has to happen once per gate belongs behind the shard-1 condition in `scripts/check.sh`, which `test/macos-shard.test.ts` pins.
- CI rerun policy (#1257): a red `check` job gets **one** rerun of the failed jobs on the same head SHA (`gh run rerun <run id> --failed`), never a new commit or an empty push to retry. If the rerun passes, the first failure is a flake: it is not "fixed by the rerun", it goes into the flake ledger below with the failing test named. If the rerun fails too, or the same test failed on an earlier head, treat it as a defect and investigate before any third attempt; a hang (the watchdog stop, a shard at its timeout) is investigated even when the rerun passes. Never edit or skip a test to get green (AGENTS.md). The aggregator names (`check (ubuntu-latest)`, `check (macos-latest)`, `seeded guards`) and the identical-tree reuse proof (`scripts/ci-reuse.mjs`, `scripts/ci-gates.mjs`) are unchanged by a rerun: a rerun is another attempt of the same run, and the proof reads the final state of its jobs.
- Flake ledger (#1257): the weekly `flake-ledger` workflow (`scripts/flake-ledger.ts`, `permissions`: `contents: read`, `actions: read`, `issues: write`) reads the Actions runs for `check.yml` of the last 28 days and lists the gate shard jobs that failed and then passed on the same head SHA, per test file and failing test name (the `(fail)` lines of the failed job's log, under the `##[group]test/x.test.ts:` header they ran in), split into macOS-only, Ubuntu-only and both-OS classes. It edits one tracking issue titled `CI flake ledger (check.yml)` (found by that title and a body marker, created once, never one issue per run). It is bounded: five run pages, 60 runs, 40 logs, 8 MiB per log, and it says when a bound cut the window. A job that failed with no `(fail)` line (a hang, a crash) is listed under its job name, never dropped. The top entries (the issue ranks by test file, since one broken file fails many tests at once) each need an owner and a deadline: a fix, or a quarantine with its own issue. Read it before calling a failure "just a flake". Run it by hand with `GITHUB_REPOSITORY=<owner/name> bun scripts/flake-ledger.ts --dry-run`; the aggregation (`parseFailures`, `flakyJobs`, `aggregateFlakes`, `pickTrackingIssue`) is pure and pinned by `test/flake-ledger.test.ts`.
- Shard weights (#1257): `scripts/test-timings.json` is regenerated monthly, or when a shard exceeds its budget by 25 % (budget 15 min, so a shard past 18.75 min; `scripts/lib/ci-shards.ts`). `bun scripts/refresh-test-timings.ts --check` prints the shard times of the newest green `main` run, the 25 % rule and the age of the weights file (exit 1 when a shard is over budget or the file is older than 35 days). `bun scripts/refresh-test-timings.ts [run id]` downloads the four macOS shard logs of that run and rewrites the file through `scripts/make-test-timings.ts` (it takes several logs, a shard log holding only its own files); review the diff and commit it in its own PR, never inside a PR that is squash-merged with unrelated changes. The format is unchanged (`{ "version": 1, "files": { "test/x.test.ts": ms } }`, slowest first), so `bun test --shard --timings` and `scripts/check.sh` read it as before. A file missing from it still runs with the median time, so stale weights are slow, never wrong.
- A fake-ripwire CodeFacts fixture (`test/memory-code-overlay-684.test.ts`, `test/memory-stale-followups-684.test.ts`, #723, #1261) installs the fake through `installFakeRipwire` (`test/helpers/ripwire-probe.ts`) and builds `CodeFacts` with `trace: probe.trace`. A failure then carries, beside the fake's shim, script and output timings, the product's own time for every git step of `tree()` and every ripwire launch (`CodeFacts` option `trace`, absent in production, read-only, no effect on an answer, bound or cap). Read that report before changing a bound: the two files failed on macOS shard 2/4 five times before the shim warm-up of #1197 and never in 120 attempts after it, and no cause was observed (a 40-way local stress did not reproduce it), so a recurrence is the evidence to read. Never lengthen the 5 s product cap or the 20 s test timeout for it, and never skip the test.
- A test that proves a daemon answers while work is still running asserts ordering (the answer arrived before the producer finished), never an elapsed wall-clock bound: the daemon promises no millisecond figure for `status`, so a bound measures the runner, not the product (#531); a request timeout in such a test is a hang guard only.
- A tight wall-clock bound in a test must be sized for the slowest CI runner, or replaced by a barrier (#559). Hosted macOS shards run each test about 1.5 times slower than the old single leg (and git-heavy tests about 7 times), so three unchanged tests tipped over once each after #954: `test/path-policy.test.ts` (the #541 hardlink loops took 10.6 s idle for three layouts in one test and 27 s on a shard, past the 20 s limit: the loops are now five parts of 1000 iterations per layout, 5000 per layout kept, about 0.8 s per part), `test/code-facts.test.ts` (a 400 ms deadline raced the fake CLI writing its child marker, which takes about 0.3 s idle and 1.4 s at 30-way load: the test now holds the deadline timers by the configured value, waits for the marker and fires the analysis's own deadline callback, a barrier with the real deadline code; because the held deadlines never fire by themselves, its `finally` must `close()` the reader and await the analysis before the fixture is removed, and a second test pins that teardown) and `test/smoke-pty.test.ts` (the macOS PTY bridge hung inside `Bun.spawn` with a `terminal` when its child wrote and exited before the call returned: Bun up to 1.4.3, oven-sh/bun#45300, fixed in 1.4.4; 26 of 96 bare-Bun runs at 12-way parallel, none of 180 on 1.4.4. A longer timeout cannot help a process that never starts and a retry only lowers the odds, so until the 1.4.4 pin (hub task 940) the bridge started its child behind a gate it opened after `Bun.spawn` returned, and the retry helper is gone (#560); the bridge also stops its child when its caller dies, and a test names a hung bridge with `runPtyWith` instead of relying on load). When a test needs a bound, measure the slow tail under 30-way local load, size the bound from it with the number in a comment, and prefer a readiness signal (a marker file the fake writes before it hangs, with the deadline fired after it) over a shorter deadline or a longer margin: a margin still depends on the runner's speed, a barrier does not.
- A request that a test expects a stop or shutdown to cut gets its rejection handler where the request is created, never after the awaited teardown: a late `catch` races the reset and the run fails on an unhandled rejection.
- Run `bun scripts/seeded-check.ts` before reporting the seeded-guard gate complete. After changing seeded guard logic, run its affected seeds even when search-anchor counts are unchanged. Put asynchronous calls inside `resolves`/`rejects` expectations so a mutated refusal fails a named assertion. Keep the `scripts/seeds.json` cases sequential; require the same named test green before its seeded assertion fails. Seed rot, survivors, setup/compiler failures, timeout/watchdog termination and process leaks fail the gate. A change that moves or rewrites a line a `scripts/seeds.json` case searches for updates that case's search and replacement in the same PR (seed rot fails the gate), keeping its mutant effect and named test. `scripts/check.sh`, `--changed` included, never runs the seeds, so rot shows only in CI's `seeded guards` job (the `profile-cli-dry-flags` anchor needed a search-text update in both #1100 and #1110, 2026-11-02). Before pushing a change to a file `scripts/seeds.json` names, confirm every anchor still matches once: `bun -e 'const f=require("fs");for(const x of JSON.parse(f.readFileSync("scripts/seeds.json","utf8")).seeds){const n=f.readFileSync(x.file,"utf8").split(x.search).length-1;if(n!==1)console.log("seed rot:",x.id,n)}'` prints nothing when every anchor is intact. Never run the full seed runner from a unit test or mutate the source checkout; inspect preserved failed fixtures before removing them. CI runs it as four sequential Linux shards (`--shard i/4`) beside the ordinary check, separately from `scripts/check.sh`; the required `seeded guards` job passes only when every shard passed, or when the decision job reused a verified identical-tree full gate (`admission == 'reuse'`). Keep that job name: branch protection and `scripts/ci-gates.mjs` read it (#457). On seed rot the checker names the anchor's symbol at a base commit and where it is now (`seedRotContext`): `--base <commit>` sets that base (CI passes the PR base from a `fetch-depth: 0` checkout; keep both), and without it the base is `merge-base origin/main HEAD`. The context is evidence only: it never relaxes the one exact match, and an unavailable base says so instead of guessing.
- `scripts/lib/ts-ast.ts` is the one TypeScript AST helper for scripts and source-scanning tests (`parseSource`, `callSites`, `symbolSpans`, `enclosingSymbol`, `findSymbol`; inline HTML scripts keep their offsets). It gives lexical locations only, never resolved call edges, and stays dev tooling: never import it from `src/`.
- The native branch ratchet (`test/daemon-native-branches.json`) is reviewed data, never regenerated by a test (rule: `adapters.md`). `test/daemon-native-proof-gates.test.ts` runs daemon code cut out of `src/hub/daemon.ts` by its text, from `  function frontendProxyState(` to `  const manualPaused =` and from `  async function changePermission(` to `  async function confirmPermissionDefault(`, and the `  const isSupportedPeer =` and `  const readOnlyPeer =` bindings: renaming, reordering or reindenting them updates the test in the same PR. Test Claude launch permission proof through `createClaudeLaunchProof` in `src/hub/claude-launch-proof.ts`; never restore the removed daemon wrapper just to slice it in a fixture.
- The #1057 worktree tests cut source by its text: `test/worktree-shelf.test.ts` reads `src/hub/daemon.ts` from `case "worktrees":` to `// #604 (agent-hub#1030)`; `test/worktree-panel.test.ts` reads it from `async function worktreeShelf(` and `function worktreesView(` to `async function uiMemorySnapshot(`, `src/ui/index.html` from `function renderWorktrees(shelf)` to `function renderBench(bench)` (plus the helper lines it names) and `src/hub/sdlc.ts` from `export async function readSdlcPr(` to `export async function readSdlcPrHead(`. Moving, renaming or reordering those lines updates the test in the same PR. The removal-module lists pinned there and in `test/worktree-tidy.test.ts` (`src/hub/code-facts.ts`, `src/hub/task-worktree.ts`, `src/cli/worktree-tidy.ts`) are never extended to let a new removal pass (rule: `daemon.md`).

- `scripts/check.sh` pins the test environment (#610): `GIT_CONFIG_GLOBAL=/dev/null`, `NO_COLOR` unset, `TERM=xterm-256color`, temp root under the OS per-user temp dir, agent markers cleared. A test that needs a person's git config or color settings sets them itself. `--changed` selects tests with `scripts/changed-tests.mjs`: changed tests (nested suites included) plus every test that names a changed file directly; docs need none; any other changed file no test names, and any gate, package or shared-fixture change, runs everything.
- `scripts/check.sh` holds the repo's heavy-job slot (`<git common dir>/ahub-heavy.lock`, #398) for the whole run, so a test never runs the real gate; `test/check-lock.test.ts` runs a copy in a scratch repo.
- A red gate names its step (#1577 entry 3): `scripts/check.sh` wraps each once-only step in `step NAME CMD...` and prints `check: FAILED step '<name>' (exit N)` through `failed_line` (plus a `::error` annotation under GitHub Actions); after `bun test` it adds the failing-test count, the first `(fail)` line and the last test file header, read from the summary file `scripts/progress-tee.sh FILE SUMMARY` writes, or says the runner exited or was signalled with no `(fail)` line, and names the leak scan. That count is distinct `(fail)` rows: bun prints every failing test again in its `N tests failed:` recap after the last file, byte for byte, and the recap carries no file header, so the last header is still the file that was running. A new step in the gate goes through `step`, and `test/check-failure-names.test.ts` runs the real script against a fake `bun` to prove each path. It changes no exit status and adds no retry.
- The whole-suite watchdog is `scripts/hang-watch.sh PID SECONDS [PROGRESS_FILE QUIET_SECONDS]` (#115, #516). `scripts/check.sh` sends bun's stderr (where it prints results) through a fifo to `scripts/progress-tee.sh FILE`, which forwards every line unchanged and appends one byte to FILE per `(pass)`, `(fail)`, `(skip)` or `(todo)` line and per test file header (under mawk only with `-W interactive`: mawk reads a pipe in blocks, so without it nothing counts until the input ends, #883); the watchdog stops the suite when FILE has not grown for `AHUB_CHECK_QUIET_S` (default 300, set in `.github/workflows/check.yml`, above the 120 s of the longest explicit test timeout). That is the hang detector, so a slow suite that keeps passing tests is never cut, and a test that logs without finishing is not progress. `AHUB_CHECK_HANG_S` (default in `scripts/check.sh`, 2700 s since #1564: healthy full runs exceeded the earlier 2250 s backstop while still reporting passing tests; hosted values for both OSes in `.github/workflows/check.yml`; #378, #593) is only the backstop for a run that keeps printing results while hung: raise it, with the job's `timeout-minutes` (room above it for setup), only when a healthy run nears it, never for a hung test, and keep the per-test 20 s timeout. The two-argument form (no file) is the old total-time bound, still used by the CI timing job and `scripts/seeded-check.ts`. A fifo and a filter of its own, never a pipe (`$!` must stay bun's pid) and never a process substitution (it cannot be waited on with a bound); `scripts/progress-tee.sh` is in the `--changed` FULL list. `test/hang-watch.test.ts` covers the watchdog, the filter and the fifo wiring.
- A seed's named test must run on Linux, where the seeded job runs: a darwin-only test reports no result there and fails the job (#382). Cover a macOS-only protection with its regression test instead.

- The `closing-refs` workflow (`.github/workflows/closing-refs.yml`, #760) runs `scripts/check-closing-refs.mjs` (PR number from argv or `PR_NUMBER`) on `opened`, `edited`, `reopened` and `synchronize`: it reads `gh pr view --json closingIssuesReferences,body,title,commits` and fails when GitHub would close an issue the title and body only mention with `Refs`, a negation or a qualifier (`Refs #15. Does not close #15.` and `Refs #15. Partially fixes #15.` fail, `Refs #15.` and `Fixes #15` pass), or when a commit message has a closing keyword, negated or not, for an issue the title and body do not mean (a squash merge carries it). An issue linked only in the sidebar passes. A keyword is meant only when nothing earlier in its sentence (ending at `.`, `!`, `?`, `;` or a line break, never a comma) matches `NEGATION`; widen that list, never narrow it to let a qualified close pass (background: README). `mentioned`, `keywordReferences`, `intentionalCloses`, `closingMisuse` and `commitMisuse` are pure and covered by `test/closing-refs.test.ts` with the real `gh` shape (`repository.name`, `repository.owner.login`); its command test puts a fake `gh` first on `PATH`, never the real one. Run it by hand with `GITHUB_REPOSITORY=<owner/repo> node scripts/check-closing-refs.mjs <number>`.

- A test of `runCheck` (`src/hub/checks.ts`, #558) injects a `CheckSpawn` (argv and options in, `{ pid, exited, signalCode, stdout, stderr }` out) and never patches `node:child_process`: the runner reads a child's exit and pipes as values through `Bun.spawn`, because node's event layer can report a quick child's exit inside `spawn()` before a listener exists under load on macOS (oven-sh/bun#45483). Keep the `ended` fixtures for the already-ended case, and do not raise the 5 s limit or the 1 s kill grace to fix a flake.

- A daemon test that writes a config file and then calls `settings_reload` passes `configWatch: false` (`DaemonOptions`, #546), unless the watcher is what it tests. The daemon's file watcher (100 ms poll, 100 ms debounce) publishes the same bytes, so whichever of the two runs second reports `applied: []`, and a watcher pass between a preview and its confirm replaces the confirmation token. Never lengthen a sleep or loosen `applied` for it; the watcher has its own tests in `test/settings-reload-daemon.test.ts`.
- A daemon test of a tool that reaches a public host passes the host-only transport seam (`DaemonOptions.webFetchTransport`, #553) and asserts what the daemon handed the tool, never a real round trip or a longer wait. The tool, the proxy URL and the allowlist stay the daemon's own; only the request is replaced. The proxy's own behaviour has its tests in `test/proxy.test.ts` and the web-proxy block of `test/web-fetch.test.ts`.
- The preload leaves `HOME` unchanged and clears inherited `CLAUDE_CONFIG_DIR` and `CODEX_HOME`; tests that need fixture selectors set them after preload. A test that spawns `ahub setup`, `ahub autonomy` or `ahub init` under machine defaults, or reaches `discoverClaudeHomes` or the profile hook, sets `HOME`, `CLAUDE_CONFIG_DIR`, `AGENTHUB_HOME` and `AMEM_HOME` to temp directories, as `test/autonomy-machine-cli.test.ts` does; unit tests pass `{ home, env }` instead of `process.env`. A test that runs `ahub doctor` through the CLI also sets `CODEX_HOME` to a temp directory and puts a fake `amem` first on PATH, because doctor runs `amem setup <tool> --json` (#1025, `test/doctor-memory-capture.test.ts`).
- The `@staix/agent-mem` dependency is a declared range (`>=X.Y.Z <M.0.0`), so tests read the installed release (`import.meta.resolve` plus its `package.json`) instead of a literal: `test/memory.test.ts`, `test/memory-profile.test.ts`, `test/memory-profile-daemon.test.ts`, `test/doctor-model-aliases.test.ts` and the recovery-package fixtures derive their expected version that way, and a range raise moves only `package.json` and `bun.lock`. Any other test edit in a range raise adapts a fixture to a changed package contract (an index file name, a transport read before screening) with a comment naming the package version; never weaken an assertion to pass a raise. A test that names a package file reads the name from what the store creates (`indexFileOf` in `test/memory-store.test.ts`), never a fixed `index.db`.
- `test/fixtures/release-n-1` and `test/fixtures/protocol-v16` are separately exact-locked published packages (own `bun.lock`, installed by `scripts/check.sh`), never root dependencies, and `PUBLISHED_FIXTURES` in `test/published-protocol-compat.test.ts` pins their versions and compatibility metadata. In a minor release PR, retarget release N-1 to the latest stable patch of the preceding minor together with the version bump; update its package manifest (an `overrides` entry pins amem to an exact version when the published package declares a range), lockfile and `PUBLISHED_FIXTURES` row, with `memoryRange` as the published package declares it, `memoryVersion` as the fixture lock resolves it, and the protocol read from the published package (AGENTS.md Releasing step 1, procedure in `docs/operations.md` #1164). The guard requires the fixture minor to be the package minor minus one. protocol-v16 stays at its version while protocol 16 is promised (#1168).
- Keep CI's Bun version sourced from `.bun-version` through the pinned setup-bun action; update the version file rather than adding per-job version literals.
- Release verification requires both OS checks and the aggregate `seeded guards` success for an identical tree, a tag matching `package.json` on `origin/main`, and fresh ancestor-bound documentation stamps. Preserve the separate npm OIDC publish job and GitHub Release write job; neither job gets the other's credential authority.
- `test/conformance/` runs real adapters against fake transports. The shared kit and the transport fakes live in `src/adapters/conformance/` (public `@staix/agent-hub/conformance`); `test/conformance/kit.ts` and the matching `test/fakes/*.ts` only re-export them, so change the packaged file, and `--changed` runs everything for it; `test/conformance/enrollment.ts` enrolls every `ADAPTERS` definition, each `:reviewer` variant and each `:implementer` (`headlessVariant`) variant. Record a case that does not apply in its `UNSUPPORTED` or `UNSUPPORTED_LEGS` map with a concrete reason naming the dedicated coverage, never `test.skip` or synthetic success, and never change native production behavior to satisfy a generic case.

- Keep the CI admission lock around the whole controller workflow, not just its decision job, in its per-PR (`check-pr-<number>`, `queue: single`, `cancel-in-progress` true: a newer head replaces the older run, pending or in progress, #1490) or main (`check-main`, `queue: max`, never cancelled) group, never with `cancel-in-progress: true` beside `queue: max` (GitHub refuses it) (#609); a cancelled run or a fresh draft-deferred run is never a successful full gate (the draft's macOS aggregate fails when the gate runs, and `successfulFullGate` needs all three required jobs `success`). Two groups admitting one tree at once is an accepted duplicate run, never a reason to fail closed on another tree. Preserve successful identical-tree full proof and required job names; a skipped job, pending controller or unavailable active inventory is never a successful full gate. In `readFullGateAdmission`, lost successful proof (404, malformed proof, a per-read timeout) only means a fresh gate runs; unknown active coverage and the global read ceilings (`GateReadLimitError`) stay unknown and refuse. A GitHub 429 or 5xx on one read is retried at most twice after a short backoff (#872), only while the shared deadline leaves room for the backoff, and every retry counts against the 240-read budget; never extend retries to any other status, a timeout or malformed data. CI checks out the PR head (`pull_request.head.sha`), not a merge with main: after a fix lands on main, merge main into the branch before reading CI as proof. CI reuse tests use fixed metadata fixtures and never dispatch real duplicate workflows.

- Headless-reviewer tests run `test/fakes/fake-claude-print.ts` and headless Claude implementer tests run `test/fakes/fake-claude-implementer.ts` through `command` or a PATH stand-in (the implementer with `HOME` and `CLAUDE_CONFIG_DIR` in a temp dir), and fresh Codex reviewer tests run `test/fakes/fake-codex-reviewer.ts` through `codex_bin`; a test that reaches the daemon's reviewer or implementer start must never run the real `claude` or `codex`. The fake's sandbox markers test host admission only, never native isolation. Fresh Kimi reviewer tests set and restore `KIMI_CODE_HOME` to a fixture native home (the backend links that home's `credentials/`, `oauth/` and `device_id`, else the person's `~/.kimi-code`) and run `test/fakes/fake-kimi-reviewer.ts` through `command` or a PATH stand-in, never the real `kimi`. Qwen TUI tests run `test/fakes/qwen-dual.ts` (scripted by submit text) as the launched Qwen or the daemon's `qwen_cmd` (an adapter unit test also passes its own `table`), never the real `qwen`. agy tests put a fake `agy` first on PATH and set `HOME` to a temp dir before any transcript readback (`readAgyTranscript` reads `$HOME/.gemini`). Code-facts tests build `new CodeFacts({ env })` with a PATH whose first `ripwire` is a wrapper around `test/fakes/fake-ripwire.ts` (`FAKE_RIPWIRE_MODE` selects its failures) or an inline fake installed with `installFakeRipwire` (`test/helpers/ripwire-probe.ts`, #1197), or inject Tasks' `prepareReviewBrief`; never rely on an installed ripwire, which CI does not have. `installFakeRipwire` runs the shim once outside the measured region, and `withProbe` and the probe's `watch` append where each call spent its time when a test fails; read that before calling a fake-ripwire failure a flake, and never widen the 5 s per-call cap or the 20 s timeout for it.
- Turn-model and reviewer-quota fixtures use the existing fakes' opt-in knobs, never a new fake or a real agent (#1402, #1440, #1446): `FAKE_CLAUDE_MODEL_USAGE` adds a result row's `modelUsage` to `fake-claude-print.ts` and `fake-claude-implementer.ts`, `--model-id <id>` (with `--model-shape config` for the `configOptions` form) makes the ACP and Pi fakes report a session model, a `REROUTE:<model>` prompt makes the Codex app-server fake emit `model/rerouted`, its `rateLimitsRead` argument scripts `account/rateLimits/read`, and `FAKE_CODEX_REVIEW_QUOTA=1` makes `fake-codex-reviewer.ts` refuse its review turn with a usage-limit error. The Kimi reviewer fakes write a native 1.5 usage wire under the fixture home, never a quota frame.
- A Pi fake the daemon starts through `createPi` answers `--version` with a version `COMPAT.pi` verifies, as `src/adapters/conformance/fakes/pi-rpc.ts` and `test/fakes/pi-data-policy.ts` do: the factory's preflight (`piVersionAsync`, #847) refuses the start otherwise.
- A daemon test that declares a headless Claude implementer in a repository whose `origin` is on GitHub passes `shellDefaultBranchProbe` (`DaemonOptions`, #845), or the start runs `git ls-remote` against github.com; a test of `readTaskShellDefaultBranch` itself puts a fake `git` first on the `PATH` it passes.
- A test of `scripts/release-prepare.ts` or `scripts/release-tag.ts` runs the script with its root in a scratch repository whose only remote is a local bare directory: set `AHUB_RELEASE_ROOT` to it, or copy the script into it as `test/release-tag-daemon.test.ts` does. Without that the script takes its root from its own location and fetches and runs `ls-remote` against this checkout's real origin. Consent comes from a fake port, a stand-in `AHUB_CLI` or a scratch daemon, never the person's hub.
- Production `MemoryClient` (`src/memory/client.ts`) is the in-process amem store and never opens `memory.worker_url` (#752). A test that needs the legacy worker shape injects `FakeMemoryClient` (`test/fakes/mem-worker.ts`) as `DaemonOptions.memoryClient` or in place of the client; never add an HTTP path to the production client for a test. An amem-backed test sets its own temp `AMEM_HOME` and reads only its own fixture memory directory.
- CLI print guards (#814, `test/cli-json-guard.test.ts`): two scans over every file in `src/cli`. One finds `console.log(JSON.stringify(...))` and passes only behind a `--json` branch (`selectsJson`) or a named `DATA_FORMAT` entry (`NOT_YET_CONVERTED` is empty since #899; keep it empty). The other finds a print of a hub tool's text (`console.log(await taskOp(<op>))`, or a variable bound from one) and passes only behind `--json`, for a named `SENTENCE_OPS` op (checked against the daemon's case), or named debt (`TEXT_DEBT`, `CONDUCTOR_DEBT`, `REFUSAL_FALLBACK`). A list entry with no matching site fails, so the lists only shrink. Add a command's `--json` branch or renderer; never add a list entry to make a new print pass. Per-command output tests (`test/task-output.test.ts`, `test/sdlc-output.test.ts`) run the real CLI against a fake control server and assert default not JSON, `--json` byte equality, 80 and 200 columns and `--color=never`.
- Hard-coded values inventory (#719, #1180, `scripts/inventory-hardcoded-values.ts --check`, a once-only step of `scripts/check.sh`): a constant or inline literal you add to `src/` or `scripts/` is an inventory entry, and the gate fails until it is classified in `scripts/inventory-hardcoded-values.classifications.json` (`operational`, `safety floor`, `contract` or `test seam`, by the reasons of `docs/verification/2026-10-30-operational-settings-closure.md`). Never add a key to `scripts/inventory-hardcoded-values.baseline.json`: it is the list of keys that were unclassified when the check began and it only shrinks. Classify a baseline key by adding it to the classifications file and deleting it from the baseline in the same commit; the check refuses either half alone. For `src/hub` bounds and truncations, apply the committed conventions and rulings in `docs/verification/2026-11-05-hardcoded-values-classification-rules.md` (#739/#741). Before each batch, run a fresh blind sample of 80 already-decided entries and proceed only at 85% agreement or more. Outside that settled slice, a baseline key needs a calibrated mechanical rule that the committed file agrees with on at least 94% of its decided keys; leave an undecided shape in the baseline pending a ruling, never guess its label. Do not classify keys in bulk from reading the code: a blind pass agreed with the committed file on 58% of a sample, because the file counts hub-internal caps, injected `opts.x ?? N` defaults and script deadlines as operational (`docs/verification/2026-11-05-hardcoded-values-ratchet.md`). A line moved inside a file changes no key; a changed value or name does. After adding keys to the classifications file, keep it sorted by key in codepoint order (a key appended at the end breaks `test/inventory-hardcoded-values.test.ts`, which `--check` does not catch) and run that test. Seen on hub task 992 (PR #1544) and hub task 991 (PR #1548), 2026-11-17.
