Garry's Opinionated OpenClaw/Hermes Agent Brain
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=1explicitly disarms it with a warning. Installer fixtures set both HOME before Bun startup and GBRAIN_HOME per fixture;test/real-home-guard-preload.test.tsverifies 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 manualnative_onlyuses 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 inputsrace_hunt,stress_filesandstress_base/stress_headlikewise run only their lane under a-diagnosticconcurrency group and name the aggregatefull-suite-not-run.test-statusalso gatesstress-changed-tests;race-huntruns 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.tsevaluates the actual event/input conditions and executes the scope/result scripts;test/scripts/ci-pr-scope.test.tspins Bun parity and the classification comments;test/scripts/ci-gates.test.tsretains 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 freshCREATE DATABASE … TEMPLATEdatabase 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/reportfor the PR gate (stress-changed-tests, intest-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.ps1freezes the old program for A; B forwards the actual production program. The separate read-onlywindows-backup-dotnet-inspect.ps1reports 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.tspins 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.shexposesensure_pglite_snapshot(legacy primary env) andensure_default_pglite_snapshot(absolute auxiliaryGBRAIN_TEST_DEFAULT_SNAPSHOT); failure visibly falls back to cold init.GBRAIN_NO_SNAPSHOT=1clears 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. KeepcomputeSnapshotSchemaHashand 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: everybun build --compileinvocation (CLI one-liners carrying--outfile, or['build', '--compile', …]spawn arrays) inpackage.json,CLAUDE.md,CONTRIBUTING.md,.github/,scripts/anddocs/must carry--no-compile-autoload-bunfig, because a compiled Bun binary otherwise auto-loads a cwdbunfig.tomland runs itspreloadbefore any gbrain code (beforecli-preflight.ts). Prose that names the command without--outfileis ignored;test/compile helpers are out of scope (throwaway binaries run from temp dirs). Self-tested viatest/fixtures/guards/check-compile-autoload.sh/{bad,good}/; wired ascheck:compile-autoloadin verify CHECKS.scripts/check-gateway-routed-no-direct-anthropic.sh— CI guard that fails the build ifsrc/core/cycle/synthesize.tsorsrc/core/think/index.tsreintroduces a runtimenew Anthropic()constructor call or a value-shapedimport 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. Mirrorsscripts/check-jsonb-pattern.sh. Wired intobun run verify. ExtendGUARDED_FILESwhen 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 agetPage(call with no second argument (or theX ? {sourceId} : undefinedany-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 markergbrain-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 ascheck:getpage-scopein 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: anexecuteRaw/executeRawDirect/.unsafe()call whose balanced arg span bindsJSON.stringify(x)into a bare$N::jsonbcast. 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 inlinejsonb-guard-okcomment). PGLite's nativedb.queryis deliberately not scanned (it parses text→jsonb, so the bug can't occur there). Heuristic by design (whole-span correlation; can't see aJSON.stringifyassigned to a variable before the call) — the real backstop is the DATABASE_URL-gated e2e parity tests. Runs over the real tree inbun 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)}::jsonbinterpolation pattern (postgres.js v3 double-encodes it), or (b)max_stalled INTEGER NOT NULL DEFAULT 1in any schema source file (must be DEFAULT 5 to preserve SIGKILL-rescue). It also invokesscripts/check-jsonb-params.mjsand propagates its exit code. Wired intobun test.scripts/check-module-size.sh+scripts/module-size-limits.tsv— the module-size ratchet (bun run check:module-size, wired intobun run verify). The TSV commits a per-filewc -lceiling (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 unlistedsrc/**/*.ts(excluding*.generated.ts/*.test.ts) above the 1500-line new-file cap fails (split it or add a row).ratchetis 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 intobun run verify. The former greps src/ forwithRetry(...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 iswithRetry(() => 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 undertest/fixtures/guards/. The latter extracts every string-literalauditSite: '...'from src/ and validates each appears in theBATCH_AUDIT_SITESconst insrc/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 intobun run testviascripts/check-progress-to-stdout.sh && bun testin package.json.scripts/check-retired-phrases.sh— the retired-phrase guard (bun run check:retired-phrases, inbun run verify): grepsCLAUDE.md,AGENTS.md,CONTRIBUTING.md,docs/andskills/for contributor-workflow phrases refactor wave 1 retired (theRETIREDtable: pattern + the current instruction) and printsFAIL: <file:line>/Why:/Fix:/See: docs/ci-guards.md#retired-phrase-guardper hit. Historical records (docs/designs/,docs/test-audit/,docs/incidents/,docs/plans/,docs/proposals/,docs/research/,docs/issues/,docs/superpowers/,docs/migrations/,skills/migrations/, thedocs/architecture/wave-1-*porting kit) are exempt;CHANGELOG.mdis not scanned.GBRAIN_GUARD_ROOTseam; fixturestest/fixtures/guards/check-retired-phrases.sh/(onebad-<location>tree per scanned location); pinned bytest/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*.shexcepttest/fixtures/guards/, because macOS/bin/bashis 3.2 and rejects shapes bash 5 accepts (a heredoc inside$(...)with an odd quote). Parser order:GBRAIN_BASH32(a bash 3.x binary;dockerforces the image),/bin/bashwhen it is 3.x, then the digest-pinnedbash:3.2image. No parser prints one skip line and exits 0;GBRAIN_TEST_BASH32_REQUIRE=1makes it exit 2. PrintsFAIL: <file:line>/Why:/Fix:/See: docs/ci-guards.md#bash-32-parse-guard. Parse only, not inbun run verify; run by thetest.ymlverify job (image) andmacos-validation.yml(/bin/bash, followed bybun run verify).GBRAIN_GUARD_ROOTseam; fixturestest/fixtures/guards/check-bash32.sh/{bad,good}; pinned bytest/scripts/check-bash32.test.ts.scripts/check-source-id-projection.sh— CI grep guard for the multi-source bug class. Grepssrc/core/postgres-engine.ts+src/core/pglite-engine.tsforSELECT.*FROM pagesprojections matching therowToPagefeeder shape (id + slug + type + title) and fails ifsource_idis missing.Page.source_idis required at the type level; a projection dropping the column producesPagerows withsource_id: undefinedwhile TypeScript's: stringlies about it. Wired intobun run verify.scripts/check-worker-lock-renewal-shape.sh— CI guard wired intobun run verify. Two invariants onsrc/core/minions/worker.ts: (1) the bug patternlockTimer = setInterval(async ...)must NOT appear (narrowed vialockTimer =prefix so unrelatedsetInterval(async)calls — like the stall detector — don't false-fire), (2)runLockRenewalTickmust remain referenced so the pure-function test seam survives refactors. Bug-pattern-specific by design — a future refactor tosetTimeout-recursion orAbortController-based scheduling passes as long as the bug pattern stays absent. POSIX ERE +[[:space:]]for BSD-grep portability. HonorsGBRAIN_LOCK_RENEWAL_SHAPE_TARGETenv override for fixture-based meta-tests. Pinned bytest/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-anchoredreadFileSync/Bun.filereaders, exec-scan grep windows oversrc|scripts|docs, and thedoctorSource()/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 anunknownbucket emitted as comment rows (surfaced, never silently dropped). Modes: bare = rewrite the TSV;--check= byte-for-byte regenerate-and-diff freshness (wired asbun run check:structural-manifestinbun run verifyviascripts/check-structural-manifest.sh);--summary= counts only. Fix misclassifications in the detector list, never by hand-editing the TSV.render-coverage-summary.tsconsumes 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; everytest/e2e/row ofscripts/e2e-backend-matrix.txtbelongs to thetier1-backend-matrixjob) 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-e2eand every worker are required by e2e-status; each worker owns Postgres. Pinned bytest/scripts/e2e-matrix.test.tsand 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-falsefull_corpusmanual 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 throughsetupLegacyEmbeddingDB()under a keyless temporary home before tests. No selected-lane exclusions apply. Workers publish distincte2e-Ncoverage manifests and successful executed-file receipts; full-profilee2e-statusrequires 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.tsandmerge-lcov.test.tspin 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 setsGBRAIN_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 arun_id— astatus: runningreservation appended BEFORE the command starts (cost = the estimate, so a concurrent guard already counts it) and astatus: donereconciliation 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 afterGBRAIN_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 withcost_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 bytest/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 diffssrc/**/*.tsbetween the merge-base withorigin/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 (thescripts/lib/normalize-tokens.tsnormal form, relativeimport()/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 tounmapped. Each entry recordskind(moved/split/extracted), the old path that still exports the name (facade) andwasExported. The markdown (recipes per conflict kind, generated-file commands, agent prompt, landing window) is rendered from the JSON; the JSON'slandingblock (integration owner, freeze window, who lifts it) survives regeneration, and--renderrefreshes only the markdown. Pinned bytest/scripts/generate-wave-1-moves.test.ts(everynew/facadeentry 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 ofscripts/check-*CI guards (53 guards) and its self-test harness. Every guard is classifiedscanner(greps/parses repo sources — must eventually carry fixtures),buildfresh, orrepostate(exempt-with-reason, not fixture-tested).guard-self-test.sh(bun run check:guard-self-test, wired intobun run verify) runs eachselftest=yesscanner against known-bad (must exit non-zero) and known-good (must pass) fixture trees undertest/fixtures/guards/<guard>/{bad,good}/via theGBRAIN_GUARD_ROOTenv seam (independent guards runGUARD_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 newscripts/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'sCHECKSarray remains the execution list, and a registered guard is not automatically wired into verify. New guard = new manifest row (+ fixtures if scanner) + aCHECKSentry if it should gate pushes.scripts/llms-config.ts+scripts/build-llms.ts— Generator forllms.txt(llmstxt.org-spec web index) +llms-full.txt(inlined single-fetch bundle). Curated config drives both. Runbun run build:llmsafter adding a new doc.LLMS_REPO_BASEenv 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.tswalks artifact dirs forlcov.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, thelineHitsextension the diff gate consumes, and never-loaded src files as count + sorted list — deliberately never a percentage, since physical lines ≠ executable lines);--manifest-expectpins the lane set; SHA, duplicate identities, and actual per-lane LCOV counts are validated (--shasupports offline artifacts), and a missing/incomplete lane or ashardlane withlcovCount != 1(the xargs-batching tripwire) marks the summarydegraded: true— still exit 0 (degraded is data, and both gates go report-only on it).coverage-diff-gate.tsgates added/changed gate-scoped lines (non-test, non-generatedsrc/**.ts) at ≥80% covered plus zero changed-but-never-loaded files; report-only unlessCOVERAGE_GATE_ENFORCE=1; a[coverage-exempt: reason]commit trailer passes with a loud warning;coverage-gate-exemptions.txtrows (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.tsreads the baseline viagit 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: truein the baseline (the current state — both corpus sections unseeded) keeps it report-only regardless of enforcement;update-coverage-baseline.tswrites the working-tree baseline (per-file detail limited to the committedwatchlist) and--promoteflipsprovisional: false.render-coverage-summary.tsrenders the summary JSON as markdown on stdout for$GITHUB_STEP_SUMMARY, including the behavioral-vs-structural counts fromscripts/structural-suites.tsv. Wiring: 16 PR-corpus lanes in test.yml (10 matrix shards + four serial partitions + the two dedicated slow jobs) uploadcoverage-*artifacts and the advisorycoverage-reportjob merges + renders + runs both gates report-only (deliberately absent fromtest-status/cache-writeuntil graduation); scheduled or explicitly dispatchedcoverage-full-{unit,serial,slow,e2e}+coverage-full-reportin e2e.yml produce the self-contained fullCorpus number (full e2e glob included) and thecoverage-full-mergedtrend artifact. Collection isCOVERAGE_DIR-opt-in intest-shard.sh/run-serial-tests.sh/run-e2e.sh— unique coverage dir per bun process (a reused dir overwriteslcov.info), lane manifest written only on a green run,run-e2e.shrequires an ABSOLUTECOVERAGE_DIRand honorsE2E_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, sosrc/cli.tsundercounts. Pinned bytest/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 ofvalidate.ts(--robot-secondsceiling, default 1200 PGLite, 880 Postgres;--robot-scope=pr|full,--explore-day; CI:persistence-validation.yml).ops.tsis 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 agentverifyAccessTokenresolves), a source, a fixed request id and arguments whose{ $ref }values come from earlier observations; workers run each op through its registered handler. ItsretryingReadretries the robot's reads only across a session drop theSessionDropsledger shows it injected; any other closed connection fails the run.generator.tsbuilds 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.tsis 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_SEAMSmaps everyEffectKindto its trigger op and seam (typecheck-exhaustive).crash-robot.tsruns a schedule in-process or as a worker role (count,runfrozen at afault-points.tsseam and SIGKILLed by the driver,recover), plus process faults (staleindex.lock, a hung git commit holding it, Postgres session drops, the owner killed after afacts-absorbextraction commits, then the job re-run).robot-driver.tsruns 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, nightlyexplorationSeeds(day);over_budgetfails it past the ceiling. Postgres connects throughGBRAIN_PGBOUNCER_URLwhen set and, in theprscope, 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 aslease_bound_seams_skippedandlease_bound_faults_skipped.shrink.tsis dependency-preserving ddmin accepted on 3/3 reproduction;--replay/--shrinkre-run a manifest's failing runs.lock-order.tstraces each transaction's row locks (worktrees before sources, sources by id, no exclusive brain lock in a publication).history-fixture.tsexportsbuildHistoryFixture(engine, { pages, seed, sources, worktrees })(real persistence history up to 10k pages; engine graduation, attribution backfill) andprepareTopology.would-have-caught.tsreverts each fix inwould-have-caught.jsonin 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 intest/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.tsbuilds the 1k/10k history brains (buildHistoryFixtureplus 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.tsspawns 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.tstimes 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.tsruns 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 originaltests/heavy/read_latency_under_sync.shinvokes this runner. The stable admission proxy requires one resolved top-level queued journal transaction per committed UUID.test/persistence-performance.test.tsguards validity, strict threshold semantics and advisory CLI exit behavior;test/persistence-admission-observer.test.tsproves rollback/publication boundaries;test/persistence-read-diagnostics{,.serial}.test.tscovers 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;--relationaladdsrelational/corpus.ts+ its 38RELATIONAL_QUESTIONS, which with the fixture's owngraph-relationshipquery are the 39 relational questions the receipt reports beside the 11 non-relational core queries). Arms are applied withengine.setConfig(ARM_PINS: OFF =search.mode balanced,search.reranker.enabled false,search.autocut false; ON addssearch.reranker.enabled true+search.reranker.model voyage:rerank-2.5; autocut pinned off in both by default — a rerank-only comparison — and--autocut on|offis an overlay applied to BOTH arms throughapplyArmPins(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 barehybridSearchresolves them the way a production balanced brain would; scoring reusesrunRetrievalQuality/evaluateGate(no local hit@k). Per query it records deduped top-3, the rank-1evidence/create_safetytier, finite-rerank_scorerow count and thedegradedstamp. INVARIANTS: readiness (rerankerReadinessForEngine) is checked BEFORE any spend and the ON arm must show noreranker_skipped/rerank_passthroughstage 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).r1Verdictis 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-embedis the hermetic dry run (embed transport throws, OFF arm only, ON reported as skipped — needsVOYAGE_API_KEY).--jsoncarries_meta.metric_glossary(hit@1,hit@3,mrr,create_safety); exit 0 PASS/dry-run · 1 FAIL · 2 integrity/usage. Receipt (shippedbalanced,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; WITHsearch.relational_rerank_pinat 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|offoverlayssearch.relational_rerank_pinon BOTH arms: the no-pin cell is--relational-pin off(or0); the default cell omits the flag and resolves the bundle default 3 exactly as production does. Pinned bytest/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-listflag that prints the resolved file list and exits (used byci-local.sh's startup smoke-test). Falls back totest/e2e/*.test.tsplustest/phantom-redirect-engine-parity.test.tswhen 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 exportsGBRAIN_TEST_ALLOW_DATABASE_URL=1so the bunfig preload guard (test/helpers/database-url-guard-preload.ts) lets the run start, unsetsGBRAIN_DATABASE_URL(the e2e suite runs onDATABASE_URLonly — an ambientGBRAIN_DATABASE_URLwould pass the opt-in yet reach CLI-subprocess paths with no name floor), and its GBRAIN_* env scrub preservesGBRAIN_E2E_ALLOW_DBso the name-floor escape hatch the guard's own error message names stays usable. It also preservesGBRAIN_CI_DISABLE_TEST_ENV_FILE=1, keeping CI runs from loading checkout-local.env.testingcredentials after the shell-to-Bun handoff. It also exportsGBRAIN_TEST_KEEP_PROVIDER_KEYS=1so 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.tsgets 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 barebun(no outer cap) is the fallback when neither timeout binary is installed. It activates the PGLite schema snapshot like the other runners: sourcesscripts/lib/test-env.sh+ensure_pglite_snapshotafter the--dry-run-listearly exit (list mode stays instant; non-fatal on build failure), re-exportsGBRAIN_PGLITE_SNAPSHOTas 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-filedelete process.env.GBRAIN_PGLITE_SNAPSHOTopt-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.txtlists every attempted file, pass or fail;lane-manifest.json(complete:true) is written only on a green run.scripts/lib/test-env.shreceipts (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. WithGBRAIN_TEST_RECEIPT_DIRset, 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 barebun teststeps throughrun-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>.filesand Bun's JUnit report; the runner unsets the variables so tests and nested runners never inherit them (GBRAIN_TEST_RECEIPT_LANEoverrides the default lane).run-unit-parallel.shwrites receipts by default under.context/test-receipts/.run-verify-parallel.shrecords each check as pass, fail, timeout or skip (a self-skipping check printsGBRAIN_CHECK_SKIPPED: <reason>) inoutcomes.tsvand 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 resultincomplete(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 uploadreceipts-<lane>artifacts and run it report-only in theirexecuted-receiptsjobs (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.txtplus a same-commit manifest only after all selected files succeed.SHARD=N/Mproduces lanee2e-N; unsharded runs retaine2e. 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.tsclassifies the changed files (git: committedorigin/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 everytest/e2e/*.test.tsand prints "E2E narrowing is retired" (a diff map selected all files on 40 of 40 merged PRs).ci-changed-files.shlists a PR's or merge-group entry's files from the GitHub API forprepare-e2eand 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.shis the doc-only gateci:local:diffandci:ubicloud:diffrun (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_SHARDSsizes both unit matrices underUNIT_SHARD_BUDGET_MS(test/scripts/unit-shard-budget.test.ts); test.yml runsUNIT_SHARDS_PER_JOBper runner viascripts/test-shard-pack.sh(jobtest (N, M), artifacts per shard).--sumprints 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|e2evalidates 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--logabove its job cap): unit from each shard'stimings-unit-Ncapture artifact, which must record one capture start and a finalcomplete exit=0; serial fromgh run view --job <id> --log. E2E defaults to merging selected-job observations; explicit--e2e-profile full --run IDrequires 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 whenGITHUB_EVENT_NAME=schedule; else the share warns (stdout + step summary) with the lane's miner command. Tests:test/scripts/check-weight-coverage.test.tsplus 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: theplugin-doorsjob 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.tspins those boundaries. Fixed-width vector fixtures explicitly usesetupLegacyEmbeddingDB()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.tsrecognizes 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 fromtest/e2e/search-quality.test.ts:23-28for 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 listsrelevant_slugs[]+first_relevant_slug; the test computestop1_match_rate(top-1 == first_relevant) andrecall@10(fraction of relevant_slugs in top-10), asserting both meet floors (defaults>= 0.80and>= 0.85). Env-overridable floorsGBRAIN_REPLAY_GATE_TOP1_FLOOR/GBRAIN_REPLAY_GATE_RECALL_FLOOR(viawithEnv()per R1). Refresh discipline: when ranking changes intentionally move expected slugs, editqrels-search.jsondirectly with aWhy:line in the commit body or the gate degrades to rubber-stamp. Pinned bytest/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). Drivestest/e2e/whoknows.test.ts(seeds a matching synthetic brain, asserts the >=80% gate) and thewhoknows_healthdoctor 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.tsverifies 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 pureBun.spawn({terminal:})(Bun 1.3.10+; engines.bun pin in package.json; no node-pty).launchTtyspawns any CLI under a true pseudo-terminal with the hermetic env contract fromtest/helpers/agent-harness.ts(hermeticChildEnv;dropEnvstrips pass-through auth keys), records timestamped output frames, and exposeswaitFor/waitForAny/mark/sendKey/waitForQuiet/waitForExit/close. Lifecycle rule: onlyclose()clears the wall-clock kill timer — always call it in afinally. Pure helpers (stripAnsi,computeStalls,renderStallsReport,parseDriveCommand,buildClaudeTuiSeed) are unit-tested intest/tty-harness.test.ts; that file's live-PTY smokes aredescribe.skipIf(!ptySupported())-gated. Transcript writes are structurally redacted:redactSecrets(secrets ≥MIN_REDACT_SECRET_LEN→[REDACTED:<name>]) runs at every write site,coalesceSecretStraddlesmerges frames so a secret split across a frame boundary can't bypass redaction, andsaveTranscripttakes an explicitredactmap (seam — dx-explore builds it, tty-harness stays import-free of it).scripts/dx-explore.tsis 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 interactivegbrain initpickers are asserted for real intest/init-picker-pty.test.ts(serial lane, so it runs in required CI).test/cli-cwd-dotenv-quarantine.test.tsdrives its two Ctrl-C cases withBun.spawn({ terminal })directly, gated onptySupported(), because those fixtures need their exact env rather thanhermeticChildEnv.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: trueops are excluded fromoperations.filter(op => !op.localOnly); the seven sensitive localOnly ops snapshot-pinned by name) plus targeted handler-invocation guards for the HTTP-callable classes:submit_jobwithname='shell'+ctx.remote=trueMUST reject (shell-job RCE);search_by_imagewithimage_path+ctx.remote=trueMUST reject (image leak); and the list-op read-leak class —find_orphans/get_recent_salience/find_anomalies/find_expertsinvoked withctx.remote=trueover a seededvisibility: privatepage 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;excludeduntouched; anomalycountmirrors the visible slug list), and a soft-delete re-probe pinning the includeDeleted fail-closed path.file_uploadandsync_brainomitted from handler-invocation tests because they'relocalOnly: true(that path would test an impossible production scenario). The shell guard grepssrc/for any module importing theoperationsvalue outside the canonical filter site atsrc/commands/serve-http.ts(three import shapes: destructured, aliased, namespace), with an explicit 10-entry allow-list + a literal-string check thatserve-http.tsstill containsoperations.filter(op => !op.localOnly). Wired intobun 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.jsonexportsvia package name, pins a canary symbol per module, and fails when the exports map gains, loses or renames a subpath without a matchingEXPECTED_EXPORTSedit. It also importsgbrain/versionin a fresh process and pins that it exports onlyVERSION(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 throughdispatchToolCall(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_memorychannel 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 itsmcp.*gate; plus aPARAM_FACTORYentry if it can return corpus data — the failure message prints exactly what to add). A separate arm asserts everylocalOnlyop is denied fail-closed over non-stdio transports;KNOWN_EXPOSEDop-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.tsbypassesdispatchToolCall) 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.