Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
58.6 KB
Raw Blame

Key files: Tooling And Tests

Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.

  • test/e2e/migration-wave-*.test.ts + test/helpers/migration-wave-*.ts — isolated both-engine acceptance for phase-boundary lease loss, oversized-healing rollback, prepared embedding/withdrawal ordering, archived-source refusal, incompatible-model publication, failed partial migration and reopened retrieval, malformed provider batches, and actual SIGKILL around durable authorization reservation/dispatch. Fixtures prove their PostgreSQL database differs from the supplied test base. Providers and reranker pricing are synthetic; phase takeovers are controlled injections, not exhaustive schedules.

  • test/safety-wave-coverage-export-ledger.test.ts + test/safety-wave-coverage-invocation-inheritance.test.ts — export ledger capacity/read-failure and source-binding contracts, plus nested invocation allowance, settlement and async-isolation checks. These pure fixtures supplement, rather than replace, real-engine snapshot and process-crash acceptance.

  • test/helpers/real-home-guard-preload.ts — detection-only backstop for changes to the real-home autopilot wrapper, environment file, start script and launchd/systemd units. It compares file metadata before/after tests without reading secret-bearing contents and attributes earlier changes separately. GBRAIN_TEST_ALLOW_REAL_HOME_WRITES=1 explicitly disarms it with a warning. Installer fixtures set both HOME before Bun startup and GBRAIN_HOME per fixture; test/real-home-guard-preload.test.ts verifies fake-live sentinels and the autopilot suite in disposable subprocess homes.

  • .github/workflows/test.yml — required full validation remains the default for pushes, pull requests and manual runs. Explicit manual native_only uses a distinct concurrency group to preserve in-flight full persistence soaks, runs the native matrix, and emits only a scoped native result (full_ci: false), never the full-suite aggregate check name. The diagnostic dispatch inputs race_hunt, stress_files and stress_base/stress_head likewise run only their lane under a -diagnostic concurrency group and name the aggregate full-suite-not-run. test-status also gates stress-changed-tests; race-hunt runs on the schedule and stays outside it. Every event-conditional behavior carries a parity or named-exception comment (docs/ci-event-parity.md). test/scripts/native-only-workflow.test.ts evaluates the actual event/input conditions and executes the scope/result scripts; test/scripts/ci-pr-scope.test.ts pins Bun parity and the classification comments; test/scripts/ci-gates.test.ts retains all default required-result failures.

  • .github/workflows/stress.yml + scripts/stress/run.ts + scripts/stress/plan.ts + scripts/stress/gate.ts — repeated-run lanes. bun run test:stress (run.ts) runs files N times per execution profile (unit, serial, slow with PR values, both arms of a gated suite, E2E via run-e2e.sh), a fresh CREATE DATABASE … TEMPLATE database per database iteration with owned-resource cleanup (exit, signal, next run), a JUnit receipt per iteration, unexpected-skip, zero-executed and arm-never-connected failures, and a credential-free reproduce line. plan.ts: changed files versus the merge base, helper fan-in (25 importers, then a 10-file sample seeded by the head SHA), profiles, measured-weight shards with iteration splitting. gate.ts: plan/report for the PR gate (stress-changed-tests, in test-status; "not a PR event" outside PRs; trusted, signature-matched, expiring exemptions from open issues) and the race hunt (test/postgres-unit-arms.txt × 10, 6-12 shards of 55 minutes, depth rotation, "race hunt over budget"). Docs: scripts/stress/README.md. Tests: test/scripts/stress-plan.test.ts, test/scripts/stress-gate.test.ts, test/scripts/test-stress.test.ts, test/scripts/test-stress-postgres.test.ts (listed in test/postgres-unit-arms.txt).

  • .github/workflows/native-locks.yml — native glibc Linux, macOS and Windows jobs also run publication, Git helper, historical sync-origin and backup portability contracts in separate Bun processes, collecting fatal suite outcomes. macOS/Windows publication fixtures require an actual case-insensitive filesystem. Separate six-cell Windows diagnostic jobs opt into a directory-only hidden-window comparison and file/directory cmdlet-versus-production comparisons after real PGLite setup; neither filters or replaces native acceptance. test/fixtures/windows-backup-cmdlet-protect.ps1 freezes the old program for A; B forwards the actual production program. The separate read-only windows-backup-dotnet-inspect.ps1 reports actual owner/SYSTEM, protected-DACL, rights, inheritance and propagation for the independent oracle. The persistence deployment matrix separately executes the publication journal and all three sync-safety suites with PostgreSQL; E2E parity wrappers select them in the local full gate. test/scripts/data-safety-native-workflow.test.ts pins mandatory native/database execution without ignored failures and requires both file and directory observations; actual results, not configuration or simulated paths, establish platform coverage.

  • test/native-export-publication.test.ts + test/export-publication-native.test.ts — native export primitive, wrapper and compiled-publication contracts run on all eight addon targets, including the native musl containers. macOS/Windows wrapper checks require a real case-insensitive volume. Failures remain fatal; a compiled fixture runs outside the checkout and checks successful completion, repeat refusal and incomplete output after process death.

  • test/memory-safety-wave.serial.test.ts + test/e2e/memory-safety-wave-postgres.test.ts — provider-free cross-feature lifecycle on isolated PGLite/PostgreSQL. A repair owner is killed after the metadata commit and a new process resumes the cursor without duplicating edits. Remember/withdraw survives projection and fact-vector migration; source-scoped export and stale reimport retain withdrawal intent. Actual HTTP MCP checks lexical privacy/misses; a fresh stdio process uses a loopback embedding provider to verify vector-positive retrieval and private/foreign/withdrawn exclusions after reconnect. Synthetic basis vectors establish routing and persistence, not retrieval quality.

  • scripts/build-pglite-snapshot.ts — bun run build:pglite-snapshot [--profile legacy|default] bakes post-schema PGLite snapshots. Legacy (the default) matches the unit preload; default follows canonical CLI embedding defaults. Profiles have disjoint tar/version/lock paths and CI cache keys. Version sidecars retain schema-byte hash, dims and model. The builder requires PID/token lock ownership, only reclaims confirmed dead owners using its retirement protocol, times out on live/unknown locks, and publishes temporary files via atomic rename with the version last. Normal release and crash recovery retain the same nonempty owner tombstone so a delayed observer cannot move a replacement lock. scripts/lib/test-env.sh exposes ensure_pglite_snapshot (legacy primary env) and ensure_default_pglite_snapshot (absolute auxiliary GBRAIN_TEST_DEFAULT_SNAPSHOT); failure visibly falls back to cold init. GBRAIN_NO_SNAPSHOT=1 clears both and survives preloads. BrainBench overrides only CLI children, including run-all, to the default path. The production loader's per-process memoization, schema/shape refusal and in-memory-only gate remain authoritative and unchanged. Keep computeSnapshotSchemaHash and every CI profile cache key aligned with imported SQL helpers, including grants, withdrawals, page state and persistence schemas. Tests: test/scripts/build-pglite-snapshot.test.ts, test/snapshot-shape-guard.test.ts, BrainBench CLI E2E and operator preload tests.

  • scripts/check-compile-autoload.sh — CI scanner: every bun build --compile invocation (CLI one-liners carrying --outfile, or ['build', '--compile', …] spawn arrays) in package.json, CLAUDE.md, CONTRIBUTING.md, .github/, scripts/ and docs/ must carry --no-compile-autoload-bunfig, because a compiled Bun binary otherwise auto-loads a cwd bunfig.toml and runs its preload before any gbrain code (before cli-preflight.ts). Prose that names the command without --outfile is ignored; test/ compile helpers are out of scope (throwaway binaries run from temp dirs). Self-tested via test/fixtures/guards/check-compile-autoload.sh/{bad,good}/; wired as check:compile-autoload in verify CHECKS.

  • scripts/check-gateway-routed-no-direct-anthropic.sh — CI guard that fails the build if src/core/cycle/synthesize.ts or src/core/think/index.ts reintroduces a runtime new Anthropic() constructor call or a value-shaped import Anthropic from '@anthropic-ai/sdk' import. Type-only imports (import type Anthropic from '@anthropic-ai/sdk') stay allowed for adapter types; comment lines (// or * prefixes) are excluded so JSDoc doesn't false-fire. Mirrors scripts/check-jsonb-pattern.sh. Wired into bun run verify. Extend GUARDED_FILES when migrating another file off direct SDK construction.

  • scripts/check-getpage-scoped-write.mjs — CI scanner for the unscoped-check/scoped-write source-isolation bug class: flags any non-test src file containing BOTH a getPage( call with no second argument (or the X ? {sourceId} : undefined any-source-when-unset ternary) AND a write-path call (putPage(/importFromContent(/importFromFile(). Fix pattern: getPage(slug, { sourceId: x ?? 'default' }) (mirror the write's schema default); opt-out marker gbrain-allow-unscoped-getpage: <reason> for documented read-only first-match sites (span, preceding lines, or trailing same-line comment). Grandfathered allowlist is EMPTY. Comment/string-aware balanced-paren span walker (same skeleton as check-jsonb-params.mjs); argv-overridable roots; wired as check:getpage-scope in verify CHECKS + guards-manifest + test/fixtures/guards/check-getpage-scoped-write.mjs/{bad,good}/ + test/check-getpage-scoped-write.test.ts.

  • scripts/check-jsonb-params.mjs — AST-lite CI guard for the POSITIONAL jsonb double-encode form the template grep above misses: an executeRaw/executeRawDirect/.unsafe() call whose balanced arg span binds JSON.stringify(x) into a bare $N::jsonb cast. Walks each call's balanced span respecting strings/templates/comments, handles generic-typed calls (executeRaw<T>(), and allows the sanctioned forms ($N::text::jsonb, $N::text[], executeRawJsonb, sql.json, an inline jsonb-guard-ok comment). PGLite's native db.query is deliberately not scanned (it parses text→jsonb, so the bug can't occur there). Heuristic by design (whole-span correlation; can't see a JSON.stringify assigned to a variable before the call) — the real backstop is the DATABASE_URL-gated e2e parity tests. Runs over the real tree in bun run verify (check:jsonb-params); scan roots overridable via argv for its self-test (test/check-jsonb-params.test.ts).

  • scripts/check-jsonb-pattern.sh — CI grep guard. Fails the build if any source contains (a) the ${JSON.stringify(x)}::jsonb interpolation pattern (postgres.js v3 double-encodes it), or (b) max_stalled INTEGER NOT NULL DEFAULT 1 in any schema source file (must be DEFAULT 5 to preserve SIGKILL-rescue). It also invokes scripts/check-jsonb-params.mjs and propagates its exit code. Wired into bun test.

  • scripts/check-module-size.sh + scripts/module-size-limits.tsv — the module-size ratchet (bun run check:module-size, wired into bun run verify). The TSV commits a per-file wc -l ceiling (path max_lines policy note); four rules, all violations reported before a single exit 1: a file above its ceiling fails (raise a ceiling only as a conscious TSV edit); a ceiling more than 50 lines above the measured size fails (stale slack after a shrink — lower it so the ratchet holds); a TSV row whose path no longer exists fails (remove the row); an unlisted src/**/*.ts (excluding *.generated.ts/*.test.ts) above the 1500-line new-file cap fails (split it or add a row). ratchet is the only policy (any other policy value is refused as unknown). Self-test seams: GBRAIN_GUARD_ROOT, GBRAIN_MODULE_SIZE_SLACK, GBRAIN_MODULE_SIZE_NEWFILE_CAP.

  • scripts/check-no-double-retry.sh + scripts/check-batch-audit-site.sh — CI lint guards wired into bun run verify. The former greps src/ for withRetry(...engine.{addLinksBatch|addTimelineEntriesBatch|upsertChunks}) patterns and fails the build on hit (prevents 3×3=9 retry amplification on incomplete reverts); its single-line pattern crosses arrow-callback parens (the canonical banned shape is withRetry(() => engine.addLinksBatch(...)) — a paren-stopping regex cannot see it), and its multi-line fallback runs under perl (always present locally and in CI). Both are proven fail-able by the guard self-test fixtures under test/fixtures/guards/. The latter extracts every string-literal auditSite: '...' from src/ and validates each appears in the BATCH_AUDIT_SITES const in src/core/retry.ts (typo guard — prevents fragmented doctor output).

  • scripts/check-progress-to-stdout.sh — CI guard against regressing to \r-on-stdout progress. Wired into bun run test via scripts/check-progress-to-stdout.sh && bun test in package.json.

  • scripts/check-retired-phrases.sh — the retired-phrase guard (bun run check:retired-phrases, in bun run verify): greps CLAUDE.md, AGENTS.md, CONTRIBUTING.md, docs/ and skills/ for contributor-workflow phrases refactor wave 1 retired (the RETIRED table: pattern + the current instruction) and prints FAIL: <file:line> / Why: / Fix: / See: docs/ci-guards.md#retired-phrase-guard per hit. Historical records (docs/designs/, docs/test-audit/, docs/incidents/, docs/plans/, docs/proposals/, docs/research/, docs/issues/, docs/superpowers/, docs/migrations/, skills/migrations/, the docs/architecture/wave-1-* porting kit) are exempt; CHANGELOG.md is not scanned. GBRAIN_GUARD_ROOT seam; fixtures test/fixtures/guards/check-retired-phrases.sh/ (one bad-<location> tree per scanned location); pinned by test/scripts/check-retired-phrases.test.ts.

  • scripts/check-bash32.sh — the bash 3.2 parse guard (bun run check:bash32): runs the real GNU bash 3.2 parser (bash -n) over every tracked *.sh except test/fixtures/guards/, because macOS /bin/bash is 3.2 and rejects shapes bash 5 accepts (a heredoc inside $(...) with an odd quote). Parser order: GBRAIN_BASH32 (a bash 3.x binary; docker forces the image), /bin/bash when it is 3.x, then the digest-pinned bash:3.2 image. No parser prints one skip line and exits 0; GBRAIN_TEST_BASH32_REQUIRE=1 makes it exit 2. Prints FAIL: <file:line> / Why: / Fix: / See: docs/ci-guards.md#bash-32-parse-guard. Parse only, not in bun run verify; run by the test.yml verify job (image) and macos-validation.yml (/bin/bash, followed by bun run verify). GBRAIN_GUARD_ROOT seam; fixtures test/fixtures/guards/check-bash32.sh/{bad,good}; pinned by test/scripts/check-bash32.test.ts.

  • scripts/check-source-id-projection.sh — CI grep guard for the multi-source bug class. Greps src/core/postgres-engine.ts + src/core/pglite-engine.ts for SELECT.*FROM pages projections matching the rowToPage feeder shape (id + slug + type + title) and fails if source_id is missing. Page.source_id is required at the type level; a projection dropping the column produces Page rows with source_id: undefined while TypeScript's : string lies about it. Wired into bun run verify.

  • scripts/check-worker-lock-renewal-shape.sh — CI guard wired into bun run verify. Two invariants on src/core/minions/worker.ts: (1) the bug pattern lockTimer = setInterval(async ...) must NOT appear (narrowed via lockTimer = prefix so unrelated setInterval(async) calls — like the stall detector — don't false-fire), (2) runLockRenewalTick must remain referenced so the pure-function test seam survives refactors. Bug-pattern-specific by design — a future refactor to setTimeout-recursion or AbortController-based scheduling passes as long as the bug pattern stays absent. POSIX ERE + [[:space:]] for BSD-grep portability. Honors GBRAIN_LOCK_RENEWAL_SHAPE_TARGET env override for fixture-based meta-tests. Pinned by test/scripts/check-worker-lock-renewal-shape.test.ts (5 cases).

  • scripts/classify-tests.ts + scripts/structural-suites.tsv — suite-level behavioral-vs-structural test classification (the intent axis described in docs/TESTING.md "File taxonomy"). Content-based detectors — repo-anchored readFileSync/Bun.file readers, exec-scan grep windows over src|scripts|docs, and the doctorSource()/doctorFileSource() helpers — mark a suite STRUCTURAL when its assertions read repo source/doc text rather than executing product code; tmpdir-anchored reads don't count, and files with detectors but no attributable suite land in an unknown bucket emitted as comment rows (surfaced, never silently dropped). Modes: bare = rewrite the TSV; --check = byte-for-byte regenerate-and-diff freshness (wired as bun run check:structural-manifest in bun run verify via scripts/check-structural-manifest.sh); --summary = counts only. Fix misclassifications in the detector list, never by hand-editing the TSV. render-coverage-summary.ts consumes the TSV for the behavioral-vs-structural line in the CI coverage report.

  • scripts/e2e-matrix.ts — freezes selected E2E paths after the named-job, live-key, persistence-validation and backend-matrix exclusions (E2E_EXCLUSIONS; every test/e2e/ row of scripts/e2e-backend-matrix.txt belongs to the tier1-backend-matrix job) into at most eight weighted partitions, printing each excluded file's owner. Explicit empty sentinel is the only no-op; malformed/missing input fails. Workers validate paths and filesystem confinement, pass argv directly, clear inherited SHARD and register cancellation handlers before spawning, retaining any signal received before the child handle is available. prepare-e2e and every worker are required by e2e-status; each worker owns Postgres. Pinned by test/scripts/e2e-matrix.test.ts and workflow wiring tests.

  • .github/workflows/e2e.yml + scripts/verify-nightly-e2e.ts — full E2E discovery runs on four weighted, independent Postgres workers, sequential fresh Bun processes within each. Schedules and explicit default-false full_corpus manual dispatches share the same full-profile jobs, aggregation, reports and receipts; ordinary selection is unchanged and full manual runs have their own concurrency group. Each worker bootstraps its guarded service schema through setupLegacyEmbeddingDB() under a keyless temporary home before tests. No selected-lane exclusions apply. Workers publish distinct e2e-N coverage manifests and successful executed-file receipts; full-profile e2e-status requires successful job results plus exact, disjoint, same-commit partitions. The advisory report validates those receipts before merging all four multi-file LCOV lanes. Coverage count is not executed-file count: skip-only files may emit no LCOV. test/scripts/nightly-e2e.test.ts, e2e-runner.test.ts, ci-gates.test.ts and merge-lcov.test.ts pin discovery, isolation, failure/cancellation, artifacts and completeness. See docs/TESTING.md for cross-lane coverage responsibilities.

  • scripts/eval-spend-guard.sh — hard spend cap for paid eval runs: scripts/eval-spend-guard.sh <cap_usd> <estimate_usd> -- <command...>. INVARIANT: a paid command never launches when ledger total + estimate would exceed the cap, and every launch is appended to the ledger whether or not it succeeded, so the running total can only under-state spend if the command itself lies about its cost. FAILS CLOSED on anything it cannot account for: a missing ledger (a missing file is NOT a $0 ledger — the first run sets GBRAIN_EVAL_SPEND_LEDGER_INIT=1, which prints a loud NEW LEDGER line), an unparseable ledger line (named by line number), a signed or malformed amount (a negative estimate would drive the ledger backwards). Ledger $GBRAIN_EVAL_SPEND_LEDGER (default ~/gbrain-lme-receipts/spend.jsonl): every launch writes TWO rows sharing a run_id — a status: running reservation appended BEFORE the command starts (cost = the estimate, so a concurrent guard already counts it) and a status: done reconciliation after it exits (actual cost, exit code); the sum is reconciled rows + unreconciled reservations, so a guard killed by INT/TERM/HUP (trap-reconciled at the estimate) or SIGKILL (reservation left standing) never under-counts, and an unwritable ledger refuses the launch — the command's process group gets TERM, then KILL after GBRAIN_EVAL_SPEND_GUARD_KILL_GRACE_SECONDS (default 10); terminal stdin is EOF; a SIGKILLed guard's live group is reported (<ledger>.leases/), never killed. Legacy single-row lines {ts, estimate_usd, cost_usd, exit_code, command} still count. The recorded cost comes from $GBRAIN_EVAL_ACTUAL_COST_FILE (exported to the child as a scratch path when unset; bare unsigned number or JSON with cost_usd) only when positive, else the estimate (over-stating is the safe direction). Amounts normalize to %.6f; awk/grep/sed only — no jq or bun at runtime. Exit: the wrapped command's code · 2 usage · 3 refused. Pinned by test/eval-spend-guard.test.ts.

  • scripts/generate-plugin-tree.ts + scripts/check-plugin-tree.sh + plugin/ — generator, byte-diff drift gate (in the skills commit gate), and the committed curated skill tree both plugin lanes ship (70 skills + shared conventions/_*.md deps + a generated README carrying the CLI-primary starter note).

  • scripts/generate-wave-1-moves.ts + docs/architecture/wave-1-moves.json + docs/architecture/wave-1-porting.md — the refactor wave 1 porting kit. The generator diffs src/**/*.ts between the merge-base with origin/master (--base) and HEAD (--head) and maps every changed top-level symbol (functions, class members, variables, types) to its new home(s): whole-body token containment first (the scripts/lib/normalize-tokens.ts normal form, relative import()/require() specifiers resolved to repo paths), then sub-statement chunks for splits, then same-named delegation from a remaining façade member, then the name. Symbols with unchanged tokens and in-place edits are omitted; removed symbols with no destination go to unmapped. Each entry records kind (moved / split / extracted), the old path that still exports the name (facade) and wasExported. The markdown (recipes per conflict kind, generated-file commands, agent prompt, landing window) is rendered from the JSON; the JSON's landing block (integration owner, freeze window, who lifts it) survives regeneration, and --render refreshes only the markdown. Pinned by test/scripts/generate-wave-1-moves.test.ts (every new/facade entry resolves in the tree; markdown equals the rendering; classifier on a synthetic base/head pair).

  • scripts/guards-manifest.tsv + scripts/guard-self-test.sh — THE single registry of scripts/check-* CI guards (53 guards) and its self-test harness. Every guard is classified scanner (greps/parses repo sources — must eventually carry fixtures), buildfresh, or repostate (exempt-with-reason, not fixture-tested). guard-self-test.sh (bun run check:guard-self-test, wired into bun run verify) runs each selftest=yes scanner against known-bad (must exit non-zero) and known-good (must pass) fixture trees under test/fixtures/guards/<guard>/{bad,good}/ via the GBRAIN_GUARD_ROOT env seam (independent guards run GUARD_SELF_TEST_JOBS, default 4, at a time; results print in manifest order; the pass has a 30 s wall-clock budget), and fails the build when a new scripts/check-* script is missing from the manifest — so a guard whose pattern rots into a permanently-green no-op fails CI instead of masquerading as coverage. The manifest registers and classifies guards but does not itself schedule them — run-verify-parallel.sh's CHECKS array remains the execution list, and a registered guard is not automatically wired into verify. New guard = new manifest row (+ fixtures if scanner) + a CHECKS entry if it should gate pushes.

  • scripts/llms-config.ts + scripts/build-llms.ts — Generator for llms.txt (llmstxt.org-spec web index) + llms-full.txt (inlined single-fetch bundle). Curated config drives both. Run bun run build:llms after adding a new doc. LLMS_REPO_BASE env lets forks regenerate with their own URL base. FULL_SIZE_BUDGET (600KB) caps the inline bundle; generator WARNs if exceeded. Committed output has no runtime consumer; committed for GitHub browsing and fork-safe fetching.

  • scripts/merge-lcov.ts + scripts/coverage-diff-gate.ts + scripts/coverage-baseline-gate.ts + scripts/update-coverage-baseline.ts + scripts/render-coverage-summary.ts + scripts/coverage-gate-exemptions.txt + scripts/coverage-baseline.json — the coverage measurement + gating cluster; the operating guide is docs/TESTING.md "Coverage lanes and gates". merge-lcov.ts walks artifact dirs for lcov.info + lane-manifest.json, sums DA hits per file:line, normalizes paths repo-relative, and emits a merged lcov + summary JSON (src-only totals/per-dir/per-file, the lineHits extension the diff gate consumes, and never-loaded src files as count + sorted list — deliberately never a percentage, since physical lines ≠ executable lines); --manifest-expect pins the lane set; SHA, duplicate identities, and actual per-lane LCOV counts are validated (--sha supports offline artifacts), and a missing/incomplete lane or a shard lane with lcovCount != 1 (the xargs-batching tripwire) marks the summary degraded: true — still exit 0 (degraded is data, and both gates go report-only on it). coverage-diff-gate.ts gates added/changed gate-scoped lines (non-test, non-generated src/**.ts) at ≥80% covered plus zero changed-but-never-loaded files; report-only unless COVERAGE_GATE_ENFORCE=1; a [coverage-exempt: reason] commit trailer passes with a loud warning; coverage-gate-exemptions.txt rows (exact path or trailing-/ prefix; SHRINK-ONLY — additions need a graduation review) are excluded from the gate but still reported ([e2e-exempt] / [subprocess-undercount]); exit contract: 0 = pass or report-only, 1 = fail while enforcing, 2 = infrastructure error (never conflated with a coverage verdict). coverage-baseline-gate.ts reads the baseline via git show origin/master:scripts/coverage-baseline.json (never the working tree, so a PR can't weaken its own bar) and compares corpus-matched sections only (--corpus prCorpus|fullCorpus), failing on >0.5pp global or >1.0pp per-dir drops; provisional: true in the baseline (the current state — both corpus sections unseeded) keeps it report-only regardless of enforcement; update-coverage-baseline.ts writes the working-tree baseline (per-file detail limited to the committed watchlist) and --promote flips provisional: false. render-coverage-summary.ts renders the summary JSON as markdown on stdout for $GITHUB_STEP_SUMMARY, including the behavioral-vs-structural counts from scripts/structural-suites.tsv. Wiring: 16 PR-corpus lanes in test.yml (10 matrix shards + four serial partitions + the two dedicated slow jobs) upload coverage-* artifacts and the advisory coverage-report job merges + renders + runs both gates report-only (deliberately absent from test-status/cache-write until graduation); scheduled or explicitly dispatched coverage-full-{unit,serial,slow,e2e} + coverage-full-report in e2e.yml produce the self-contained fullCorpus number (full e2e glob included) and the coverage-full-merged trend artifact. Collection is COVERAGE_DIR-opt-in in test-shard.sh/run-serial-tests.sh/run-e2e.sh — unique coverage dir per bun process (a reused dir overwrites lcov.info), lane manifest written only on a green run, run-e2e.sh requires an ABSOLUTE COVERAGE_DIR and honors E2E_FILE_TIMEOUT_SECS (both deliberately non-GBRAIN_-prefixed to survive the hermetic env scrub). Bun/JSC emits line records only (function coverage is informational) and no subprocess coverage, so src/cli.ts undercounts. Pinned by test/scripts/merge-lcov.test.ts, test/scripts/coverage-diff-gate.test.ts, test/scripts/render-coverage-summary.test.ts.

  • scripts/persistence/{harness,schedules,worker,validate,failure-diagnostics}.ts — executable concurrency gate using real journal/coordinator APIs: 1,000 seeded schedules per engine, eight actual process-kill publication boundaries, and 10,000 writes from four producer processes. Each phase owns a temporary disk PGLite datastore or a fresh test Postgres database. Independent accounting queries verify conservation; every soak receipt is compared to its canonical snapshot and file. JSON manifests separate actual counts and latency measurements from the configured Linux/Bun CI matrix. Failed runs preserve private fixtures and collect bounded, allowlisted request/queue/owner diagnostics without changing deadlines or hiding the original error. Cleanup commands read the existing test URL from the environment. The PGLite loopback endpoint is a fixture transport, not production authentication coverage. Contract and commands: scripts/persistence/README.md; smoke entries: test/persistence-chaos.slow.test.ts, test/e2e/persistence-chaos.test.ts; diagnostic/retention contracts: test/persistence-failure-diagnostics.test.ts.

  • scripts/persistence/{ops,generator,model,crash-robot,robot-driver,shrink,lock-order,history-fixture,would-have-caught}.ts — the crash robot, a phase of validate.ts (--robot-seconds ceiling, default 1200 PGLite, 880 Postgres; --robot-scope=pr|full, --explore-day; CI: persistence-validation.yml). ops.ts is the JSON op-descriptor protocol between driver and workers: each descriptor names an op kind (put/edit/delete/restore page, remember/forget, takes add/supersede, timeline add, sync, connector publish, revoke access), an actor (the local CLI or a remote agent verifyAccessToken resolves), a source, a fixed request id and arguments whose { $ref } values come from earlier observations; workers run each op through its registered handler. Its retryingRead retries the robot's reads only across a session drop the SessionDrops ledger shows it injected; any other closed connection fails the run. generator.ts builds seeded schedules: the fixed cross-boundary sequences (crossBoundarySequences: withdrawal then republication, overlapping slugs, competing writers, caller-bound replay, revoked authority, sync/connector races) plus random sequences with concurrent groups. model.ts is the temporal oracle: receipts and revisions at the observation point, legal later transitions, late receipts against page history, withdrawal permanence on recall/get_page/facts, source isolation, caller-bound replay, takes/facts fence projections, attribution, orphans, drain and wedge bounds; EFFECT_SEAMS maps every EffectKind to its trigger op and seam (typecheck-exhaustive). crash-robot.ts runs a schedule in-process or as a worker role (count, run frozen at a fault-points.ts seam and SIGKILLed by the driver, recover), plus process faults (stale index.lock, a hung git commit holding it, Postgres session drops, the owner killed after a facts-absorb extraction commits, then the job re-run). robot-driver.ts runs one fixed list on every event (a passed run is reusable): each seam the fixed sequences reach (all of them on full PGLite), ROBOT_RANDOM_SEEDS, nightly explorationSeeds(day); over_budget fails it past the ceiling. Postgres connects through GBRAIN_PGBOUNCER_URL when set and, in the pr scope, skips the seams and the pooler disconnect fault that can wait out a dead owner's claim lease (effect:*, consumer:prepared, three publication seams), listed in the manifest as lease_bound_seams_skipped and lease_bound_faults_skipped. shrink.ts is dependency-preserving ddmin accepted on 3/3 reproduction; --replay/--shrink re-run a manifest's failing runs. lock-order.ts traces each transaction's row locks (worktrees before sources, sources by id, no exclusive brain lock in a publication). history-fixture.ts exports buildHistoryFixture(engine, { pages, seed, sources, worktrees }) (real persistence history up to 10k pages; engine graduation, attribution backfill) and prepareTopology. would-have-caught.ts reverts each fix in would-have-caught.json in a scratch worktree and runs the pre-robot gate and robot on it. Tests: test/persistence-crash-robot.test.ts, test/persistence-crash-robot.slow.test.ts (shrunk regressions in test/fixtures/crash-robot/), test/persistence-history-fixture.test.ts.

  • scripts/persistence/{graduation-fixture,graduation-process,graduation-ttv}.ts — engine graduation test inputs and measurements. graduation-fixture.ts builds the 1k/10k history brains (buildHistoryFixture plus deterministic chunk vectors) or the hand-built legacy brain (test/fixtures/graduation/) in a keyless child process, caches each as a tarball keyed by its source files, schema version, seed and size, and re-homes a restore (database paths, managed-root records, owner stamps re-stamped with the new inode and birth time; sources marked synced). Its report lists bytes, chunks, versions, requests, effects and embeddings. graduation-process.ts spawns the real CLI or an older release with an isolated home and no provider keys, with optional boundary hooks, plus MCP stdio/HTTP clients and the JSON contract accessors. graduation-ttv.ts times plan to green doctor (five-minute gate at 1k pages; exit 1 under --enforce, 3 on a harness crash). Owners: test/scripts/graduation-fixture.test.ts, test/graduation-legacy-fixture.test.ts, test/e2e/graduation-{crash,faults,clients,cli}.test.ts, tests/heavy/graduation_10k.sh.

  • scripts/persistence/{matrix,matrix-cases}.ts — required real Postgres/PgBouncer deployment matrix: 24 combinations of RLS policy enforcement, ordinary pool sizes 1/2/3 and shared/separate direct capacity. Production bulk reservations must leave short claims, renewals and reads usable; size-one publication stays queued. Fresh fixtures also verify successor manifests, stale owners, retained native lock exclusion during root replacement and source deletion/recreation. test/e2e/persistence-runtime-matrix.test.ts runs it when configured and refuses missing required pooler fixtures. Supplied URLs pass the test-database guard before its CREATE/DROP control connection uses the maintenance database; fresh case databases isolate it from other E2E shards.

  • scripts/persistence/{performance,read-workload,read-metrics,read-admission,read-diagnostics}.ts — required median-of-three read-workload validity check with advisory CI latency around the existing heavy query corpus (500 pages, 200 reads, four writers, writesPerWriter 25, four-connection PostgreSQL pool). Both engines use public page mutation handlers; every read/write or drained sampler error invalidates the sample, actual in-flight mutation intervals must cover at least 90% of reads, and CI reports the 50% loaded-versus-idle p99 threshold without blocking on that ratio. CI uses --informational, which never suppresses invalid-workload failures; the default CLI and explicit strict heavy runs still enforce the threshold. Isolated children retain runtime/source hashes, queue/admission/commit/RSS/recovery/pool metrics and bounded diagnostic records with total/dropped counts, including failed partial observations. Numeric query/corpus/write indices and monotonic timestamps correlate reads, admissions, terminal receipts and pool samples without retaining SQL, parameters, identifiers, content or raw errors. Fixed failure stages retain only allowlisted error properties; raw stacks are omitted. The root postgres.js begin observer covers lexical readers and writers, preserves the original promise/receiver/arguments, and excludes nested savepoints. Dispatch-to-callback includes BEGIN and client scheduling, not pure checkout wait; PGLite has no transaction-entry timing. Identical 20ms timers record event-loop lateness in both phases. Observers run during seed/warmup before measurement; context setup and read retention sit outside query timing where possible, but transaction/timer callbacks add unquantified overhead. No SQL or server sampling is added, and sparse pool samples cannot establish lock causes. The original tests/heavy/read_latency_under_sync.sh invokes this runner. The stable admission proxy requires one resolved top-level queued journal transaction per committed UUID. test/persistence-performance.test.ts guards validity, strict threshold semantics and advisory CLI exit behavior; test/persistence-admission-observer.test.ts proves rollback/publication boundaries; test/persistence-read-diagnostics{,.serial}.test.ts covers bounds, transparency, nested transactions, safe failure retention, tiny manifests and late sampler rejection.

  • scripts/r1-namedthing-rerank-ab.ts — Phase C′ rule R1 receipt: balanced reranker ON vs OFF on NamedThingBench, paired per query, in ONE in-memory PGLite brain seeded ONCE with real embeddings (seedNamedThingCorpus; --relational adds relational/corpus.ts + its 38 RELATIONAL_QUESTIONS, which with the fixture's own graph-relationship query are the 39 relational questions the receipt reports beside the 11 non-relational core queries). Arms are applied with engine.setConfig (ARM_PINS: OFF = search.mode balanced, search.reranker.enabled false, search.autocut false; ON adds search.reranker.enabled true + search.reranker.model voyage:rerank-2.5; autocut pinned off in both by default — a rerank-only comparison — and --autocut on|off is an overlay applied to BOTH arms through applyArmPins(engine, arm, overlay) so the ON arm can run in the pre-R2 shipped balanced shape (autocut on) without changing the pinned defaults the tests pin), so bare hybridSearch resolves them the way a production balanced brain would; scoring reuses runRetrievalQuality/evaluateGate (no local hit@k). Per query it records deduped top-3, the rank-1 evidence/create_safety tier, finite-rerank_score row count and the degraded stamp. INVARIANTS: readiness (rerankerReadinessForEngine) is checked BEFORE any spend and the ON arm must show no reranker_skipped/rerank_passthrough stage and ≥1 reranked row per non-empty query, else exit 2 (fail-open would silently turn ON into OFF); embedding degradation (embed_unavailable/embed_timeout/vector_arm_failed) in a live arm is exit 2 too; --embed-cache PATH (installEmbedCache) makes both arms see byte-identical query vectors and the receipt says whether that held (identical_query_vectors). r1Verdict is pure: PASS iff hit@1 losses == 0 and hit@3 losses ≤ 1, losses counted per query (OFF hit, ON miss) and never offset by wins; create_safety downgrades are counted and named, not gated. A pass-through rerank transport tees the API-echoed model id + usage into the receipt. --stub-embed is the hermetic dry run (embed transport throws, OFF arm only, ON reported as skipped — needs VOYAGE_API_KEY). --json carries _meta.metric_glossary (hit@1, hit@3, mrr, create_safety); exit 0 PASS/dry-run · 1 FAIL · 2 integrity/usage. Receipt (shipped balanced, voyage:rerank-2.5): the 11 core queries show 0 hit@1 / 0 hit@3 losses in every cell; the 39 relational queries WITHOUT the relational re-pin fell hit@1 21→3 (19 losses) and hit@3 27→5 (22 losses) — R1 FAIL; WITH search.relational_rerank_pin at its default 3 (measured with --autocut on, the shape that shipped before rule R2 turned autocut off) 0 losses, hit@1 21/39 and hit@3 27/39 — R1 PASS, the balanced reranker stays ON. --relational-pin N|off overlays search.relational_rerank_pin on BOTH arms: the no-pin cell is --relational-pin off (or 0); the default cell omits the flag and resolves the bundle default 3 exactly as production does. Pinned by test/r1-namedthing-rerank-ab.test.ts.

  • scripts/run-e2e.sh — Sequential E2E runner. Accepts an optional argv-driven file list (used by the Selected E2E workers) and a --dry-run-list flag that prints the resolved file list and exits (used by ci-local.sh's startup smoke-test). Falls back to test/e2e/*.test.ts plus test/phantom-redirect-engine-parity.test.ts when invoked with no args (the phantom-redirect Postgres arm is only reachable through a DATABASE_URL-bearing lane; the unit wrappers strip the URL, so this lane must carry it). This wrapper is the database-URL opt-in boundary: it exports GBRAIN_TEST_ALLOW_DATABASE_URL=1 so the bunfig preload guard (test/helpers/database-url-guard-preload.ts) lets the run start, unsets GBRAIN_DATABASE_URL (the e2e suite runs on DATABASE_URL only — an ambient GBRAIN_DATABASE_URL would pass the opt-in yet reach CLI-subprocess paths with no name floor), and its GBRAIN_* env scrub preserves GBRAIN_E2E_ALLOW_DB so the name-floor escape hatch the guard's own error message names stays usable. It also preserves GBRAIN_CI_DISABLE_TEST_ENV_FILE=1, keeping CI runs from loading checkout-local .env.testing credentials after the shell-to-Bun handoff. It also exports GBRAIN_TEST_KEEP_PROVIDER_KEYS=1 so the unit-lane provider-key strip preload (test/helpers/provider-keys-preload.ts) leaves the real keys that live embed/parity e2e tests skip-gate on. Each file runs under a gtimeout/timeout wedge backstop (default signal: SIGTERM — the bun test child installs no JS-level handler for it, so kernel-default termination applies) — 180s default, with a per-file override for known-slow files (skills.test.ts gets 420s: the real ingest-skill run replays every migration, so its floor grows as master adds migrations); the cap is a wedge backstop, not a per-test budget, and bare bun (no outer cap) is the fallback when neither timeout binary is installed. It activates the PGLite schema snapshot like the other runners: sources scripts/lib/test-env.sh + ensure_pglite_snapshot after the --dry-run-list early exit (list mode stays instant; non-fatal on build failure), re-exports GBRAIN_PGLITE_SNAPSHOT as an ABSOLUTE path (e2e tests spawn CLI subprocesses with varying cwd — a relative path silently misses the tar there), and its env keep-list preserves the var; e2e files that assert the path TO post-initSchema() state carry per-file delete process.env.GBRAIN_PGLITE_SNAPSHOT opt-outs with one-line reasons. Each file pass records an executed-test receipt (below) that keeps its native JUnit report; processes still running with a file's HOME after its bun process exits are killed and named, and a HOME that still cannot be removed fails that file by name while the partition continues. executed-files.txt lists every attempted file, pass or fail; lane-manifest.json (complete:true) is written only on a green run.

  • scripts/lib/test-env.sh receipts (receipts_init, receipt_begin, receipt_end, receipt_empty) + scripts/run-with-receipt.sh + scripts/ci-executed-counts.ts — executed-test receipts and the identity ledger. With GBRAIN_TEST_RECEIPT_DIR set, every bun invocation a runner makes (test-shard, run-unit-shard per file, run-unit-parallel rescue passes, run-serial-tests pooled and rescue runs, run-slow-tests, run-e2e per file pass, and CI's bare bun test steps through run-with-receipt.sh <lane> <tag> -- bun test ...) writes <id>.receipt (lane, kind primary/rerun/rescue, shard/of, arm, sha, run id and attempt, exit), <id>.files and Bun's JUnit report; the runner unsets the variables so tests and nested runners never inherit them (GBRAIN_TEST_RECEIPT_LANE overrides the default lane). run-unit-parallel.sh writes receipts by default under .context/test-receipts/. run-verify-parallel.sh records each check as pass, fail, timeout or skip (a self-skipping check prints GBRAIN_CHECK_SKIPPED: <reason>) in outcomes.tsv and a JUnit receipt, and keeps its logs on failure. ci-executed-counts.ts --head-run <id>[,<id>] [--base-run ...] (or --head-dir/--base-dir) accounts for every test by (lane, file, test, arm): repeated names inside a file are numbered by occurrence, a later rerun/rescue supersedes earlier attempts for its files, and missing, truncated or prior-attempt receipts, missing shards, empty lanes and missing artifacts make the result incomplete (exit 1). Each base identity that no longer executes must match a row of the expected-deltas TSV (--deltas; retire with evidence, move, skip, job), or the tool prints the row to add. test.yml and e2e.yml upload receipts-<lane> artifacts and run it report-only in their executed-receipts jobs (e2e also prints the missing-provider-key skip count). Tests: test/scripts/ci-executed-counts.test.ts, test/scripts/run-with-receipt.test.ts.

    Every file needs a fresh parent-owned native JUnit report, its selected-file header and matching final console totals; zero exit alone or a nested child's summary cannot establish completion. All-skipped reports remain valid and explicit. Coverage runs atomically claim a new destination, refusing existing paths without deleting their contents, and write executed-files.txt plus a same-commit manifest only after all selected files succeed. SHARD=N/M produces lane e2e-N; unsharded runs retain e2e. The per-file LCOV directories remain independent, and the nightly validator accounts for every partition without equating LCOV count with executed-file count.

  • scripts/select-e2e.ts + scripts/ci-changed-files.sh + scripts/ci-doc-checks.sh — E2E selection. select-e2e.ts classifies the changed files (git: committed origin/master...HEAD, working tree and untracked-unignored files; or --changed-files <path|->) as EMPTY / DOC_ONLY / SRC: DOC_ONLY (root *.md, docs/, LICENSE, VERSION) selects nothing, everything else selects every test/e2e/*.test.ts and prints "E2E narrowing is retired" (a diff map selected all files on 40 of 40 merged PRs). ci-changed-files.sh lists a PR's or merge-group entry's files from the GitHub API for prepare-e2e and exits 1 on a capped (3000 PR / 300 compare), short or failed list or with no PR context, so the workflow falls back to the whole corpus. ci-doc-checks.sh is the doc-only gate ci:local:diff and ci:ubicloud:diff run (llms freshness, check:doc-history, test/docs-repo-paths.test.ts, skill refs, privacy guards). Tests: test/select-e2e.test.ts, test/scripts/e2e-wiring.test.ts, test/scripts/ci-local-rendering.test.ts.

  • scripts/sharding.ts + scripts/mine-shard-weights.ts + scripts/capture-test-log.ts — deterministic weighted partitioning and timing refresh. CLI takes lane-specific weights; missing entries use p75, equal loads prefer fewer files then shard index, and serial may explicitly opt into warning/fallback on bad advisory weights. UNIT_SHARDS sizes both unit matrices under UNIT_SHARD_BUDGET_MS (test/scripts/unit-shard-budget.test.ts); test.yml runs UNIT_SHARDS_PER_JOB per runner via scripts/test-shard-pack.sh (job test (N, M), artifacts per shard). --sum prints a shard's predicted weight (test-shard.sh logs it with nproc, load, steal, CPU model: slow draw or slow tests). weights:mine --lane unit|serial|e2e validates complete lane logs before replacing and records run/commit/unit metadata. A GitHub refresh reads one job at a time (gh refuses a whole-run --log above its job cap): unit from each shard's timings-unit-N capture artifact, which must record one capture start and a final complete exit=0; serial from gh run view --job <id> --log. E2E defaults to merging selected-job observations; explicit --e2e-profile full --run ID requires a successful source-matched run, pins its attempt/job IDs, resolves basename headers against committed default discovery including the outside-directory parity entry, and replaces the map only after exact disjoint corpus validation. Metadata retains log/corpus hashes; file/stdin sources cannot claim full-profile provenance. Capture keeps stdout/stderr, records timestamped GitHub-format artifacts, forwards cancellation to its process group and marks failed runs unmineable. A failed Actions run appends its last 50 failures to the step summary: file, test, backend arm, first error block and a reproduction command (or the last log lines when no (fail) line printed). Unit and E2E artifacts keep 14 days. scripts/check-weight-coverage.ts (check:weight-coverage, in verify) fails on a unit/serial/E2E/Ubicloud weight naming a missing file and on an unweighted lane share above 5% (unit) or 10% (serial, E2E) only when GITHUB_EVENT_NAME=schedule; else the share warns (stdout + step summary) with the lane's miner command. Tests: test/scripts/check-weight-coverage.test.ts plus guard self-test fixtures.

  • test/e2e/codex-plugin-install-real.serial.test.ts + test/e2e/claude-plugin-install-real.serial.test.ts — the plugin doors: clean-tree staging (git archive HEAD), real marketplace add/plugin add, snapshot + exec-bit + non-root-mcp.json pins, tools/list starter-surface oracle, cold-home fast-fail, --source-guard block/allow, coexistence + removal probes, auth-gated SMOKE turns. CI: the plugin-doors job in heavy-tests.yml (pinned binary provisioning + expected-pass-count refuse-green).

  • test/e2e/helpers.ts — shared guarded test database lifecycle. setupDB() preserves physical schema, stored embedding identity and the migration ledger while clearing data, other operator configuration and source sync identity; migration fixtures opt into cold replay, and a missing ledger also takes the cold path. test/e2e/fixture-reset-postgres.test.ts pins those boundaries. Fixed-width vector fixtures explicitly use setupLegacyEmbeddingDB() to align empty text-embedding columns and stored model/dimensions with canonical legacy test configuration after truncation. This prevents earlier CLI-init fixtures from leaking a different identity or width into weighted execution order. Custom-shape fixtures retain ordinary setup. importFixtures() accepts an explicit engine for fixtures that own a separate database. test/db-guard-coverage.test.ts recognizes both guarded entry points.

  • test/helpers/test-backends.ts — shared persistence-suite backend selection. Direct root suites retain local-only defaults and explicit dual-engine invocation; E2E wrappers capture PostgreSQL-only selection while registering tests and fail closed without a safe database. The unit and E2E lanes jointly retain every backend contract without repeating the local arm.

  • test/e2e/mechanical.test.ts — the healthy-doctor block imports the full corpus into a fresh UUID-isolated Postgres database and directs every CLI connection there. It preserves unrelated OAuth/grant state in the shared E2E database; a retained confidential-client fixture with an empty secret hash must not invalidate this healthy-brain assertion. Both human and JSON doctor paths require exit zero, and JSON checks must contain no failures. Failure diagnostics retain failed-check names with bounded credential/connection redaction.

  • test/eval-replay-gate.test.ts + test/fixtures/eval-baselines/qrels-search.json — hermetic retrieval qrels gate running in the standard PR unit-shard CI matrix (.github/workflows/test.yml, NOT the fixed-file E2E workflow). Uses the canonical PGLite block (test-isolation R3+R4) and the basis-vector embedding pattern from test/e2e/search-quality.test.ts:23-28 for fully hermetic retrieval. The qrels fixture (12 queries) uses PLACEHOLDER names only (alice-example, widget-co-example, etc. — privacy rule) and embeds each query at a deterministic basis dimension so retrieval is reproducible. Each query lists relevant_slugs[] + first_relevant_slug; the test computes top1_match_rate (top-1 == first_relevant) and recall@10 (fraction of relevant_slugs in top-10), asserting both meet floors (defaults >= 0.80 and >= 0.85). Env-overridable floors GBRAIN_REPLAY_GATE_TOP1_FLOOR / GBRAIN_REPLAY_GATE_RECALL_FLOOR (via withEnv() per R1). Refresh discipline: when ranking changes intentionally move expected slugs, edit qrels-search.json directly with a Why: line in the commit body or the gate degrades to rubber-stamp. Pinned by test/eval-replay-gate.test.ts (incl. a privacy-grep guard against real names).

  • test/fixtures/whoknows-eval.jsonl — 10-row synthetic placeholder demonstrating the eval-fixture schema ({query, expected_top_3_slugs, notes?} JSONL). End users replace with their own real queries; placeholder uses obviously-example slugs (wiki/people/example-alice). Drives test/e2e/whoknows.test.ts (seeds a matching synthetic brain, asserts the >=80% gate) and the whoknows_health doctor check.

  • test/helpers/agent-harness.ts — Hermetic real-agent door-test adapters and persistent keyless seeds. A seeded nondefault source has its own Git worktree even when the synthetic home is itself a repository, keeping canonical files separate from coordination locks. Source registration and disconnect failures propagate. test/agent-harness-seed.serial.test.ts verifies two durable seeds and reopen without model/provider access.

  • test/helpers/tty-harness.ts + scripts/dx-explore.ts — the shared DX real-PTY harness, on pure Bun.spawn({terminal:}) (Bun 1.3.10+; engines.bun pin in package.json; no node-pty). launchTty spawns any CLI under a true pseudo-terminal with the hermetic env contract from test/helpers/agent-harness.ts (hermeticChildEnv; dropEnv strips pass-through auth keys), records timestamped output frames, and exposes waitFor/waitForAny/mark/sendKey/waitForQuiet/waitForExit/close. Lifecycle rule: only close() clears the wall-clock kill timer — always call it in a finally. Pure helpers (stripAnsi, computeStalls, renderStallsReport, parseDriveCommand, buildClaudeTuiSeed) are unit-tested in test/tty-harness.test.ts; that file's live-PTY smokes are describe.skipIf(!ptySupported())-gated. Transcript writes are structurally redacted: redactSecrets (secrets ≥ MIN_REDACT_SECRET_LEN → [REDACTED:<name>]) runs at every write site, coalesceSecretStraddles merges frames so a secret split across a frame boundary can't bypass redaction, and saveTranscript takes an explicit redact map (seam — dx-explore builds it, tty-harness stays import-free of it). scripts/dx-explore.ts is the DX-exploration driver built on it — a developer instrument, not a test: nothing asserts, transcripts land gitignored under .context/dx-runs/ (doc: docs/guides/bootstrap.md). The interactive gbrain init pickers are asserted for real in test/init-picker-pty.test.ts (serial lane, so it runs in required CI). test/cli-cwd-dotenv-quarantine.test.ts drives its two Ctrl-C cases with Bun.spawn({ terminal }) directly, gated on ptySupported(), because those fixtures need their exact env rather than hermeticChildEnv.

  • test/operations-trust-boundary.test.ts + scripts/check-operations-filter-bypass.sh — operations trust-boundary contract coverage. Pure assertions over all 74 ops (every op has a scope annotation; every mutating op has a non-read scope; localOnly: true ops are excluded from operations.filter(op => !op.localOnly); the seven sensitive localOnly ops snapshot-pinned by name) plus targeted handler-invocation guards for the HTTP-callable classes: submit_job with name='shell' + ctx.remote=true MUST reject (shell-job RCE); search_by_image with image_path + ctx.remote=true MUST reject (image leak); and the list-op read-leak class — find_orphans/get_recent_salience/find_anomalies/find_experts invoked with ctx.remote=true over a seeded visibility: private page MUST NOT return its slug/title, with a local positive control proving the assertions non-vacuous, count self-consistency assertions pinning the no-count-oracle posture (both orphan denominators shrink with hidden rows; excluded untouched; anomaly count mirrors the visible slug list), and a soft-delete re-probe pinning the includeDeleted fail-closed path. file_upload and sync_brain omitted from handler-invocation tests because they're localOnly: true (that path would test an impossible production scenario). The shell guard greps src/ for any module importing the operations value outside the canonical filter site at src/commands/serve-http.ts (three import shapes: destructured, aliased, namespace), with an explicit 10-entry allow-list + a literal-string check that serve-http.ts still contains operations.filter(op => !op.localOnly). Wired into bun run verify. Dynamic sibling: test/remote-privacy-sweep.test.ts (next entry) — same doctrine, corpus-seeded, catches leaks in ops neither curated list has heard of yet.

  • test/public-exports.test.ts — runtime contract test (R2). Imports every public subpath in package.json exports via package name, pins a canary symbol per module, and fails when the exports map gains, loses or renames a subpath without a matching EXPECTED_EXPORTS edit. It also imports gbrain/version in a fresh process and pins that it exports only VERSION (the package version) with no startup output.

  • test/remote-privacy-sweep.test.ts — registry-driven, corpus-seeded leak detection across the ENTIRE dispatch surface (catches a new remote surface that forgets the world-only filter). Seeds a hermetic PGLite corpus carrying high-entropy PRIVATE sentinels (private page title/body, a private fact, a non-world take, fence-row content — never slugs, which are legitimately echoed in "Page not found" errors and would false-positive on correct behavior) plus WORLD markers as positive controls; enumerates every non-localOnly op from the registry; dispatches each one remote-shaped through dispatchToolCall (the exact layer both MCP transports share) in BOTH caller shapes — scalar source-scoped (like stdio) and federated with an auth-array read grant; and asserts no private sentinel appears anywhere in the serialized response envelope: structured fields, rendered text, error messages, and the _meta.brain_hot_memory channel alike. Fail-closed maintenance contract: EXPECTED_OUTCOME's key set must be set-equal to the enumerated registry, so a NEW op FAILS the suite until classified (data = must prove corpus contact via a WORLD marker / ok / error — envelope still sentinel-checked / denied = publish-gated, must error naming its mcp.* gate; plus a PARAM_FACTORY entry if it can return corpus data — the failure message prints exactly what to add). A separate arm asserts every localOnly op is denied fail-closed over non-stdio transports; KNOWN_EXPOSED op-wide exemptions must stay empty absent written justification + review. Phase W covers mutating ops against fresh slugs (destructive ops last, corpus-intact re-checks between phases). Honest scope: covers the dispatch surface for transport-floor callers; does NOT cover the IPC context-pack handler (src/mcp/context-pack-handler.ts bypasses dispatchToolCall) or write-triggered restoration echoes — the write-side sweep is a filed TODO. Static siblings: test/operations-trust-boundary.test.ts (previous entry) + scripts/check-operations-filter-bypass.sh.