Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.59.20.0 test: retire blind tests and dead modules, fill coverage holes, redact source webhook secrets (#5692)
Garry Tana9c46ffbf684
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex d387ace420..2ae810908e 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.18.0",+ "version": "0.59.20.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 759d93b3d8..b12fbc6d80 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.18.0",+ "version": "0.59.20.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex 0d5362836f..99b1377844 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -263,7 +263,7 @@ jobs:# (test/e2e/helpers.ts) as the other DB-backed files on this line.# Also added to the E2E_EXCLUSIONS in scripts/e2e-matrix.ts so a PR# touching sync.ts doesn't run it a second time there.- run: bun test --timeout=60000 test/e2e/mechanical.test.ts test/e2e/mcp.test.ts test/e2e/job-isolation.test.ts test/e2e/sync-reconcile-postgres.test.ts+ run: bun test --timeout=60000 test/e2e/mechanical.test.ts test/e2e/job-isolation.test.ts test/e2e/sync-reconcile-postgres.test.tsenv:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test# #3485 preload guard: this job intentionally tests against a DB.diff --git a/.gitignore b/.gitignoreindex 360bf3aad6..0416d77f18 100644--- a/.gitignore+++ b/.gitignore@@ -5,6 +5,8 @@ node_modulesbin/.DS_Store*.log+# Committed test-audit evidence (mutation-probe and measured-run logs).+!docs/test-audit/**/*.log.env.env.*!.env.*.examplediff --git a/.gitleaks.toml b/.gitleaks.tomlindex 2bec03e5b5..33692de4b2 100644--- a/.gitleaks.toml+++ b/.gitleaks.toml@@ -20,7 +20,7 @@ condition = "AND"paths = ['''^test/(auth-register-client-output-pin|claw-test-cli|config|config-get-plane|google-access|google-auth|mcp-registration-blocks|secret-scan|session-receipts|tty-harness|transcript-render)\.test\.ts$''','''^test/creds-vault\.serial\.test\.ts$''',- '''^test/e2e/transcripts-ingest-pglite\.test\.ts$''',+ '''^test/transcripts-ingest-pglite\.test\.ts$''','''^\.claude/skills/gstack/(browse/test/commands|test/skill-e2e-cso)\.test\.ts$''',]regexTarget = "secret"diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex a5851c2e65..bbb14395c4 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.59.18.0 -->+<!-- gbrain-runbook-stamp: 0.59.20.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fe0f9b2597..59e4781445 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,68 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.59.20.0] - 2026-09-29++**Two commands could print a source's webhook secret, and hundreds of tests in gbrain's own suite guarded nothing: they stayed green with the code broken, or tested code the product never runs. Both are fixed.**++Security first. If you attached a folder to an existing source that already had a GitHub webhook secret, `gbrain call sources_add` and `gbrain sources add --path` printed the whole source record, secret included, and the second one also kept that record in the database's change history. Both now hide the secret. Setting or rotating a webhook still shows the new secret exactly once, because you need to paste it into GitHub.++The rest of the release is a cleanup of gbrain's own test suite, done the careful way: every test we removed was first shown to stay green while the code it claimed to guard was deliberately broken, and every hole that turned up got a real test before anything was deleted. About 5,000 lines of tests that could not fail and about 4,700 lines of code nothing ever ran are gone. Along the way the new tests caught a real bug: a sync interrupted twice in quick succession left its lock behind for 30 minutes. That is fixed too.++### What changes for you++| Situation | Before | Now |+| --- | --- | --- |+| `gbrain call sources_add` attaching a path to a source with a webhook secret | Printed the secret | Secret hidden |+| `gbrain sources add --path` (managed) in the same case | Printed the secret and kept it in the change history | Hidden in the output, the replay and the stored record |+| `gbrain sources webhook set` | Printed the new secret twice | Printed once, in the paste block |+| A sync killed by two signals at once (for example `gbrain sync \| head` then Ctrl-C) | Lock stayed for 30 minutes | Lock released before exit |+| Guides naming commands or flags that do not exist | Nothing noticed | A test fails; 13 stale guides fixed |++### How to use it++Nothing to configure. If you rely on attaching paths to webhook sources, re-run the command; the output no longer carries the secret. To see a webhook secret, rotate it: `gbrain sources webhook rotate <source>`.++### Things to watch++- Full-database backups still contain source configs, secrets included, by design: restoring a brain needs them. Treat backup archives as sensitive, as `gbrain backup` already warns.+- `gbrain config set auto_chronicle true` has done nothing since v0.51.0.0, and `gbrain onboard --history` always returns empty. We did not delete the code behind them; both are filed as P1 follow-ups.++### What we caught and fixed before merging++The plan went through CEO, developer-experience and engineering reviews with two independent AI reviewers each. They stopped us from deleting code that user docs still promise (the inbox folder, the greenfield importer and the `gbrain/ingestion` daemon stay until that is a product decision), from treating the webhook rotate reveal and full backups as leaks, and from replacing weak tests with new checks that still could not fail.++### Itemized changes++**Security**+- `src/core/ops/sources.ts`, `src/core/persistence/source-lifecycle.ts`: attach-path receipts go through `redactSourceConfig()`; the retained `persistence_topology_changes` record and its replay are redacted too. `src/commands/sources.ts`: `webhook set` prints the secret once.+- New `test/source-config-secret-surfaces.test.ts` covers every surface that serializes source config (sources CLI human/`--json`, remote MCP `sources_list`/`sources_status`/`get_status_snapshot`/`run_doctor`, `doctor --json`, admin `GET /admin/api/sources`, backup metadata, restore receipts, `GBRAIN_HOME` logs) and pins the create/rotate one-time reveals. `scripts/check-source-config-leak.sh` header lists the audited surfaces.++**Bug fix**+- `src/core/process-cleanup.ts`: later signals await the in-flight cleanup pass (`cleanupPass ??= runCleanupCallbacks()`), so a second signal no longer exits before the sync lock row is deleted. Unit and real-process E2E regressions.++**Coverage holes filled** (each new test fails on a targeted mutation; the old tests passed it)+- `gbrain features` shipped output, supervisor health reconnect (all five arms), embed default concurrency on both pools, experimental schema verbs, `check-resolvable` fix shapes, image OCR opt-in through `importImageFile` (seam `_maybeOcrGatedForTests` removed), `postgres-engine.ts` routed to its singleton E2E owners, a real-process SIGPIPE lock-release test (50/50 under load), embed pool abort, singleton lifecycle races, backfill registry.++**Tests removed** (evidence per test in `docs/test-audit/2026-09-29/` and the PR)+- 42 test files and ~130 individual cases: source-text pins that passed with behavior broken or failed on renames, doc phrase pins, copied-function tests, `typeof` export probes, tautologies, byte-identical duplicates, `expect(true)` placeholders, a stale MCP E2E that re-implemented the tool mapping, and duplicate E2E runs (attendance PGLite arms, `reconcile-crash` now owned on PRs by `persistence-validation.yml`).+- 15 source-grep test files rewritten as behavior tests; one table-driven `test/doc-claims.test.ts` replaces one-off doc pins.++**Dead code removed** (no runtime caller; per-module disposition in the PR)+- 24 modules across the misc, calibration and minions clusters, including the never-wired minions budget tracker, self-fix and lease-cap controller, calibration E3/E5/E7/E8 surfaces, `upgrade-checkpoint` and `brain-pack-lint`; test-only seams such as `_resetRerankWarningsForTest` (was reachable from the `gbrain/ai/gateway` export). The `take_nudge_log` migration stays. Ingestion, progressive-batch, chronicle backstop, onboard impact capture and archive-crawler config are held.++**Guards and docs for contributors**+- `scripts/check-orphan-modules.mjs`: the test-only count ceiling becomes a named `PERMITTED_TEST_ONLY` list with reasons; new or stale entries fail with a remedy.+- New `bun run check:test-placeholders` (AST scan for no-op `expect(true)` assertions) in `verify`.+- `test/test-reads-source-smell.test.ts` now sees `join(...)`, `Bun.file`, `readFile` and path-constant reads, requires a category tag on `test-reads-source-ok` markers, and ratchets unjustified read sites per file.+- Docs-CLI truth check: `gbrain <verb> --flag` in `docs/guides`, `docs/migrations` and `skills` must resolve against the real CLI (`<!-- gbrain-cli: historical -->` marker for history).+- `docs/TESTING.md`: authoring gate (4 questions), "Retiring a test" with an evidence template, lane-move pilot table, live-key E2E run commands, `reconcile-crash` ownership.++**CI lanes**+- 20 PGLite-only `test/e2e` files moved to the unit (10), serial (7) and slow (3) lanes; the Ubicloud E2E lane drops ~300 s and the moved files now run on every PR. Key-gated OpenRouter/Voyage live files leave the default `run-e2e.sh` list (by-name runs still work).++**Contributor note:** deleted and moved tests are listed in the PR; `check:test-placeholders`, the stricter source-read policy and the orphan permitted list are new `verify`/unit rules, and each failure message names the fix and a `docs/TESTING.md` anchor.+## [0.59.18.0] - 2026-09-29**Dream no longer keeps made-up quotes, wrong-speaker quotes or invented numbers as memory, and `gbrain eval compare` computes the statistics it claims.**diff --git a/CLAUDE.md b/CLAUDE.mdindex 0c098224ec..288b3c4990 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -160,7 +160,7 @@ detail on demand.)| publishing the brain's MCP server to other devices and agents (`gbrain mcp expose`, Tailscale default, Grok Bot / Muse hosted path) | `docs/guides/remote-mcp.md` + `docs/mcp/DEPLOY.md` + the `remote-mcp` skill || memory verbs / MCP tool surface (`--surface`) / conformance | `docs/protocol/MEMORY_VERBS_v1.md` + the `verbs*`/`surface.ts`/`protocol.ts` entries in `KEY_FILES.md` || the CLI surface (commands + flags) | `gbrain --help` / `gbrain --tools-json`, plus the relevant `KEY_FILES.md` entry |-| running or writing tests | `docs/TESTING.md` |+| running, writing or retiring tests | `docs/TESTING.md` ([authoring gate](docs/TESTING.md#authoring-gate), [retiring](docs/TESTING.md#retiring-a-test)) || bulk-command progress wiring | `docs/progress-events.md` || eval methodology / metrics | `docs/eval/` || brains vs sources / topology | `docs/architecture/brains-and-sources.md`, `topologies.md` |@@ -172,9 +172,7 @@ detail on demand.)The per-file index (`## Key files`), the thin-client routing seam, and the testingdiscipline used to live inline here. They moved to the docs above so this file-stays small enough to load every session. Nothing was lost — the pre-move content-is in git, and the docs carry every load-bearing invariant (compressed to-current-state).+stays small enough to load every session.## Maintaining CLAUDE.md and the reference docsdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ffd4996ebe..fd44d77b3a 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -85,9 +85,8 @@ skills/ Fat markdown skills for AI agentstest/ Unit tests (bun test, no DB required)test/e2e/ E2E tests (requires DATABASE_URL, real Postgres+pgvector)fixtures/ Miniature realistic brain corpus (16 files)- helpers.ts DB lifecycle, fixture import, timing+ helpers.ts DB lifecycle, fixture import, diagnosticsmechanical.test.ts All operations against real DB- mcp.test.ts MCP tool generation verificationskills.test.ts Tier 2 skill tests (requires OpenClaw + API keys)docs/ Architecture docs```@@ -214,11 +213,21 @@ Vacuous-assertion shapes to avoid (they recur):- asserting a substring that would also appear in the broken output —assert parsed structure instead.-Relatedly: a test whose only assertion is a regex over `readFileSync`'d-source text pins spelling, not behavior. New tests that read `src/` text-need a `test-reads-source-ok: <why>` comment (or a behavioral assertion-alongside); `test/test-reads-source-smell.test.ts` enforces this for new-files and ratchets the pre-existing list down.+Before adding a test, answer the four questions in the+[authoring gate](docs/TESTING.md#authoring-gate); before deleting one, follow+[Retiring a test](docs/TESTING.md#retiring-a-test) and record its evidence+table in the PR body.++Relatedly: a test whose only assertion is a regex over source text pins+spelling, not behavior. A test that reads `src/` text (`readFileSync`,+`readFile` or `Bun.file` on a `src/` path, directly or through a path+constant) needs a tagged marker on or just above the read:+`// test-reads-source-ok[<category>]: <why>`, with the category one of+`prompt-byte`, `trust-boundary`, `generated-artifact`, `structural` or+`raw-bytes`. `test/test-reads-source-smell.test.ts` enforces this and ratchets+pre-existing files by their exact count of unjustified read sites. It counts+read sites only, so new assertions over an existing source binding still need+the authoring gate. See [Source reads in tests](docs/TESTING.md#source-reads-in-tests).### Local CI gate (recommended before pushing)diff --git a/TODOS.md b/TODOS.mdindex 81ec6b4613..ee403ce18f 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,42 @@# TODOS+## Test-audit follow-ups (filed 2026-09-29)++Evidence for each item is in `docs/test-audit/2026-09-29/`.++- [ ] **P2 — Reusable test-audit scanners under `scripts/test-audit/`.**+ **What:** the 2026-09-29 audit inventories (source-read pins, typeof probes, placeholder assertions, near-duplicate files, test-only exports, unreachable modules) came from one-off scanner scripts that were not committed. **Fix:** rewrite them as maintained `scripts/test-audit/*` commands with fixtures, so the next audit re-runs them instead of rebuilding them, and so their output format matches the committed inventories. **Effort:** M. **Priority:** P2.+- [ ] **P2 — CI mutation-probe job for changed tests.**+ **What:** the audit found many tests that pass when the behavior they name is broken. Nothing in CI checks that a new or changed test can fail. **Fix:** an opt-in (then required) job that, for each changed test file, applies a small set of targeted mutations to the production code it imports and reports tests that survive every mutation; start advisory and graduate with a budget per PR. **Effort:** L. **Priority:** P2.+- [ ] **P3 — Per-symbol review of 136 dead-in-prod exported functions.**+ **What:** `docs/test-audit/2026-09-29/lane-seams/seams.md` §3.4 lists 136 exported functions with no reference outside tests (beyond the test-seam names and dead modules the plan already handles). **Fix:** review each: wire it, make it module-private, or delete it with its tests, one small PR per subsystem. **Effort:** M. **Priority:** P3.+- [ ] **P2 — Extract a testable autopilot tick function, then retire the 8 autopilot wiring greps.**+ **What:** 8 test files (~75 tests: auto-drain, cycle-failure-classification, fanout-wiring, nightly-probe-wiring, parser-probe-wiring, shutdown-engine-close, supervisor-wiring, self-upgrade) pin the inline autopilot tick body as source text because no callable tick exists. **Fix:** extract the tick into an exported function with injected clock, engine and job submitter, cover each wiring behavior with a real call, then delete the source greps. **Effort:** M. **Priority:** P2.+- [ ] **P3 — Speed passes on `test/helpers/reset-pglite.test.ts` (~15 s) and `test/docs-navigation.test.ts` (~3.5 s).**+ **What:** the two most expensive files in their audit lanes. `docs-navigation` is the only Markdown link and fragment checker, so it must stay; scope or cache its parsing instead. **Fix:** profile both and cut repeated setup (shared engine or fixture reuse for the reset helper; parse each doc once for the link checker). **Effort:** S. **Priority:** P3.+- [ ] **P3 — CONTRIBUTING.md "first green test" block.**+ **What:** a contributor has no single keyless path from clone to one passing test. **Fix:** add a block with a keyless clone, `bun install --frozen-lockfile`, and one small representative test command with its expected output, measured once on a clean checkout. **Effort:** S. **Priority:** P3.+- [ ] **P3 — `gbrain features` dead-links check: remove or justify.**+ **What:** `scanFeatures` recommends "Fix Dead Links" when `getHealth().dead_links > 0`, but `links.to_page_id` cascades on page delete on both engines, so that count cannot become non-zero and the recommendation never fires. `test/features.test.ts` covers every other check and deliberately does not stub this one. **Fix:** delete the check (and the matching `featuresTeaserForDoctor` clause), or document a third-party engine or schema state that can produce dangling links and test it there. **Effort:** S. **Priority:** P3.+- [ ] **P3 — Supervisor: decide whether a failed reconnect should retry on every later failing tick.**+ **What:** after the third consecutive health failure the supervisor warns and calls `engine.reconnect()`. A failed reconnect leaves the failure counter at 3 or more, so every later failing health tick warns `db_connection_degraded` and reconnects again (pinned as current behavior in `test/supervisor-health-reconnect.test.ts`). No doc or CHANGELOG entry says whether that per-tick retry is intended. **Fix:** confirm it is intended and document it, or add a backoff between reconnect attempts and update the test. **Effort:** S. **Priority:** P3.+- [ ] **P1 — `auto_chronicle` does nothing since v0.51.0.0.**+ **What:** v0.51.0.0 moved the facts backstop onto the effects queue and dropped the chronicle backstop, so `gbrain config set auto_chronicle true` has no reader (`isAutoChronicleEnabled` is only called from the unwired `src/core/chronicle/backstop.ts`), yet the advisor still tells users to enable it. **Fix:** restore the chronicle backstop on the effects queue, or retract the setting and the advisor text. `backstop.ts` is held in the orphan guard's permitted set until then.+- [ ] **P1 — `gbrain onboard --history` always returns nothing.**+ **What:** `src/core/onboard/impact-capture.ts` is the only writer of `migration_impact_log`, which `onboard --history` reads, and it has no runtime caller. **Fix:** wire impact capture into the migration path or retract `--history`. Held in the orphan guard's permitted set.+- [ ] **P2 — archive-crawler `scan_paths` safety fence is documented as enforced but is not.**+ **What:** `skills/archive-crawler/SKILL.md` says the fence is enforced by `src/core/storage-config.ts`; the enforcing module `src/core/archive-crawler-config.ts` is unwired. **Fix:** wire the check or correct the skill text. Held in the permitted set.+- [ ] **P2 — Progressive-batch rewire or retire.**+ **What:** the progressive-batch orchestrator, retrofit-wrap and stage-report modules lost their callers in #1519 while an open item (see the progressive-batch entry below) still plans to rewire them. **Fix:** decide rewire vs abandon; held in the permitted set until then.+- [ ] **P2 — `gbrain embed --all` exits 0 with pages unembedded when the page snapshot read throws.**+ **What:** in the `--all` pool path the worker pool swallows a thrown snapshot read, so the run reports `failures: 0`. Same class as #3037. **Fix:** count the error as a failure and exit non-zero; add a test that throws from the snapshot read.+- [ ] **P2 — `gbrain auth rescope-client … --dry-run` and `auth local-writer register … --dry-run` fail with "unknown flag".**+ **What:** the handlers read `--dry-run`, but the generated flag registry drops it for `auth` (the generator deletes `--dry-run` unless it finds a quoted use in the command's own module). Two guides document these commands and are allowlisted in the docs-CLI truth check. **Fix:** teach the generator about delegated handlers, regenerate, and remove the allowlist entries.+- [ ] **P3 — `jobs watch` budget-owners panel reads columns only the deleted minions budget tracker wrote.**+ **What:** the panel now always renders empty. **Fix:** remove the panel or feed it from the live budget meter. Also `RECOVERABLE_CLUSTERS` in `error-classify.ts` has no consumer left.+- [ ] **P3 — Seven remaining CLI flag mismatches in README and `docs/` outside the truth-check scope** (for example `recall --entity`, `dream --slug`). Listed in the test-reduction wave PR description; extend the truth check to README and `docs/**` and fix them.+- [x] **P2 — A second signal during the cleanup pass exits before the lock is released.** **Completed: 2026-09-29 (test-reduction wave)** — `runCleanupPass` in `src/core/process-cleanup.ts` now keeps the in-flight pass promise, so a later signal or stdout `EPIPE` waits for that pass (still bounded by its 3s deadline) before exiting; callbacks still run once. Pinned by `test/process-cleanup.test.ts` (SIGTERM, then SIGPIPE, then a stdout `EPIPE` during a held cleanup: no exit until the callback finishes) and `test/e2e/sync-lock-recovery.test.ts` (closing the sync output pipe the moment the lock row appears leaves no lock row). Before the fix, closing the pipe at the lock boundary leaked the `gbrain-sync:default` row 6 of 6 times; after it, 0 of 20. The stdout/stderr `EPIPE` listeners stay: under Bun 1.3, writes through `console.log` surface only as SIGPIPE, but writes through `process.stdout.write` also emit `EPIPE` error events on the stream (measured with a shell pipe, a Bun parent and a Node parent), so the listeners are reachable.+## Skillopt honesty + model provenance wave follow-ups (filed 2026-09-28, #5584 / #5585 fix wave)- [ ] **P1 — TODO-D: validated Anthropic default-model migration.**@@ -642,7 +679,7 @@ deferred M-effort issues above are NOT repeated here.across the cut is lost to both. **Blocked on:** post-wave Cat 35 receiptsshowing transcripts actually chunk (`details.synthesis.jobs` >`transcripts_processed`) — don't pay the determinism-test churn- (test/e2e/dream-synthesize-chunking byte-stability) before the receipts say+ (test/dream-synthesize-chunking.serial.test.ts byte-stability) before the receipts sayit matters. **Where:** src/core/cycle/synthesize.ts splitTranscriptByBudget.- [ ] **P3 — E3: borderline-band second-pass triage call (#4152 escalation).****What:** when the scalar score lands in [rescue_floor, threshold) and the@@ -2248,6 +2285,7 @@ Each was explicitly deferred in the pass's CEO/eng/outside-voice reviews.the existing SHARD support (only ci-local uses it). Fold into the Postgrestemplate-database entry below in this file (CREATE DATABASE … TEMPLATE, ~50ms).**Current status:** selected E2E is on the measured PR critical path. Four isolated weighted CI workers now address it without moving tests between lanes; PGLite-only lane moves remain deferred. **Effort:** M. **Priority:** P2.+ **Status (2026-09-29 test audit):** the audit counted 113 PGLite-only files in `test/e2e` (`docs/test-audit/2026-09-29/lane-e2e/pglite-files.txt`). The test-reduction pilot moved the 20 heaviest into the unit (10), serial (7) and slow (3) lanes (docs/TESTING.md "Lane-move pilot"). Matched `ci:ubicloud` runs: the E2E lane dropped from 304 files/2,756 s to 284 files/2,456 s of compute; the moved files cost 330 s in E2E and 340 s in their new lanes, and wall time stayed bounded by the slow-lane long poles (317 s vs 337 s). On GitHub the gain is the sequential selected-E2E workers losing ~506 s of weighted work while every PR now runs these files. Next: move the remaining ~93 PGLite-only files with the same criterion, and add an explicit unit-owned set to `scripts/select-e2e.ts` so sources whose only E2E owner moved stop failing closed to all E2E.- [ ] **Second PGLite snapshot keyed by dims/model.** Implemented for BrainBench default-profile CLI children in the CI optimization pass; extending reuse to other deliberately reconfigured tests remains deferred. **What:** ~34 test filesconfigure retired-embedding/1280 and always cold-init (the snapshot's shape gate correctlyrefuses the 1536 fixture). Bake a second snapshot per shape; the version-file@@ -2474,6 +2512,7 @@ review-deferred, not fix-now). Grouped by component.hasDatabase/DATABASE_URL gate + header read; lockstep: e2e-test-map rows,e2e-unmapped-baseline shrink, classify-tests, seeded weights), a possiblefour-way `coverage-full-e2e` nightly matrix, and unit matrix 10→12.+ **Status (2026-09-29 test audit):** Phase 5 is superseded by the test-reduction plan's lane-move pilot (the 20 heaviest of 113 PGLite-only `test/e2e` files, same move criterion and lockstep updates, measured on matched runs); the pilot landed (see the PGLite-only lane entry above for the measurement and next step).The selected-E2E matrix, timing refresh, `weights:mine` command, and refreshcadence are completed by the CI speed pass above. Graduated batch gates:5×-green first batch per class, 2×+CI@@ -4052,9 +4091,10 @@ infra and reaches into third-party packs that live outside the host skills dir.> `list_brain_skillpack` op (NOT folded into `list_skills` — the host catalog is> host-global and ignores `ctx.sourceId`, so per-source packs needed their own> tenancy-correct surface). `get_skill` gained an optional `source_id` for-> per-source fetch disambiguation. The `tools:` version-skew lint below is now-> implemented (`src/core/skillpack/brain-pack-lint.ts`, run by-> `gbrain skillpack init-brain-pack`). STILL DEFERRED to this PR2: thin-client+> per-source fetch disambiguation. The `tools:` version-skew lint below was+> written (`src/core/skillpack/brain-pack-lint.ts`) but never wired into+> `gbrain skillpack init-brain-pack`, and was deleted in the test-reduction fix+> wave. STILL DEFERRED to this PR2: thin-client> BINARY install (`build_skillpack` download) — a thin client today gets the> pack's git scaffold spec and `resolveSource`s it on its own machine. The> `include_skillpacks` host-global merge below is intentionally still open@@ -4902,7 +4942,7 @@ note. Filing it as a TODO would imply it's ready to pull; it isn't.CEO D16. Closes the unbounded-growth concern that codex flagged asload-bearing pass-3 #5.-- [ ] **v0.41.1: full E5 A/B dispatcher (currently scaffolded as dry-run only).**+- [x] **v0.41.1: full E5 A/B dispatcher (currently scaffolded as dry-run only).** **Closed in the test-reduction fix wave:** the lease-cap controller never had a runtime caller; it, its tests, `scripts/e5-lease-cap-ab.ts` and the dry-run receipt fixture were deleted.`scripts/e5-lease-cap-ab.ts` ships the spec + harness + receipt fixtureshape but the real-run dispatcher (queue submit + worker spin-up + 15-min429 injector + tick loop + cost-tracking) is deferred. v0.41.1 follow-up@@ -4921,7 +4961,7 @@ note. Filing it as a TODO would imply it's ready to pull; it isn't.case, already shipped); one accepts an existing tx (rate-leases +maxWaiting use cases). Filed via Eng D9.-- [ ] **v0.42: semantic-aware `prompt_too_long` reduction in E6 self-fix.**+- [x] **v0.42: semantic-aware `prompt_too_long` reduction in E6 self-fix.** **Closed in the test-reduction fix wave:** `src/core/minions/self-fix.ts` never had a runtime caller and was deleted.v0.41 ships truncate-with-leaf-preservation (first 1000 + last 2000 chars).Codex pass-1 #11 specified the right strategy: walk the conversation, droptool_result blocks first (largest non-task content), summarize older@@ -5418,7 +5458,9 @@ at plan time and got carved out:with the right shape so these drop in cleanly.- [ ] **v0.40.7+: T16 — hermetic schema-authoring eval gate.**- Extend `src/commands/eval-schema-authoring.ts` into a PGLite harness+ Rebuild `gbrain eval schema-authoring` as a PGLite harness (the unwired+ v0.39 scaffold and its `aggregateVerdict` were deleted in the test-reduction fix wave;+ recover them from git history)driving detect → suggest → add-type → sync end-to-end on 3 fixtures.Filing-accuracy delta metric (not top-3 hit rate per codex C18). DIseam via `suggestFn`. 3 hours CC + placeholder-name fixtures.@@ -5644,7 +5686,7 @@ contributor traps.- [ ] **T18 follow-through — DELETE `skills/_brain-filing-rules.{md,json}`.** v0.39.0.0 shipped step (a) of the 4-step deprecation sequence: `gbrain schema show --as-filing-rules` emits the JSON shape the legacy file held. v0.39.1 ships steps (b) + (c) + (d): migrate `filing-audit.ts:79`, `synthesize.ts:619`, `patterns.ts:305`, `check-resolvable.ts:196+:226` to consume `gbrain schema show --as-filing-rules` output; update 5 test files (filing-audit.test.ts, check-resolvable.test.ts, dry-fix.test.ts, resolver.test.ts, cycle-patterns.test.ts); then DELETE the two files. Codex finding #3 from /plan-eng-review made this load-bearing — premature deletion makes protected synthesize/patterns phases fail with NO_ALLOWLIST. Sequencing matters.- [ ] **T19 follow-through — per-source pack federation across mounts.** v0.39.0.0 ships the correct REJECTION posture (`SchemaPackTrustGateError` when sources resolve to divergent packs). v0.40 ships the true per-source closure via `buildPerSourceBindings` + `buildSourceClosureCte` (engine already provides; the read-path callers need to thread the per-source pack identity through the SQL generation step). Reference: codex finding #2 from /plan-eng-review.-- [ ] **T16 follow-through — hermetic eval-schema-authoring CLI harness.** v0.39.0.0 ships the aggregator (`aggregateVerdict`) + scaffold; v0.39.1 wires the in-process PGLite engine + fixture brain replay (3 fixtures: 1 hand-curated `notion-refugee` + 2 synthetic via faker per D6(eng)). Pattern: mirror `src/eval/longmemeval/harness.ts`.+- [ ] **T16 follow-through — hermetic eval-schema-authoring CLI harness.** v0.39.0.0 shipped the aggregator (`aggregateVerdict`) + scaffold, deleted unwired in the test-reduction fix wave (recover from git history); v0.39.1 wires the in-process PGLite engine + fixture brain replay (3 fixtures: 1 hand-curated `notion-refugee` + 2 synthetic via faker per D6(eng)). Pattern: mirror `src/eval/longmemeval/harness.ts`.- [ ] **T1.5 follow-through — wire `whoknows` / `find_experts` / `enrichment-service` / `facts/eligibility` to consume pack-aware type sets.** v0.39.0.0 added the seam (`activePack` parameter threaded through parseMarkdown/import/sync). The runtime sites that compute their type filter still use the v0.38 hardcoded constants. v0.39.1 migrates each call site to read from `loadActivePackForOp(ctx)` + use `expertTypesFromPack` / `extractableTypesFromPack` (helpers already exist in `src/core/schema-pack/`). Per the T19 closure fix, this is now safe to wire (federated_read with divergent packs throws permission_denied at the load step).- [ ] **D14 thesis retro — authoring vs derivation framing.** v0.39.0.0 ships the cathedral with 6 verbs marked experimental-tier + T15 schema-events audit + T23 `gbrain schema usage` for measurement. v0.40+ retro reads 60-90 days of usage telemetry and decides which experimental verbs to deprecate per codex's derivation-thesis structural argument. Pass condition: each verb gets >=5% of the cathedral's invocations. Below 5% = deprecation candidate.@@ -5669,9 +5711,9 @@ contributor traps.- [ ] **Async-batched audit writes.** Sync `appendFileSync` is fine at typical volumes (~5ms × 100 crosses = ~500ms — not noticeable inside a $1 brainstorm run). Profiling trigger criterion: when 100+ crosses on a large brain shows audit-write time dominating wall-clock cost, switch to an async write queue. Fixing prematurely costs complexity for no measurable benefit.-- [ ] **`BudgetLedger` unification with `BudgetTracker`.** `src/core/enrichment/budget.ts` defines a separate `BudgetLedger` primitive for per-day, per-scope/resolverId enrichment caps. Different shape from `BudgetTracker` (daily reset windows + multi-tier scope keys). Unification is possible but requires careful schema design to preserve enrichment's existing report semantics. Deferred because: (a) BudgetTracker covers the per-command case cleanly today, (b) the existing BudgetLedger isn't a customer-facing surface — it backs `gbrain enrich`'s internal accounting, (c) merging them would require a schema migration on the enrichment budget audit JSONL. Revisit when the enrichment surface gets its next major touch.+- [x] **`BudgetLedger` unification with `BudgetTracker`.** **Closed in the test-reduction fix wave:** `BudgetLedger` never had a runtime caller (the claim below that it backs `gbrain enrich` was wrong; `gbrain enrich` uses `BudgetTracker`), so it was deleted. The `budget_ledger` migration stays. `src/core/enrichment/budget.ts` defines a separate `BudgetLedger` primitive for per-day, per-scope/resolverId enrichment caps. Different shape from `BudgetTracker` (daily reset windows + multi-tier scope keys). Unification is possible but requires careful schema design to preserve enrichment's existing report semantics. Deferred because: (a) BudgetTracker covers the per-command case cleanly today, (b) the existing BudgetLedger isn't a customer-facing surface — it backs `gbrain enrich`'s internal accounting, (c) merging them would require a schema migration on the enrichment budget audit JSONL. Revisit when the enrichment surface gets its next major touch.-- [ ] **judges.ts internal chunking → payload-fitter delegation.** v0.37.x ships `src/core/diarize/payload-fitter.ts` with the batch strategy ready to consume from `src/core/brainstorm/judges.ts`'s `runJudge` chunking path. Today judges.ts keeps its own copy of the chunking loop (~30 lines) — straightforward refactor: replace the inline split with `fit({strategy:'batch', items: ideas, maxTokensPerCall, estimateTokens})` and concatenate results. The cost-guardrails test suite already pins the public contract; the refactor is mechanical. Touch one function; trivial.+- [x] **judges.ts internal chunking → payload-fitter delegation.** **Closed in the test-reduction fix wave:** payload-fitter never had a runtime caller and was deleted; `judges.ts` keeps its own chunking loop. v0.37.x ships `src/core/diarize/payload-fitter.ts` with the batch strategy ready to consume from `src/core/brainstorm/judges.ts`'s `runJudge` chunking path. Today judges.ts keeps its own copy of the chunking loop (~30 lines) — straightforward refactor: replace the inline split with `fit({strategy:'batch', items: ideas, maxTokensPerCall, estimateTokens})` and concatenate results. The cost-guardrails test suite already pins the public contract; the refactor is mechanical. Touch one function; trivial.## v0.37 PGLite fresh-install fix wave — deferred follow-ups (v0.37.x+ / v0.38.x)@@ -6549,7 +6591,7 @@ After the sweep, both should be fixable and renameable back to plain `*.test.ts`- `test/e2e/cycle.test.ts` (live cycle + chunks + lock cleanup).- `test/e2e/doctor.test.ts` (gbrain doctor exits 0 on healthy DB) — possibly related to v0.26.2 schema changes since CHANGELOG mentions extension of doctor checks.- `test/brain-registry.test.ts` (empty/null/undefined id routes to host) — unrelated to OAuth surface.-- `test/e2e/claw-test.test.ts` (fresh-install scripted scenario) — needs investigation; took 3.9s and reported "produces zero error/blocker friction" failure.+- `test/claw-test.slow.test.ts` (fresh-install scripted scenario) — needs investigation; took 3.9s and reported "produces zero error/blocker friction" failure.**Why:** These failures pre-date v0.26.2 (CHANGELOG already documents "18 pre-existing master timeouts" from v0.26.0 merge). v0.26.2 brings the count to 22, suggesting a 4-test drift on master between v0.26.0 ship and now. Fixing inside v0.26.2 would balloon scope from a 6-file OAuth fix-wave to a 30+ file test-infra repair. The fix-wave deserves its own PR with focused triage.@@ -6807,6 +6849,8 @@ purpose; needs baseline-governance care per the BrainBench gate rules.**What:** Unit shards exclude `test/e2e/*` (`scripts/test-shard.sh`), and `.github/workflows/e2e.yml` runs only explicitly named files (a handful across its jobs — e.g. `test/e2e/mechanical.test.ts`, `test/e2e/mcp.test.ts`, the jsonb-parity pair); there is no glob. Every other `test/e2e/*.test.ts` — including PGLite-only files that need no `DATABASE_URL`, like `init-fresh-pglite.test.ts` — executes only when someone runs `bun run test:e2e` by hand. Decide per file: wire into a required workflow, re-home PGLite-only files to the serial lane (the pattern `test/init-picker-pty.serial.test.ts` uses), or explicitly document them as manual-only.+**Status (2026-09-29 test audit):** partly stale. Every `test/e2e` file now runs in the nightly `coverage-full-e2e` glob, and PRs run the diff-selected set (`scripts/select-e2e.ts`, falling back to all files on unmapped changes). What remains is re-homing PGLite-only files so they run on every PR regardless of the diff; that is the test-reduction plan's lane-move pilot (see the PGLite-only lane entry above).+**Why:** Tests that never run in required CI are silent coverage loss — they rot without failing. Surfaced by the TTY-harness cleanup review when the new PTY picker test almost landed in the same dead lane.**Effort:** S-M (CC ~30-60m for the audit + re-homing; workflow wiring adds CI-minutes cost per file).diff --git a/VERSION b/VERSIONindex d06303e067..c3c002d19f 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.59.18.0+0.59.20.0diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 0deee6fad7..fa46570017 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -119,7 +119,7 @@ Search reliability has real-planner and transport regressions in`test/e2e/vector-candidate-safety-postgres.test.ts`,`test/e2e/search-query-contract-postgres.test.ts`,`test/e2e/projection-statistics-postgres.test.ts`, and-`test/e2e/search-readiness-http.test.ts`. The statistics tests include owner,+`test/search-readiness-http.test.ts`. The statistics tests include owner,restricted-reader and FORCE-RLS roles; the candidate tests distinguish naturalplans from forced-HNSW controls and prove server cancellation of exact fallback.`test/e2e/projection-recovery-parity.test.ts` runs the shared Markdown/code@@ -187,6 +187,38 @@ can reduce maintenance while keeping both engine arms. Making one crash laneauthoritative or collecting LCOV in a named owner requires a separate ownershipchange; nightly sharding alone makes neither change.+The 2026-09-29 test audit's lane reports, inventories and mutation-probe logs+are committed under [docs/test-audit/2026-09-29/](test-audit/2026-09-29/README.md);+cite them for the surviving-owner and probe evidence behind a consolidation.++Recorded ownership changes:++- `test/e2e/reconcile-crash.test.ts` and `test/e2e/reconcile-crash-unactivated.test.ts`:+ the PR owner is `persistence-validation.yml`, called from `test.yml` on every+ PR on both supported Bun versions against pg16. Its "Require all+ reconciliation crash boundaries" step runs both files by name and uploads the+ crash manifests, unchanged. Both files are in `E2E_EXCLUSIONS`+ (`PERSISTENCE_VALIDATION_OWNED` in `scripts/e2e-matrix.ts`), so PR+ `selected-e2e` no longer runs them a second time; `scripts/select-e2e.ts`+ prints `excluded: <file> (owned by persistence-validation.yml)` on stderr when+ a mapped source changes. The nightly full-corpus E2E run and the local gates+ (`ci:local`, `ci:ubicloud`, their `:diff` forms) still run them. Run them+ locally with the same command the workflow uses, with `DATABASE_URL`+ exported for the test database from "E2E test DB lifecycle":++ ```bash+ GBRAIN_TEST_ALLOW_DATABASE_URL=1 \+ GBRAIN_TEST_RECONCILE_CRASH_MANIFEST_DIR=.context/reconcile-crashes \+ bun --no-env-file test --timeout=180000 \+ test/e2e/reconcile-crash.test.ts test/e2e/reconcile-crash-unactivated.test.ts+ ```++- Attendance parity (`test/attendance-retrieval.test.ts`,+ `test/attendance-repair.test.ts`, `test/extract-timeline-attendance.test.ts`):+ the unit lane owns the PGLite arm; the `test/e2e/*-postgres.test.ts` wrappers+ load the scenarios through `registerPostgresTests`, so E2E runs only the+ PostgreSQL arm.+Name the profile when reporting “all tests.” The local fast loop, `test:full`,`ci:local`, required PR checks and nightly `fullCorpus` are not interchangeablesupersets. Native matrices, sustained persistence validation, browser tests and@@ -195,6 +227,69 @@ E2E schedule does not shorten a PR critical path dominated by persistence.Report matched executed timings separately from dry-run partition estimates,including setup, queueing and retries; never count skip-only output as coverage.+### Authoring gate++Before adding a test, answer four questions in the PR description or the test+header:++1. What observable behavior or contract does it protect?+2. What credible regression makes it fail?+3. Why does existing coverage not already catch it?+4. Does it need a production seam that no production caller needs?++A regression test must fail when its fix is reverted; prove it with+`scripts/check-test-discriminates.sh` (see CONTRIBUTING.md). If question 1 has+no answer, or the answer to question 3 names an existing owner at the same+boundary, do not add the test.++Good: a test that runs `gbrain remote ping` against a fake MCP server returning+`{ status: 'failed' }` and asserts exit code 1 with the failure reason in the+JSON output. It protects a user-visible contract, fails if the poll loop reads+the wrong field, and needs no seam.++Bad: a test that reads `src/commands/remote.ts` and asserts it contains+`job.status`. It passes when the loop is broken in a way that keeps the token,+fails on a harmless rename, and duplicates the behavioral test above.++### Retiring a test++Delete or merge a test only with evidence, recorded in the PR body:++1. Name the contract the test claims to protect and classify the evidence case+ below.+2. Probe it: make a behavior-breaking edit to the production code (or, for a+ vacuous assertion, show that such an edit passes), run the test and the+ surviving owner, then revert. Behavior-preserving edits that fail the test+ are useful extra evidence of implementation coupling.+3. Confirm the surviving owner executes (executed-test counts, not skip output)+ at the same or a more frequent cadence, with an equal or stronger failure+ gate, per "Coverage responsibilities before consolidation" above.+4. Remove the deleted file's entries from `scripts/ubicloud/weights.json`,+ `scripts/test-weights.json`, `scripts/serial-weights.json` and+ `scripts/e2e-weights.json`, grep `scripts/`, `.github/`,+ `scripts/e2e-test-map.ts` and `test/fixtures/e2e-unmapped-baseline.txt` for+ the path, and regenerate `scripts/structural-suites.tsv`+ (`bun scripts/classify-tests.ts`).++Evidence cases:++- **Retained contract:** the contract still matters. Evidence is a surviving+ owner at the same boundary plus an executed mutation that fails it.+- **Intentionally abandoned contract:** the behavior is being removed or was+ never shipped. Evidence is the approved disposition plus reachability proof+ (no production caller) and a check that no user-facing promise (docs, skills,+ `--help`, CHANGELOG) still describes it.+- **Vacuous assertion:** the test asserts nothing about product behavior (a+ constant compared to itself, a copied function, a `typeof` probe that+ typecheck already enforces). Evidence is a demonstration that a+ behavior-breaking edit leaves it passing, or that it imports no product code.++Evidence template:++| Deleted test | Probe edit | Result | Surviving owner | Owner result |+|---|---|---|---|---|+| `test/x.test.ts` › "name" | `src/y.ts`: what changed | deleted test passes (blind) | `test/z.test.ts` › "name" | fails (N of M) |+### Test command tiersThe sequential E2E runner gives each test file a fresh `HOME` and `GBRAIN_HOME`.@@ -363,7 +458,7 @@ covers PGLite/Postgres page/fact/config parity. Output redaction usesManaged writer fixtures use isolated PGLite and guarded disposable Postgres:`test/e2e/fact-vector-repair-parity.test.ts`,`test/e2e/fact-embedding-backfill-parity.test.ts`, and-`test/e2e/fact-backfill-resident.test.ts` cover preserved vectors, bounded+`test/fact-backfill-resident.test.ts` cover preserved vectors, boundedNULL-only fact backfill, selected-config refusal and owner-held PGLite IPC;`test/ai/google-embed-batch-items.test.ts` pins 100-item provider batches.`test/persistence-embedding-effects.test.ts`,@@ -657,7 +752,7 @@ per-file rules. They do not cache passing results. Candidate scanner failuresfail the guard, and matching files retain the same allowlists and diagnostics.`scripts/guards-manifest.tsv` is THE single registry of `scripts/check-*`-guards (currently 48), each classified `scanner` (greps/parses repo sources —+guards (currently 56), each classified `scanner` (greps/parses repo sources —must eventually carry fixtures), `buildfresh`, or `repostate` (build/freshnessguards are exempt-with-reason, not fixture-tested).`scripts/guard-self-test.sh` (`bun run check:guard-self-test`, wired into@@ -669,10 +764,45 @@ trees under `test/fixtures/guards/<guard>/{bad,good}/` via thebuild. A guard whose pattern rots into a permanently-green no-op fails CIinstead of masquerading as coverage.+### Placeholder assertions++`scripts/check-test-placeholders.mjs` (`bun run check:test-placeholders`, in+`bun run verify`) parses every `test/**/*.test.ts` file outside+`test/fixtures/` with the TypeScript compiler API and fails on the no-op forms+`expect(true)` with no matcher, `expect(true).toBe(true)`,+`expect(true).toBeTruthy()` and `expect(1).toBe(1)`. Text inside strings and+template literals is ignored, and `expect(true).toBe(false)` fail sentinels+are allowed. Remaining sites (type-only contracts enforced by typecheck,+skip-arm markers, gates that fail by throwing) sit in a reasoned allowlist in+the script, keyed by file, test name and exact count; a site above its count+fails as new, and an entry whose file, test or count shrank fails as stale.+This is a hygiene check for one pattern, not a detector of low-value tests in+general; the authoring gate above owns that.++### Source reads in tests++`test/test-reads-source-smell.test.ts` finds test code that reads `src/` text:+`readFileSync`, `readFile` (including `fs.promises.readFile`) and `Bun.file`+calls whose arguments name a `src/` literal, a `'src'` path segment, or a+constant holding such a path. Each read site needs a tagged marker on its line+or within the three lines above:++```ts+// test-reads-source-ok[structural]: <why a source read is the right tool>+```++The category is one of `prompt-byte`, `trust-boundary`, `generated-artifact`,+`structural` or `raw-bytes`, and every marker must carry one. Files that+predate the rule are ratcheted by their exact count of unjustified read sites,+so a new untagged read in such a file fails and a count that drops must be+lowered. The ratchet counts read sites only: a new assertion over an existing+source binding is not detected and remains the authoring gate's job. Rerun with+`bun test test/test-reads-source-smell.test.ts`.+### Registry-walking ratchetsStructural suites that walk a registry so the NEXT gap of a known class-cannot ship silently. All allowlists below are shrink-only.+cannot ship silently. All allowlists below are shrink-only unless noted.- `test/operations-coverage-ledger.test.ts` — every op in`src/core/operations.ts` maps to a covering test file in a checked-in@@ -696,9 +826,30 @@ cannot ship silently. All allowlists below are shrink-only.test corpus for references, so a never-called engine method can't ship.- `scripts/check-orphan-modules.mjs` (verify battery, guard-manifestregistered with bad/good fixtures) — transitive import walk from the- cli/mcp/engine entrypoints; a src module reachable from no entrypoint- fails unless in the 4-entry reasoned allowlist, and the- test-only-reachable tier has a shrink-only ceiling.+ cli/mcp/engine entrypoints; see [Orphan-module guard](#orphan-module-guard).++#### Orphan-module guard++`bun run check:orphan-modules` walks static, dynamic and `require` relative+imports from the runtime entrypoints (CLI, MCP server, plugin engines, admin,+package `exports`). Every `src/` module it cannot reach needs a disposition:++- Imported by nothing, not even tests: fails as `hard-orphan` unless it has a+ reasoned `ALLOWLIST` entry (shrink-only).+- Imported only by tests (or scripts): fails as `unpermitted-test-only`+ unless it is named in `PERMITTED_TEST_ONLY` with a `reason`. The set may+ grow only with a reason in a reviewer-visible edit; modules reached from+ `scripts/**` use reason `script-reachable`, which the guard verifies.+- A permitted entry whose module was deleted, wired into a runtime+ entrypoint, dropped by every test, or tagged `script-reachable` without a+ `scripts/**` importer fails as `stale-permitted-entry`. Remove or correct+ the record; never restore code to satisfy the list.++Each failure prints the rule, the module, the tests that import it, the+reason, the remedy, the rerun command and this anchor. Fixture mode+(`GBRAIN_GUARD_ROOT`) reads the permitted set from+`<root>/permitted-test-only.json`; `test/scripts/check-orphan-modules.test.ts`+proves every rule fails on a bad tree.The takes-bootstrap graduation instrument (`evals/takes-bootstrap/`: 123-casecorpus, scorer, live harness + $0 replay) is CI-guarded keyless by@@ -930,7 +1081,7 @@ Four escalating tools; reach for the cheapest one that answers the question:| Question | Tool | Example ||---|---|---|| Does the TTY/non-TTY branch logic pick right? | Inject `isTTY` into the pure function — no subprocess | `test/init-provider-picker.test.ts`, `test/jobs-watch-mode.test.ts` |-| Does the real CLI behave right when stdin is NOT a terminal? | Spawn the CLI with piped/ignored stdio | `test/cli-stdin-hang.test.ts` (fast loop); `test/e2e/init-fresh-pglite.test.ts` (manual `test:e2e` lane — see the TODOS e2e CI-lane entry) |+| Does the real CLI behave right when stdin is NOT a terminal? | Spawn the CLI with piped/ignored stdio | `test/cli-stdin-hang.test.ts` (fast loop); `test/init-fresh-pglite.slow.test.ts` (slow lane) || Does the real CLI render menus and read typed input under a REAL terminal? | `launchTty` from `test/helpers/tty-harness.ts` in a `*.serial.test.ts` file | `test/init-picker-pty.serial.test.ts` || How does the install FEEL (stalls, copy, silence windows)? | `scripts/dx-explore.ts` — instrument, not a test; nothing asserts | transcripts under `.context/dx-runs/` (see `docs/guides/bootstrap.md`) |@@ -954,6 +1105,17 @@ Any change under `skills/` must regenerate it: `bun run scripts/generate-skills-`bun run verify`) regenerates to a tmp file and diffs, failing CI on drift; at runtime`gbrain doctor` reports the same drift as a warn-only `skills_manifest_integrity` check.+### Docs CLI truth check++`test/docs-cli-commands.test.ts` checks every `gbrain <verb>` in code fences and+inline code across README, docs and skills against the registered verbs. In+`docs/guides/`, `docs/migrations/` and `skills/` it also runs each invocation's+flags through the CLI's own validator, via `test/helpers/cli-command-surface.ts`.+When a hit is stale, fix the doc. When the example documents an older release,+put `<!-- gbrain-cli: historical -->` on the line above its code fence, or on the+line with the inline code. The test's `ALLOWLIST` is a last resort: it only+shrinks, every entry needs a reason, and stale entries fail.+### Test-isolation lint and helpers**This section is the canonical home of the test-isolation discipline** — CONTRIBUTING.md and other docs link here rather than restating the rules.@@ -1120,7 +1282,7 @@ deliberate (live embed/parity tests skip-gate on them). The routing-only`thin-client` fixtures still strip provider state in every child, set both`HOME` and `GBRAIN_HOME` to their temporary brain, and pass Bun`--no-env-file` (including provisioned shell commands). They exercise routing-without spending provider tokens even inside the keyed nightly lane.+without spending provider tokens even when a lane carries keys.Fixture-specific environment overrides apply last; unrelated credentials arepreserved rather than removed with a broad key-name pattern.@@ -1217,10 +1379,8 @@ Unit tests and what they cover:- `test/dry-fix.test.ts` — auto-fix: three shape-aware expander pure-function tests; five guards (working-tree-dirty, no-git-backup, inside-code-fence, already-delegated within 40 lines, ambiguous-multi-match, block-is-callout).- `test/doctor-fix.test.ts` — `gbrain doctor --fix` CLI integration: dry-run preview, apply path, JSON output shape.- `test/backoff.test.ts` — load-aware throttling, concurrency limits, active hours.-- `test/fail-improve.test.ts` — deterministic/LLM cascade, JSONL logging, test generation, rotation.- `test/transcription.test.ts` — provider detection, format validation, API key errors.- `test/enrichment-service.test.ts` — entity slugification, extraction, tier escalation.-- `test/data-research.test.ts` — recipe validation, MRR/ARR extraction, dedup, tracker parsing, HTML stripping.- `test/minions.test.ts` — Minions job queue: CRUD, state machine, backoff, stall detection, dependencies, worker lifecycle, lock management, claim mechanics, depth/child-cap, timeouts, cascade kill, idempotency, `child_done` inbox, attachments, removeOnComplete/Fail, `max_stalled` clamp/default/plumbing coverage.- `test/minion-queue-renewlock-signal.test.ts` — `renewLock` forwards its optional AbortSignal to `executeRawDirect` (stub-engine capture); legacy 3-arg calls unchanged; token-fence miss returns false.- `test/cycle-drain-renewal.test.ts` — `runDrainRenewalTick` (cycle drain): per-call signal aborted on timeout (slot released), onLost once on a lost fence, throws swallowed, hung renewal resolves at the deadline. Plus two structural source-text pins on `inline-drain.ts` (the shape guard only covers `worker.ts`): the renewal must not go back to a raw `setInterval(() => queue.renewLock(...))`, and the handler invocation must stay wrapped in `withChatPhase('job:<name>')` so a drained child's gateway spend is attributed to the child rather than absorbed by an enclosing `phase:` tag.@@ -1339,6 +1499,48 @@ Unit tests and what they cover:- `test/conversation-facts-pricing-wiring.test.ts` — `pricing.overrides` reaches every conversation-facts entry point: the strict config registry accepts the key, and direct extraction, the cycle backfill, and `transcripts --facts` all price through the operator override.- `test/cycle/extract-atoms-model-config-fail-soft.test.ts` — a throwing `getConfig` during extract_atoms model resolution falls back to the tier default instead of rejecting the phase.+### Lane-move pilot (2026-09)++The 20 heaviest PGLite-only files in `test/e2e/` (by `scripts/e2e-weights.json`)+moved out of the sequential Postgres runner into the lanes that run on every PR.+Each met the move criterion: it constructs PGLite (or spawns a PGLite CLI)+directly, imports nothing from `test/e2e/helpers.ts`, has no+`DATABASE_URL`/`hasDatabase` gate, and its header confirmed no Postgres use.+`sync-delegation-under-serve.serial` and `dream-synthesize-pglite` stayed in+`test/e2e/` because named `e2e.yml` jobs run them. Assertions are unchanged;+executed-test counts match the E2E runs. A file becomes serial when it mutates+process-global state and slow when it takes about 30 s or more. The remaining+PGLite-only E2E files are a TODOS.md item decided from the pilot measurement.++Source files whose only E2E owner moved (`src/commands/claw-test.ts`,+`src/core/claw-test/**`, `src/core/brain-resolver.ts`, `src/commands/mounts.ts`,+`src/commands/connect.ts`, `src/core/connect-probe.ts`,+`src/commands/embed-facts-delegate.ts`) no longer have an `E2E_TEST_MAP` row,+so a change to them selects all E2E (fail-closed); their owners run in every PR.++| Former path | New path | Lane | Command | Lane reason |+|---|---|---|---|---|+| `test/e2e/claw-test.test.ts` | `test/claw-test.slow.test.ts` | slow | `bash scripts/run-slow-tests.sh test/claw-test.slow.test.ts` | over 30 s (harness subprocess runs) |+| `test/e2e/init-fresh-pglite.test.ts` | `test/init-fresh-pglite.slow.test.ts` | slow | `bash scripts/run-slow-tests.sh test/init-fresh-pglite.slow.test.ts` | over 30 s (CLI subprocesses) |+| `test/e2e/mounts-routing-pglite.test.ts` | `test/mounts-routing-pglite.slow.test.ts` | slow | `bash scripts/run-slow-tests.sh test/mounts-routing-pglite.slow.test.ts` | about 30 s (two persistent PGLite brains, CLI spawns) |+| `test/e2e/qm-provisioning.test.ts` | `test/qm-provisioning.test.ts` | unit | `bun test test/qm-provisioning.test.ts` | no process-global state, under 30 s |+| `test/e2e/minions-field-report-repro.test.ts` | `test/minions-field-report-repro.test.ts` | unit | `bun test test/minions-field-report-repro.test.ts` | no process-global state, under 30 s |+| `test/e2e/fresh-install-pglite.test.ts` | `test/fresh-install-pglite.serial.test.ts` | serial | `bash scripts/run-serial-tests.sh test/fresh-install-pglite.serial.test.ts` | mutates `process.env` and `console` |+| `test/e2e/remote-privacy-journeys.test.ts` | `test/remote-privacy-journeys.serial.test.ts` | serial | `bash scripts/run-serial-tests.sh test/remote-privacy-journeys.serial.test.ts` | constructs PGLite outside `beforeAll` (isolation rule R3) |+| `test/e2e/serve-stdio-roundtrip.test.ts` | `test/serve-stdio-roundtrip.test.ts` | unit | `bun test test/serve-stdio-roundtrip.test.ts` | no process-global state, under 30 s |+| `test/e2e/serve-http-surface-ceiling.test.ts` | `test/serve-http-surface-ceiling.test.ts` | unit | `bun test test/serve-http-surface-ceiling.test.ts` | no process-global state, under 30 s |+| `test/e2e/skillpack-flow.test.ts` | `test/skillpack-flow.test.ts` | unit | `bun test test/skillpack-flow.test.ts` | no process-global state, under 30 s |+| `test/e2e/v0_28_5-fix-wave.test.ts` | `test/v0_28_5-fix-wave.serial.test.ts` | serial | `bash scripts/run-serial-tests.sh test/v0_28_5-fix-wave.serial.test.ts` | mutates `process.env` |+| `test/e2e/backfill-perf-pglite.test.ts` | `test/backfill-perf-pglite.test.ts` | unit | `bun test test/backfill-perf-pglite.test.ts` | no process-global state, under 30 s |+| `test/e2e/connect-bearer.test.ts` | `test/connect-bearer.test.ts` | unit | `bun test test/connect-bearer.test.ts` | no process-global state, under 30 s |+| `test/e2e/bootstrap-hook-under-serve.serial.test.ts` | `test/bootstrap-hook-under-serve.serial.test.ts` | serial | `bash scripts/run-serial-tests.sh test/bootstrap-hook-under-serve.serial.test.ts` | mutates `process.env`; already a serial file |+| `test/e2e/upgrade-bun-link-arc.serial.test.ts` | `test/upgrade-bun-link-arc.serial.test.ts` | serial | `bash scripts/run-serial-tests.sh test/upgrade-bun-link-arc.serial.test.ts` | mutates `process.argv`; already a serial file |+| `test/e2e/dream-synthesize-chunking.test.ts` | `test/dream-synthesize-chunking.serial.test.ts` | serial | `bash scripts/run-serial-tests.sh test/dream-synthesize-chunking.serial.test.ts` | mutates `process.env` |+| `test/e2e/search-readiness-http.test.ts` | `test/search-readiness-http.test.ts` | unit | `bun test test/search-readiness-http.test.ts` | no process-global state, under 30 s |+| `test/e2e/transcripts-ingest-pglite.test.ts` | `test/transcripts-ingest-pglite.test.ts` | unit | `bun test test/transcripts-ingest-pglite.test.ts` | no process-global state, under 30 s |+| `test/e2e/bootstrap-harness-lifecycle.serial.test.ts` | `test/bootstrap-harness-lifecycle.serial.test.ts` | serial | `bash scripts/run-serial-tests.sh test/bootstrap-harness-lifecycle.serial.test.ts` | mutates `console`; already a serial file |+| `test/e2e/fact-backfill-resident.test.ts` | `test/fact-backfill-resident.test.ts` | unit | `bun test test/fact-backfill-resident.test.ts` | no process-global state, under 30 s |+### E2E test inventoryE2E tests live in `test/e2e/` and run against real Postgres+pgvector (require `DATABASE_URL`), except where noted as PGLite in-memory (no `DATABASE_URL` needed). One file outside the directory also rides the e2e lane: `test/phantom-redirect-engine-parity.test.ts` (Postgres arm; see the file taxonomy above).@@ -1381,9 +1583,9 @@ E2E tests live in `test/e2e/` and run against real Postgres+pgvector (require `D- `test/e2e/source-isolation-pglite.test.ts` — PGLite in-memory regression suite pinning the source-isolation seal at two layers. Engine layer: `searchKeyword` / `searchVector` / `searchKeywordChunks` / `listPages` / `getPage` / `traverseGraph` / `traversePaths` apply `sourceId` (scalar fast path) and `sourceIds` (array path) correctly across both engines. Op-handler layer: routes through `sourceScopeOpts(ctx)` so a `read+write`-scoped OAuth client bound to `--source dept-x` cannot see rows from neighboring sources via `search`, `query`, `list_pages`, `get_page`, or `find_experts`. Covers both `ctx.sourceId` (single-source clients) and `ctx.auth.allowedSources` (federated_read clients) precedence; federated array wins over scalar wins over nothing. No `DATABASE_URL` needed.- `test/e2e/think-source-isolation-pglite.test.ts` — PGLite in-memory suite pinning the `think` gather stage's source scope: seeds three sources with cross-source links and embedded takes, then asserts `runGather` under a federated `sourceIds` grant (and under a scalar `sourceId`) keeps every stream — hybrid retrieval, takes keyword + vector (`searchTakes`/`searchTakesVector`), and the `traversePaths` graph walk — inside the grant while still reaching authorized neighboring sources. No `DATABASE_URL` needed.- `test/e2e/skill-brain-first.test.ts` — doctor reports `skill_brain_first` check with structured issues; `--fix --dry-run` previews insertion without writing; `--fix` applies the canonical Convention callout idempotently; `brain_first: exempt` frontmatter resolves the warn; `brain_first_typo` surfaces a paste-ready hint; audit JSONL records `detected` / `resolved` / `fixed` transitions; stable brain emits 0 audit lines/run.-- Journey suites (each claimed by an `scripts/e2e-test-map.ts` row; DATABASE_URL-gated unless noted): `migrate-engine-pglite-to-postgres.test.ts` (whole-brain `runMigrateEngine` transfer incl. the child-process failure arm — config not flipped), `takes-write-ops-postgres.test.ts` (takes op layer + `withPageLock` serialization), `propose-takes-jsonb-postgres.test.ts` + `calibration-profile-write.test.ts` (JSONB bind shape on real Postgres), `engine-parity-cjk.test.ts` (cross-engine CJK keyword parity on an identical corpus — both engines route `hasCJK()` queries through the shared ILIKE builder in `src/core/search/cjk-keyword-sql.ts`; top-slug agreement, chunk-grain parity, mixed-query AND semantics, nonexistent-term strictness), `code-edges-read-parity.test.ts` / `ontology-merge-parity.test.ts` / `chronicle-event-projection-parity.test.ts` / `health-parity-postgres.test.ts` (read-path + getHealth parity), `sync-sigkill-resume-postgres.test.ts` (real SIGKILL mid-sync; DB-polled checkpoint, stranded-lock reclaim, exactly-once resume), `serve-http-source-grant.test.ts` (legacy no-grant federated widening vs granted confinement over real `/mcp`), `mounts-routing-pglite.test.ts` (hermetic mount-routing tiers, no DATABASE_URL), `serve-http-surface-ceiling.test.ts` (hermetic 7-verb `--surface verbs` ceiling; the FORCE_SURFACE env is narrow-only), `autopilot-linux-lifecycle.serial.test.ts` + `upgrade-bun-link-arc.serial.test.ts` (PATH-shimmed crontab/systemctl and bun-link upgrade arcs, hermetic), and the thin-client daily-driver verb extension inside `thin-client.test.ts`.+- Journey suites (each claimed by an `scripts/e2e-test-map.ts` row; DATABASE_URL-gated unless noted): `migrate-engine-pglite-to-postgres.test.ts` (whole-brain `runMigrateEngine` transfer incl. the child-process failure arm — config not flipped), `takes-write-ops-postgres.test.ts` (takes op layer + `withPageLock` serialization), `propose-takes-jsonb-postgres.test.ts` + `calibration-profile-write.test.ts` (JSONB bind shape on real Postgres), `engine-parity-cjk.test.ts` (cross-engine CJK keyword parity on an identical corpus — both engines route `hasCJK()` queries through the shared ILIKE builder in `src/core/search/cjk-keyword-sql.ts`; top-slug agreement, chunk-grain parity, mixed-query AND semantics, nonexistent-term strictness), `code-edges-read-parity.test.ts` / `ontology-merge-parity.test.ts` / `chronicle-event-projection-parity.test.ts` / `health-parity-postgres.test.ts` (read-path + getHealth parity), `sync-sigkill-resume-postgres.test.ts` (real SIGKILL mid-sync; DB-polled checkpoint, stranded-lock reclaim, exactly-once resume), `serve-http-source-grant.test.ts` (legacy no-grant federated widening vs granted confinement over real `/mcp`), `autopilot-linux-lifecycle.serial.test.ts` (PATH-shimmed crontab/systemctl arc, hermetic), and the thin-client daily-driver verb extension inside `thin-client.test.ts`.- Tier 2 (`test/e2e/skills.test.ts`) requires OpenClaw + API keys, runs nightly in CI.-- `test/e2e/claw-test.test.ts` also covers live mode token-free via shim agents (`OPENCLAW_BIN=<sh script>`): the success-oracle break path (a do-nothing agent FAILS), the E0 child-friction merge surviving tempdir cleanup, and the upgrade staging + schema-version probe.+- `test/claw-test.slow.test.ts` (slow lane since the lane-move pilot) also covers live mode token-free via shim agents (`OPENCLAW_BIN=<sh script>`): the success-oracle break path (a do-nothing agent FAILS), the E0 child-friction merge surviving tempdir cleanup, and the upgrade staging + schema-version probe.- If `.env.testing` doesn't exist in this directory, check sibling worktrees: `find ../ -maxdepth 2 -name .env.testing -print -quit` and copy it here if found.- **Run E2E tests without asking permission.** When you want to verify behavior, there's a relevant E2E test, or you're shipping anything covered by an E2E suite — spin up the test DB, run the tests, tear down. Don't ask, don't propose it, don't defer. The lifecycle is short (~2-30s startup, sub-minute tests, instant teardown) and the gate value is high. Skipping with "DATABASE_URL unset" is silent regression, not caution.@@ -1404,6 +1606,18 @@ When asked to "run all E2E tests" or "run tests", that means ALL tiers:- Tier 2: `test/e2e/skills.test.ts` (requires OpenAI + Anthropic + openclaw CLI)- Always spin up the test DB, source zshrc, run everything, tear down.+Key-gated live files that no CI job has keys for are left out of the+`scripts/run-e2e.sh` default glob, so the nightly full corpus and the local+gates stop counting their skips as discovered coverage. Naming a file on the+command line still runs it (the runner keeps provider keys):++| File | Required key | Command |+|---|---|---|+| `test/e2e/openrouter-anthropic-subagent-replay.live.test.ts` | `OPENROUTER_API_KEY` | `OPENROUTER_API_KEY=... bash scripts/run-e2e.sh test/e2e/openrouter-anthropic-subagent-replay.live.test.ts` |+| `test/e2e/openrouter-deepseek-subagent-replay.live.test.ts` | `OPENROUTER_API_KEY` | `OPENROUTER_API_KEY=... bash scripts/run-e2e.sh test/e2e/openrouter-deepseek-subagent-replay.live.test.ts` |+| `test/e2e/voyage-rerank-live.test.ts` | `VOYAGE_API_KEY` | `VOYAGE_API_KEY=... bash scripts/run-e2e.sh test/e2e/voyage-rerank-live.test.ts` |+| `test/e2e/voyage-multimodal.test.ts` | `VOYAGE_API_KEY` | `VOYAGE_API_KEY=... bash scripts/run-e2e.sh test/e2e/voyage-multimodal.test.ts` |+### E2E test DB lifecycle (ALWAYS follow this)The sequential E2E runner requires Python 3 for standard-library XML validationdiff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex d80c5c6cd5..7391878f1c 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -93,7 +93,6 @@ src/core/schema-pack/mutate.ts 0 filesystem_guard The shared manifest write primsrc/core/schema-pack/page-to-alias.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/schema-pack/page-to-link.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/schema-pack/retype.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.-src/core/schema-pack/rewrite-links-batch.ts 1 early_refusal Managed mode refuses this legacy entry point before its canonical filesystem/provider effects.src/core/schema-pack/sync.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/search/safe-chunks.ts 1 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.src/core/source-config-sql.ts 1 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex 4ba62a7ac9..9b218eef40 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -22,7 +22,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/bootstrap/serve-health.ts` — serve `/health` probe + scopes version-skew floor, re-exported by `harness.ts`. `probeServeHealth(mcpUrl, fetchFn, timeoutMs=3000)` GETs `<base>/health` and returns `{ok, version?, engine?, detail?}`, never throws; `fetchFn` is an explicit argument (no ambient fetch, no engine, no config). `isServeOlderThanScopes(v)` compares against the PINNED `SCOPES_MIN_SERVE_VERSION` constant — a comparison against the moving CLI VERSION would false-flag every scope-aware serve on the next release. An older serve verifies scoped tokens as FULL ACCESS, so callers print the floor line unconditionally.- `src/core/bootstrap/opencode-json.ts` — the ONE direct opencode-config writer (workspace stdio lane, harness remote lane, connect `--install`). ALL edits ride jsonc-parser `modify`/`applyEdits` (comments/formatting/EOLs survive byte-for-byte outside the edited range — opencode's own `mcp add` preserves comments, and JSONC is its effective grammar for BOTH `.json` and `.jsonc` filenames, which MERGE when both exist). Ownership is a 4-state STRUCTURAL FINGERPRINT (`opencodeEntryKind` → ours-same-source | ours-other-source | foreign | absent; GBRAIN_SOURCE EQUALITY for local entries, receipt-url match or the `{env:GBRAIN_REMOTE_TOKEN}` interpolation for remote), never a marker key (a future strict-schema flip must not brick the host). Distinct read-failure classes (ENOENT create / empty-as-{} / unreadable refuse); foreign refusal on write AND remove; post-render validation (our entry round-trips + every other key survives) keeps the original on failure; 0600 for inline-bearer targets; backups are UNIQUE per operation (`<config>.bak-<hex>`, returned in the result with `writtenText`, the exact rendered bytes) so overlapping runs can never clobber each other's snapshot, and a backup is chmod'd 0600 whenever the COPIED content carries an inline bearer (write AND remove paths); the ours-other-source refusal is caller-appropriate (url + `--force` wording on the remote/expect-url path, GBRAIN_SOURCE wording on the local path); `removeOpencodeMcpEntry` takes a caller expectation + optional `skipOtherSource` — the uninstall lane passes THIS workspace's source id so an ours-other-source match becomes a calm skip-with-note (another workspace's registration is never deleted; foreign still refuses); `reconcileOpencodeSiblingGlobal` clears a same-name gbrain entry from the OTHER global filename before a global write (foreign → refuse naming both files) — opencode merges both, so a leftover sibling entry is a shadow registration; the bun-run ownership lane is ANCHORED (an exact `gbrain`/`gbrain-*` path segment in some arg — a gbrainy-fork cli path is NOT ours, fail-closed); `parseOpencodeEntryBearer` recovers the harness `--status` token url-matched only; `opencodeRemoteEntryExists` is the stdio-lane ownership arbiter (codexBlockOwnsName analog). Callers hold `acquireBootstrapLock` (config-dir → opencode-dir ordering). Pinned by `test/opencode-json.test.ts` (incl. the fingerprint truth-table suite).- `src/core/bootstrap/atomic-write.ts` — the ONE atomic config-file writer for bootstrap host surfaces: symlink-target-resolving, mode-inheriting (`freshMode` for new files, `forceMode` for secret-bearing targets), random-suffix tmp + rename, tmp unlinked best-effort when write/chmod/rename throws (ENOSPC/EACCES never strand `.tmp-` litter), and the existsSync→realpathSync race falls back to fresh-path resolution instead of throwing raw ENOENT. hooks.ts (JSON), codex-toml.ts (TOML+EOL), and opencode-json.ts (JSONC) all swap through it; serialization and EOL policy stay caller-side.-- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath; non-TTY requires `--yes`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with the `LIVE_SERVE` escape hatches when no token was supplied and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/e2e/bootstrap-harness-lifecycle.serial.test.ts`.+- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath; non-TTY requires `--yes`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with the `LIVE_SERVE` escape hatches when no token was supplied and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`.- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`.- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`.- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). `genuineUserTurnIndexes` separately records user-role turns containing real text blocks, because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 0b2e5e4edf..c38ae4adc3 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -33,6 +33,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/code-scope.ts` — shared `--source`/`--all-sources` resolution for the four code-* CLI commands (code-def, code-refs, code-callers, code-callees), extracted so the four can't drift. `positionalArgs` skips value-taking flags AND their values (`--source`, `--limit`, `--lang` — a naive scan looked up the flag's value as the symbol); inline `name=value` spellings are one token and consume nothing. A bad `.gbrain-source`/`GBRAIN_SOURCE` pin is recognized through the shared `isResolverUserError` predicate (exported by `src/core/source-resolver.ts`, next to the messages it matches) and exits 2 with a clean `invalid_source_pin` envelope instead of an uncaught stack. Also exports `pushSourcePredicate(params, opts)`, the source-scope SQL fragment builder code-def/code-refs share.-- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which names `capture` — a starter-surface MCP op — alongside `put_page` for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`, `issuerFromMcpUrl`, the `OAUTH_SECRET_NOTE` secret-hygiene constant, and `openclawThinClientBlock` — the honest openclaw wiring print: a scoped `gbrain init --mcp-only` thin-client block, deliberately NOT a stdio mcpServers config since that grants full local DB access) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them — `OAUTH_SECRET_NOTE` included — so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (required for `--install` in non-TTY), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing a managed block with the inline `http_headers = { Authorization = "Bearer <t>" }` credential (codex-cli >=0.149 rejects inline `bearer_token` for streamable_http at config load) because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/e2e/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/e2e/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set including `capture`, a starter-surface MCP op) + `test/serve-skills-publish-nudge.test.ts`.+- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which names `capture` — a starter-surface MCP op — alongside `put_page` for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`, `issuerFromMcpUrl`, the `OAUTH_SECRET_NOTE` secret-hygiene constant, and `openclawThinClientBlock` — the honest openclaw wiring print: a scoped `gbrain init --mcp-only` thin-client block, deliberately NOT a stdio mcpServers config since that grants full local DB access) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them — `OAUTH_SECRET_NOTE` included — so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (required for `--install` in non-TTY), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing a managed block with the inline `http_headers = { Authorization = "Bearer <t>" }` credential (codex-cli >=0.149 rejects inline `bearer_token` for streamable_http at config load) because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set including `capture`, a starter-surface MCP op) + `test/serve-skills-publish-nudge.test.ts`.- `src/commands/db-repair.ts` — `gbrain db-repair [--yes] [--apply-rewrites] [--json] [--force] [--undo-last-rewrite] [--dry-run]`: ENGINE-FREE Postgres-access repair, sibling of pglite-repair (PGLite brains are redirected there). Never calls connectEngine; default invocation is DIAGNOSE-ONLY (`--dry-run` is an explicit alias). Consent is tiered and flag-gated, never TTY-dependent: auto tier under `--yes` (bounded reconnects, pending migrations in-process, `CREATE EXTENSION vector`, `docker start` of gbrain's own container via `docker-postgres.ts`); rewrite tier under `--yes --apply-rewrites` only (config-file `database_url` rewrites — pooler form, session pooler, `?sslmode=require` — printed first, candidate connect-probed BEFORE persisting, receipted, undo-able); manual tier never applied (credentials/paused-project/env recipes printed — relaying the recipe IS the repair). `--apply-rewrites` without `--yes` is an error. Invariants: fix targets derive only from the CURRENT config URL, never error text; the prober uses exactly ONE connection (`poolSize: 1` — diagnosing pool exhaustion with a 10-connection pool would worsen the outage); rewrite cooldown is ≤24h per (reason, action) with `--force` bypass while auto-tier fixes are NEVER cooldown-blocked (availability first); every rewrite stores the prior URL in the 0600 `~/.gbrain/db-repair-undo.json` (a secret — never the redacted receipts) and `--undo-last-rewrite` (`--yes`-gated) restores it — undo runs INSIDE the advisory lock, emits the same `--json` envelope, validates the record's postgres:// scheme before restoring, and is itself reversible (the outgoing URL becomes the new undo record); an `O_EXCL`-created advisory lockfile blocks concurrent double-rewrites (check-then-write race closed; one stale-holder retry; other write failures stay fail-open); a healthy probe exits 0 "nothing to fix" (the forged-marker defense) and additionally REPORTS (never rewrites) stale DB-plane `engine`/`database_url` rows; the schema probe treats a ZERO-ROW `pg_extension` result as `pgvector_missing` (the query never errors on an absent extension); the docker arm matches the container's REAL inspected host port (`deps.docker.hostPort`) as well as the default 5434; a successful rewrite prints the "restart long-lived gbrain processes" note (config rewrites reach NEW processes only). Refusals: thin-client (no local DB), non-host brain resolution (a mount outage must never rewrite host config — mount-targeted repair is a filed TODO), PGLite (→ pglite-repair). Injectable `DbRepairDeps` prober/executor seam for tests; `defaultDeps.probeAccess` is also reused by the init ladder (one prober, one contract). Pinned by `test/db-repair.serial.test.ts`.diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex a90ec10677..45f7f8e444 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -29,4 +29,4 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE).-- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-helper-migration.test.ts` (asserts the helper is wired in AND no inline `let nextIdx = 0` + `Promise.all(Array.from({length: numWorkers}, ...))` pool shape remains). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed.+- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed.diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex 383cf4a29e..c094b98929 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.-- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-workers.test.ts` + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. Managed bulk calls, including segmentation-only previews, refuse before queue or provider work; they are listed separately from the supported coordinated fact operation.+- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip) + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. Managed bulk calls, including segmentation-only previews, refuse before queue or provider work; they are listed separately from the supported coordinated fact operation.- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). The full fs/db walks buffer candidates 100 at a time and flush via `addLinksBatch` / `addTimelineEntriesBatch` (additive); `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs, and every other file looked deleted and was skipped in silence; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on directory-read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the exact (date, source, summary) rows the page's previous version produced that its current text no longer does. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. Both return `ExtractForSlugsResult { created, processed }`; `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.generated.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.- Extract CLI help — `EXTRACT_HELP` in `src/commands/extract.ts` is the canonical detailed usage shared by `--help` and invalid-subcommand errors. `src/cli.ts` routes `extract --help` before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by `test/cli-help-discoverability.test.ts`.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex cafe940ed1..323fde8681 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/skillify.ts` + `src/core/skillify/{generator,templates}.ts` — `gbrain skillify scaffold <name>` creates all stubs for a new skill: SKILL.md, script, tests, routing-eval.jsonl, resolver entry, filing-rules pointer. `gbrain skillify check <script>` runs the 10-step checklist (LLM evals, routing evals, check-resolvable gate, filing audit) against a candidate skill before it lands.-- `src/commands/skillpack.ts` + `src/core/skillpack/{bundle,scaffold,reference,migrate-fence,scrub-legacy,harvest,harvest-lint,copy,apply-hunks,diff-text,installer}.ts` — `install`/`uninstall` are not supported (they exit non-zero with a hint to the replacement). Surface: `scaffold` (one-time additive copy via `copyArtifacts` in `copy.ts`; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmatter `sources:`), `reference` (read-only diff lens + `--apply-clean-hunks` two-way auto-apply via pure-JS unified-diff parser/applier in `apply-hunks.ts` + `diff-text.ts`), `migrate-fence` (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), `scrub-legacy-fence-rows` (opt-in row cleanup with skill-present + non-empty-triggers gate), `harvest` (host→gbrain inverse with symlink-reject + canonical-path containment via a `validateUploadPath`-style gate + default-on privacy linter in `harvest-lint.ts` against `~/.gbrain/harvest-private-patterns.txt` plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter `sources:` array (validated by `loadSkillSources` in `bundle.ts`). `autoDetectSkillsDir` (in `src/core/repo-root.ts`) has a `cwd_walk_up` tier ahead of `~/.openclaw/workspace` (`$OPENCLAW_WORKSPACE` precedence preserved). `gbrain skillpack check --strict` exits non-zero on drift (CI gate); top-level `gbrain skillpack-check` keeps exit-1-on-issues for cron. Companion editorial skill `skills/skillpack-harvest/SKILL.md` drives the genericization checklist. Doc: `docs/guides/skillpacks-as-scaffolding.md`. Test coverage across `test/skillpack-{copy,scaffold,reference,reference-apply,apply-hunks,migrate-fence,scrub-legacy,harvest,harvest-lint,frontmatter-sources}.test.ts` + 9-case E2E in `test/e2e/skillpack-flow.test.ts`. `installer.ts` + `test/skillpack-install.test.ts` remain because `gbrain skillpack diff` uses `diffSkill` from there.+- `src/commands/skillpack.ts` + `src/core/skillpack/{bundle,scaffold,reference,migrate-fence,scrub-legacy,harvest,harvest-lint,copy,apply-hunks,diff-text,installer}.ts` — `install`/`uninstall` are not supported (they exit non-zero with a hint to the replacement). Surface: `scaffold` (one-time additive copy via `copyArtifacts` in `copy.ts`; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmatter `sources:`), `reference` (read-only diff lens + `--apply-clean-hunks` two-way auto-apply via pure-JS unified-diff parser/applier in `apply-hunks.ts` + `diff-text.ts`), `migrate-fence` (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), `scrub-legacy-fence-rows` (opt-in row cleanup with skill-present + non-empty-triggers gate), `harvest` (host→gbrain inverse with symlink-reject + canonical-path containment via a `validateUploadPath`-style gate + default-on privacy linter in `harvest-lint.ts` against `~/.gbrain/harvest-private-patterns.txt` plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter `sources:` array (validated by `loadSkillSources` in `bundle.ts`). `autoDetectSkillsDir` (in `src/core/repo-root.ts`) has a `cwd_walk_up` tier ahead of `~/.openclaw/workspace` (`$OPENCLAW_WORKSPACE` precedence preserved). `gbrain skillpack check --strict` exits non-zero on drift (CI gate); top-level `gbrain skillpack-check` keeps exit-1-on-issues for cron. Companion editorial skill `skills/skillpack-harvest/SKILL.md` drives the genericization checklist. Doc: `docs/guides/skillpacks-as-scaffolding.md`. Test coverage across `test/skillpack-{copy,scaffold,reference,reference-apply,apply-hunks,migrate-fence,scrub-legacy,harvest,harvest-lint,frontmatter-sources}.test.ts` + 9-case E2E in `test/skillpack-flow.test.ts`. `installer.ts` + `test/skillpack-install.test.ts` remain because `gbrain skillpack diff` uses `diffSkill` from there.- `src/commands/sources-lifecycle{,-args}.ts` — strict source mutation parsing before engine connection, with stable UUIDs and source incarnation preconditions. The private CLI administration envelope delegates to a live PGLite owner, retains request IDs after lost responses, and refuses preactivation administration or legacy hardening rather than changing worktrees through an uncoordinated writer. Managed purge names one archived source; the expiry worker separately coordinates each source. `test/persistence-source-cli.test.ts` executes real CLI subprocesses, checks replay after deletion/recreation, and verifies global page/lifecycle request identity.diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex 3f4bd3bceb..e3a7e45974 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -11,7 +11,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ai/dims.ts` — per-provider `providerOptions` resolver for embed-time dimension passthrough; the single source of truth for "which provider needs which knob to produce `vector(N)`". Exports `dimsProviderOptions(implementation, modelId, dims)` (called by `embed()` in `gateway.ts`), `VOYAGE_OUTPUT_DIMENSION_MODELS` (private const — the 7 hosted Voyage models that accept `output_dimension`: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3` — nano deliberately excluded), `VOYAGE_VALID_OUTPUT_DIMS = [256, 512, 1024, 2048] as const`, `supportsVoyageOutputDimension(modelId)`, `isValidVoyageOutputDim(dims)`. Voyage path uses the SDK-supported `dimensions` field (`{ openaiCompatible: { dimensions: N } }`), NOT Voyage's `output_dimension` wire-key — the `voyageCompatFetch` shim in `gateway.ts:541` translates `dimensions → output_dimension` before the HTTP body is built (the AI SDK's openai-compatible adapter doesn't recognize the wire-key, so sending it from here would be silently dropped and Voyage would return its default 1024-dim). Runtime guard: when a Voyage flexible-dim model is configured with `dims` outside `VOYAGE_VALID_OUTPUT_DIMS`, throws `AIConfigError` with a paste-ready `gbrain config set embedding_dimensions <256|512|1024|2048>` hint at the embed boundary (most common trigger: `embedding_model: voyage:voyage-4-large` without `embedding_dimensions`, retaining an incompatible 1536-dimensional setting from another provider). Every lookup in this module folds through the private `modelMatchKey` (trim + lowercase) so cased hub-form ids (`Qwen/Qwen3-Embedding-4B`) match the all-lowercase tables — the folded key is a MATCH key only, never sent to a provider (wire model ids are case-sensitive; error messages keep the original id so they stay paste-ready); the Qwen3-Embedding native-width table lives at module scope alongside the other dim tables. Consequence, deliberate: a cased Voyage/Perplexity config matches and fails loudly at init when its `dims` is invalid, rather than skipping validation and silently producing wrong-width vectors.-- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (an assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance.+- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance.- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape. `embeddingDimsForModel` matches recipe `model_dims` keys exactly first, then case-insensitively with BOTH sides folded (configured ids arrive cased, and user-editable recipe tables can carry cased keys; without the fold a cased id would fall through to `default_dims` and `gbrain init` would build a wrong-width column), before falling back to `default_dims`.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 95c2a07ec6..3c079e7487 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -39,7 +39,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/synthesize-verify.ts` — Mechanical claim verification on every page a synthesis child wrote (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/ellipsis/case folding WITH an offset map back to the original string, so every replacement is a verbatim transcript slice) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors always, plain `Label:` anchors when the label is a role word or opens two or more lines), canonical numbers and dates (`numericFacts`: `$250K` = `$250,000` = `250 thousand`, `2026-03-14` = `March 14th`; the file basename counts), and speaker-mention patterns. `groundQuote` runs the ladder exact → normalized → near (word-trigram anchors, window clipped to the anchor's speaker turn, ≥0.8 token overlap, ambiguity within 0.05 falls through, trimmed to the first/last shared token, refused above 1.3x the quote length) and never accepts a match that touches a speaker label (`reason: 'crosses_speakers'`). `verifyBody` splits a body into claim units (`claimUnits`: sentences within a line, whole list items, whole table rows; no boundary inside a quote) and checks each NEW unit: every quote must ground in some source, a quote whose sentence names a transcript speaker must name the speaker of the matched turn, and every numeric/date claim (outside grounded quotes, code, wikilinks and link targets) must appear in a source. Any failure removes the whole unit from the body; `verifyDreamPage` records it in frontmatter `unverified_claims` (`text`, `reason` = `quote_not_in_source` / `quote_crosses_speakers` / `speaker_mismatch` / `number_not_in_source`, `detail`, `sources`, `detected_at`) and records every grounded quote's source path, character span and speaker in `grounding.quotes`; records from the pre-run revision carry forward, capped at 100 / 200. Frontmatter is neither chunked nor searched, so quarantined claims stay reviewable through `get_page` but out of search, recall, think and context packs. A page whose every unit failed keeps `ALL_CLAIMS_QUARANTINED_BODY`. Scope (`verifyAndRepairDreamPages(engine, refs, transcriptsByPath, { since, sinceByTranscript, checkedAt })`): sources are the transcripts of every child that wrote the page; the page epoch is the earliest `loadChildWriteEpochs` entry of its sources (child job `created_at`, so resumed or coalesced children keep their original epoch), else `since` (`readVerifyEpoch`, taken before fan-out). Pages created at or after the epoch are verified whole; older pages are verified only on units absent from their pre-epoch revision (`loadPreRunRevision`: the first `page_versions` snapshot at or after the epoch; none means the page was not overwritten → `skipped_unchanged`). Write-back goes through `importFromContent` (`noEmbed`; the phase-end embed sweep backfills) with a `beforeCommit` that re-projects timeline entries, facts, takes (`prepareCanonicalProjections`) and automatic links (`prepareAutomaticLinks`) from the verified body in the same transaction, so no derived row outlives its quarantined claim. Fail-open per page (read-back miss / write throw → `errors` + continue; abort still unwinds). Kill switch `dream.synthesize.quote_verify` (default on). Telemetry shape = `QuoteVerifyStats` in `details.synthesis.quote_verify`. Pinned by `test/cycle-synthesize-verify.test.ts`, the write-path mini-eval `test/cycle-write-path-mini-eval.test.ts`, and the three-cycle repeated-consolidation pin `test/cycle-repeated-consolidation.test.ts` (harness `test/helpers/repeated-consolidation.ts`, printable run `scripts/repeated-consolidation-experiment.ts`).-- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/e2e/dream-synthesize-chunking.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails OPEN with a stderr warn). `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported.+- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails OPEN with a stderr warn). `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported.- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`.diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.mdindex 724c6004d6..ff603278d2 100644--- a/docs/architecture/key-files/core-minions-1.md+++ b/docs/architecture/key-files/core-minions-1.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, stagger, handlers/shell). Private dream-inline-* queues carry an explicit lifecycle: owner job id + owner token + a renewable lease (columns on minion_jobs; `queue.ts` `reconcilePrivateQueue` terminalizes one queue through the normal cancelJobs bookkeeping and stamps every cancellation with the machine-readable `private_queue_reconciled:` reason family; `renewPrivateQueueLease` is MONOTONIC — GREATEST — so a default-horizon renewal can never shrink a creation-time lease; `reconcileOrphanedPrivateQueues` cancels only provably-orphaned queues: no healthy child lock, owner terminal/missing or lease expired; legacy unowned rows are left to Doctor/retriage; `classifyPrivateQueueForRecovery` is PUBLIC so the doctor orphan check buckets through the same verdict). Recovery runs in `gbrain jobs work` after driver/selected-child readiness and `ensureSchema`, for bare AND supervised workers (including autopilot spawns/respawns); the standalone parent does not recover queues in `beforeSpawn`. `maybeRunWorkerStartupRecovery(queue, process.env, true)` keeps this worker-owned ordering even under `GBRAIN_SUPERVISED=1`. Dream-cycle start also recovers (cycle.ts, next to the cycle lock reap — the ONLY lane on PGLite, which inlines every child). `deriveWedgeSignal` is queue-aware: a dream-inline queue is never 'wedged' (no shared worker can claim it) — it reports `private_queue: true` so jobs stats / get_job_stats / doctor all point at reconciliation instead of the impossible worker restart.+- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, handlers/shell). Private dream-inline-* queues carry an explicit lifecycle: owner job id + owner token + a renewable lease (columns on minion_jobs; `queue.ts` `reconcilePrivateQueue` terminalizes one queue through the normal cancelJobs bookkeeping and stamps every cancellation with the machine-readable `private_queue_reconciled:` reason family; `renewPrivateQueueLease` is MONOTONIC — GREATEST — so a default-horizon renewal can never shrink a creation-time lease; `reconcileOrphanedPrivateQueues` cancels only provably-orphaned queues: no healthy child lock, owner terminal/missing or lease expired; legacy unowned rows are left to Doctor/retriage; `classifyPrivateQueueForRecovery` is PUBLIC so the doctor orphan check buckets through the same verdict). Recovery runs in `gbrain jobs work` after driver/selected-child readiness and `ensureSchema`, for bare AND supervised workers (including autopilot spawns/respawns); the standalone parent does not recover queues in `beforeSpawn`. `maybeRunWorkerStartupRecovery(queue, process.env, true)` keeps this worker-owned ordering even under `GBRAIN_SUPERVISED=1`. Dream-cycle start also recovers (cycle.ts, next to the cycle lock reap — the ONLY lane on PGLite, which inlines every child). `deriveWedgeSignal` is queue-aware: a dream-inline queue is never 'wedged' (no shared worker can claim it) — it reports `private_queue: true` so jobs stats / get_job_stats / doctor all point at reconciliation instead of the impossible worker restart.- `src/core/minions/admission.ts` — submit-side queue admission control (the drain-side pool-starvation half is the job-isolation work; claim fairness is a filed TODO, deliberately out of scope). Three primitives resolved per name via `resolveAdmissionPolicy` (config `minions.*` > per-name defaults tables, 60s in-process cache, fail-open with a once-per-process stderr warn; env kill-switch `GBRAIN_MINIONS_ADMISSION=0` disables all three): PARAM-COALESCING (`PARAM_COALESCE_DEFAULT` — on for `subagent`; `computeParamHash` = sha256 of stable-stringified payload excluding only `__param_hash` itself — `__owner_client_id` is deliberately INCLUDED so owner lanes never cross; parentless + waiting-only + age-bounded to ttl/2), WAITING-TTL (`WAITING_TTL_DEFAULT_HOURS` — 48h for `subagent`; swept by `MinionQueue.handleWaitingTTL` through `cancelJobs(ids, {reason, rootStatuses:['waiting']})` so descendants cancel, child_done lands, aggregator parents resolve, and the reason stamps ROOT ids only; ≤500/tick oldest-first; warn-before-act is `runWaitingTtlTick` — first tick counts affected + stamps `TTL_NOTICE_SHOWN_KEY` with an ISO timestamp, sweeping starts only after `ttlNoticeGraceMs()` (1h default, env `GBRAIN_MINIONS_TTL_NOTICE_GRACE_MS`) elapses; `gbrain upgrade` prints the same one-shot notice and starts the same clock; legacy `'true'` flag values sweep immediately), and NAME-GLOBAL QUOTA (`QUOTA_MAX_WAITING_DEFAULT` EMPTY by operator decision — activates only via `minions.quota_max_waiting.<name>`; counts the name across ALL queues so per-run `dream-inline-*` fanout queues can't dodge it, EXACT under concurrency via a `minion_quota:<name>` advisory xact lock taken only when a quota is configured; throws typed `QueueQuotaExceededError`, checked everywhere via `isQueueQuotaExceededError` — dream submitters record a phase skip, synthesize rolls back the current transcript's fresh chunks, agent fanout cancels the whole tree, `submit_agent` maps to a structured `rate_limited` OperationError). `TTL_REASON_PREFIX` is the single source for the sweep's error_text prefix and the stats/doctor LIKE patterns; `safeConfigSegment` gates untrusted job names out of copy-pasteable config hints. Alerting rides `getStats` (`drained_completed/failed/dead/cancelled` keyed on finished_at + `waiting_now` + `oldest_waiting_minutes`), the `jobs stats` DIVERGENT-QUEUE / waiting-TTL screams (`GBRAIN_QUEUE_DIVERGENCE_RATIO`=2, `GBRAIN_QUEUE_DIVERGENCE_MIN_WAITING`=50; divergence compares intake vs COMPLETED so TTL-cancel storms can't masquerade as throughput) + `--json`, and doctor `checkQueueHealth`. Pinned by `test/minions-admission.test.ts` + `test/jobs-stats-divergence.serial.test.ts`.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 9d74546e05..b9a2ffa5a3 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -5,9 +5,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM polish/fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output; `applyPattern` never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as `ParseResult.date_fallback_count`, undefined when zero), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; polish and fallback are thin wrappers), `llm-polish.ts` (opt-IN; headroom guard skips when tracker within $0.10 of cap; pure `applyPolish` for merge/drop/edit ops), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true` (belt-and-suspenders full-body recompute of the winner). The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading (unlike `bold-time-dash`'s bold-name+time+dash anchor) is a plausible label in ordinary prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only a solitary `**You:**` heading (or several repeats of the SAME role) falls back to the ordinary flat-density score instead of getting the same acceptance immunity a genuine two-party exchange gets. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because distinct-speaker count alone still lets ONE genuine `**You:**`/`**ChatGPT:**` pair embedded anywhere inside an otherwise unrelated long document (both roles present) through: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (tolerating a short title/heading preamble, not an arbitrary amount of unrelated prose before the transcript). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,llm-polish,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](../conversation-parser-patterns.md).--- `src/core/diarize/payload-fitter.ts` — generic fit-arbitrarily-large-items-into-per-call-token-budget utility. `'batch'` strategy is deterministic token-budgeted chunking with no LLM calls. `'summarize'` strategy embed-clusters into ceil(items/4) groups via cheap deterministic nearest-neighbor on cosine, Haiku-summarizes each cluster via `Promise.allSettled` at parallelism=4. Each Haiku call composes the active BudgetTracker via the AsyncLocalStorage. Quality gate: when `success_ratio < min_success_ratio` (default 0.75), result is flagged `degraded: true` — the fitter preserves the successful subset; the caller decides whether to surface a partial result or abort.+- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output; `applyPattern` never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as `ParseResult.date_fallback_count`, undefined when zero), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; fallback is a thin wrapper), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true` (belt-and-suspenders full-body recompute of the winner). The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading (unlike `bold-time-dash`'s bold-name+time+dash anchor) is a plausible label in ordinary prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only a solitary `**You:**` heading (or several repeats of the SAME role) falls back to the ordinary flat-density score instead of getting the same acceptance immunity a genuine two-party exchange gets. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because distinct-speaker count alone still lets ONE genuine `**You:**`/`**ChatGPT:**` pair embedded anywhere inside an otherwise unrelated long document (both roles present) through: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (tolerating a short title/heading preamble, not an arbitrary amount of unrelated prose before the transcript). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](../conversation-parser-patterns.md).- `src/core/facts/conversation-types.ts` — single-source conversation-type allowlist (`ALLOWED_TYPES`: conversation, meeting, slack, email, imessage, imessage-daily + `AllowedType`). Every consumer derives from this frozen leaf module — `extract-conversation-facts.ts` (which re-exports both names verbatim for its existing importers), the cycle backfill phase, `doctor.ts` + `doctor/checks/search-eval.ts`, `sources.ts`, `jobs.ts` — so no hand-copied list can drift. It lives under `src/core/facts/` (not `src/commands/`) because `scripts/generate-flag-registry.ts` scans option-shaped literals one relative-import level deep — importing the constant straight from `extract-conversation-facts.ts` would transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded by `test/conversation-facts-type-allowlist-drift.test.ts`.diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.mdindex e9a3219ada..0cf7264212 100644--- a/docs/architecture/key-files/core-services-3.md+++ b/docs/architecture/key-files/core-services-3.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/think/intent.ts` + `src/core/think/entity-extract.ts` — pure `classifyIntent(question)` returns `'temporal' | 'knowledge_update' | 'other'` (regex-first, no LLM, `'other'` fast path short-circuits with zero SQL). `extractCandidateEntities(question, retrievedSlugs)` pulls high-precision candidates from retrieved entity-prefix slugs (`people/`, `companies/`, `organizations/`) and medium-precision noun phrases. Stop-word boundaries + leading-verb stripper handle "When did I last meet Marco" → `marco`. Both consumed by `runThink` and the LongMemEval harness so the two paths cannot drift. Pinned by `test/think-intent.test.ts` and `test/think-entity-extract.test.ts`.-- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when a file has zero turn-shaped records (`type` user/assistant, not sidechain) and zero skipped lines — a title/metadata-only stub is understood, not drift, while turn records that yield no text and unparseable lines still drift), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message, assistant from `response_item` output_text; role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), ~300KB message-boundary splitting with 2-message overlap (under the embed-skip threshold), part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — a session whose part-1 `frontmatter.id` already has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/transcripts-retitle.test.ts`, `test/e2e/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).+- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when a file has zero turn-shaped records (`type` user/assistant, not sidechain) and zero skipped lines — a title/metadata-only stub is understood, not drift, while turn records that yield no text and unparseable lines still drift), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message, assistant from `response_item` output_text; role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), ~300KB message-boundary splitting with 2-message overlap (under the embed-skip threshold), part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — a session whose part-1 `frontmatter.id` already has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/transcripts-retitle.test.ts`, `test/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 78803135ea..1acd29aa28 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -19,9 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/config.ts:ensureGitignore` — idempotent retroactive writer of `~/.gbrain/.gitignore` (single line `*`). Called from `saveConfig()` so every config-writing path lays it down, AND from `runPostUpgrade()` so existing users pick it up on `gbrain upgrade`. Never clobbers a user-customized `.gitignore` (checks file exists + content non-empty before writing). Scope: blocks casual `git add ~/.gbrain` from inside an enclosing worktree, but does NOT cover already-tracked files, screenshots, backups (Time Machine / iCloud / Dropbox), or `git add -f`. The doctor check `home_dir_in_worktree` surfaces what `.gitignore` can't.-- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; their in-flight work runs to its own bounded timeout because their opts can't carry a signal yet). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, AND synthesize so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/cycle/cycle-lock-ttl.test.ts` (pins `LOCK_TTL_MINUTES === 5`), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run.--- `src/core/data-research.ts` — Recipe validation, field extraction (MRR/ARR regex), dedup, tracker parsing, HTML-to-text conversion. `stripEmailHtml` caps input before at most two non-recursive passes decoding supported named/decimal entities. Quote-aware removal of comments, style/script blocks, and recognized HTML tags runs before each decode and once afterward, discarding recognized tags before decoding their attribute contents. Unknown tag names and invalid tag forms remain literal, preserving angle-bracket addresses and non-HTML comparisons; actual HTML-shaped text is still interpreted as markup. Decimal entities must be valid Unicode scalars; invalid values and unsupported entities stay literal. Preserves paragraph breaks. This is a conversion helper, not a browser sanitizer or a live Gmail ingestion hook. Pinned by `test/data-research.test.ts`.+- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; their in-flight work runs to its own bounded timeout because their opts can't carry a signal yet). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, AND synthesize so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/core/cycle.serial.test.ts` (5-minute DB-lock and file-lock TTL behavior), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run.- `src/core/doctor-cause-rank.ts` — pure cause-ranking for `gbrain doctor`. `rankIssues(checks)` returns non-ok checks ordered fail-before-warn then root-before-symptom then name (deterministic). `ROOT_CAUSE_CHECKS` / `SYMPTOM_CHECKS` are ORDERING ONLY — tier membership asserts no causality. `downstream_of` is set ONLY from a small map of KNOWN grounded edges (`queue_health` / `supervisor` → `worker_oom_loop`, since they read the same `aborted: watchdog` / `rss_watchdog` source) AND only when the named root is itself failing — never a root×symptom cartesian (co-occurrence never implies causality). `fix` prefers `details.fix_hint` else the message. `CAUSE_GRAPH_NAMES` + `allKnownCheckNames()` back a drift guard asserting every graphed name is a real check. Consumed by `computeDoctorReport` (`top_issues` field, additive, schema_version stays 2) + the "Top issues (ranked by cause)" header in `outputResults`. Pinned by `test/doctor-cause-rank.test.ts`.@@ -37,8 +35,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/eval-capture.ts` — op-layer capture wrapper called from `src/core/operations.ts` `query` + `search` handlers (catches MCP + CLI + subagent tool-bridge from one site). Fire-and-forget; failures route to `engine.logEvalCaptureFailure` so `gbrain doctor` sees drops cross-process. Capture is off by default — `isEvalCaptureEnabled` resolution: explicit `config.eval.capture` (true/false) wins, else `process.env.GBRAIN_CONTRIBUTOR_MODE === '1'`, else off. Contributors set `export GBRAIN_CONTRIBUTOR_MODE=1`. PII scrubber gate is independent and defaults to true regardless of CONTRIBUTOR_MODE.-- `src/core/fail-improve.ts` — Deterministic-first, LLM-fallback loop with JSONL failure logging and auto-test generation.-- `src/core/filing-audit.ts` + `skills/_brain-filing-rules.json` — Check 6 of `check-resolvable`. Parses `writes_pages:` / `writes_to:` frontmatter on skills and audits their filing claims against the filing-rules JSON (error severity). Internal `parseFrontmatter` is a thin wrapper over the shared `src/core/skill-frontmatter.ts` parser so both filing-audit and skill-brain-first read the same shape (`tools?`, `triggers?`, `brain_first?: 'exempt'`, typed `brain_first_typo`) from one source of truth.- `src/core/fts-language.ts` — Single source for the Postgres text-search configuration name used by FTS. `getFtsLanguage()` resolves `GBRAIN_FTS_LANGUAGE` (default `english`), validates against `/^[a-z][a-z0-9_]*$/` (tsvector config names can't be bound as parameters, so the value is interpolated into raw SQL — the allowlist regex is the injection guard; invalid values warn once and fall back to `english`), and caches on first read (`resetFtsLanguageCache()` is test-only). Consumed by both engines' `searchKeyword`/`searchKeywordChunks` (`websearch_to_tsquery` query side), the `configurable_fts_language` migration, and `reindex-search-vector` (write-side trigger functions). Pinned by `test/fts-language.serial.test.ts` + `test/fts-language-migration.serial.test.ts` (includes the `'; DROP TABLE pages; --` injection cases).@@ -51,7 +47,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/operations-descriptions.ts` — Constants module for tool descriptions. Pinned via `test/operations-descriptions.test.ts`. Houses `GET_RECENT_SALIENCE_DESCRIPTION`, `FIND_ANOMALIES_DESCRIPTION`, `GET_RECENT_TRANSCRIPTS_DESCRIPTION` plus `LIST_PAGES_DESCRIPTION`, `QUERY_DESCRIPTION`, `SEARCH_DESCRIPTION`. Stable surface for the Tier-2 LLM routing eval — keeping them here keeps the test from binding to whatever is in `operations.ts` at test-run time.-- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Fresh same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`); `add_timeline_entry` resolves an authorized stored request before that fresh-write preflight so exact replay retains its outcome after page purge or recreation: a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` deduplication may resolve another slug by content hash or `frontmatter.id`, but returns an authorized read-only `duplicate` outcome. The original target's revision never authorizes publication to that other page. Preparation and guarded validation recheck the duplicate's current authority, readability, concrete page identity and revision; neither its canonical fields nor its file are written. OAuth and delegated subagent fences still apply, and denials do not name an inaccessible duplicate. Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/e2e/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `get_tags` resolves `readPolicyOpts`, so an untrusted caller gets no tags for a `visibility: private` page (unless the operator's private-pages opt-out is on) or a soft-deleted page. `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page` submits through `submitPageMutation` to the durable journal. Existing-page replacements require `expected_revision` or explicit `force`; omission is create-only. The designated owner publishes under native root and database guards, with recoverable file replacement and a terminal receipt committed with canonical state. Accepted contention returns `write_pending` after the synchronous wait; admission failure does not fabricate a queued receipt. Git and embeddings report separate effect outcomes. Trusted-local `delete_page` with `purge: true` uses the same journal, revision and recovery protocol: artifact-removal failure preserves the prior row, and exact replay retains the original terminal outcome after deletion. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).+- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Fresh same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`); `add_timeline_entry` resolves an authorized stored request before that fresh-write preflight so exact replay retains its outcome after page purge or recreation: a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` deduplication may resolve another slug by content hash or `frontmatter.id`, but returns an authorized read-only `duplicate` outcome. The original target's revision never authorizes publication to that other page. Preparation and guarded validation recheck the duplicate's current authority, readability, concrete page identity and revision; neither its canonical fields nor its file are written. OAuth and delegated subagent fences still apply, and denials do not name an inaccessible duplicate. Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `get_tags` resolves `readPolicyOpts`, so an untrusted caller gets no tags for a `visibility: private` page (unless the operator's private-pages opt-out is on) or a soft-deleted page. `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page` submits through `submitPageMutation` to the durable journal. Existing-page replacements require `expected_revision` or explicit `force`; omission is create-only. The designated owner publishes under native root and database guards, with recoverable file replacement and a terminal receipt committed with canonical state. Accepted contention returns `write_pending` after the synchronous wait; admission failure does not fabricate a queued receipt. Git and embeddings report separate effect outcomes. Trusted-local `delete_page` with `purge: true` uses the same journal, revision and recovery protocol: artifact-removal failure preserves the prior row, and exact replay retains the original terminal outcome after deletion. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).- `src/core/pg-access-classify.ts` — Postgres ACCESS-error classifier, the reason/remediation layer of the db-availability loop (detect → `GBRAIN_DB_ACCESS` marker → skills/db-repair → `gbrain db-repair`). Two entry points, one diagnosis type: `classifyPgAccessError(err, ctx?)` for thrown errors (data-driven ordered `REASON_ROWS` table, first match wins — specific rows before general ones) and `diagnoseDbConfig(ctx)` for errorless config-plane reasons (`no_url`, `env_shadowed` — there is no error object at connectEngine's no-config exit or under an env shadow; never fake one). The `PgAccessReason` union (16 reasons) is APPEND-ONLY — a compatibility surface once the bundled skills are in the wild, like progress phase names; consumers switch exhaustively with a `never` sentinel. Invariants: `message`/`remediation` are ALWAYS pre-redacted (safe for transcripts/receipts/issues); every `fix` descriptor is hardcoded or derived from the CURRENT config URL (`deriveSessionPoolerUrl`/`deriveDirectUrl`), never from anything parsed out of error text, and `run_command` argv[0] is always `gbrain`; **remediation copy has exactly ONE home: this module** — db-repair, doctor, and MCP dispatch all render `diagnosis.remediation`, skills reference the command and never duplicate recipe text. TWO-AXIS design note (mirrored in `retry-matcher.ts`'s header — do not "fix" one side to match the other): retry-matcher answers "should I retry?" and deliberately treats `password authentication failed` as retryable (auth race during DNS failover); this module answers "what went wrong?" and reports the same error `auth_failed` + `transient: false` — both correct on their own axis; unknown reasons defer `transient` to `isRetryableConnError`. Also exports `DB_ACCESS_MARKER_PREFIX`/`formatDbAccessMarker` (the single source of the marker literal that skills/db-repair pins in both `description:` and `triggers:`; the action a reader takes is ALWAYS the hardcoded `gbrain db-repair`, never a command parsed from the marker), `isDbAccessFailure` (the ACCESS-class subset fail-open recall arms use to tell "one arm degraded" from "the DB is down"), and Supabase enrichment `{pooler, projectRef, pausedSuspect}` (paused projects aren't a distinct wire error — modeled as a suspicion flag on dns/timeout/tenant reasons). Pinned by `test/pg-access-classify.test.ts`.diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex 398964211e..597010e8f9 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -11,7 +11,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`.-- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The package-private `#postgres` import maps directly to the shipped cancellation-capable `vendor/postgres` source (the same source is embedded by compiled builds); `vendor/README.md` and the hash-verifying updater own provenance and regeneration. `postgres-engine/cancellation.ts` shares actual reserved-owner capability detection, typed `postgres_cancellation_unavailable` errors, and abort-bounded reservation with late-owner release; unsignalled diagnostic queries remain usable. Signalled SQL must retain cancellation/discard safety, including through transaction-mode poolers. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/postgres-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — a superset of PGLite's probe set: the shared column-only forward-reference cases (`files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`/`archived_at`/`archive_expires_at`, `timeline_entries.event_page_id`) plus Postgres-blob-only probes for state the PGLite blob doesn't carry (`dream_verdicts.expires_at` — see the forward-reference-bootstrap.ts entry); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-ownership.test.ts`. `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). Test seam `__resetFactsEmbeddingCastCacheForTest()` clears the per-engine cache. `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`).+- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The package-private `#postgres` import maps directly to the shipped cancellation-capable `vendor/postgres` source (the same source is embedded by compiled builds); `vendor/README.md` and the hash-verifying updater own provenance and regeneration. `postgres-engine/cancellation.ts` shares actual reserved-owner capability detection, typed `postgres_cancellation_unavailable` errors, and abort-bounded reservation with late-owner release; unsignalled diagnostic queries remain usable. Signalled SQL must retain cancellation/discard safety, including through transaction-mode poolers. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/postgres-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — a superset of PGLite's probe set: the shared column-only forward-reference cases (`files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`/`archived_at`/`archive_expires_at`, `timeline_entries.event_page_id`) plus Postgres-blob-only probes for state the PGLite blob doesn't carry (`dream_verdicts.expires_at` — see the forward-reference-bootstrap.ts entry); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-lifecycle.test.ts` (concurrent-connect ownership, `db.disconnect()` detaching the singleton before awaiting `end()`, and the instance-reconnect `_reconnecting` guard). `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`).- `src/core/supabase-admin.ts` — Supabase Management-API client (`listProjects`, `discoverPoolerUrl`, `extractProjectRef` — refs are lowercase ALPHANUMERIC, `[a-z0-9]+`). Consumed by the `init --prefer-postgres` ladder's rung 2 (DISCOVERY only — project creation stays dashboard guidance; discovered URLs are candidates, connect-probed before persisting) and by the classifier's Supabase hints. The access token is never persisted, logged, or written to receipts/config.diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex 4dac3a4dcd..577f5b2107 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -43,7 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/source-id.ts` — single canonical source_id validation, dependency-free by design (imported by both engines, cycle, source-resolver, sources-ops). `SOURCE_ID_RE` (strict: 1-32 lowercase alnum, interior hyphens only, no edge hyphens); `isValidSourceId` (boolean — for tiers that silently fall back: dotfile, brain_default) vs `assertValidSourceId` (throws — for tiers that must reject loudly: explicit `--source`, `GBRAIN_SOURCE`, `cycleLockIdFor`); `ALL_SOURCES = '__all__'` sentinel (deliberately NOT a valid id so it can never collide with a real source or leak into lock ids/path joins; `sourceScopeOpts` translates it to an unscoped read for trusted local callers and keeps it unsatisfiable for remote callers, fail-closed). `normalizeSourceInput`/`normalizeFederatedReadInput` normalize the `/admin/api/register-client` HTTP body, mirroring the CLI's `--source`/`--federated-read` flags: omitted `source` → `'default'`; omitted `federatedRead` → `undefined` so `registerClientManual` applies its own `[sourceId]` default; present-but-invalid values throw so the route returns a structured 400 (`invalid_source`) instead of failing at INSERT time. Pinned by `test/register-client-source-normalize.test.ts`.-- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `src/commands/sync.ts:1497-1519` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed), with `maybeWarnUnscopedDefaultWrite` as its warning-only projection; `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating.+- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `src/commands/sync.ts:1497-1519` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed); `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating.- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`. `assertNoOverlappingPath(engine, id, path)` is the ONE overlapping-path guard shared by every surface that binds a `local_path` (`addSource`, `gbrain sources set-path`): a path equal to, nested inside, or enclosing another source's `local_path` throws `SourceOpError('overlapping_path')` — overlapping trees make sync/write-through attribute files to the wrong source, so no add or repair path may skip it. The guard compares by spelling AND by realpath (both the candidate and each sibling `local_path` are `realpathSync`'d when they exist, fail-open to the spelling otherwise), so a symlink resolving into or over another source's tree cannot slip past it; the stored pointer and the error message keep the operator's spelling.diff --git a/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.mdindex 29c5aca9ca..224849d6fd 100644--- a/docs/architecture/key-files/hindsight.md+++ b/docs/architecture/key-files/hindsight.md@@ -26,15 +26,10 @@ unresolvable+true|false, pre-v80 NULL/NULL rows survive).- `src/core/cycle/grade-takes.ts` — walks unresolved takes older than 6 months, retrieves evidence, asks judge model, caches verdict. Auto-resolve DISABLED by default. Conservative thresholds: >=0.95 single OR >=0.85 ensemble 3/3 unanimous. `aggregateEnsemble` reuses the cross-modal substrate; fires on the borderline 0.6-0.95 band. Writes to `take_grade_cache`. Same global-error posture as propose-takes: a judge failure that classifies as a whole-run condition breaks the take loop with `aborted_global_error` (auth/billing first hit; rate_limit after 3 consecutive takes; `fail` status when zero judge calls succeeded, else `warn` + warning count; `judge_calls_succeeded`/`judge_calls_failed`/`halted` in details). Rejected ensemble judges are classified the same way — `Promise.allSettled` never flattens a revoked key or exhausted spend limit into a silent null verdict. Per-take auto-apply failures stay per-take.- `src/core/cycle/calibration-profile.ts` — aggregates resolved takes into 2-4 narrative pattern statements + active bias tags. Voice-gated via `gateVoice()`. Cold-brain skip when <5 resolved. Writes to `calibration_profiles` with audit columns (`voice_gate_passed`, `voice_gate_attempts`, `grade_completion`).- `src/core/calibration/voice-gate.ts` — single `gateVoice()` function, mode parameter (`pattern_statement` | `nudge` | `forecast_blurb` | `dashboard_caption` | `morning_pulse`). 2 regens then template fallback from `src/core/calibration/templates.ts`. Haiku judge with mode-specific rubrics; all rubrics structurally forbid clinical/preachy voice.-- `src/core/calibration/cross-brain.ts` — 4-rule contract for cross-brain calibration reads. Local-first → mount-fallback (only with `canReadMountsForCtx(ctx)` true) → cross-brain attribution via `source_brain_id` + `from_mount` → subagent prohibition closes the OAuth-token-to-cross-brain-leak surface. All 4 rules pinned in `test/cross-brain-calibration.test.ts`.-- `src/core/calibration/nudge.ts` — real-time pattern surfacing. `evaluateAndFireNudge(opts)`: threshold check (conviction > 0.7, holder match, slug-derived domain hint matches active bias tag) → cooldown probe (14d via take_nudge_log) → fire + log. STDERR-only output; multi-channel deferred.-- `src/core/calibration/take-forecast.ts` — Brier-trend at write time. Pure math over existing `TakesScorecard`; no LLM. Returns `predicted_brier`, `bucket_n`, `overall_brier`. Insufficient-data branch at `MIN_BUCKET_N = 5`. `batchForecast` memoizes per (holder, domain) tuple.- `src/core/calibration/gstack-coupling.ts` — outcome-driven learnings coupling. `writeIncorrectResolution(opts)` shells out to the `gstack-learnings-log` binary. Config gate `cycle.grade_takes.write_gstack_learnings` (default false for external users). Namespace prefix `gbrain:calibration:v0.36.1.0:` so `--undo-wave` can scrub.- `src/core/calibration/svg-renderer.ts` — server-rendered SVG for the admin SPA Calibration tab. Pure functions: data → SVG string. Inlines design tokens; XSS-safe via `escapeXml()`. Four renderers: `renderBrierTrend`, `renderDomainBars`, `renderAbandonedThreadsCard`, `renderPatternStatementsCard`. SPA renders via `<TrustedSVG>` wrapper behind `requireAdmin`.- `src/core/calibration/undo-wave.ts` — `undoWave` reverses calibration's mutations: unsets `takes.resolved_*` for wave-applied resolutions (cross-checks resolved_by so manual writes persist), deletes calibration_profiles, purges nudge logs, marks grade-cache rows applied=false. `--dry-run` shows counts without writing. Idempotent on wave_version match.- `src/core/calibration/think-ab.ts` — A/B harness. `runAbTrial` calls thinkRunner twice (baseline + with-calibration), records preference to `think_ab_results`. `buildAbReport` aggregates over a 30-day window; flags `calibration_net_negative` when n>=20 + win rate < 45% on decisive trials.-- `src/core/calibration/recall-footer.ts` — formatter for the morning-pulse calibration block. Cold-brain branch when <5 resolved. Opt-in via the wiring layer.-- `src/core/eval-contradictions/calibration-join.ts` — cross-reference. `tagFindingWithCalibration(finding, profile)` returns bias-tag context for contradictions matching active patterns. Returns null when profile missing (output unchanged when no profile exists).- `src/core/think/prompt.ts` — anti-bias prompt shaping. `withCalibration` option on `buildThinkSystemPrompt` adds anti-bias rules. `buildCalibrationBlock()` emits the `<calibration>` XML. `buildThinkUserMessage` has TWO shapes: default (question first), and with-calibration (retrieval → calibration → question) when opt-in. Wired into `runThink` via `opts.withCalibration` + `opts.calibrationHolder`.- `src/commands/calibration.ts` — CLI: `gbrain calibration` (read + print), `--regenerate`, `--undo-wave <ver>`, `ab-report`. MCP op `get_calibration_profile` (scope: read) backs the same data path. Source-scoped via `sourceScopeOpts(ctx)`.- `src/core/owner-holder.ts` — single source of truth for "the brain owner" holder string. `DEFAULT_OWNER_HOLDER = 'self'` (matches the consolidate facts→takes writer + `docs/takes-vs-facts.md`); `resolveOwnerHolder({override, configValue})` returns override > `emotional_weight.user_holder` config > `'self'`. Consumed by the calibration_profile cycle phase, `gbrain calibration` CLI, the `get_calibration_profile` op, `think`'s calibration block, `emotional-weight`'s `DEFAULT_USER_HOLDER`, and doctor's `calibration_freshness`. Pure; unit-tested in `test/owner-holder.test.ts`. Does NOT unify owner-identity fragmentation (`self`/`brain`/`people-<owner>`) — tracked separately.@@ -44,5 +39,4 @@ unresolvable+true|false, pre-v80 NULL/NULL rows survive).- `admin/src/index.css` — `--text-muted: #777` (WCAG AA contrast bump to ~5.5 on the #0a0a0f bg).- `test/fixtures/calibration/extract-takes-corpus/` — synthetic prompt-tuning corpus. Ships 5 representative pages; full 50-page + 10-page holdout generated by `gbrain calibration build-corpus`. All anonymized per CLAUDE.md placeholder list.- `scripts/check-synthetic-corpus-privacy.sh` — CI guard in `bun run verify`. Greps for explicit dollar amounts + verifies non-essay fixtures reference at least one placeholder name.-- `test/regressions/v0.36.1.0-iron-rule.test.ts` — R1-R5 IRON-RULE inventory; pins all 5 rules in one place.- `DESIGN.md` — repo-root design system. Formalizes the de facto admin tokens. Calibration target for future `/plan-design-review` and `/design-review`.diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex 14c5fe11a6..2aca865a69 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness), each producer isolated so one failure never drops another's key; empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`.-- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract. It is compile-time source text (no runtime filesystem dependency; static imports of pure core leaves are fine — the rule bans filesystem/dynamic loading) and is imported by the stdio SDK server, OAuth HTTP SDK server, and legacy raw HTTP initialize path so all transports return the same instructions without drift. The contract covers skill routing, untrusted-content posture, source scope, and the `put_page` whole-page replacement/read-before-write rule. Two append-only extensions compose on top of it, in a fixed order: `buildMcpInstructions({writeback?})` adds the opt-in ambient-writeback section (from `src/core/facts/writeback-instructions.ts`) when `memory.auto_writeback` is enabled — absent/off is BYTE-IDENTICAL to `GBRAIN_MCP_INSTRUCTIONS`, and three exact-equality transport pins depend on that; `resolveMcpInstructions(config, env?, { writeback? })` takes that composed base and appends the operator-set deployment identity LAST under a `Deployment identity:` banner (no transport can weaken the contract): `GBRAIN_MCP_INSTRUCTIONS` env wins when non-blank, else `mcp.instructions` from the FILE plane (`~/.gbrain/config.json`; `gbrain config set|unset mcp.instructions` route there via `FILE_PLANE_DOTTED_KEYS` in `src/commands/config.ts`); an empty or whitespace-only env value is UNSET, not an override, and blank identity + writeback off returns the byte-identical canonical contract. Every transport calls `resolveMcpInstructions` with its own writeback opts: stdio once at boot via the fail-closed resolver (restart-to-flip, the strict-params posture; read failure = OFF bundle, never a wrong visibility posture; a running `gbrain serve` also needs a restart to pick up a new identity); OAuth per request (write-scope-gated, and the section renders only when THIS token's actual visible set — surface filter + bound-client fence — can call `remember`; `extract_facts` advertised under the same predicates); legacy bearer per initialize (surface-clamped: a surface without `remember` gets no section). All three route availability through `ambientOptsFrom(wb, {remember, extractFacts})`. Pinned over a real SDK `StdioClientTransport` by `test/e2e/serve-stdio-roundtrip.test.ts`, over raw HTTP by `test/http-transport.test.ts`, the identity plane (incl. the three-way composition order) by `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`, and the enabled-state builder/parity matrix by `test/mcp-instructions-writeback.test.ts`.+- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract. It is compile-time source text (no runtime filesystem dependency; static imports of pure core leaves are fine — the rule bans filesystem/dynamic loading) and is imported by the stdio SDK server, OAuth HTTP SDK server, and legacy raw HTTP initialize path so all transports return the same instructions without drift. The contract covers skill routing, untrusted-content posture, source scope, and the `put_page` whole-page replacement/read-before-write rule. Two append-only extensions compose on top of it, in a fixed order: `buildMcpInstructions({writeback?})` adds the opt-in ambient-writeback section (from `src/core/facts/writeback-instructions.ts`) when `memory.auto_writeback` is enabled — absent/off is BYTE-IDENTICAL to `GBRAIN_MCP_INSTRUCTIONS`, and three exact-equality transport pins depend on that; `resolveMcpInstructions(config, env?, { writeback? })` takes that composed base and appends the operator-set deployment identity LAST under a `Deployment identity:` banner (no transport can weaken the contract): `GBRAIN_MCP_INSTRUCTIONS` env wins when non-blank, else `mcp.instructions` from the FILE plane (`~/.gbrain/config.json`; `gbrain config set|unset mcp.instructions` route there via `FILE_PLANE_DOTTED_KEYS` in `src/commands/config.ts`); an empty or whitespace-only env value is UNSET, not an override, and blank identity + writeback off returns the byte-identical canonical contract. Every transport calls `resolveMcpInstructions` with its own writeback opts: stdio once at boot via the fail-closed resolver (restart-to-flip, the strict-params posture; read failure = OFF bundle, never a wrong visibility posture; a running `gbrain serve` also needs a restart to pick up a new identity); OAuth per request (write-scope-gated, and the section renders only when THIS token's actual visible set — surface filter + bound-client fence — can call `remember`; `extract_facts` advertised under the same predicates); legacy bearer per initialize (surface-clamped: a surface without `remember` gets no section). All three route availability through `ambientOptsFrom(wb, {remember, extractFacts})`. Pinned over a real SDK `StdioClientTransport` by `test/serve-stdio-roundtrip.test.ts`, over raw HTTP by `test/http-transport.test.ts`, the identity plane (incl. the three-way composition order) by `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`, and the enabled-state builder/parity matrix by `test/mcp-instructions-writeback.test.ts`.- `src/mcp/publish-gates.ts` — publish-gate resolution for the honest tools/list. `readPublishGate(engine, config, key)`: dual-plane (DB > file > false), never throws — a FAILED read resolves false (hide-on-doubt matches the default-off consent posture). `disabledOpsForPublishGates(engine, config)`: the op-name set tools/list subtracts; one getConfig read per distinct gate key per call, deliberately NOT memoized so `gbrain config set mcp.publish_skills true` takes effect on the next list without a restart. Call-time gates inside the handlers stay as the fail-closed backstop (their denials carry `detail: 'config_key=<key>'` — the machine-readable denial grammar). Pinned by test/publish-gates.test.ts.@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run` via `resolveSocketPathForConfig`; the bound-source posture rejects requests naming any other source) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live listener (another serve) returns the null binding (that serve is the IPC provider). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. Pinned by `test/resolve-ipc-binding.test.ts`.-- `src/mcp/server.ts` — MCP stdio server (generated from operations). Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/e2e/serve-stdio-roundtrip.test.ts`.+- `src/mcp/server.ts` — MCP stdio server (generated from operations). Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`.- `src/mcp/source-preflight.ts` — `assertStdioSourceBindable(engine, env?)`: stdio-lane boot preflight called first thing in `startMcpServer`, before any transport attaches. A well-formed `GBRAIN_SOURCE` that names no ACTIVE source row (`SELECT id FROM sources WHERE id = $1 AND archived = false`, the same predicate as `assertSourceExists` in `src/core/source-resolver.ts`) throws a message naming the value and the fix (`gbrain sources list`), so serve exits 1 instead of binding every call to a phantom scope where reads return `[]` and writes die on the sources FK while health stays green. An inherited `__all__` emits an engine-free stderr warning with a source-binding recovery action, without widening its fail-closed scope. Unset env and malformed values are left to the resolver; an engine error fail-opens (guards config, not connectivity); a degraded engine (`isEngineDegraded`) is never touched so the boot does not spend the proxy's reconnect attempt. HTTP is out of scope (tokens carry their own source grant). Pinned by `test/mcp-stdio-source-preflight.test.ts` and real PostgreSQL/PGLite processes in `test/e2e/mcp-search-transport-matrix.test.ts`.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex 321b95d01e..15ff8ee2f8 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -8,13 +8,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embedding-migration-budget.ts` — finite authorization in the existing migration marker, conservatively debited under the acquired leases before each provider attempt with the existing BudgetTracker. Resume preserves uncertain dispatched liability; unknown prices or missing input bounds refuse. Marker corruption cannot erase a versioned authorization. Only an explicitly reauthorized legacy marker without authorization fields can be replaced.- `src/core/facts/embedding-identity.ts` — active fact eligibility and stale model/text/width census shared by migration and fact repair. Legacy identity stays unknown. Both engine writers accept explicit `embedding_model` and compute the exact text hash; duplicate vector selection requires matching caller identity. `embed-facts.ts` installs under source-incarnation, row-version, withdrawal and configuration guards, retaining the outer migration invocation budget when nested.-- `src/core/anthropic-pricing.ts` — bare-keyed Anthropic VIEW of `model-pricing.ts` (the `anthropic:` canonical entries with the prefix stripped). Kept distinct because many callers look up by bare Claude id and because `estimateMaxCostUsd(modelId, inTokens, maxOutTokens)` carries the null-on-miss contract the dream-cycle budget gate depends on (non-Anthropic ids return null; `BudgetMeter` tries `canonicalLookup` first and only falls back here, so it warns `BUDGET_METER_NO_PRICING` and runs unbounded only when canonical has no rates either). `estimateMaxCostUsd` routes bare/colon/slash ids through `splitProviderModelId`. Do NOT hand-edit prices here — the map is derived from canonical, so it cannot drift. `ANTHROPIC_PRICING` is consumed by `budget/budget-tracker.ts`, `minions/batch-projection.ts`, and `cycle/budget-meter.ts`.+- `src/core/anthropic-pricing.ts` — bare-keyed Anthropic VIEW of `model-pricing.ts` (the `anthropic:` canonical entries with the prefix stripped). Kept distinct because many callers look up by bare Claude id and because `estimateMaxCostUsd(modelId, inTokens, maxOutTokens)` carries the null-on-miss contract the dream-cycle budget gate depends on (non-Anthropic ids return null; `BudgetMeter` tries `canonicalLookup` first and only falls back here, so it warns `BUDGET_METER_NO_PRICING` and runs unbounded only when canonical has no rates either). `estimateMaxCostUsd` routes bare/colon/slash ids through `splitProviderModelId`. Do NOT hand-edit prices here — the map is derived from canonical, so it cannot drift. `ANTHROPIC_PRICING` is consumed by `budget/budget-tracker.ts` and `cycle/budget-meter.ts`.- `src/core/contextual-retrieval-service.ts` — captures the complete originating projection before synopsis/embedding providers, then installs vectors with UPDATE-only CAS and stamps mode/generation in the same guarded transaction. Stored corpus generation participates in `page-state/projections.ts` indexing context even when the mode and canonical revision stay unchanged. New vectors receive the captured provider model; text, chunk identity, metadata and retrieval seal remain intact. Source contextual policy is rechecked before publication. Superseded preparation returns the existing retryable database result. Empty/disabled-mode stamps compare identity, seal, context and raw chunk inventory under the guard; unsealed nonempty chunks never reach a provider. `test/embedding-completion-atomic.serial.test.ts` covers real service/edit/rechunk/context interleavings and ordinary retrieval on both engines.- `src/core/embed-backfill-submit.ts` — Automatic per-source embed-backfill submitter with a true discriminated result union: `submitted` requires `jobId` plus an explicit spend-bypass payload, `cooldown` requires a reason plus a numeric remaining duration or explicit `null` for active work, `spend_capped` requires cap/spend payloads, and `no_worker_surface` requires the refused engine kind. It queries cooldown/spend state only after the shared admission classification accepts a worker-backed engine, preserving Postgres behavior while guaranteeing PGLite/unknown refusal before config, schema, or SQL access; callers handle every status exhaustively.-- `src/core/embed-facts.ts` — explicit source-scoped NULL-fact vector repair with read-only default preview, finite nonnegative spend cap plus optional count/time bounds, row-version/incarnation/withdrawal CAS and per-attempt cost accounting. Selected-brain policy is a trusted out-of-band argument; engine DB off-switch and policy are rechecked on every provider attempt. Managed mode updates physical projection only and live PGLite delegates through private `writer_embed_facts`, not a canonical fact rewrite. Tests: `test/e2e/fact-embedding-backfill-parity.test.ts`, `test/e2e/fact-backfill-resident.test.ts`.+- `src/core/embed-facts.ts` — explicit source-scoped NULL-fact vector repair with read-only default preview, finite nonnegative spend cap plus optional count/time bounds, row-version/incarnation/withdrawal CAS and per-attempt cost accounting. Selected-brain policy is a trusted out-of-band argument; engine DB off-switch and policy are rechecked on every provider attempt. Managed mode updates physical projection only and live PGLite delegates through private `writer_embed_facts`, not a canonical fact rewrite. Tests: `test/e2e/fact-embedding-backfill-parity.test.ts`, `test/fact-backfill-resident.test.ts`.- `src/core/embed-oversize-heal.ts` — heals ALREADY-STORED chunks that exceed the active embedding model's per-input token cap (new imports respect `resolveMaxChunkTokens()`, but `--stale` re-embeds existing `chunk_text` rows chunked under looser caps, which fail every sweep forever). `healOversizedChunks` splits oversized rows in place (never truncates; char-based hard split as the pathological fallback), re-indexes contiguously, carries each piece's modality/code-symbol metadata, and leaves embeddings unset so `upsertChunks` preserves vectors for unchanged `(chunk_index, chunk_text)` pairs and NULLs the split/shifted ones; `healOversizedPageChunks` is the load-split-upsert-reload wrapper. `healedChunksToStaleRows(chunks, slug, sourceId)` remaps a post-heal chunk list back into the stale-row shape — the shared seam between `src/commands/embed.ts:embedAllStale` and `src/core/embed-stale.ts:embedStaleForSource` so the two drains cannot drift; `chunk_source` passes through UNCHANGED (coercing `fenced_code` to `compiled_truth` would make `wrapChunkTextsForStoredMode` prefix code chunks, violating the D20-T4 never-wrap convention). Pinned by `test/embed-oversize-heal.test.ts`.@@ -42,7 +42,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/model-config.ts` — Model-string resolution (the seam every internal LLM call walks through). Four-tier system (`ModelTier = 'utility' | 'reasoning' | 'deep' | 'subagent'`) with `TIER_DEFAULTS` (utility→haiku-4-5, reasoning→sonnet-4-6, deep→opus-4-7, subagent→sonnet-4-6) and `tier?: ModelTier` on `ResolveModelOpts`. `resolveModelDetailed()` runs the 8-step chain and reports WHICH step won (`ResolveSource`): cliFlag → config key → deprecated key → `models.tier.<tier>` → `models.default` → env var (`GBRAIN_MODEL`) → key-aware tier default → caller fallback (the tier key sits ABOVE `models.default` — tier-specific beats generic, so setting a cheap utility tier is honored even when `models.default` is also set); `resolveModel()` is the thin wrapper for callers that only want the string. When the subagent capability gate replaces a configured model, the detailed result carries `substituted_from` + `substitution_reason` (`no_tools` / `no_subagent_loop` / `unknown_provider`); `describeResolveOrigin(source, opts)` renders the key-name origin (`models.tier.deep`, `models.default`, `GBRAIN_MODEL`, `built-in default`) used by the skillopt banner and `gbrain models`. Step 7 is KEY-AWARE: `resolveTierDefault(tier, env?)` walks `PROVIDER_TIER_DEFAULTS` (anthropic first — zero change for keyed installs; openai second so an OPENAI_API_KEY-only install resolves servable defaults) over the merged provider env (`mergedProviderEnv`, config-file keys folded, env wins, empty strings dropped); injected `env` is used EXCLUSIVELY (no config read — hermetic for tests); when neither anthropic nor openai key is present, a SERVABLE file-plane pin for the tier (utility→`expansion_model`, other tiers→`chat_model`, checked via `providerKeyReady`, `PIN_KEY_BY_TIER` is the single tier→key map) wins over the floor so a single-provider install (DeepSeek-only, OpenRouter-only, ...) routes every bare-default caller — extract_atoms, facts classify, page-summary — to the provider it actually has a key for; no key and no servable pin → `TIER_DEFAULTS` unchanged. The openai entry carries NO literal model pins: it resolves per call through the latest-model discovery cache (`src/core/ai/openai-latest.ts`, account-discovered, priced-only) with `openaiStaticTierFallback()` — the openai recipe's chat list ranked by the same grammar — as the offline floor, so the recipe is the single human-updated source and the account is the runtime source. The `gpt` alias resolves dynamically through the same path (the map entry is a documentation floor). `resolveEffectiveChatModel(fileCfg, env)` / `resolveEffectiveExpansionModel` are the ENGINE-FREE shared effective-model resolvers (`GBRAIN_MODEL` > servable file pin per `providerKeyReady` (recipe `auth_env.required`) > key-aware tier default; unservable pins warn once and fall through) — used by BOTH `reconfigureGatewayWithEngine`'s fallback layer and `detectCapabilities`' extraction probe so runtime routing and the capability report cannot diverge; they read RAW `loadConfig()` output, never gateway state (the boot fold stamps defaults, making explicit pins indistinguishable there). `isAnthropicProvider(modelString)` checks `provider:model` prefix OR `claude-` bare-id pattern (routes through `splitProviderModelId` from `src/core/model-id.ts` so slash-form ids like `anthropic/claude-sonnet-4-6` classify correctly). `enforceSubagentCapable()` is the layer-2 runtime guard: `tier === 'subagent'` resolutions are classified via `classifyCapabilities()` — `unusable:no_tools`/`unknown` warn once and fall back to `TIER_DEFAULTS.subagent`; `degraded:no_caching` (e.g. OpenAI) passes with a once-per-`(source, model)` cost warn. `_resetDeprecationWarningsForTest()` clears all three warn memos (deprecation, subagent, unservable-pin). Pinned by `test/model-config.serial.test.ts`.-- `src/core/model-id.ts` — `splitProviderModelId(input: string | null | undefined): {provider: string | null, model: string}` shared parser for the pricing side. Splits on `:` first, then `/`. Defensive contract: null/undefined/empty/whitespace returns `{provider: null, model: ''}`. Five sites consume it (`src/core/anthropic-pricing.ts:estimateMaxCostUsd`, `src/core/budget/budget-tracker.ts:lookupPricing`, `src/core/eval-contradictions/cost-tracker.ts:pricingFor`, `src/core/minions/batch-projection.ts` at two call sites, `src/core/model-config.ts:isAnthropicProvider`) so the pricing + classification surface has no parallel re-implementations of `provider:model` splitting — slash-form ids (`anthropic/claude-sonnet-4-6`) classify correctly instead of falling through to "unknown model". Distinct from the gateway-side `parseModelId` in `src/core/ai/model-resolver.ts`, which throws on bare names because routing needs an explicit provider; this one returns `{provider: null, model: 'bare'}` because pricing lookups happen against bare model ids. Pinned by `test/model-id.test.ts`.+- `src/core/model-id.ts` — `splitProviderModelId(input: string | null | undefined): {provider: string | null, model: string}` shared parser for the pricing side. Splits on `:` first, then `/`. Defensive contract: null/undefined/empty/whitespace returns `{provider: null, model: ''}`. Five sites consume it (`src/core/anthropic-pricing.ts:estimateMaxCostUsd`, `src/core/budget/budget-tracker.ts:lookupPricing`, `src/core/eval-contradictions/cost-tracker.ts:pricingFor`, `src/core/model-config.ts:isAnthropicProvider`) so the pricing + classification surface has no parallel re-implementations of `provider:model` splitting — slash-form ids (`anthropic/claude-sonnet-4-6`) classify correctly instead of falling through to "unknown model". Distinct from the gateway-side `parseModelId` in `src/core/ai/model-resolver.ts`, which throws on bare names because routing needs an explicit provider; this one returns `{provider: null, model: 'bare'}` because pricing lookups happen against bare model ids. Pinned by `test/model-id.test.ts`.- `src/core/model-pricing.ts` — single source of truth for paid-cloud CHAT/completion model pricing (USD per 1M tokens, input | output). `CANONICAL_PRICING` is a `provider:model`-keyed table (Anthropic Opus 5/4.8/4.7/4.6 `$5/$25`, Sonnet 4.6 `$3/$15`, Haiku 4.5 `$1/$5` both dateless + dated, plus OpenAI / Google / Together / DeepSeek panel models). Exported as `gbrain/core/model-pricing` for companion evaluators to enforce the canonical price cap. `canonicalLookup(modelId)` resolves bare (`claude-opus-4-8`), colon (`anthropic:claude-opus-4-8`), and slash (`anthropic/...`) forms — bare ids default to the `anthropic:` provider; nested OpenRouter ids (`openrouter:anthropic/...`) intentionally MISS so OpenRouter markup isn't repriced as the inner vendor; after the exact match, a case-insensitive fallback folds BOTH sides (some canonical keys carry cased model tails verbatim), safe only while no two canonical keys collide case-insensitively (pinned by the drift guard). Every other chat-pricing table is a DERIVED view of this one (NOT a hand-copied duplicate), so cross-table price drift is structurally impossible. Embeddings live separately in `embedding-pricing.ts` (different unit). Pinned by `test/model-pricing.test.ts` whose drift guard asserts each derived view equals canonical and that the cross-modal panel models are all present.diff --git a/docs/architecture/key-files/skills.md b/docs/architecture/key-files/skills.mdindex 97489aff62..f0d5e519ad 100644--- a/docs/architecture/key-files/skills.md+++ b/docs/architecture/key-files/skills.md@@ -23,7 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/skillopt/{reflect,output-cap,run-outcome,remediation,checkpoint,models-plan,job,bootstrap-run,must-abort,preflight}.ts` — skillopt run honesty and model provenance (user docs: `docs/guides/skillopt.md` "Optimizer output" + "Model provenance"). **Output caps** (`output-cap.ts`): one optimizer cap for every reflect call (patch + rewrite modes) and the eval-internal one-shot ablation, precedence `--reflect-max-tokens` / MCP+job `reflect_max_tokens` (remote callers clamped to 256-32000) > `skillopt.reflect_max_tokens` (invalid warns once, valid honored exactly) > `defaultMaxOutputTokens(optimizer)` (32000 thinking, 4096 otherwise); `skilloptOutputCap(model, siteCap)` gives the judge (200) and bootstrap sites `max(siteCap, 8192)` on thinking models only — gateway `chat()` semantics are untouched. **Reply classification** (`reflect.ts`): at most one error per call, in precedence `reflect_<mode>_truncated` (length stop; partial edits dropped) > `_empty_reply` > `_no_parseable_edits` > `_invalid_edits`; a fenced or bare `{"edits": []}` is a deliberate, usable empty; partial invalid drops sum into `reflect_invalid_edits_dropped`; the skill body is sent whole when it fits `resolveChatContextTokens(optimizer)` minus output cap and bounded prompt overhead at 3 chars/token (unknown window → 120,000 chars), else truncated with an in-prompt disclosure + `skill_body_truncated`; prompt + cap over the window refuses the call (`_context_too_small`), provider length errors map to `_context_overflow`; the one-shot rewrite refuses on `one_shot_rewrite_output_cap_too_small` / `_body_truncated` and never promotes a `_truncated` reply. The judge records `judge_error: llm_truncated` and bootstrap rows skip as `truncated` on a length stop. **Must-abort** (`must-abort.ts`): budget exhaustion, AI spend-policy refusals, runtime deadline and SIGINT rethrow (the validation gate uses the same predicate) at every optimizer/judge/held-out/bootstrap site, so the run ends `aborted` with its real reason. **Outcome** (`run-outcome.ts`): `accepted` if any candidate was accepted (even after an early stop), `errored` with `abort_detail: optimizer_output_unusable: <first error>` when no optimizer reply in the whole run was usable, else `no_improvement`; 2 consecutive fully-unusable steps (any class) stop the loop (`stop_reason: early_stop_unusable_output`); `buildResumeCommand` rebuilds the exact resume command from the stored run spec plus the run's mode, cost cap, runtime cap, `--models-strict` and `--force` (only when the run used it; the dirty-tree gate admits a resume whose SKILL.md equals the checkpoint's best text); output-cap failures (from `abort_detail`, or the trailing reflect error of an early stop) double the reflect cap, contract failures put a quoted `'<other-model>'` in place of the optimizer model. An early-stopped run keeps its checkpoint and resume command even when it resolves `no_improvement`; a resume re-runs the trailing fully-unusable steps (`rewindCursor`) and restarts the early-stop streak, a kept checkpoint banks the final evaluation's spend and the rewound cursor is persisted before any save, the cycle's skillopt phase GCs kept checkpoints older than 7 days, and a legacy checkpoint whose best text moved past its baseline counts as already accepted. CLI exit map: accepted 0, no_improvement 1, aborted/errored 2. **Remediation** (`remediation.ts`): `SKILLOPT_REMEDIATION_CODES` → `{code, fix, docs}` receipt entries whose `docs` anchors into the guide's error-code table (pinned by `test/skillopt/error-code-docs.test.ts`); errors deduped, max 20 x 300 chars. **Checkpoint/resume** (`checkpoint.ts`): stores a `next_epoch`/`next_step` cursor (legacy checkpoints converted), the early-stop counter, the reflect tally, ledger rows and cost on completed steps and handled aborts (an abort saves the step-start tally, since resume re-runs that step), and a run spec; `--resume` refuses a changed benchmark/held-out/split or a no-mutate → mutate widening, and allows optimizer model, reflect cap and cost cap overrides; the receipt merges prior segments into `models_used` (`models_used_scope: full_run`, or `since_resume` for legacy checkpoints) plus `prior_segments_cost_usd`. **Models plan** (`models-plan.ts`): `resolveSkillOptModels` is the ONE role resolution (optimizer→tier deep, target→subagent, judge→reasoning; flag > config chain) used by the CLI, the `run_skillopt` op, the cycle phase and the job handler (four-path golden test); `buildModelsPlan` adds per-task judge overrides (benchmark + held-out; the default judge is inactive when no reachable LLM-judged task lacks its own `judge.model`), gateway expansion/chat with retained sources, the embedding model of the column search actually reads (file plane / `GBRAIN_EMBEDDING_MODEL`, never DB rows) and the reranker when enabled; the stderr banner prints before any spend and `models_plan` lands on the receipt + `run_start` audit. Strict mode (`--models-strict` / `skillopt.models_strict`; unrecognized values warn and count as on) aborts before spend when any active touchpoint came from `models_default`, `tier_default`, `fallback`, `unknown` or a capability substitution, listing a copy-paste fix per touchpoint (an unreadable `skillopt.models_strict` counts as on; an explicit `embedding_columns.embedding` override counts as configuration); it applies to batch, fleet, both bootstrap modes and background jobs. Echoed strings pass `sanitizeEcho` (control chars stripped, 200-char cap). **Jobs** (`job.ts`): job data records the model flags and strict setting; the handler re-resolves sources and re-runs the strict check at execution time, legacy jobs resolve as `unknown`. **Bootstrap** (`bootstrap-run.ts`): both bootstrap modes resolve the optimizer via the plan, print its banner row, honor strict and `--dry-run`, and run under a `--max-cost-usd` tracker. **Preflight** (`preflight.ts`): prices each role's per-call reservation with the tracker's `reservationCostUsd` at effective caps and aborts pre-spend with `reservation_exceeds_cap` naming the role; the heuristic expected-cost estimate is reported separately. The cycle phase forwards `abort_reason`/`abort_detail`/`run_id`/`remediation`, records `skipped_budget` (no calls; retried only after the admission fingerprint — optimizer/target/judge models, reflect cap, per-skill cap, `pricing.overrides`, gbrain version, benchmark content (unreadable benchmark re-admits) — changes) and gates `errored` retries 24h via `cycle.skillopt.last_error.<skill>` without banking `last_run`.-- `src/core/skillpack/{init-brain-pack,brain-pack-advisory,brain-pack-lint,brain-resident-locate,nag-state}.ts` — brain-resident skillpacks. `manifest-v1.ts` gains optional `brain_resident` + `schema_pack` (additive). `runInitBrainPack` scaffolds a pack beside brain content (`brain_resident:true`, exact `gbrain_min_version`, 5-section machine-parseable README); `applyWritePlan` is factored out of `init-scaffold.ts` for the shared refuse-overwrite loop. `brain-pack-lint.lintBrainPackTools` validates each skill's `tools:` against the serving op set (E6 version-skew). Topology A: `src/commands/sources.ts` `runAdd` prints `brain-pack-advisory` to stderr after `opsAddSource`, fail-open; `nag-state.ts` (`~/.gbrain/skillpack-nag-state.json`) keys declines by `(source-repo brain_id, source_id, pack_name)` with pure `decideNagAction` (first/reminder/version-bump/ceiling) — declines count ONLY on CLI-interactive displays. Topology B: `brain-resident-locate.loadResidentPacksForServer` (source-scoped via `sourceScopeOpts`) backs the `list_brain_skillpack` op; `getResidentSkillDetail` backs `get_skill` `source_id`; `scaffold_spec` is the git source, never a server FS path. Tests: `test/skillpack-{init-brain-pack,nag-state,brain-resident-locate}.test.ts` + the brain-resident cases in `test/skillpack-manifest-v1.test.ts`.+- `src/core/skillpack/{init-brain-pack,brain-pack-advisory,brain-resident-locate,nag-state}.ts` — brain-resident skillpacks. `manifest-v1.ts` gains optional `brain_resident` + `schema_pack` (additive). `runInitBrainPack` scaffolds a pack beside brain content (`brain_resident:true`, exact `gbrain_min_version`, 5-section machine-parseable README); `applyWritePlan` is factored out of `init-scaffold.ts` for the shared refuse-overwrite loop. Topology A: `src/commands/sources.ts` `runAdd` prints `brain-pack-advisory` to stderr after `opsAddSource`, fail-open; `nag-state.ts` (`~/.gbrain/skillpack-nag-state.json`) keys declines by `(source-repo brain_id, source_id, pack_name)` with pure `decideNagAction` (first/reminder/version-bump/ceiling) — declines count ONLY on CLI-interactive displays. Topology B: `brain-resident-locate.loadResidentPacksForServer` (source-scoped via `sourceScopeOpts`) backs the `list_brain_skillpack` op; `getResidentSkillDetail` backs `get_skill` `source_id`; `scaffold_spec` is the git source, never a server FS path. Tests: `test/skillpack-{init-brain-pack,nag-state,brain-resident-locate}.test.ts` + the brain-resident cases in `test/skillpack-manifest-v1.test.ts`.- `src/core/skillpack/{manifest-v1,tarball,state,remote-source,trust-prompt,bootstrap-display,scaffold-third-party,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit}.ts` + `examples/skillpack-reference/` + `docs/skillpack-anatomy.md` + `scripts/build-skillpack-anatomy.ts` — third-party skillpack ecosystem. `gbrain skillpack scaffold <owner/repo|https-url|./tgz|./local-dir>` resolves the spec via `classifySpec`, fetches through SSRF-hardened `git-remote.ts` (git) or extracts the tarball into `~/.gbrain/skillpack-cache/<host>/<owner>/<repo>/<sha>/`, validates `skillpack.json` (api_version `gbrain-skillpack-v1`), checks `gbrain_min_version`, surfaces a TOFU first-install identity-confirm prompt (author + source + pinned commit + tarball SHA + tier; non-TTY requires `--trust`), records the pin in machine-owned `~/.gbrain/skillpack-state.json` (schema `gbrain-skillpack-state-v1`, atomic `.tmp + rename`, `isAlreadyTrusted` skips re-prompt on author+pin match), runs through `enumerateScaffoldEntries` → `copyArtifacts` (one-time additive, refuses to overwrite), then DISPLAYS `runbooks/bootstrap.md` WITHOUT executing (deliberately does not auto-execute). Registry catalog at `garrytan/gbrain-skillpack-registry` split into `registry.json` (PR-able, `gbrain-registry-v1`) + `endorsements.json` (maintainer-only overlay, `gbrain-endorsements-v1`); `effectiveTier` merges. `registry-client.ts` fetches both via `If-None-Match` etag with 1h soft-TTL + stale-fallback (origins `fresh_fetch | cache_warm | cache_soft_stale | cache_hard_stale`); hard-fail only on no-cache + no-network. CLI: `gbrain skillpack {search,info,registry,doctor,init,pack,endorse}`. Doctor walks `SKILLPACK_RUBRIC_V1` (10 binary dimensions: 5 required CORE — manifest_valid, skills_have_skill_md, routing_evals_present ≥5 intents, skills_have_unique_triggers MECE, changelog_present_and_current — and 5 quality BADGES — unit_tests_present, e2e_tests_present, llm_eval_present ≥3 cases, bootstrap_runbook_present, license_present); tier eligibility: `endorsed` needs all 10, `community` needs core + ≥3 badges, `experimental` needs core only, `blocked` when any core fails. `--quick` ~5s structural sweep; `--fix --yes` auto-scaffolds `auto_fixable: true` dimensions and refuses to overwrite files whose mtime is newer than `skillpack.json`. `gbrain skillpack init <name>` lands 11 files (skillpack.json, SKILL.md, routing-eval.jsonl, test/example.test.ts, e2e/example.e2e.test.ts, evals/example.judge.json, runbooks/{bootstrap,uninstall,upgrade-template}.md, CHANGELOG, README, LICENSE); freshly-init'd scores 10/10; `--minimal` skips test/e2e/evals. `gbrain skillpack pack` packs a deterministic tarball via GNU tar (`--sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner` + `GZIP=-n` + `TZ=UTC`); refuses on `tier_eligibility === 'blocked'`. Extract caps (5000 files / 100MB total / 1MB per file / 255-char paths / 100:1 compression ratio); rejects symlinks/hardlinks/devices/FIFOs. `gbrain skillpack endorse <name> [--tier ...] [--push] [--dry-run]` runs in a clone of the registry repo: validates the pack in `registry.json`, mutates `endorsements.json` via pure `applyEndorsement`, stable-key-orders the write, commits `endorse: <name> -> <tier>`, optionally pushes. JSONL audit at `~/.gbrain/audit/skillpack-YYYY-Www.jsonl` (ISO-week rotated, honors `GBRAIN_AUDIT_DIR`). `examples/skillpack-reference/` is a 10/10 reference pack pinned by `test/e2e/skillpack-third-party.test.ts`. `docs/skillpack-anatomy.md` auto-generated via `scripts/build-skillpack-anatomy.ts` (`--check` for CI drift). CLI dispatch in `src/commands/skillpack.ts` disambiguates third-party (contains `/`, `://`, `.tgz`) from bundled-skill kebab; kebab routes bundled-first, registry-fallback. Tests: `test/skillpack-{manifest-v1,tarball,state,remote-source,trust-prompt,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit,scaffold-third-party}.test.ts` + `test/e2e/skillpack-third-party.test.ts`. Spec at `docs/designs/SKILLPACK_REGISTRY_V1_SPEC.md`.diff --git a/docs/designs/KNOWLEDGE_RUNTIME.md b/docs/designs/KNOWLEDGE_RUNTIME.mdindex 3433e7c336..91e5570923 100644--- a/docs/designs/KNOWLEDGE_RUNTIME.md+++ b/docs/designs/KNOWLEDGE_RUNTIME.md@@ -3,6 +3,7 @@**Status:** DRAFT for CEO review.**Date:** 2026-04-18.**Supersedes:** The earlier "Feynman Ideas Assessment + Phase A/B" plan.+**Implementation note (later):** `src/core/enrichment/budget.ts` (`BudgetLedger`), `src/core/enrichment/completeness.ts` (`CompletenessScorer`), `src/core/fail-improve.ts`, `src/core/data-research.ts` and `src/core/minions/stagger.ts` were built but never gained a runtime caller, and were removed in the test-reduction fix wave. References to them below are historical.---diff --git a/docs/guides/cron-schedule.md b/docs/guides/cron-schedule.mdindex 2baf3ab395..ec7630e18d 100644--- a/docs/guides/cron-schedule.md+++ b/docs/guides/cron-schedule.md@@ -95,7 +95,7 @@ infer your current location and timezone. All times shown in YOUR local timezone// Hold the notification, fold into morning briefingget_user_timezone():- calendar = gbrain search "flight" --type calendar --recent 7d+ calendar = gbrain query "flight" --types calendar --since 7dif recent_flight:return infer_timezone(flight.destination)return config.default_timezone // fallback: US/Pacificdiff --git a/docs/guides/minions-deployment.md b/docs/guides/minions-deployment.mdindex 6096f9d97b..1002882c79 100644--- a/docs/guides/minions-deployment.md+++ b/docs/guides/minions-deployment.md@@ -442,7 +442,7 @@ for pid in $(pgrep -f 'gbrain jobs work'); do ps eww -p "$pid"; done \| grep -o -e '--allow-shell-jobs' -e 'GBRAIN_ALLOW_SHELL_JOBS=[^ ]*' | sort -u \|| echo "shell jobs not enabled"# An unflagged worker that claims a shell job dead-letters it instantly:-gbrain jobs list --status dead --name shell --limit 3+gbrain jobs list --status dead --json | jq '[.[] | select(.name == "shell")][:3]'```## Uninstalldiff --git a/docs/guides/minions-shell-jobs.md b/docs/guides/minions-shell-jobs.mdindex 36c759f786..f8385f6ef2 100644--- a/docs/guides/minions-shell-jobs.md+++ b/docs/guides/minions-shell-jobs.md@@ -255,7 +255,7 @@ cat ~/.gbrain/audit/shell-jobs-*.jsonl | jq '.'# First-time failure mode: submitted without env flag on the worker.# The handler is always registered but guarded: an unflagged worker that claims# a shell job dead-letters it immediately (UnrecoverableError, no retries).-gbrain jobs list --status dead --name shell+gbrain jobs list --status dead --json | jq '.[] | select(.name == "shell")'# → error_text: "shell handler disabled on this worker (start it with --allow-shell-jobs or GBRAIN_ALLOW_SHELL_JOBS=1 ...)"# `waiting` pileups mean NO worker is running at all (flagged or not) — check# `gbrain jobs supervisor status` in that case.diff --git a/docs/incidents/2026-05-20-lsd-cost-explosion.md b/docs/incidents/2026-05-20-lsd-cost-explosion.mdindex ed69d84e62..3f1098afcf 100644--- a/docs/incidents/2026-05-20-lsd-cost-explosion.md+++ b/docs/incidents/2026-05-20-lsd-cost-explosion.md@@ -220,7 +220,7 @@ architectural rounds shipped in the budget-cathedral wave that followed:`reason: 'cost' | 'runtime' | 'no_pricing'`. `record()` throws whencumulative spend exceeds the cap (TX1). `reserve()` hard-fails on`no_pricing` when the cap is set + model missing from pricing maps (TX2).-- **P6 (payload-fitter):** `src/core/diarize/payload-fitter.ts` with+- **P6 (payload-fitter; never wired, removed in the test-reduction fix wave):** `src/core/diarize/payload-fitter.ts` with`'batch'` and `'summarize'` strategies. Summarize embed-clusters(k=ceil(items/4)), Haiku-summarizes each cluster in parallel via`Promise.allSettled` at parallelism=4. Surfaces `degraded: true` flagdiff --git a/docs/migrations/v0.41.2-markdown-greenfield.md b/docs/migrations/v0.41.2-markdown-greenfield.mdindex 33bf12be94..d44c1b90eb 100644--- a/docs/migrations/v0.41.2-markdown-greenfield.md+++ b/docs/migrations/v0.41.2-markdown-greenfield.md@@ -28,62 +28,16 @@ import with provenance).gbrain apply-migrations --yes```-## The dry-run pass+## Status: the importer is not wired to the CLI-Always start with `--dry-run` to see what the importer would do-without writing anything:--```bash-gbrain capture --source markdown-greenfield \- --repo ~/git/brain \- --dry-run \- --limit 100-```--The output reports:-- `emitted` — atoms/concepts/ideas that would import cleanly-- `skipped_no_type` — files without a `type:` frontmatter (counted- as benign skips; no audit appended)-- `skipped_invalid` — files that failed validation (these append to- `~/.gbrain/audit/markdown-greenfield-failures-YYYY-Www.jsonl`)--Inspect the audit JSONL:-```bash-ls ~/.gbrain/audit/markdown-greenfield-failures-*.jsonl-cat ~/.gbrain/audit/markdown-greenfield-failures-*.jsonl | jq .-```--Common failures:-- **Empty frontmatter** — file has `---` but no fields. Not a real- brain page; safe to leave skipped.-- **Malformed YAML** — fix the file in your OpenClaw then re-run.-- **Missing required field** — usually means the original OpenClaw- skill output a partial page; check whether the file is worth- preserving.--## The actual import--When the dry-run looks clean, drop the `--dry-run` and `--limit`-flags:--```bash-gbrain capture --source markdown-greenfield --repo ~/git/brain-```--Expect ~30-60 minutes for the full 24K-page set (atoms + concepts +-ideas). The importer:--1. Walks `atoms/{YYYY-MM-DD}/*.md`, `concepts/*.md`, `ideas/*.md` in- deterministic alphabetical order so partial-run resumes pick up- where they left off.-2. Stamps `imported_from: markdown-greenfield` + `imported_at:- <ISO timestamp>` on every page's frontmatter, preserving ALL- original fields verbatim under `metadata.original_frontmatter`.-3. Emits each as an IngestionEvent with `mode: 'migration'` (T2),- which bypasses the daemon's 24h DedupWindow. The importer owns- its own permanent slug-keyed idempotency.-4. Routes through `put_page` so pages land with proper FK chains and- embedding eligibility.+The importer (`src/core/ingestion/sources/markdown-greenfield.ts`) shipped+as a module only; no gbrain command invokes it. The invocation this guide+originally documented, `gbrain capture --source markdown-greenfield --repo+~/git/brain`, fails with `unknown flag --repo`: `capture --source` selects a+brain source id, and `capture` has no `--repo` flag. To index an existing+markdown brain today, use `gbrain import <dir>` (see `gbrain import --help`).+Pages imported that way do not carry the `imported_from:+markdown-greenfield` marker described above.## After the import@@ -121,33 +75,3 @@ The OpenClaw skills themselves shrink to thin wrappers:- `atom-backfill-coordinator` → DELETED (backfill is now part ofextract_atoms via the Source Quote + lesson enrichment in oneHaiku call per transcript)--## Rolling back--The import is fully reversible:--```bash-# Soft-delete every page with the marker (recoverable for 72h)-gbrain query "imported_from:markdown-greenfield" --type atom --json | \- jq -r '.[].slug' | xargs -I{} gbrain pages delete {}-# OR hard-delete past the soft-delete window-gbrain pages purge-deleted --older-than 0h-```--Your OpenClaw's `~/git/brain/atoms/` + `concepts/` + `ideas/` directories-are untouched by the importer — they remain the source of truth for-rollback. The greenfield importer only READS from them.--## Re-running after partial failures--The importer is idempotent at the page-slug level: re-running on the-same `--repo` produces zero net-new pages (every page either lands-fresh or matches an existing slug). If you fix some validation-failures in your OpenClaw and want to retry just those:--```bash-gbrain capture --source markdown-greenfield --repo ~/git/brain-```--Already-imported pages stay; previously-failed pages get a fresh-attempt; the audit JSONL accumulates per-week (ISO week file rotation).diff --git a/docs/operations/conversation-parser-llm-fallback.md b/docs/operations/conversation-parser-llm-fallback.mdindex 685b1ffce0..466b307665 100644--- a/docs/operations/conversation-parser-llm-fallback.md+++ b/docs/operations/conversation-parser-llm-fallback.md@@ -27,8 +27,7 @@ The key is registered explicitly, so neither command needs `--force`.Values other than the exact string `true` leave the fallback disabled.The setting affects conversation fact extraction. It does not make the-synchronous `conversation-parser scan` command call a model, and it does not-enable the separate LLM polish scaffold.+synchronous `conversation-parser scan` command call a model.## Select the utility model and run a canarydiff --git a/docs/test-audit/2026-09-29/README.md b/docs/test-audit/2026-09-29/README.mdnew file mode 100644index 0000000000..0ffdc6d14f--- /dev/null+++ b/docs/test-audit/2026-09-29/README.md@@ -0,0 +1,69 @@+# Test audit evidence, 2026-09-29++Read-only discovery records from the 2026-09-29 test audit of gbrain at+`2ede415` (v0.59.11.0). Five lanes looked for tests that protect no shipped+behavior, the production code only those tests keep alive, and the coverage+holes that must be filled before anything is removed. Every candidate carries a+mutation probe: a behavior-breaking edit the test missed, or a+behavior-preserving edit it failed on.++These files are a historical research record. They describe the tree as it was+at `2ede415`; line numbers and counts drift as master moves, so re-verify a+reference against the current checkout before acting on it. They are not part of+the `llms.txt` bundles (`scripts/llms-config.ts` lists its sources explicitly+and does not include `docs/test-audit/`). The scanner scripts that produced the+inventories are not committed.++How a test is retired, and the evidence each deletion needs, is described in+[docs/TESTING.md](../../TESTING.md) ("Coverage responsibilities before+consolidation").++## Lanes++| Lane | Report | What it establishes | Consumed by |+|---|---|---|---|+| source-grep | [lane-source-grep/source-grep.md](lane-source-grep/source-grep.md) | Tests that read `src/**` as text: which are blind to behavior changes (probe edits they miss), which pin real contracts, and which need a routing fix before they can go | Blind/duplicate deletions; the source-grep rewrites; the `postgres-engine.ts` E2E map entry |+| doc-pins | [lane-doc-pins/doc-pins.md](lane-doc-pins/doc-pins.md) | Tests that assert on committed docs, skills, templates and recipes: prose-only pins versus generated-artifact freshness, link integrity and shipped prompt contracts | Doc-pin deletions; the resolver fixture tests; the doc-claims consolidation |+| e2e | [lane-e2e/e2e.md](lane-e2e/e2e.md) | How `test/e2e` files are routed in CI, which files run only PGLite, which wrappers double-run scenarios, and where selected E2E spends time | E2E lane corrections; the PGLite-only lane-move pilot |+| patterns | [lane-patterns/patterns.md](lane-patterns/patterns.md) | Cross-cutting low-value shapes over `test/**`: typeof probes, placeholder assertions, copied-function tests, near-duplicate files | Placeholder and typeof-probe cleanup; the `gbrain features` behavioral tests |+| seams | [lane-seams/seams.md](lane-seams/seams.md) | Test-only exports in `src/`, seams with no callers, and `src/` modules unreachable from every runtime entry (static walk, orphan guard, poison probe) | Seam cleanup; the dead-module cluster removals and their disposition gate |++## Inventories and probe logs++| File | Contents |+|---|---|+| [lane-source-grep/inventory.tsv](lane-source-grep/inventory.tsv) | Per test file: lane, test count, source reads, source imports, spawns, weight (ms), LOC |+| [lane-source-grep/pertest.json](lane-source-grep/pertest.json) | The same inventory with each file's test names |+| [lane-source-grep/struct_src.json](lane-source-grep/struct_src.json) | Files whose source reads look structural (counts, weight, LOC) |+| [lane-source-grep/probes.log](lane-source-grep/probes.log) | Raw mutation-probe results for the source-grep lane |+| [lane-e2e/e2e-files.json](lane-e2e/e2e-files.json) | Every `test/e2e` file classified by engine, key gating, spawning and weight |+| [lane-e2e/pglite-files.txt](lane-e2e/pglite-files.txt) | PGLite-only `test/e2e` files by weight (lane-move candidates) |+| [lane-e2e/attendance-retrieval-postgres.log](lane-e2e/attendance-retrieval-postgres.log), [lane-e2e/attendance-repair-postgres.log](lane-e2e/attendance-repair-postgres.log) | Measured runs showing the attendance wrappers execute both engine arms in the E2E lane |+| [lane-patterns/scan.json](lane-patterns/scan.json), [lane-patterns/scan2.json](lane-patterns/scan2.json) | Raw pattern-scan output (assertion shapes per file and per test) |+| [lane-patterns/neardup.txt](lane-patterns/neardup.txt) | Near-duplicate test file pairs by similarity |+| [lane-patterns/probes.log](lane-patterns/probes.log) | Raw mutation-probe results for the patterns lane |+| [lane-seams/test-only-exports.tsv](lane-seams/test-only-exports.tsv) | Exported `src/` symbols with no production caller, and the tests that use them |+| [lane-seams/seam-callers.tsv](lane-seams/seam-callers.tsv) | Test-named exports with their caller counts |+| [lane-seams/unreachable.tsv](lane-seams/unreachable.tsv), [lane-seams/dead-modules.txt](lane-seams/dead-modules.txt) | `src/` modules unreachable from any runtime entry, with LOC and the tests that import them |+| [lane-seams/dead-tests.txt](lane-seams/dead-tests.txt) | Test files that exist only to test those modules |+| [lane-seams/bundled-src.txt](lane-seams/bundled-src.txt) | `src/` files reached by a `bun build` of every runtime entry and package export |++The doc-pins lane recorded its probe results inline in its report; it has no+separate probe log.++## Implementation evidence++`implementation/` holds the per-slice evidence tables from the fix wave that+acted on these reports (v0.59.20.0): each deleted test's probe and surviving+owner, each new test's mutation, and each dead module's disposition.++| File | Slice |+| --- | --- |+| `implementation/security.md` | Source-config secret surfaces |+| `implementation/holes.md` | Coverage holes filled |+| `implementation/e2e-lanes.md` | E2E lane corrections |+| `implementation/deletions-guards.md` | Blind/duplicate test deletions, placeholder guard, source-read policy, docs |+| `implementation/dead-modules.md` | Dead-module clusters and the orphan permitted list |+| `implementation/pending-deletions.md` | Deletions that waited on new owners; process-cleanup fix |+| `implementation/lane-pilot.md` | Lane-move pilot and measurements |+| `implementation/rewrites.md` | Behavior rewrites, doc claims, docs-CLI truth check |diff --git a/docs/test-audit/2026-09-29/implementation/dead-modules.md b/docs/test-audit/2026-09-29/implementation/dead-modules.mdnew file mode 100644index 0000000000..94dd4fb49e--- /dev/null+++ b/docs/test-audit/2026-09-29/implementation/dead-modules.md@@ -0,0 +1,64 @@+# Evidence — dead-module clusters (misc, progressive-batch, calibration, minions) + orphan named-set ratchet++Base: master a6eca5e (v0.59.17.0). Ingestion cluster and `src/core/source-config-redact.ts` HELD by instruction (untouched).++## Disposition gate++(a) Reachability at base. `node scripts/check-orphan-modules.mjs` at a6eca5e: `45/46 test-only-reachable`, same 45 modules as the lane report (30 cluster + 7 ingestion + source-config-redact + 7 script-used). No cluster module gained a runtime caller. Poison probe: `throw new Error("POISON_PROBE <path>")` prepended to all 30 cluster modules, then `bun src/cli.ts --version` (rc 0), `bun src/cli.ts --help` (rc 0), `await import()` of all 31 other runtime entries and package exports (mcp/server, openclaw-context-engine, admin-embedded, agent-install/entry and every `package.json#exports` target: all rc 0), and `bun build <all entries> --packages external` (rc 0; `grep -rl POISON_PROBE` over the bundle: no match; bundle includes lazily imported commands, e.g. `runDream`). Reverted.++(b)/(c)/(d) One disposition per module:++| Module | Callers ever (git log -G on src/ imports) | User-facing promise found | Disposition |+|---|---|---|---|+| data-research.ts | none since v0.10.0 | skills/data-research is pure markdown; names no code | intentionally abandoned |+| fail-improve.ts | none since v0.10.0 | skill-autobench uses the taxonomy only ("taxonomy only" upstream note) | intentionally abandoned |+| eval-capture-graph.ts | none since v0.34.0.0 ("W7 capture wiring" left in v0.34.1 backlog) | skills/migrations/v0.34.0.0.md W7 bullet (annotated) | intentionally abandoned |+| commands/eval-schema-authoring.ts | never dispatched (v0.48.4.0 E4 kept it pending T16) | none (no CLI dispatch); TODOS T16 items reworded to rebuild from history | intentionally abandoned |+| artifact/index.ts | none since v0.39.1.0 | none | intentionally abandoned |+| distribution/index.ts | none since v0.39.1.0 (re-export barrel) | none | intentionally abandoned |+| diarize/payload-fitter.ts | none since v0.39.0.0 | TODOS "judges.ts → payload-fitter delegation" (closed; judges.ts keeps its own loop); incident doc annotated | intentionally abandoned |+| conversation-parser/llm-polish.ts | none since v0.41.16.0; config.ts documented "polish scaffold remains unwired" | docs/operations/conversation-parser-llm-fallback.md sentence (removed) | intentionally abandoned |+| enrichment/budget.ts (BudgetLedger) | none since v0.13.0 | design doc only; TODOS claim "backs gbrain enrich" false (`gbrain enrich` uses src/core/budget/budget-tracker.ts `BudgetTracker`) — closed. `budget_ledger` migration kept | intentionally abandoned |+| enrichment/completeness.ts | none since v0.16.0 | design doc; enrichable.ts comments (fixed) | intentionally abandoned |+| upgrade-checkpoint.ts | none since v0.30.1 | `gbrain upgrade --resume` promised only in the module header and CHANGELOG v0.30.1 (line ~23727/23744); no README/docs/help/skills promise; `--resume` absent from src/commands/upgrade.ts | intentionally abandoned (CHANGELOG note needed) |+| schema-pack/expand-type-filter.ts | none since v0.41.22.0 | skills/schema-unify/SKILL.md (2 sites) — corrected to describe the live alias closure | superseded by `expandEngineTypeFilters` (src/core/schema-pack/query-types.ts, used by ops/search.ts and search/hybrid.ts): gbrain-base-v2 `media` declares `article` as alias, so `--type article` still returns the pages (superset incl. other media) |+| schema-pack/rewrite-links-batch.ts | none since v0.41.22.0 | canonical-writers.tsv row (removed) | intentionally abandoned |+| skillpack/brain-pack-lint.ts | never wired into init-brain-pack (v0.42.47.0) | CHANGELOG v0.42.47 claim; scaffold SKILL.md comment "used by the version-skew lint" (corrected in init-brain-pack.ts); TODOS note corrected | intentionally abandoned (CHANGELOG note needed) |+| archive-crawler-config.ts | none since v0.25.1 (skill is pure markdown) | skills/archive-crawler/SKILL.md: safety fence "enforced by src/core/storage-config.ts" (false) | **HOLD** (required-but-unwired security fence claim) |+| chronicle/backstop.ts | live in put_page until **v0.51.0.0 (d13aa742f)** removed it during the durable-writes refactor (facts-backstop moved to the effects queue; chronicle dropped, commit message silent) | CHANGELOG v0.42.56 "turn it on with `gbrain config set auto_chronicle true`"; advisor tells users "enable auto_chronicle"; `isAutoChronicleEnabled` has no other reader → setting is a no-op | **HOLD** (accidental drop = bug) |+| onboard/impact-capture.ts | never wired (T12/T13/T15 integration never landed) | `gbrain onboard --history` (CHANGELOG v0.41.18) reads `migration_impact_log`; this module is its only writer → always empty | **HOLD** (required-but-unwired) |+| progressive-batch/{orchestrator,retrofit-wrap,stage-report}.ts | 3 retrofit sites landed in #1510 (f702ec053) and were removed an hour later by #1519 (8ab733471) merge resolution; TODOS.md:4541 records "The merge took ours (workers)" with an OPEN "re-compose progressive-batch + workers on the 3 reindex sites" item, plus open 9-site retrofit item (TODOS.md:4579) | doctor `progressive_batch_audit_health` reads an audit nothing writes; post-upgrade-reembed.ts:120-131 comment claims reindex writes it | **HOLD** pending parent decision (deliberate merge choice with open rewire TODO; not an accidental drop) |+| calibration/take-forecast.ts, recall-footer.ts, cross-brain.ts, nudge.ts; eval-contradictions/calibration-join.ts | none since v0.36.1.0 | CHANGELOG v0.36.1.0 E3/E5/E7/E8/T16 claims (stderr nudge, forecast blurb, contradiction tags, cross-brain sharing, `gbrain takes nudge --reset` — that CLI does not exist); skills/conventions/calibration.md "Cross-brain semantics (D18)" + "`canReadMountsForCtx()`" (that function exists nowhere) — corrected; plugin trees regenerated. `take_nudge_log` migration kept | intentionally abandoned (CHANGELOG note needed) |+| minions/budget-tracker.ts | none (only self-fix.ts, itself dead) | no `--budget-usd` flag on `gbrain jobs`; CHANGELOG v0.41.0 | superseded: live delegated-subagent spend cap is `withDelegatedSpend` → `src/core/minions/budget-meter.ts reserve/settle` (per-client daily cap, `pg_advisory_xact_lock` + reservation before each call = same bounded-overspend reservation property, keyed on client/day instead of batch owner) plus in-process `src/core/budget/budget-tracker.ts` via the gateway |+| minions/self-fix.ts | none | `minions.self_fix_max_depth` read nowhere | intentionally abandoned |+| minions/lease-cap-controller.ts | none | none (harness `scripts/e5-lease-cap-ab.ts` never imported it; deleted with its fixture) | intentionally abandoned |+| minions/batch-projection.ts | none | none (`gbrain jobs submit` prints no projection) | intentionally abandoned |+| minions/stagger.ts | none since v0.13.0 | cron-scheduler skill uses an agent-level 5-minute rule, not this hash; `stagger_key` not exposed by CLI/ops. Migration kept | intentionally abandoned |++## Deleted tests and dead mixed-file portions++| Deleted test | Case | Probe / evidence | Surviving owner | Owner result |+|---|---|---|---|---|+| 21 pure unit/serial files + 3 E2E files (minions-budget-cathedral, minions-controller-bounce-only, minions-self-fix-flow) for the 24 deleted modules | abandoned contract | poison probe above: only these tests detect the modules; every runtime entry unaffected; promises per table above | none needed (no runtime contract) | n/a |+| company-brain-schema: `expandTypeFilter('product').canonical` assertion | abandoned (dead helper property) | helper had no caller | same test's `expandClosure('company'/'product')` lines own the live closure | pass |+| skillpack-init-brain-pack: `lintBrainPackTools (E6)` describe (2 cases) | abandoned | lint never invoked by init-brain-pack | scaffolder cases in same file | pass |+| minions-quiet-hours: `staggerMinuteOffset` describe (5 cases) | abandoned | stagger offset never applied | v12 migration cases (stagger_key column + index) kept | pass |+| silent-abort-3516: "BudgetExhausted from the UNRELATED minions class" | vacuous after deletion | the confusable second `BudgetExhausted` class no longer exists | same file's classifyAbortError cases | pass |+| regressions/v0.36.1.0-iron-rule: R2 block | vacuous | pinned only the unwired calibration-join helper; contradictions output cannot change | n/a (PR 2 deletes the file whole) | pass |+| e2e/schema-cathedral: T22d block | abandoned | artifact abstraction never wired | rest of file | pass |+| e2e/v030_1-integration-pglite: Lane E (4 cases) | abandoned | upgrade-checkpoint never wired; no `--resume` | Lanes A-D (PR 3 deletes the file whole) | pass |+| e2e/jobs-watch-readsnapshot: fixture writer `setOwnerBudget` replaced by direct SQL | retained contract (readSnapshot budget_owners query) | mutation `budget_owner_job_id = mj.id` → `<> mj.id` in src/commands/jobs-watch.ts | the same test | FAILED under mutation (1 fail), passes restored |++## Orphan ratchet (named permitted set)++Before (MAX_TEST_ONLY_REACHABLE=46, 45 test-only): the 45 modules in (scratch) testonly-before.txt.+After (21 named entries, 0 ceiling): 7 script-reachable (bootstrap/template-repo, eval-contradictions/fixture-redact, eval/longmemeval/diagnostics, eval/longmemeval/evidence-packet, eval/shared/autocut-replay, mcp/http-transport, mcp/tool-catalog), source-config-redact (held), 7 ingestion (held), archive-crawler-config, chronicle/backstop, onboard/impact-capture, progressive-batch/{orchestrator,retrofit-wrap,stage-report} (held with reasons). Hard-orphan allowlist of 4 unchanged.++| Guard rule test | Probe edit | Result |+|---|---|---|+| unpermitted-test-only (incl. delete-one-add-one swap) | `const unpermitted = []` | 2 tests FAIL |+| stale-permitted-entry (deleted module) | skip the `!srcSet.has(path)` branch | 1 test FAILS |+| stale script-reachable tag | skip the script-reachable branch | 1 test FAILS |+| guard-self-test | bad fixture (hard orphan) → exit 1, good fixture (permitted test-only + script-reachable) → exit 0 | ok |++Guard runtime on the full corpus: 0.53 s wall (no network).diff --git a/docs/test-audit/2026-09-29/implementation/deletions-guards.md b/docs/test-audit/2026-09-29/implementation/deletions-guards.mdnew file mode 100644index 0000000000..1573d748dd--- /dev/null+++ b/docs/test-audit/2026-09-29/implementation/deletions-guards.md@@ -0,0 +1,110 @@+# PR 2 slice evidence — delete blind and duplicate tests, seams, guards, docs++Base: master @ a6eca5e (v0.59.17.0). All probes were temporary edits reverted by the probe tool+(`(scratch) pr2/probe.py`); raw output for every row is in `(scratch) pr2/probes.log`+(48 probe records). "git:<path>" means the deleted/trimmed test was materialized from HEAD next to+its original path for the probe run. Postgres probes ran against a local `pgvector/pgvector:pg16`+container with `GBRAIN_TEST_ALLOW_DATABASE_URL=1`.++Evidence cases: **R** = retained contract (surviving owner + executed mutation failure),+**A** = intentionally abandoned contract (disposition + reachability/promise evidence),+**V** = vacuous assertion (demonstrated lack of contract).++## Source-grep pins++| Deleted test | Case | Probe edit | Result | Surviving owner | Owner result |+|---|---|---|---|---|---|+| `test/voyage-response-cap.test.ts` (whole file, 6) | R | `src/core/ai/gateway.ts`: `MAX_VOYAGE_RESPONSE_BYTES` 256 MB → 512 MB | 6 pass / 0 fail (blind) | `test/ai/gateway.test.ts` › "Voyage OOM-cap: too-large response throws" | 38 pass / 2 fail (Layer 1 + Layer 2) |+| `test/remote-ping-status-field.test.ts` (whole file, 4) | R | `src/commands/remote.ts`: terminal check reads `job.state` | 3 / 1 (text pin) | `test/remote-cli.test.ts` › "remote ping poll loop" | 7 / 2 (behavioral: blip survives, failed → exit 1) |+| `test/connection-resilience.test.ts` 22 copied-function tests (isConnectionError ×12, classifyWorkerExit ×6, reconnect ×2, supervisor counter ×2) | V | `src/core/minions/exit-classification.ts`: always `'clean_exit'` | 25 / 0 (file imports no `src/`; tests its own copies) | `test/exit-classification.test.ts` (real function) | 11 / 6 |+| `fix-wave-structural` › "parseOpArgs handles --no-<key>" | R | `src/cli.ts`: `params[positiveKey] = true` | fails (text pin) | `test/cli-args.test.ts` › "--no-<boolean> maps to false…" | 11 / 1 |+| `fix-wave-structural` › "exports classifyPgliteInitError + buildPgliteInitErrorMessage" | R | `src/core/pglite-engine.ts`: bunfs arm removed | 31 / 0 (blind) | `test/pglite-init-classifier.test.ts` | 27 / 6 |+| `worker-lock-renewal-shape` › "launchJob calls runLockRenewalTick" | R | `src/core/minions/worker.ts`: call site replaced, import kept | old shape file 17 / 1 | `test/worker-lock-renewal-e2e.serial.test.ts` › H "worker survives renewLock throws" | 0 / 1 |+| (same) note | — | same mutation | — | `scripts/check-worker-lock-renewal-shape.sh` (plan's named owner) | **rc=0 — misses it**: invariant 2 greps the whole file, so the import satisfies it. Owner is the serial behavior test above. |+| `dream-cli-flags` 9 `--source` + 5 `--once` pins | R | `src/commands/dream.ts`: bare `--once` guard unreachable | 27 / 1 | `test/dream.test.ts` › "runDream — --once (issue #2860)" | 40 / 5 |+| `book-mirror` 5 pins (export, trust comment, cost-estimate, idempotency, partial-failure) | V | `src/commands/book-mirror.ts`: child `idempotency_key: undefined` | 9 / 0 (strings survive in comments/help) | none needed; `allowed_tools` + `remote: false` pins kept; export owned by typecheck + CLI registration spawn tests | — |++## Doc pins++| Deleted test | Case | Probe edit | Result | Surviving owner | Owner result |+|---|---|---|---|---|---|+| `test/readme-hero-anchors.test.ts` (5) | V | lane probe P1 (meaning-preserving reword fails it); imports no product code | — | README links/commands/privacy owned by `docs-navigation`, `docs-cli-commands`, `check:privacy` | — |+| `test/docs-bootstrap-persistence-table.test.ts` (2) | V | `src/commands/hook.ts`: `GBRAIN_STOP_PUSH === '0'` check removed | 2 / 0 (blind) | `test/hook-command.serial.test.ts` › "GBRAIN_STOP_PUSH=0 disables the per-turn push" | pass at baseline → **fail** under mutant (10 other push-spawn cases fail at baseline in this sandbox; environment) |+| `test/docs-timeline-extraction-guide.test.ts` (2) | V | imports no product code; pins doc wording only | — | behavior: `test/extract.test.ts` | — |+| `docs-mcp-deploy` 7 doc-only pins | V | `src/commands/serve-http.ts`: nonce TTL 5 → 60 min | 9 / 0 (blind) | none (prose); route anchor test kept | — |+| `docs-mcp-deploy` › "auth help points at the owner login flow" | R (moved) | now asserts spawned `gbrain auth --help` output | — | `test/cli-help-discoverability.test.ts` › "auth help points at the owner login flow…" (new, 4 strings incl. "do not GET the generated link") | passes |+| `skillopt/deadline-and-hermetic` #4741 (2) | V | lane probe P5: reworded retracted claim passes | — | none (comment/doc wording) | — |+| 16 per-guard "wired into verify" tests (tool-catalog 1, no-tracked-symlinks 2, check-bootstrap-guards 5, privacy-script-wired 5, check-engine-dynamic-import 3) | R | `scripts/run-verify-parallel.sh`: all 7 target guards dropped from CHECKS | — | `test/scripts/run-verify-parallel.test.ts` › "every manifest guard is executed by verify or explicitly exempt" | 7 / 2, missing list names all 7 |+| (same) precondition | — | all 7 targets (`check-tool-catalog-fresh.sh`, `check-no-tracked-symlinks.sh`, `check-bootstrap-tag.sh`, `check-bootstrap-templates.sh`, `check-grok-pin.sh`, `check-privacy.sh`, `check-engine-dynamic-import.sh`) are `scripts/guards-manifest.tsv` rows; none is in `EXECUTION_EXEMPT` | — | — | — |+| "test.yml runs `bun run verify`" (privacy-script-wired) + "verify delegates to run-verify-parallel.sh" | R (moved) | `.github/workflows/test.yml`: verify step → `echo skipped` | — | `test/scripts/ci-gates.test.ts` › "the verify job runs `bun run verify`, which dispatches through run-verify-parallel.sh" (new) | 8 / 1 |+| 5 real-repo `checkResolvable` duplicates (resolver ×2, check-resolvable ×3) | R | `skills/RESOLVER.md`: row points at missing `academic-verifyx/SKILL.md` | resolver 152/2, check-resolvable 50/2 | `check-resolvable` › "repo skills/ pass check-resolvable cleanly" + `check:resolver` in verify | 48 / 1 |+| `ambient-recall-templates` › rendered template-repo HEARTBEAT pin | R | rendered copy only: `gbrain context-pack` → `gbrain ctx-pack` | 3 / 1 | `scripts/check-bootstrap-templates.sh` (verify) + `check-bootstrap-guards` › "check-bootstrap-templates.sh passes on this repo" | rc=1 / 46 / 1 |++## Cross-cutting patterns++| Deleted test | Case | Probe edit | Result | Surviving owner | Owner result |+|---|---|---|---|---|---|+| `regressions/v0.36.1.0-iron-rule` R1 | R | `src/core/think/prompt.ts`: anti-bias section always on | 6 / 1 | `test/think-with-calibration.test.ts` (R1 guards) | 9 / 2 |+| iron-rule R2 | R | `calibration-join.ts`: null profile returns a tag | 6 / 1 | `test/eval-contradictions-calibration-join.test.ts` | 12 / 1 |+| iron-rule R3 | R | `takes-resolution.ts`: quality=correct → outcome null | 6 / 1 | `test/takes-resolution.test.ts` | 20 / 2 |+| iron-rule R4, R5, inventory | V | `expect(true).toBe(true)` / self-comparison of a local literal; cites nonexistent `test/source-isolation-pglite.test.ts` | — | — | — |+| 4 "phase functions exported for unit testing" + `__testing` exports (v0_12_0, v0_12_2, v0_13_0, v0_21_0) | V + A (seam) | `v0_12_0.ts`: `phaseASchema` throws on entry | typeof probe passes (4 / 1 overall) | `migrations-v0_12_0` › "dry-run skips all side-effect phases" | fails; `__testing` had zero other callers (grep) |+| ~29 typeof / "module imports" probes in 16 files (enrichment-service 4, transcription 3, doctor 3, code-callers-cli 2 [whole file], cycle-abort 1, eval-whoknows 1, whoknows 1, salience 1, extract 1, migrate 1, v0_37_fix_wave 1, gateway-chat 2, operations-embedding-column 2, query-op-autocut 1, query-op-adaptive-return 1, agent-harness 4) | V | `src/core/transcription.ts`: `transcribe` throws on entry | old file 4 / 2 (3 probes still pass) | same file's behavioral tests; missing exports fail `bun run typecheck` (tsconfig includes test) | 1 / 2 |+| `v0_37_fix_wave` › "GBrainConfig includes voyage_api_key (TS compile guard)" | V | body never references the field; `expect(true)` | — | typecheck over real consumers | — |+| `schema-pack-manifest-v041_2` › AggregatorKind tautology | V | `count_based` renamed | tautology passes, 2 siblings fail | same file › "exposes exactly 4 v1 aggregator kinds", "accepts all 4 aggregator kinds" | 18 / 2 |+| `link-extraction-relative-path` › "flat layout unchanged…" (byte-identical duplicate) | R | `link-extraction.ts`: `founded` not inferred | 13 / 1 | `link-extraction-dir-whitelist-2576` › "verb inference works for non-whitelisted dirs" | 9 / 1 |+| `e2e/schema-cathedral` T22d block (2) | R | `artifact/index.ts`: `.gbrain-schema` unrecognized | 7 / 1 | `test/artifact-abstraction.test.ts` | 5 / 1 |+| `e2e/cjk-roundtrip` › "vector path skip-gracefully" | V | unconditional `expect(true).toBe(true)`, imports nothing | — | — | — |++## Seams++| Deleted | Case | Probe / evidence | Result | Surviving owner | Owner result |+|---|---|---|---|---|---|+| `_clearIdentityCacheForTest`, `_clearPromptStateForTest`, `_resetFactsDimCheckCacheForTest`, `_resetRerankWarningsForTest`, `clearRegistryForTests`, `_resetRollupErrorLogForTests` | A | grep of `src test scripts admin/src docs`: zero callers (only comments); typecheck green after removal | — | — | — |+| `PostgresEngine.__resetFactsEmbeddingCastCacheForTest` + `embedding-dim-check-facts` pin | A + V | zero callers; pin only greps the method name; key-files doc sentence removed | — | — | — |+| `backoff` › "_resetForTest clears module state" | V | `backoff.ts`: `_activeProcesses++` removed | seam test passes | same file: "concurrent process limit…", "complete decrements…", "preflight returns boolean" | 7 / 3 |+| `core/git-head` case 10 | V | real HEAD probe always `null` | 21 / 0 | `test/source-health.test.ts` | 30 / 3 |+| `resolvers` › "_resetDefaultRegistry gives a fresh instance" | V | reset made a no-op | only this test fails (58 / 1) — it tests the seam | — | — |+| `title-match` › `MIN_CONTENT_TOKENS` pin + `__test__` export | R | floor 2→3 and 2→1 | — | same file's positive/negative behavior tests | 11/2 and 12/1 |+| `checkDnsRebinding` wrapper + 3 tests | R | `ssrf-validate.ts`: static `isInternalUrl` layer dropped | wrapper test fails too | `test/ssrf-validate.test.ts` + `resolvers` › "blocks localhost via SSRF guard", "blocks RFC1918" | 15 / 5, and resolver real-path tests fail |+| `maybeWarnUnscopedDefaultWrite` wrapper | R (repointed) | 10 assertions now call `assessUnscopedDefaultWrite(...).warning`; mutation: tier check dropped | — | `test/source-resolver-default-write-guard.test.ts` | 21 / 6 |++## Placeholder guard: disposition of every reported site (12 at this base)++| Site | Disposition |+|---|---|+| `backoff.test.ts:33,50,52` | rewritten: infinite load/memory thresholds, escape hatches removed; mutation (`_activeProcesses++` removed) fails 3 tests |+| `seed-pglite.serial.test.ts:90` | rewritten: `expect(existsSync(dbPath)).toBe(true)` |+| `extract-stale.test.ts:100` | rewritten: seeded page stays unstamped and stale after an empty batch |+| `core/background-work.test.ts:135` | rewritten: `await expect(drain…).resolves.toBeUndefined()` |+| `operation-context-sourceid-required.test.ts:35,61` | allowlisted: assertion is `@ts-expect-error`, enforced by typecheck |+| `e2e/embedding-column-postgres.test.ts:29`, `e2e/upsert-chunks-registry-column.test.ts:552` | allowlisted: bodies of `describe.skip` markers, never execute |+| `e2e/graph-signals-eval.test.ts:225` | allowlisted: gate fails by throwing above the marker |+| `e2e/sync-credential-preflight.test.ts:111` | allowlisted: absent file is the correct outcome; other branch asserts contents |+| (deleted earlier in this slice) cjk-roundtrip, iron-rule ×2, `v0_37_fix_wave:252` | deleted with their tests |++## Pending integration (NOT deleted in this slice)++1. **`test/postgres-engine-singleton-ownership.test.ts`** — needs PR 1 item 7 (e2e-test-map entry) **and** unit rewrites for three properties the E2E owners miss. Probes against `postgres-engine-disconnect-idempotency`, `db-singleton-shared-recovery`, `postgres-reconnect-singleton`:++ | Property | Mutation | Unit pin | E2E owners |+ |---|---|---|---|+ | P1 db.connect borrower returns false | borrower returns true | fails | idempotency 3/2, shared-recovery 2/1 — **caught** |+ | P2a engine stores db.connect token | flag always true | fails | 3/2, 2/1 — **caught** |+ | P2b no TOCTOU pre-sample | `getConnection()` probe before `db.connect` | fails | 5/0, 3/0, 3/0 — **missed** |+ | P3 disconnect only when owner | unconditional `db.disconnect()` | fails | 3/2, 2/1 — **caught** |+ | P4 snapshot + null before awaiting end | end awaited before nulling | fails | 5/0, 3/0, 3/0 — **missed** |+ | P5 module reconnect never tears down shared pool | `db.disconnect()` before `db.connect` in module branch | **passes (unit pin blind)** | reconnect-singleton 2/1 — **caught** |+ | P6 instance reconnect `_reconnecting` guard | guard assignment removed | fails | 5/0, 3/0, 3/0 — **missed** |++ Still needed: keep or rewrite P2b, P4 and P6 as unit tests (P4 is the eng-named snapshot-and-null case), land the map entry, record the cadence exception, then delete.++2. **`test/embed-helper-migration.test.ts`** — needs PR 1 item 3 **and** replacements for two pins the surviving owners miss (embed.serial, embed-stale.serial, embed-stale-signature-pagination.serial, embed-stale-chunkless-pages.serial, embed-oversize-heal-drain.serial):+ - signal threading: removing `signal: effectiveSignal` from the stale-path pool → pin fails, all five owners pass (52/0, 23/0, 7/0, 15/0, 3/0).+ - `failureLabel` slug projector: removing it (pool falls back to `String(page)`) → pin fails, all owners pass. Note `embedOnePage`/`embedOneKey` catch their own errors, so `failures[]` is only reached if they throw; a behavior test would need to force a throw.+ - gap found: removing the embedAll path's `...(signal && { signal })` passes the pin AND every owner.+ Still needed: a barrier-transport abort test for the stale pool (and the embedAll pool), plus either a forced-throw failureLabel test or an explicit reachability disposition, then delete.++3. **`features` typeof probes** (`exports runFeatures`, `exports featuresTeaserForDoctor`, `covers all 7 recipes`) — needs PR 1 item 1. Probe: `runFeatures` throws on entry → `features.test.ts` 12/0 and `features-recipe-secrets.test.ts` 7/0 (all blind). Delete once the behavioral features tests land.++4. **`e2e/mcp.test.ts` "MCP server module can be imported"** — left for PR 3, which deletes the whole file.diff --git a/docs/test-audit/2026-09-29/implementation/e2e-lanes.md b/docs/test-audit/2026-09-29/implementation/e2e-lanes.mdnew file mode 100644index 0000000000..e09a92ac65--- /dev/null+++ b/docs/test-audit/2026-09-29/implementation/e2e-lanes.md@@ -0,0 +1,146 @@+# PR 3: E2E lane corrections (test-reduction plan, items 1-8)++Scope: plan "PR 3 — E2E lane corrections" items 1-8 with the DX "PR 3 documentation" and eng amendments. The lane-move pilot is not in this PR. No production (`src/`) code changes. No VERSION/CHANGELOG change (the fix-wave integration does one bump).++## LOC (`git diff --numstat`)++| Area | Added | Removed |+|---|---:|---:|+| Production (`src/`) | 0 | 0 |+| Tests (`test/`) | 187 | 570 |+| CI/scripts/manifests (`scripts/`, `.github/`) | 40 | 21 |+| Docs (`docs/TESTING.md`, `CONTRIBUTING.md`) | 42 | 2 |++Whole files deleted: `test/e2e/mcp.test.ts` (70), `test/e2e/v030_1-integration-pglite.test.ts` (222), `test/e2e/v0_30_3-fix-wave.test.ts` (201).++## Compute (from `scripts/ubicloud/weights.json`, ms)++| Change | Before | After | Where it saves |+|---|---:|---:|---|+| delete `mcp.test.ts` | 1,201 | 0 | every run that selects it + tier1 |+| delete `v030_1-integration-pglite` | 26,038 | 0 (`backfill-base` unit 170 → 1,172) | E2E |+| delete `v0_30_3-fix-wave` | 13,153 | 0 (+~2 s unit in `bootstrap`) | E2E |+| attendance wrappers Postgres-only | 101,756 | 50,344 (27,079 + 21,285 + 1,980) | E2E when selected |+| field-report polling | 27,667 | 8,334 | E2E |+| reconcile-crash out of PR `selected-e2e` | 203,557 | 0 on PR selected-e2e (still in persistence-validation on every PR) | PRs that select them |+| live-key files out of the runner glob | 3,944 | 0 | nightly full corpus, local gates |+| mechanical "Performance Baselines" | ~1,200 | 0 | tier1 + nightly |++"After" values for changed files come from this branch's `bun run ci:ubicloud` run (10 VMs, same harness that produced the "before" weights), written into `scripts/ubicloud/weights.json`. That's one run each, not a matched multi-run comparison. Full gate: 9,389 s of test compute, 315 s wall.++## Evidence table++Mutation probes were run against the real production code with the named edit applied, then reverted (`git status src/` clean after each). Deleted files were restored from `HEAD` under a probe name (for example `test/e2e/v030-probe.test.ts`), run, and removed again. Raw logs: `(scratch) pr3-probes/item{3,4,5,6,8}.log`.++### Item 1: `test/e2e/mcp.test.ts` deleted (owners: `test/mcp-tool-defs.test.ts`, `test/operations-descriptions.test.ts`)++| Deleted test | Probe edit | Deleted test result | Surviving owner | Owner result |+|---|---|---|---|---|+| operations generate valid MCP tool definitions | `src/mcp/tool-defs.ts`: `paramDefToSchema` drops `description`; `buildToolDefs` emits `required: []` | 2 pass, 0 fail (blind: it re-implements the mapping) | `mcp-tool-defs.test.ts` | 4 fail: "output equals pre-extraction inline mapping byte-for-byte", "put_page warns…", "an op with a REAL declared dry_run param keeps its own schema", "paramDefToSchema preserves description on nested items" |+| same (description truthy) | `src/core/ops/salience.ts`: `get_recent_salience` description `''` | 1 fail | `operations-descriptions.test.ts` | 1 fail: "get_recent_salience description > matches the operation registration" |+| same (op names present) | `src/core/ops/orphans.ts`: `find_orphans` renamed | 1 fail | `mcp-tool-defs.test.ts` | 1 fail: "every non-localOnly op carries a non-empty area (WP4)" |+| MCP server module can be imported | top-level `throw` in `src/mcp/server.ts` | 1 fail | `test/mcp-stdio-gate-list.test.ts` (imports server.ts) | exit 1 (unhandled import error) |++Evidence case: retained contract. Also updated: `tier1` line in `.github/workflows/e2e.yml`, `E2E_EXCLUSIONS` in `scripts/e2e-matrix.ts`, the `src/mcp/**` entry in `scripts/e2e-test-map.ts` (still selects `http-transport` and `mcp-search-transport-matrix`), the `test/select-e2e.test.ts` fixture list, `CONTRIBUTING.md` tree listing, and weights.++### Item 2: attendance wrappers run only the Postgres arm++Scenario loops in `test/attendance-retrieval.test.ts`, `test/attendance-repair.test.ts`, `test/extract-timeline-attendance.test.ts` now use `testBackends()`; the three `test/e2e/*-postgres.test.ts` wrappers use `registerPostgresTests(() => import(...))`. No assertion changed.++Executed tests (JUnit reports, `(scratch) pr3-probes/att-describes.txt`):++| Lane | Describe | Executed |+|---|---|---:|+| unit (no `DATABASE_URL`) | non-overridden canonical attendance lifecycle (pglite) | 185 |+| unit | preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) | 86 |+| unit | meeting timeline attendance roles (pglite) | 11 |+| unit | shared and filesystem canonical attendance grammar (engine-agnostic) | 17 |+| E2E (`DATABASE_URL`, pg16) | non-overridden canonical attendance lifecycle (postgres) | 185 |+| E2E | preview-bound attendance repair (postgres; …) | 87 |+| E2E | meeting timeline attendance roles (postgres) | 11 |+| E2E | shared and filesystem canonical attendance grammar (engine-agnostic) | 17 |++E2E output has zero `(pglite)` describes. Before, the lane report measured retrieval 183 pglite + 183 postgres and repair 86 + 87 in the E2E wrapper. Cadence: the PGLite arm now runs in the unit lane on every PR (more frequent than selected E2E). The 17 engine-agnostic grammar tests sit outside the backend loop and still run in both lanes, as before.++### Item 3: `test/e2e/v030_1-integration-pglite.test.ts` deleted++| Deleted test | Probe edit | Deleted test result | Surviving owner | Owner result |+|---|---|---|---|---|+| listBackfills returns the canonical registry entries | drop `registerBackfill(modalityBackfill())` | 1 fail | `backfill-base.test.ts` › backfill registry (moved) | 1 fail |+| embedding_voyage is declared-only | `v030_1_status: 'implemented'` | 1 fail | `backfill-base.test.ts` › backfill registry (moved) | 1 fail |+| v44 emotional_weight_recomputed_at column exists / emotional_weight backfill on empty brain | drop the v44 `ALTER TABLE pages ADD COLUMN … emotional_weight_recomputed_at` in `src/core/migrate.ts` | 2 fail | planned owner `schema-bootstrap-coverage.test.ts`: **0 fail** (the column is on its exemption list). New owner: `backfill-base.test.ts` › "implemented backfills against a freshly initialized PGLite brain" | 1 fail: "emotional_weight finds every column it reads…" |+| effective_date backfill on empty brain: examined=0 | `let examined = 1` in `runBackfill` | 2 fail | `backfill-base.test.ts` | 5 fail incl. "returns done with no rows when no work to do" |+| after initSchema, config.version is at LATEST_VERSION | runner skips the last pending migration | 1 fail | `bootstrap.test.ts` | 6 fail incl. "fresh install regression: initSchema on empty DB produces LATEST" |+| dropZombieIndexes on PGLite is a no-op | PGLite branch returns `dropped: ['probe']` | 1 fail | `vector-index-lifecycle.test.ts` | 1 fail: "PGLite: no-op returns dropped: []" |+| checkActiveBuild on PGLite returns active: false | PGLite branch returns `active: true` | 1 fail | `vector-index-lifecycle.test.ts` | 1 fail: "PGLite returns active: false" |+| round-trip / resumeAt | `resumeAt: ALL_STEPS[0]` | 1 fail | `upgrade-checkpoint.serial.test.ts` | 1 fail: "partial completion → resumeAt = next un-completed step" |+| cross-brain checkpoint mismatch (X2) | brain_id check disabled | 1 fail | `upgrade-checkpoint.serial.test.ts` | 1 fail: "X2: brain mismatch → reason=brain_mismatch" |+| full step progression | `all_complete` returns valid | 1 fail | `upgrade-checkpoint.serial.test.ts` | 1 fail: "all steps complete → reason=all_complete" |+| connectionManager is null on PGLite | n/a | n/a | none needed | Vacuous: asserts a property is absent; the only reader (`src/core/minions/db-probe.ts`) reads it as optional, so adding an undefined field would fail this test with no behavior change. |+| schema_version on BrainHealth is optional | n/a | n/a | none needed | Vacuous: the type is `'1' \| undefined`, so `=== undefined \|\| === '1'` cannot fail for type-correct code. |++The new PGLite block adds about 2.6 s to `backfill-base.test.ts` (0.25 s before, 2.86 s after). Upgrade-checkpoint rows are the named mixed-file exception (owner until the misc cluster deletes the module).++### Item 4: `test/e2e/v0_30_3-fix-wave.test.ts` deleted; compounded pre-v34 case merged into `test/bootstrap.test.ts`++The merged case now also checks that every dropped column comes back (the old case checked only the version).++| Probe edit (`applyForwardReferenceBootstrap`, `src/core/pglite-engine.ts`) | Deleted v0_30_3 | `schema-bootstrap-coverage.test.ts` | `bootstrap.test.ts` (merged case) |+|---|---|---|---|+| drop `effective_date` ALTER | 2 fail | 3 fail | 1 fail (compounded pre-v34) |+| drop `modality` ALTER | **0 fail** | 1 fail | 0 fail |+| drop `import_filename` ALTER | **0 fail** | 1 fail | 0 fail |+| drop `embedding_image` ALTER | 2 fail | 2 fail | 1 fail |+| drop `salience_touched_at` ALTER | **0 fail** | 1 fail | 0 fail |+| drop `search_vector` ALTER | **0 fail** | 1 fail | 0 fail |++`schema-bootstrap-coverage` catches all six, and the deleted file missed four of them. Evidence case: retained contract.++### Item 5: reconcile-crash moves out of PR `selected-e2e`++`PERSISTENCE_VALIDATION_OWNED` in `scripts/e2e-matrix.ts` (commented with `persistence-validation.yml`) is spread into `E2E_EXCLUSIONS`. `prepareMatrix` and `scripts/select-e2e.ts` print `excluded: <file> (owned by persistence-validation.yml)`; select-e2e prints it on stderr when a mapped source or the suite itself changes, and still lists the files on stdout, so the local diff gates keep running them. `docs/TESTING.md` "Coverage responsibilities before consolidation" records the ownership change and the local command. Owner: `persistence-validation.yml`, called from `test.yml` (`pull_request` to master, no path filter), step "Require all reconciliation crash boundaries before and after activation", postgres × Bun 1.3.11/1.3.13, crash-manifest upload unchanged. The nightly full-corpus run still includes them.++| New/changed test | Probe edit | Result on probe | Result on real code |+|---|---|---|---|+| e2e-matrix › drops the persistence-validation.yml crash suites and names their owner | remove `...PERSISTENCE_VALIDATION_OWNED` from `E2E_EXCLUSIONS` | 1 fail | pass |+| same + select-e2e notice tests | `exclusionNotice` always generic | 3 fail | pass |+| select-e2e › a mapped reconcile source names both crash suites | skip map matching in `persistenceOwnedNotices` | 1 fail | pass |+| select-e2e › the CLI prints the notice on stderr and still lists the files on stdout | remove the stderr write from `main` | 1 fail | pass |+| e2e-wiring › every EXCLUDE entry is named by another job here, by persistence-validation.yml, or is a live-key spender | `persistence-validation.yml` stops naming `reconcile-crash.test.ts` | 1 fail | pass |++Documented local command run against pg16: see "Commands run".++### Item 6: `minions-field-report-repro` polls instead of sleeping 25 s++| Test | Probe edit | Result on probe | Result on real code |+|---|---|---|---|+| subagent batch under lease pressure completes; zero dead-from-lease-pressure | `src/core/minions/worker.ts:1659` `isLeaseFull = false && …` | 1 fail (7.4 s) | pass; 6 runs at 7.45-9.78 s (was 27.7 s weight) |++### Item 7: mechanical "Performance Baselines" removed++Vacuous: the block has zero `expect()` calls. The master copy run with `-t "Performance Baselines"` against pg16 reports 1 pass and no `expect() calls` line. It only printed timings. Import, search and link behavior stays owned by the rest of `mechanical.test.ts` (77 tests pass). The now-unused `time()` helper in `test/e2e/helpers.ts` is removed.++### Item 8: key-gated live files left out of the `run-e2e.sh` glob fallback++Files: the 2 openrouter `.live` replays and the 2 voyage files. No workflow provides `OPENROUTER_API_KEY` or `VOYAGE_API_KEY`. Argv invocation still runs them, and each header plus `docs/TESTING.md` shows `KEY=... bash scripts/run-e2e.sh <file>`.++| Test | Probe edit | Result on probe | Result on real code |+|---|---|---|---|+| nightly-e2e › the four actual runner partitions cover the complete default discovery exactly once (now also checks argv mode lists the live files) | remove the glob filter | 1 fail | pass |+| same | apply the filter to argv too | 1 fail | pass |++`bash scripts/run-e2e.sh test/e2e/voyage-multimodal.test.ts` still runs the file by name (1 file, passed).++## Manifests++- Weights: deleted and no-longer-discovered files removed from `scripts/e2e-weights.json` (281 → 274, metadata counts synced) and `scripts/ubicloud/weights.json` (2591 → 2584). The 14 touched files' `scripts/ubicloud/weights.json` entries were refreshed from this branch's `ci:ubicloud` run. `e2e-weights.json` values are mined from GitHub nightly logs, so its changed-file entries refresh on the next mine. `test-weights.json` and `serial-weights.json` had no entries for deleted files.+- `test/fixtures/e2e-unmapped-baseline.txt`: removed the 2 deleted files; `BASELINE_SEEDED_LENGTH` in `test/scripts/e2e-wiring.test.ts` lowered 150 → 143 to match.+- `scripts/structural-suites.tsv` regenerated (no change); `bun run build:llms` produced no change.+- Grep for deleted paths across `scripts/`, `.github/`, `test/`, `docs/`: only historical TODOS.md entries and CHANGELOG remain; left untouched per the TODOS rule.++## Commands run++- Focused unit/script tests (22 files, 724 tests, then 10 files, 150 tests): all pass after fixing `test/scripts/e2e-wiring.test.ts`'s honesty test for the new exclusion.+- Local pg16 E2E: tier1 line `bun test test/e2e/mechanical.test.ts test/e2e/job-isolation.test.ts test/e2e/sync-reconcile-postgres.test.ts` 81 pass; `bash scripts/run-e2e.sh` for field-report, the 3 attendance wrappers and mechanical: 5 files, 378 tests pass; the documented reconcile-crash command: 16 pass, 16 crash manifests.+- `bun run verify`: 55/55 checks green (46 s).+- `bun run ci:ubicloud`: all lanes green in 5m15s (gitleaks 1, verify 1, unit 1993, serial 331, slow 21, e2e 307 files, 0 failed).diff --git a/docs/test-audit/2026-09-29/implementation/holes.md b/docs/test-audit/2026-09-29/implementation/holes.mdnew file mode 100644index 0000000000..196e17f23c--- /dev/null+++ b/docs/test-audit/2026-09-29/implementation/holes.md@@ -0,0 +1,123 @@+## PR 1: fill coverage holes (test-reduction plan)++Adds behavioral owners for eight contracts that had none, before any test that depends on them is removed. No tests are deleted except the OCR seam wrapper's callers, which move to the real import boundary. One production change: the `_maybeOcrGatedForTests` export is removed from `src/core/import-file.ts`.++Every new test was run against a targeted mutation of the production code (it must fail) and against the real code (it must pass). Where an old test covered the same contract, the same mutation was run against it too. Raw results: `(scratch) mut/results.tsv`, per-probe logs in `(scratch) mut/logs/`.++### Mutation evidence: new tests++| Item | Contract | Mutation (production edit) | New test result | Old test on the same mutation |+|---|---|---|---|---|+| 1 features | `missing-embeddings` fires | `missing_embeddings > 0` → `> 1e9` | fail (2) | lane probe F: `runFeatures` throwing at entry left `features.test.ts` + `features-recipe-secrets.test.ts` 19 pass / 0 fail |+| 1 | `zero-links` fires / stays silent | `link_count === 0` → `=== -1` / `>= 0` | fail (1) / fail (2) | same |+| 1 | `zero-timeline` fires / stays silent | `=== 0` → `=== -1` / `>= 0` | fail (2) / fail (2) | same |+| 1 | `low-coverage` fires / stays silent | `< 0.9` → `< 0.4` / condition → `<= 1` | fail (1) / fail (2) | same |+| 1 | integrations ANY-of secrets | `secrets.some` → `secrets.every` | fail (2) | same |+| 1 | heartbeat counts as configured | heartbeat check → `return true` | fail (1) | same |+| 1 | only `setup_complete` heartbeats count | `evt?.event === 'setup_complete'` → `!!evt` | fail (1) | same |+| 1 | `no-sync` fires / stays silent | condition → `false` / `true` | fail (1) / fail (2) | same |+| 1 | priority-1 always pitched | `priority === 1` → `=== 3` | fail (1) | same |+| 1 | declined priority-2 suppressed | declined check removed | fail (1) | same |+| 1 | brains under 3 pages skip P2 checks | `page_count >= 3` → `>= 0` | fail (1) | same |+| 1 | offers persisted | `saveOffers` removed from JSON path | fail (1) | same |+| 1 | healthy early return writes nothing | `saveOffers` added to early return | fail (1) | same |+| 1 | offers under `HOME`, not `GBRAIN_HOME` | `offersPath` uses `GBRAIN_HOME` | fail (2) | same |+| 2 supervisor | 3-strike threshold | `>= 3` → `>= 2` / `>= 4` | fail (4) / fail (3) | copied-logic tests in `connection-resilience.test.ts` pass; only the "Eng-review D3" source pin fails |+| 2 | degraded branch reachable | `>= 3` → `false` | fail (3) | same (only the D3 source pin fails) |+| 2 | reconnect called | `engine.reconnect()` removed | fail (3) | not run |+| 2 | reconnect success resets counter | reset removed | fail (1) | not run |+| 2 | reconnect failure keeps counter | reset added on failure | fail (1) | not run |+| 2 | successful health query resets | reset removed | fail (1) | not run |+| 2 | stopping suppresses | `stopping` dropped from guard | fail (1) | not run |+| 2 | configuration-blocked suppresses | `configurationBlocked` dropped from guard | fail (1) | not run |+| 2 | `db_reconnected` event | reason renamed | fail (1) | not run |+| 3 embed | default 20 on `--all` (embedAll) | default `'20'` → `'19'` / `'25'` | fail (1) / fail (1) | `embed.serial.test.ts` + `embed-helper-migration.test.ts`: 60 pass / 0 fail on `'19'` |+| 3 | default 20 on `--stale` (embedAllStale) | default `'20'` → `'19'` / `'25'` | fail (1) / fail (1) | not run |+| 4 schema | `EXPERIMENTAL_VERBS` content | set emptied | fail (1) | old constant-vs-constant test: 7 pass / 0 fail |+| 4 | one verb dropped | `graph` removed | fail (1) | not run |+| 4 | `(experimental)` tag rendered | tag → `''` | fail (1) | not run |+| 5 check-resolvable | `add_trigger` fix type | `add_trigger` → `add_row_PROBE` | fail (1 of 233 across check-resolvable, -cli, resolver) | lane probe Q3: 231 pass / 0 fail |+| 5 | fix `skill_path` / `section` | path without `skills/` / section renamed | fail / fail | not run |+| 5 | MECE whitelist filters overlaps | whitelist filter removed | fail (2) | not run |+| 5 | whitelisted skills need no triggers | gap-skip removed | fail (1) | not run |+| 5 | `brain-ops` whitelisted | entry removed | fail (1) | not run |+| 5 | overlaps reported | overlap push skipped | fail (1) | not run |+| 6 OCR | env opt-in off means no OCR | opt-in check removed | fail (2) | old `_maybeOcrGatedForTests` suite: 7 pass / 0 fail |+| 6 | env opt-in on runs OCR (positive control) | OCR never runs | fail (8) | old suite: 7 pass / 0 fail |+| 6 | hash-unchanged re-import when OCR wanted | `ocrWanted = false` | fail (1) | not run |+| 6 | budget gate | gate disabled | fail (4) | not run |+| 6 | budget consumed | `images += 1` removed | fail (3) | not run |+| 6 | config cap honored | config read ignored | fail (2) | not run |+| 6 | cap 0 means unlimited | `> 0` → `>= 0` | fail (1) | not run |+| 6 | `ocr_status: done` stamped | stamp removed | fail (1) | not run |+| 6 | OCR text persisted | OCR text dropped | fail (2) | not run |+| 7 e2e map | `postgres-engine.ts` selects its 3 singleton owners | one owner / all three removed from the map | fail (1) / fail (1) | no test existed; lane report: a `postgres-engine.ts`-only diff selected 25 files and none of the three |+| 8 SIGPIPE | broken pipe runs the cleanup route | SIGPIPE listener removed | fail (1) | old test was `test.skip` |+| 8 | cleanup deletes the lock (both cases) | cleanup pass runs no entries | fail (2) | old SIGTERM test: failed 3/3 locally, but passes vacuously whenever it misses the lock row (early-return path, now removed) |+| 8 | SIGTERM runs cleanup | SIGTERM listener removed | fail (2) | not run |+| 8 | stdout/stderr `EPIPE` listeners | both listeners removed | **pass (survived)**: under Bun the broken pipe arrives as SIGPIPE, so these listeners are unreachable; filed in TODOS.md | n/a |++All new and changed tests pass on the real code (focused run below).++### Deleted test++| Deleted | Evidence case | Probe edit | Result | Surviving owner | Owner result |+|---|---|---|---|---|---|+| `src/core/import-file.ts` `_maybeOcrGatedForTests` seam (and the old `ocr-run-budget.test.ts` cases that called it) | Retained contract | opt-in check removed; OCR never runs; budget gate disabled | old seam tests pass on the first two (they bypass the opt-in); the new tests fail on all three | `test/ocr-run-budget.test.ts` (rewritten through `importImageFile`) | fail on every mutation above, pass on real code |++The old `EXPERIMENTAL_VERBS` constant-vs-constant test body was replaced in place by the behavioral test (item 4). Vacuous-assertion evidence: emptying the set left it passing (7 pass / 0 fail).++### SIGPIPE determinism bar (item 8)++One Ubicloud `standard-8` VM, `scripts/ubicloud/setup-ci-vm.sh` (Postgres + PgBouncer slot), `scripts/run-unit-parallel.sh` looping in the background to saturate the CPU, then `test/e2e/sync-lock-recovery.test.ts` run 50 times back to back through `scripts/ubicloud/ci-item.sh e2e`, then one run with the SIGPIPE cleanup listener removed. Log: `(scratch) sigpipe/result/out/sigpipe-50.log`.++| Measure | Result |+|---|---|+| Consecutive runs | 50 of 50 passed (8 pass / 0 fail each; both boundary cases passed every run) |+| CPU load during the runs (8 vCPU) | load1 between 5.84 and 13.30; the unit saturator (`run-unit-parallel.sh`, 4 shards) ran for the whole window |+| Per-run wall time | 8-9 s |+| Mutation: SIGPIPE cleanup listener removed | failed as required (rc=1): "closing the output pipe mid-sync routes through cleanup and releases the lock" |++The bar is met, so item 8 counts as a closed hole and the plan's fallback (delete the skip, file a TODO) was not needed.++### Supervisor: reconnect on every failing tick++A failed `engine.reconnect()` leaves the failure counter at 3 or more, so each later failing health tick warns `db_connection_degraded` and reconnects again. No doc or CHANGELOG entry says whether this is intended. The test pins current behavior; TODOS.md has an entry to confirm or add a backoff.++### Production bug found (not fixed here)++`src/core/process-cleanup.ts`: a second signal during the cleanup pass calls `process.exit` before the first pass's lock DELETE finishes (`runCleanupPass` returns at once when a pass is already running, and each signal handler exits in `.finally`). Reproduced 4/4 locally by closing the sync output pipe the moment the lock row appears: two SIGPIPE deliveries, both cleanup callbacks registered, neither finished, exit 141, `gbrain-sync:default` row left until its TTL. Filed as a P2 in TODOS.md with the proposed fix.++### Diff size++| Area | Added | Removed |+|---|---|---|+| Production (`src/`) | 0 | 9 |+| Scripts (`scripts/e2e-test-map.ts`) | 5 | 0 |+| Tests (`test/`, incl. 2 new files) | 789 | 152 |+| Docs (`docs/TESTING.md`, `TODOS.md`, `.gitignore`) | 33 | 0 |+| Committed audit evidence (`docs/test-audit/2026-09-29/`, 24 files) | ~14,250 | 0 |++### Commands++| Command | Result |+|---|---|+| Focused: 23 files, each run alone (`features`, `features-recipe-secrets`, `supervisor-health-reconnect`, `supervisor`, `supervisor-wedge`, `supervisor-configuration-blocked`, `connection-resilience`, `embed-default-concurrency`, `embed.serial`, `embed-helper-migration`, `schema-cli-contract`, `check-resolvable`, `check-resolvable-cli`, `resolver`, `ocr-run-budget`, `import-image-retry`, `select-e2e`, `scripts/e2e-wiring`, `process-cleanup`, `docs-cli-commands`, `build-llms`, `docs-navigation`, `test-reads-source-smell`) | all pass (log `(scratch) focused.txt`) |+| New unit files plus gateway-sensitive neighbors in one `bun test` process | 110 pass / 0 fail |+| `bash scripts/run-e2e.sh test/e2e/sync-lock-recovery.test.ts` (local pgvector) | 8 pass / 0 fail |+| `bun run verify` | 55/55 checks green (19 s) |+| `scripts/check-privacy.sh` on the committed lane reports, plus a manual real-name review | clean; only public names (repo owner in `garrytan/gbrain`, the public Hermes harness, and a `users/garry` string quoted from an existing test) |+| `bun run ci:ubicloud` | all checks passed in 5m35s: gitleaks 1, verify 1, unit 1995, serial 331, slow 21, e2e 314, 0 failed (7 of 10 VMs became ready; the queue drained on those) |++New test timings: `features.test.ts` about 4 s (one PGLite boot), `ocr-run-budget.test.ts` about 4 s (one PGLite boot), `embed-default-concurrency.test.ts` about 1 s, `supervisor-health-reconnect.test.ts` under 0.5 s, the `check-resolvable` and `schema-cli-contract` additions a few ms each, `sync-lock-recovery.test.ts` about 11 s (both boundary cases use a 1,000-file repo).++### Contributor note (for the CHANGELOG "For contributors" section)++- `gbrain features` now has behavioral tests (`test/features.test.ts`): each feature check fires in a fixture brain with the gap and stays silent in a healthy one; recipe names in the integrations pitch follow env and heartbeat configuration; declined offers are suppressed; offers persist only under the temporary home.+- New `test/supervisor-health-reconnect.test.ts` drives the supervisor's DB health branch (3-strike degrade + reconnect, reset, failed reconnect, stopping and configuration-blocked suppression) through the real health check.+- New `test/embed-default-concurrency.test.ts` pins the default of 20 embed workers on both `--all` and `--stale` through the real gateway path.+- `test/schema-cli-contract.test.ts` checks `gbrain schema usage` output instead of grepping for verb names; `test/check-resolvable.test.ts` adds fixture trees for the unreachable-skill fix and the overlap whitelist.+- `test/ocr-run-budget.test.ts` now drives `importImageFile` (opt-in on and off, hash-unchanged retry, budget caps); the `_maybeOcrGatedForTests` export is gone.+- `scripts/e2e-test-map.ts` routes `src/core/postgres-engine.ts` to its three shared-singleton E2E owners (removed from `test/fixtures/e2e-unmapped-baseline.txt`).+- `test/e2e/sync-lock-recovery.test.ts`: the skipped `| head -5` case is replaced by a real closed-pipe test, and the SIGTERM case no longer passes when it misses the lock; both wait for the held lock first and fail if they never see it.+- The 2026-09-29 test-audit lane reports are committed under `docs/test-audit/2026-09-29/` (linked from `docs/TESTING.md`, excluded from the llms bundles and from the docs CLI-command scanner).diff --git a/docs/test-audit/2026-09-29/implementation/lane-pilot.md b/docs/test-audit/2026-09-29/implementation/lane-pilot.mdnew file mode 100644index 0000000000..2b18298a63--- /dev/null+++ b/docs/test-audit/2026-09-29/implementation/lane-pilot.md@@ -0,0 +1,84 @@+# Lane-move pilot evidence (slice: 20 PGLite-only test/e2e files)++Base: collector branch `test-reduction-wave` at faf4e0f. BEFORE run `2026-09-29T05-13-41-018Z-faf4e0fa`, AFTER run `2026-09-29T05-26-52-078Z-faf4e0fa` (same config: 10 x standard-16, 8 slots, all lanes).++## Selection (move criterion)++Ranked by `scripts/e2e-weights.json` over `docs/test-audit/2026-09-29/lane-e2e/pglite-files.txt`. Skipped: `sync-delegation-under-serve.serial` and `dream-synthesize-pglite` (named e2e.yml tier1 steps, E2E_EXCLUSIONS); `v030_1-integration-pglite` and `v0_30_3-fix-wave` were already deleted by earlier slices. Every file: constructs PGLite or spawns a PGLite CLI directly, no `test/e2e/helpers` import, no DATABASE_URL/hasDatabase skip gate (they only scrub the URL for children), header read.++## Per-file table++| Former path | New path | Lane | GitHub e2e weight (s) | ubicloud BEFORE e2e (s) | ubicloud AFTER new lane (s) | local new lane (s) | executed pass/skip (e2e = new) |+|---|---|---|---:|---:|---:|---:|---|+| `test/e2e/claw-test.test.ts` | `test/claw-test.slow.test.ts` | slow | 185.9 | 67.8 | 67.7 | 78.4 | 12/0 |+| `test/e2e/init-fresh-pglite.test.ts` | `test/init-fresh-pglite.slow.test.ts` | slow | 44.5 | 39.0 | 35.6 | 36.4 | 17/0 |+| `test/e2e/mounts-routing-pglite.test.ts` | `test/mounts-routing-pglite.slow.test.ts` | slow | 31.0 | 28.6 | 27.6 | 29.1 | 8/0 |+| `test/e2e/qm-provisioning.test.ts` | `test/qm-provisioning.test.ts` | unit | 28.3 | 26.9 | 25.1 | 27.3 | 11/0 |+| `test/e2e/minions-field-report-repro.test.ts` | `test/minions-field-report-repro.test.ts` | unit | 26.5 | 7.6 | 7.3 | 9.5 | 1/0 |+| `test/e2e/fresh-install-pglite.test.ts` | `test/fresh-install-pglite.serial.test.ts` | serial | 23.4 | 18.5 | 20.6 | 21.7 | 6/0 |+| `test/e2e/remote-privacy-journeys.test.ts` | `test/remote-privacy-journeys.serial.test.ts` | serial | 19.9 | 17.4 | 22.7 | 17.0 (separate run) | 6/0 |+| `test/e2e/serve-stdio-roundtrip.test.ts` | `test/serve-stdio-roundtrip.test.ts` | unit | 19.8 | 17.3 | 22.4 | 17.8 | 9/0 |+| `test/e2e/serve-http-surface-ceiling.test.ts` | `test/serve-http-surface-ceiling.test.ts` | unit | 16.8 | 13.6 | 17.5 | 16.1 | 6/0 |+| `test/e2e/skillpack-flow.test.ts` | `test/skillpack-flow.test.ts` | unit | 13.7 | 10.6 | 10.1 | 11.1 | 17/0 |+| `test/e2e/v0_28_5-fix-wave.test.ts` | `test/v0_28_5-fix-wave.serial.test.ts` | serial | 12.9 | 10.4 | 10.3 | 11.9 | 6/0 |+| `test/e2e/backfill-perf-pglite.test.ts` | `test/backfill-perf-pglite.test.ts` | unit | 10.8 | 9.0 | 9.7 | 10.6 | 1/0 |+| `test/e2e/connect-bearer.test.ts` | `test/connect-bearer.test.ts` | unit | 10.7 | 9.2 | 9.6 | 10.3 | 6/2 |+| `test/e2e/bootstrap-hook-under-serve.serial.test.ts` | `test/bootstrap-hook-under-serve.serial.test.ts` | serial | 9.8 | 10.0 | 8.8 | 10.5 | 6/0 |+| `test/e2e/upgrade-bun-link-arc.serial.test.ts` | `test/upgrade-bun-link-arc.serial.test.ts` | serial | 9.2 | 7.6 | 8.2 | 9.5 | 5/0 |+| `test/e2e/dream-synthesize-chunking.test.ts` | `test/dream-synthesize-chunking.serial.test.ts` | serial | 9.1 | 8.8 | 8.9 | 8.9 | 10/0 |+| `test/e2e/search-readiness-http.test.ts` | `test/search-readiness-http.test.ts` | unit | 8.7 | 6.9 | 7.4 | 8.1 | 2/0 |+| `test/e2e/transcripts-ingest-pglite.test.ts` | `test/transcripts-ingest-pglite.test.ts` | unit | 8.6 | 6.6 | 6.5 | 8.9 | 27/0 |+| `test/e2e/bootstrap-harness-lifecycle.serial.test.ts` | `test/bootstrap-harness-lifecycle.serial.test.ts` | serial | 8.3 | 6.9 | 7.1 | 8.1 | 5/0 |+| `test/e2e/fact-backfill-resident.test.ts` | `test/fact-backfill-resident.test.ts` | unit | 7.8 | 7.4 | 6.6 | 7.0 | 7/0 |+| **total** | | | 505.5 | 329.7 | 340.1 | | |++## Lane deltas (ci:ubicloud summary.json)++| Lane | BEFORE files | BEFORE compute (s) | AFTER files | AFTER compute (s) | Delta compute (s) | BEFORE lane finished (s after start) | AFTER lane finished |+|---|---:|---:|---:|---:|---:|---:|---:|+| unit | 1970 | 3347 | 1980 | 3559 | +212 | 217 | 201 |+| serial | 330 | 1873 | 337 | 1976 | +103 | 294 | 227 |+| slow | 21 | 1012 | 24 | 1169 | +157 | 315 | 335 |+| e2e | 304 | 2756 | 284 | 2456 | -300 | 226 | 234 |+| verify | 1 | 43 | 1 | 43 | +0 | 125 | 124 |+| gitleaks | 1 | 5 | 1 | 5 | -0 | 81 | 81 |+| **run** | | 9036 | | 9208 | +172 | wall 317 | wall 337 |++Reading: ci:ubicloud runs ALL E2E in parallel slots, so its wall time is bounded by the slow-lane long poles (export-scale, reconcile-crash, reindex-markdown-persistence) and moved compute does not change wall; +20 s wall is run-to-run noise (export-scale alone went 222 -> 256 s). The E2E lane lost 300 s of compute (-10.9%, 20 files); the moved files cost 330 s in E2E and 340 s in unit/serial/slow, so compute moved rather than shrank. On GitHub, selected-E2E runs sequentially on 4 weighted workers, so removing ~506 s of weighted E2E work is ~126 s per worker on an all-E2E selection; the files now run on every PR instead of only when selected. BEFORE had 1 failure (`test/test-reads-source-smell.test.ts`, stale `distribution-import-boundary` entry left by slice 19, fixed in this slice); AFTER was all green. No moved file failed or flaked in either ci:ubicloud run, the local per-lane runs, or the co-located single-process run below, so none moved back.++## New test (authoring gate)++| Test | Mutation | Result on mutation | Result on real code |+|---|---|---|---|+| `test/scripts/classify-tests.test.ts` > "a dynamic import of src/ beside a non-repo read is behavioral" | `scripts/classify-tests.ts` `isRepoAnchored`: `const code = win;` (drop the `import(...)` specifier strip) | fails (1 of 9) | passes (9 of 9) |++Why: moving `fresh-install-pglite` from `test/e2e/` to `test/` shortened `'../../src/...'` to `'../src/...'`, which the classifier's `REPO_ANCHORS` matched inside a dynamic `import()` next to a tmp-config `readFileSync`, misclassifying a behavioral suite as structural. The fix strips `import('...')` specifiers from the detector window; regenerating `scripts/structural-suites.tsv` then changes only the moved skillpack-flow path and the classifier test's own case count.++## Deletions++None. One stale ratchet entry removed: `test/test-reads-source-smell.test.ts` GRANDFATHERED `'distribution-import-boundary.test.ts': 1` (the test file was deleted in slice 19 commit 0ad8e62; the ratchet's own stale-entry test failed on the BEFORE run).++## Lockstep updates++- `scripts/e2e-test-map.ts`: moved paths removed from every row; 7 source keys whose only E2E owner moved were deleted (claw-test.ts, claw-test/**, brain-resolver.ts, mounts.ts, connect.ts, connect-probe.ts, embed-facts-delegate.ts) and now fail closed to all E2E; `src/mcp/surface.ts` stays covered by `src/mcp/**`.+- `test/fixtures/e2e-unmapped-baseline.txt`: 11 rows removed (137 -> 126); `BASELINE_SEEDED_LENGTH` 143 -> 126 (it carried 6 rows of stale slack).+- `test/select-e2e.test.ts`: dropped the two moved files from the fixture list and the two expected-selection arrays (the map no longer emits them).+- Weights: e2e keys removed from `scripts/e2e-weights.json`; carried to `scripts/test-weights.json` (unit/slow, ms) and `scripts/serial-weights.json` (serial, s); `scripts/ubicloud/weights.json` re-keyed `e2e:` -> `unit:/serial:/slow:` with the AFTER-run measured ms. Metadata files untouched (they describe the mined run).+- `scripts/structural-suites.tsv` regenerated; `.gitleaks.toml`, `scripts/check-privacy.sh`, `scripts/check-test-real-names.sh` path allowlists, two src comments, key-files docs, TODOS.md, and test cross-references updated to the new paths.+- `docs/TESTING.md`: new "Lane-move pilot (2026-09)" table (file -> lane -> command -> reason), stale E2E-inventory mentions updated. Each moved file's header gains a Lane/Run paragraph; assertions unchanged (diff of moved files is only relative paths and comments).++## Commands++| Command | Result |+|---|---|+| per-file lane wrappers (`run-unit-shard.sh` / `run-serial-tests.sh` / `run-slow-tests.sh`) for all 20 files | 20/20 pass, executed counts identical to BEFORE e2e logs |+| `bun test --timeout=60000 --max-concurrency=4` all 13 unit+slow moved files + 4 neighbours in ONE process | 306 pass, 2 skip (connect-bearer's 2, same as e2e), 0 fail, 246 s |+| `bash scripts/check-test-isolation.sh` | OK (after remote-privacy-journeys -> serial for R3) |+| `bun test test/select-e2e.test.ts test/scripts/e2e-wiring.test.ts test/scripts/classify-tests.test.ts test/test-reads-source-smell.test.ts test/scripts/serial-files.test.ts` | 72 pass, 0 fail |+| `bun run check:test-placeholders` | OK (2626 files, 6 allowlisted) |+| `bun test test/test-reads-source-smell.test.ts` | 12 pass (was 11/1 before the stale-entry fix) |+| `bun scripts/classify-tests.ts` + `scripts/check-structural-manifest.sh` | fresh |+| `bun run check:orphan-modules` | OK (1444 modules, 4 allowlisted, 20 permitted test-only) |+| `bun run verify` | 56/56 green |+| `bun run ci:ubicloud` BEFORE (clean tree) | 2626/2627; 1 pre-existing failure (source-smell stale entry) |+| `bun run ci:ubicloud` AFTER | 2627/2627 green, wall 337 s |diff --git a/docs/test-audit/2026-09-29/implementation/pending-deletions.md b/docs/test-audit/2026-09-29/implementation/pending-deletions.mdnew file mode 100644index 0000000000..03dea2b1c3--- /dev/null+++ b/docs/test-audit/2026-09-29/implementation/pending-deletions.md@@ -0,0 +1,82 @@+# Slice evidence: pending deletions + process-cleanup double-signal fix++Branch: `test-reduction-wave` (uncommitted). Bun 1.3.14. Mutations applied one at a time with an exact-string replace and reverted with `git checkout -- <file>`; counts are executed-test counts (`N pass / M fail`). E2E runs used a local `pgvector/pgvector:pg16` container (`GBRAIN_TEST_ALLOW_DATABASE_URL=1`).++## 1. `gbrain features` typeof probes (vacuous assertion)++| Deleted test | Probe edit | Result | Surviving owner | Owner result |+|---|---|---|---|---|+| `test/features.test.ts` › "exports runFeatures" | `src/commands/features.ts`: `runFeatures` throws on entry | deleted test passes (blind; HEAD file 12 pass / 6 fail, the 3 probes all pass) | `test/features.test.ts` › "runFeatures behavior" (6 cases) | fails (10 pass / 6 fail) |+| `test/features.test.ts` › "covers all 7 recipes" (asserts only `runFeatures` is defined) | same | passes (blind) | `runFeatures behavior` › "the no-integrations pitch names exactly the recipes…" (every `RECIPE_META` name checked) | fails |+| `test/features.test.ts` › "exports featuresTeaserForDoctor" | `featuresTeaserForDoctor` returns `null` | passes (blind; HEAD file 18 pass / 0 fail) | NEW `test/features.test.ts` › "the doctor teaser names missing embeddings and stays silent on a healthy brain" | fails (15 pass / 1 fail) |++The teaser had no behavioral owner before; the new case (real PGLite, one missing embedding) replaces the typeof probe. `features-recipe-secrets.test.ts` stays 7 / 0 under the throw (it owns secret names, not the command). Export existence is enforced by `bun run typecheck` (doctor.ts destructures the dynamic import).++## 2. `test/embed-helper-migration.test.ts` (8 source-grep pins, deleted)++New file `test/embed-pool-abort.test.ts`: real `runEmbedCore` → gateway path, one worker (`GBRAIN_EMBED_CONCURRENCY=1` via `withEnv`), an embed transport that aborts the caller's `AbortController` on its first call; asserts exactly one embed call and that only the first page's snapshot was read, on `--stale` and `--all`.++| Pin / property | Probe edit (`src/commands/embed.ts` unless noted) | Deleted pin | New / surviving owner | Owner result |+|---|---|---|---|---|+| stale pool gets `signal: effectiveSignal` | remove `signal: effectiveSignal` from the `embedAllStale` pool | fails (7/1) | `embed-pool-abort` › "--stale: no page after the aborting one…" | fails (1/1) |+| caller signal composed into the stale pool | `anySignal(budgetSignal, externalSignal)` → `anySignal(budgetSignal, undefined)` | passes (blind, 8/0) | same | fails (1/1) |+| `embedAll` pool's caller signal (`...(signal && { signal })`) | remove it | passes (blind, 8/0) | `embed-pool-abort` › "--all: …" | passes (2/0): **equivalent mutation**. `embedOnePage` returns on `isAborted(signal)` at entry, right after each claim, so the pool signal is redundant defense in depth |+| (same contract, both layers) | remove the pool signal AND the `embedOnePage` entry guard | passes (blind) | `embed-pool-abort` › "--all: …" | fails (1/1) |+| (entry guard alone) | remove only `if (isAborted(signal)) return;` | passes | `embed-pool-abort` | passes (pool signal still stops claims) |+| `failureLabel: (page) => page.slug` slug projector | remove it from the `embedAll` pool | fails (7/1) | none possible at the embed boundary; see disposition | `embed-pool-abort` 2/0, `embed-default-concurrency` 2/0, `embed.serial` 52/0 |+| failures[] memory bound | `src/core/worker-pool.ts`: store the item instead of `labelFn(item)` | n/a | `test/worker-pool.test.ts` › "failures store idx + label, NOT full item" | fails (23/1) |+| default 20 on both paths | (evidence-16) `'20'` → `'19'` | fails | `test/embed-default-concurrency.test.ts` | fails (1/1 each) |+| `workers: CONCURRENCY` on both pools | stale pool `workers: 5` / all pool `workers: 5` | fails | `embed-default-concurrency` | fails (1/1) / fails (1/1) |+| imports `runSlidingPool`, ≥2 call sites, old inline-pool shapes gone | structural | vacuous | pool wiring is exercised by the peak-20 barrier tests above; import existence by typecheck | — |++`failureLabel` disposition (vacuous at this boundary): both embed call sites discard the `runSlidingPool` result, so `failures[]`, the only consumer of the label, never leaves the pool; without the projector the default `String(page)` label is also a short string, so no Page object is retained either way. The memory bound is a worker-pool property owned by `worker-pool.test.ts`. **Finding (not fixed, out of scope):** in `--all`, an error thrown by the page snapshot read (outside `embedOnePage`'s try) is swallowed by the pool and dropped: a probe with a throwing `readPageSnapshot` returned `{embedded: 0, failures: 0, pages_processed: 0}`, so the run exits 0 with pages unembedded (#3037 class). Recording pool failures into `result.failures` would fix it and make the slug projector observable.++## 3. `test/postgres-engine-singleton-ownership.test.ts` (7 source pins, deleted)++New file `test/postgres-engine-singleton-lifecycle.test.ts`: no mocks, no Postgres. Each test opens its own local TCP endpoint that accepts connections and never answers the Postgres handshake (a pending `SELECT 1` holds a connect in flight), then answers with a FATAL `ErrorResponse` to release them.++| Property | Probe edit | Deleted pin | New unit test | E2E owners (idempotency / shared-recovery / reconnect-singleton) |+|---|---|---|---|---|+| P1 borrower `db.connect` returns false | `src/core/db.ts`: join path returns `true` | fails | "an engine that joins an in-flight create is a borrower…" fails (2/1) | 3/2, 2/1, 3/0: **caught** |+| P2 TOCTOU: engine pre-samples the singleton with an await before `db.connect` | `postgres-engine.ts`: `existed = getConnection()` probe; `await Promise.resolve()`; `await db.connect`; `owns = !existed` | fails | borrower test fails (2/1) | 5/0, 3/0, 3/0: **missed** |+| P2 TOCTOU: `db.connect` awaits between its null check and the create | `db.ts`: `await Promise.resolve()` after the `if (sql)` block | passes (blind, 7/0) | borrower test fails; disconnect test fails (its setup relies on the synchronous create) | not run |+| P2 pre-sample with no await (evidence-18 shape) | same probe without the `await Promise.resolve()` | fails (textual) | passes (3/0): **equivalent mutation**. The sample and `db.connect`'s own check run in one synchronous stretch, so no interleaving can separate them | missed (evidence-18) |+| P3 disconnect only when owner | unconditional `db.disconnect()` | fails | borrower test fails (2/1) | 3/2, 2/1, 3/0: **caught** |+| P4 snapshot + null before awaiting `end()` | `db.ts`: `await endPoolBounded(s)` before `sql = null` | fails | "db.disconnect() detaches the singleton before awaiting end()…" fails (1 fail) | 5/0, 3/0, 3/0: **missed** |+| P5 module reconnect never tears down the shared pool | `db.disconnect()` before `db.connect` in the module branch | passes (blind, 7/0) | passes (not targeted) | 5/0, 3/0, 2/1: **caught** by reconnect-singleton |+| P6 `_reconnecting` set | remove `this._reconnecting = true` | fails | "a reconnect during a running rebuild returns at once…" fails | 5/0, 3/0, 3/0: **missed** |+| P6 `_reconnecting` cleared in `finally` | remove `this._reconnecting = false` | passes (blind, 7/0) | same test fails (next reconnect never rebuilds) | 5/0, 3/0, 3/0: **missed** |++Cadence exception (record in PR body): the deleted pin ran on every unit shard. P2/P4/P6 now have unit owners (every unit shard, same cadence). P1/P3/P5 are owned by the three E2E files, which run when `src/core/postgres-engine.ts` changes (map entry added in PR 1 item 7); `src/core/db.ts` is unmapped, so a `db.ts` change selects the whole E2E suite. The new unit borrower test also catches P1 and P3, so only P5 relies on E2E cadence alone.++Test-only access: the P6 test sets the engine's private `_savedConfig` / `_connectionStyle` / `_sql` directly because an instance connect needs a completed handshake.++## 4. `src/core/process-cleanup.ts`: a second signal exited before the lock DELETE++Fix: `runCleanupPass` keeps the in-flight pass promise (`cleanupPass ??= runCleanupCallbacks()`); every signal handler and `triggerCleanupAndExit` awaits that same promise before `process.exit`. Callbacks still run once; the 3 s deadline still bounds the pass.++| Test | Pre-fix code | Fixed code |+|---|---|---|+| NEW `test/process-cleanup.test.ts` › "later signals and a stdout EPIPE during the cleanup pass wait for it before exiting" (held cleanup callback; SIGTERM, SIGPIPE, stdout `EPIPE`; expects exits `[143, 141, 0]` all after the callback finished) | fails (14/1: SIGPIPE exits before cleanup finished) | passes (15/0) |+| NEW `test/e2e/sync-lock-recovery.test.ts` › "closing the output pipe as soon as the lock row appears still releases the lock" | fails 3 of 3 | passes 20 of 20 consecutive local runs; whole file 9/0 |+| scratch repro (`(scratch) scratch/repro-lock-boundary.ts`: 1,000-file repo, close stdout+stderr the moment `gbrain-sync:default` carries the child PID) | lock row left 6 of 6 (exit 141, 0 imported) | lock row left 0 of 6, then 0 of 20 |++The 20-run check was on this Capy machine without a unit shard alongside, not the plan's Ubicloud bar.++EPIPE listeners: **kept (reachable)**. Measured with a Bun writer that installs a SIGPIPE listener and a stdout `error` listener, read by `| head -c 10`, a Bun parent (`Bun.spawn` pipe, reader cancelled) and a Node parent (`child_process` pipe destroyed):++| Writer | SIGPIPE listener | Events observed (all three readers) |+|---|---|---|+| `process.stdout.write` | yes | ~4,400-4,600 SIGPIPE **and** 22-24 stdout `EPIPE` error events; exit code decided by whichever handler ran first (0 or 141) |+| `process.stdout.write` | no | 39 stdout `EPIPE` events |+| `console.log` | yes | SIGPIPE only |+| `console.log` | no | nothing (writes fail silently) |++So PR 1's note ("the EPIPE listeners are not reached") holds only for `console.log` output; `process.stdout.write` output reaches them. Removing them would be unsafe. The TODOS.md P2 entry is closed with this evidence, and the misleading SIGPIPE comment in `process-cleanup.ts` was corrected.++## Ratchets and bookkeeping++- `test/test-reads-source-smell.test.ts`: removed the entries for the two deleted files, plus a **pre-existing stale entry** `distribution-import-boundary.test.ts: 1` (the file has 0 unjustified reads since slice 19; the ratchet failed at HEAD before this slice).+- Weights: removed the deleted files from `scripts/test-weights.json` and `scripts/ubicloud/weights.json` (they were not in `serial-weights.json` or `e2e-weights.json`). Grep of `scripts/`, `.github/`, `scripts/e2e-test-map.ts`, `test/fixtures/e2e-unmapped-baseline.txt`: no other references.+- `scripts/structural-suites.tsv` regenerated (`bun scripts/classify-tests.ts`): one row removed.+- Docs: `docs/architecture/key-files/commands-2.md` and `engines-2.md` repointed from the deleted pins to the new owners.diff --git a/docs/test-audit/2026-09-29/implementation/rewrites.md b/docs/test-audit/2026-09-29/implementation/rewrites.mdnew file mode 100644index 0000000000..e12dd9808c--- /dev/null+++ b/docs/test-audit/2026-09-29/implementation/rewrites.md@@ -0,0 +1,333 @@+# Evidence — PR N+1 slice: rewrites and consolidation++Mutation harness: `(scratch) mut.sh <file> <old> <new> <test...>` applies one textual edit, runs the test, reverts with `git checkout`. Counts are executed pass/fail.++## 1. Class-3 source-grep rewrites++### schema-cli-contract (6 remaining source pins → 2 behavior tests via `runSchema` on a temp GBRAIN_HOME + file-backed PGLite)++| Test | Mutation (src/commands/schema.ts) | New test | Old pins |+|---|---|---|---|+| envelope table (13 verbs, `schema_version: 1`, `tier` exactly on experimental verbs) | `graph --json` drops `tier: 'experimental'` | 2/1 fail | 7/0 pass (blind) |+| same | `review-orphans --json` drops `schema_version: 1` | 2/1 fail | 7/0 pass (blind; the count-of-`schema_version: 1` pin still clears its threshold) |+| same | parseFlags ignores `--json` | 0/3 fail | not run |+| source scoping (`--source`, `--source-id`, `=` forms) | parseFlags drops `--source-id` | 2/1 fail | variant drop pin fails only on literal text |+| same | parseFlags drops `--source=` | 2/1 fail | not probed |++Deleted pins (vacuous/implementation-coupled; new owner above): "every new verb routes through runSchema dispatch", "every new verb-handler reads parseFlags()", "parseFlags() returns the documented shape", "parseFlags accepts both --source and --source-id forms", "every new verb when --json passed produces a JSON envelope" (count of literals), "legacy v0.38 verbs are explicitly NOT in NEW_VERBS" (constant vs constant tautology). Kept: the PR 1 `schema usage` experimental-verbs behavior test. Smell ratchet: `schema-cli-contract.test.ts` 1 → 0 (entry removed).++### extract-workers (10 source pins → 4 behavior tests: `runExtractCore` through a parallel-reporting engine proxy + `runExtract` CLI on PGLite)++Each run executes the new file (4 tests) and the old pin file (10 tests) together; the fail column names which failed.++| Mutation (src/commands/extract.ts) | New file | Old pins |+|---|---|---|+| incremental (slugs) pool `workers: 1` | 1 fail (incremental concurrency) | 0 fail (blind: `runSlidingPool(` count still 3) |+| directory-walk links pool `workers: 1` | 1 fail (directory concurrency) | 0 fail (blind) |+| `resolveWorkersWithClamp(engine, undefined, …)` | 3 fail | 1 fail |+| CLI drops `workers` from the `runExtractCore` call | 1 fail (clamp warning not printed) | 1 fail |+| invalid `--workers` no longer exits | 1 fail | 0 fail (blind) |++Not covered: the timeline directory-walk pool has no await per page, so its concurrency is unobservable (and immaterial); the old pin on it only checked the call exists. Smell ratchet: `extract-workers.test.ts` 1 → 0.++### thin-client-routing-audit (22 source pins → 4 in-process route tests; REFUSE pins → 12 rows added to the one batched spawn in `cli-dispatch-thin-client`)++| Mutation | New owner | Old pins (25 tests) |+|---|---|---|+| `src/cli.ts` refusal guard skips `code-*` commands (set literal intact) | `cli-dispatch-thin-client` 4 fail (code-def/refs/callers/callees rows) | 0 fail (blind) |+| `src/commands/jobs.ts` `jobs list` thin branch disabled | `thin-client-routing-audit` 1 fail | 0 fail (blind; `callRemoteTool(cfg!, 'list_jobs'` literal intact) |+| `src/commands/recall.ts` `forget` thin branch disabled | 1 fail | 0 fail (blind) |+| `jobs get` sends `{ id: String(id) }` | 1 fail | 0 fail (blind) |+| null-engine guard also lets `stats` through | 1 fail | regex pin fails on text only |+| `'jobs'` added to `THIN_CLIENT_REFUSED_COMMANDS` | `cli-dispatch-thin-client` › jobs list 1 fail (new not-refused assertion) | old "'jobs' is NOT in the set" pin (text) |++Refused rows added to `refusedCommands`: pages, files, eval, code-def, code-refs, code-callers, code-callees, dream, transcripts, storage, takes extract, sources list (the stderr assertion `not routable` proves the `THIN_CLIENT_REFUSE_HINTS` entry exists; the no-hint fallback prints "requires a local engine"). Recall route owner: `recall-thin-client-fallback.serial.test.ts` (unchanged). Cost: +12 spawns in one `runCliBatch` (file 14.7 s locally, was about 9 s). Smell ratchet: `thin-client-routing-audit.test.ts` 6 → 0.++### models-doctor-embed (3 slice-of-function greps → 3 behavior tests: `probeEmbeddingReachability` with an injected `embed`, `runModels doctor --json` with the gateway embed transport injected and `fetch` stubbed offline)++Each run executes the new file (3 tests) and the old file (3 tests) together.++| Mutation (src/commands/models.ts) | New | Old |+|---|---|---|+| reachability no longer gated on `embeddingConfig.status === 'ok'` | 1 fail | 1 fail |+| same, with the gate text kept in a comment | 1 fail | 0 fail (blind) |+| probe embeds with `inputType: 'document'` (old text kept in a comment) | 1 fail | 0 fail (blind) |+| probe drops `abortSignal` (identifier kept) | 1 fail | 0 fail (blind) |+| reachability result never added to the report | 1 fail | 0 fail (blind) |++Smell ratchet: `models-doctor-embed.test.ts` 1 → 0. Found while writing it: an unstubbed doctor run makes a real Voyage rerank call; the new test stubs `fetch`.++### dream-cli-flags (whole file deleted: the 14 remaining source pins → behavior tests in `dream.test.ts` (5) and `dream-drain-failure-summary.serial.test.ts` (4))++Old = the deleted file (14 tests) run against the mutation; new = the named describe.++| Mutation (src/commands/dream.ts; the grepped token kept in a comment where the pin needs it) | New | Old |+|---|---|---|+| `synthInputFile` not forwarded to runCycle | 1 fail (--input reaches synthesize) | 0 fail (blind) |+| `synthDate` not forwarded | 1 fail (explicit targets bypass the cooldown) | 0 fail (blind) |+| inverted `--from/--to` range accepted | 1 fail (exit-2 table) | 0 fail (blind) |+| `--input` no longer implies `--phase synthesize` | 1 fail | 0 fail (blind; `phases = ['synthesize']` literal intact) |+| drain exits 0 while backlog remains | 1 fail (exit 3) | 0 fail (blind) |+| drain ignores `--window` | 1 fail | 0 fail (blind) |+| drain drops the resolved `--source` | 1 fail | 0 fail (blind) |+| totals line drops `patterns=` | 1 fail | 0 fail (blind) |++Help-text pins (dry-run synthesis cost, `cycle.timezone`) now assert the runtime `--help` output rather than the source file. Deleted file: `test/dream-cli-flags.test.ts` (smell ratchet entry removed; weights keys removed).++## 2. Doc claims consolidation (`test/doc-claims.test.ts`)++One table of 10 retracted honesty/privacy claims, negative only, scanned whitespace-flattened across every shipped Markdown file (`git ls-files`: README, AGENTS, CLAUDE, INSTALL_FOR_AGENTS, `docs/**` minus `docs/test-audit/**`, `skills/**`, `templates/**`, `recipes/**`, `plugin/**`, `plugin-variants/**`; CHANGELOG excluded as history). Runs in about 0.1 s.++| Deleted/moved test | Probe edit | Result | Surviving owner | Owner result |+|---|---|---|---|---|+| `mcp-registration-blocks` › "no doc prescribes the retired ~/.openclaw/config.json path" | `docs/mcp/OPENCLAW.md` re-adds `~/.openclaw/config.json` | old fails | `doc-claims` | fails |+| `mcp-registration-blocks` › "OPENCLAW.md registers via the openclaw mcp CLI" (positive) | reword the registration sentence | old passes (the phrase appears elsewhere); vacuous as a guard | none needed (dropped positive) | — |+| `docs-navigation` › "active memory guidance keeps durable preferences separate…" | `brain-vs-memory.md` re-adds "Don't store user⏎preferences in GBrain" (line-wrapped) | old passes (blind: no whitespace flattening) | `doc-claims` | fails |+| `docs-navigation` › "primary docs do not reinstate blanket graph or exclusivity promises" | `memory-boundaries.md` "not a full database backup" → "not a complete database backup" (same meaning) | old fails (prose-coupled positive) | negatives moved to `doc-claims` | — |+| same | `skills/query/SKILL.md` adds "Every `put_page` auto-creates links." | old passes (blind: skills not scanned) | `doc-claims` | fails |+| `put-page-remote-autolink-hint` › "downstream-upgrade doc and enrich skill state the MCP skip…" | `skills/enrich/SKILL.md` re-adds "MCP response includes `auto_links: { created`" | old fails | `doc-claims` | fails |+| `ambient-recall-templates` › "CODEX.md session-boundary instruction names both verbs", "ambient-recall guide exists and names both verbs" (positives) | vacuous as behavior guards (prose presence only) | — | the guide's existence moved into the kept template test | — |+| (new row, was unguarded after PR 2) | `docs/guides/skillopt.md` re-adds "keychain and survives" | — | `doc-claims` | fails |++Kept, not folded: `put-page-remote-autolink-hint` › brain-ops skill test (lane: shipped-skill honesty, keep) and `docs-mcp-deploy` (doc↔route anchor kept by PR 2). Deliberately dropped positive pins: `memory-boundaries.md` disclaimers ("no inline graph extraction", "not a full database backup", …) and `brain-vs-memory.md` positives, per the plan's "negative checks only".++## 4. Recipe checks folded into the all-recipes loop (`test/integrations.test.ts`)++5 twilio-only tests → 1 generic all-recipes test (semver version, every secret named with a non-empty `where`, `requires` resolve; runs over all 10 `recipes/*.md`) + 1 twilio-specific test (its 3 secret names, https console URLs). The generic "where is https" rule does not hold for every recipe (`restart-sweep`, `x-to-brain` point at config or a profile, not a URL), so it stays twilio-specific. "Parses correctly" and body-with-`---` are owned by the all-recipes parse test and the parseRecipe horizontal-rule test.++| Probe edit | New | Old (twilio-only) |+|---|---|---|+| `recipes/calendar-to-brain.md` version `v1.x.y` | 1 fail | 0 fail (blind: only twilio checked) |+| `recipes/email-to-brain.md` requires a missing recipe | 1 fail | 0 fail (blind) |+| `recipes/twilio-voice-brain.md` renames `TWILIO_AUTH_TOKEN` | 1 fail | fails (same contract) |++## 5. context-audit-skill executes the shipped snippet++The byte pins (`* 10 + 27 ) / 28`, `bytes/2.8`, not `* 2 / 7`, not `/ 4 ))`, not `chars/4`) are replaced by running the step-1 bash snippet from `skills/context-audit/SKILL.md` on fixture files of 1, 28, 29 and 10,000 bytes and asserting `ceil(bytes/2.8)` per file. The report-header phrases (estimate basis, `/context` deferral) stay: they are the user-facing prompt contract.++| Probe edit (skills/context-audit/SKILL.md) | New | Old |+|---|---|---|+| whitespace only: `27 ) / 28` → `27) / 28` (same behavior) | 0 fail | 1 fail (coupled) |+| estimate `* 0` (every file 0 tokens) | 1 fail | 0 fail (blind) |+| floor instead of ceil (`(n*10)/28`) | 1 fail | 1 fail |++## 3. Docs CLI truth check + shared scanner (sub-task; full evidence below)++### Evidence: docs CLI truth check (test-reduction wave sub-slice)++## Files changed (uncommitted)++- NEW `test/helpers/cli-command-surface.ts`: shared `liveCliVerbs`, `commandPosition`, `codeRegions` (with `HISTORICAL_MARKER`), `gbrainInvocations`, and `flagRejection`, which runs production `parseGlobalFlags` → `migrationCliArgumentError` → `validateCommandFlags`.+- `test/docs-cli-commands.test.ts`: uses the helper. Flags are now checked in docs/guides, docs/migrations and skills. docs/migrations and skills/migrations are no longer excluded. Adds the historical marker, a shrink-only allowlist with reasons, a stale-entry test, and a scanner self-check.+- `test/remediation-command-resolution.test.ts`: the duplicated `validCommands` / `commandPosition` / fence scanner is deleted and the file now uses the helper.+- `docs/TESTING.md`: new short section "Docs CLI truth check".+- Stale docs fixed: `docs/guides/{cron-schedule,minions-deployment,minions-shell-jobs}.md`, `docs/migrations/v0.41.2-markdown-greenfield.md`, `skills/brain-pdf/SKILL.md`, `skills/migrations/{v0.13.0,v0.14.0,v0.32.2,v0.33.0,v0.33.3.0,v0.40.5,v0.41.11.0}.md`.+- Historical markers added: `skills/migrations/{v0.33.0,v0.33.3.0,v0.34.0.0}.md`.+- Regenerated: `skills/skills.lock.json`, `plugin/skills/brain-pdf/SKILL.md` (generate-plugin-tree), `llms-full.txt` (build:llms).++## Mutation / probe evidence (new tests)++| New/changed test | Probe edit | Result | Reverted |+|---|---|---|---|+| docs-cli › every `gbrain <verb> [--flag]` … resolves | (i) append ```` ```bash\ngbrain notacommand --x\n``` ```` to docs/guides/cron-schedule.md | FAIL: `docs/guides/cron-schedule.md:354: gbrain notacommand — unknown verb` (4 pass / 1 fail) | yes |+| same | (iii) same block with `<!-- gbrain-cli: historical -->` above the fence | PASS (5/5): the marker suppresses it | yes |+| same | (ii) `skills/brain-pdf/SKILL.md`: `gbrain get "$SLUG" --no-such-flag` | FAIL: `skills/brain-pdf/SKILL.md:83: … unknown flag --no-such-flag for 'gbrain get'` | yes |+| docs-cli › ALLOWLIST has no stale entries | (iv) add allowlist entry `docs/guides/cron-schedule.md: --type` (already fixed) | FAIL: "no longer match a violation — remove them … docs/guides/cron-schedule.md: --type" | yes |+| same (production) | (vi) `src/core/cli-flag-registry.generated.ts`: add `--dry-run` to `auth` | FAIL: the auth `--dry-run` allowlist entries are reported stale | yes |+| docs-cli › scanner self-check | (v) `src/cli.ts` `validateCommandFlags`: `return null;` first line | FAIL: self-check (expected `3:--no-such-flag` missing) and stale-allowlist test both fail | yes |+| docs-cli main + remediation | (vii) `src/cli.ts`: drop `'sync'` from CLI_ONLY | FAIL: dozens of `gbrain sync — unknown verb` (docs/ENGINES.md:289, …) | yes |+| remediation › CHANGELOG top entry | (viii) add ``Run `gbrain notacommand` first.`` to the top CHANGELOG entry | FAIL: `CHANGELOG.md (top entry): gbrain notacommand is not a real command` (2 pass / 1 fail) | yes |++## Retiring-a-test evidence++No test cases were deleted. Only duplicated scanner code was deleted: `validCommands()` and `commandPosition()` in both files, plus the inline fence walker in `scanChangelogTopEntry`. The helper replaces them. One test was renamed and extended:++| Deleted test | Probe edit | Result | Surviving owner | Owner result |+|---|---|---|---|---|+| `test/docs-cli-commands.test.ts` › "every `gbrain <verb>` in README/docs/skills resolves to a live command" (renamed, not removed) | `src/cli.ts`: drop `'sync'` from CLI_ONLY | n/a (renamed) | same file › "every `gbrain <verb> [--flag]` in README/docs/skills resolves against the live CLI" | fails (1 of 5) |+| duplicated `validCommands`/`commandPosition` in `test/remediation-command-resolution.test.ts` (helper code, not a test) | CHANGELOG top entry gains `gbrain notacommand` | n/a | same file › "CHANGELOG top entry: every gbrain verb resolves" (via helper) | fails (1 of 3) |++## Stale docs found (28 hits → 0 open)++| Location | Finding | Action |+|---|---|---|+| docs/guides/minions-deployment.md:445, minions-shell-jobs.md:258, skills/migrations/v0.14.0.md:136,155 | `jobs list --name shell`: `--name` never existed (the real CLI rejects it) | `jobs list --status X --json \| jq 'select(.name == "shell")'` |+| skills/migrations/v0.14.0.md:167 | `jobs stats --orphaned` (never shipped, listed as deferred) | reworded to "an orphaned-job view in `gbrain jobs stats`" |+| docs/guides/cron-schedule.md:98 | `search --type calendar --recent 7d` (no such flags) | `query "flight" --types calendar --since 7d` |+| skills/brain-pdf/SKILL.md:83 | `get --raw` ("whatever flag exposes raw body") | `gbrain get "$SLUG"`, which already prints markdown with frontmatter |+| skills/migrations/v0.13.0.md:64 | `graph --type a,b` | `graph … --link-type invested_in` (the op param is `link_type`) |+| skills/migrations/v0.13.0.md:82 | `gbrain normalize-types` (v0.14), never shipped | claim deleted |+| skills/migrations/v0.32.2.md:62 | `gbrain rebuild` (v0.32.3), never existed | reworded to "a rebuild of the database from the repo" |+| skills/migrations/v0.33.0.md:104, v0.33.3.0.md:104 | `apply-migrations --status \| grep edges_backfilled_at_v0_34` (no `--status`, and v51 is facts_fence_columns) | `gbrain doctor --json \| jq '.checks[] \| select(.name == "schema_version")'` |+| skills/migrations/v0.40.5.md:67-68 | `gbrain exec "UPDATE …"`, never existed | `psql "$DATABASE_URL" -c "UPDATE …"`, with a note that no gbrain command sets priority |+| skills/migrations/v0.41.11.0.md:60 | `gbrain forget --where` described as a TODO | reworded so the fake flag is not shown as a command |+| docs/migrations/v0.41.2-markdown-greenfield.md:37,70,131,149 | `capture --source markdown-greenfield --repo …` never worked; the importer module is unwired (scripts/check-orphan-modules.mjs:82 "awaits a wire-up vs delete product decision") | Dry-run, import, re-run and rollback sections replaced with a "Status: not wired to the CLI" note pointing to `gbrain import <dir>` |+| skills/migrations/v0.33.0.md:130, v0.33.3.0.md:130, v0.34.0.0.md:69-70 | `gbrain wiki` / `blast` / `flow` in "what v0.34 will add / slipped" plan notes | `<!-- gbrain-cli: historical -->` marker |+| docs/guides/rls-and-you.md:188 | `gbrain rls-exempt` (the doc says it is deliberately not shipped) | allowlist (carried over) |+| docs/guides/concurrent-writes.md:398,471, shared-brain-skills.md:192 | `auth rescope-client … --dry-run`, `auth local-writer register … --dry-run` | allowlist. **Real CLI bug:** the handlers parse `--dry-run` (src/core/grants/cli.ts:19, persistence-admin.ts), but `CLI_FLAG_REGISTRY['auth']` omits it (the generator's SAFETY_FLAGS drop it because auth.ts does not consume it at depth zero). `bun src/cli.ts auth rescope-client foo --dry-run --json` → `unknown flag --dry-run for 'gbrain auth'`, exit 1. Fix: `EXTRA_FLAGS.auth = ['--dry-run']` in scripts/generate-flag-registry.ts, then `bun run build:flag-registry`; the stale-entry test then forces removal of the allowlist entries. |++## Commands run++- `bash …/gstack/scripts/install.sh --check` → exit 1; ran the installer → "Claude skills, GPT-6 Astra skills, and Chromium are ready"+- `bun install --frozen-lockfile` → ok+- `bun test test/docs-cli-commands.test.ts` → 5 pass / 0 fail, 0.47 s wall+- `bun test test/remediation-command-resolution.test.ts` → 3 pass / 0 fail, 0.60 s wall+- `bun test` build-llms, docs-navigation, skills-conformance, codex-plugin-manifest, openclaw-plugin-manifest, migrations-registry, scripts/check-skill-refs, skill-brain-first, filing-audit, post-install-advisory, doctor-skill-checks, resolver, check-resolvable, cli-flag-validation, migrations-v0_14_0 → 880 pass / 0 fail+- `bun run typecheck` → exit 0+- `bun run check:skills-manifest | check:plugin-tree | check:privacy | check:resolver | check:newlines` → all exit 0. `node scripts/check-skill-refs.mjs` and `node scripts/check-orphan-modules.mjs` → ok. `check:doc-history` → ok; its TESTING.md WARN is pre-existing (identical on a clean tree).+- `bun test test/test-reads-source-smell.test.ts` → 11 pass / 1 fail. The failure is pre-existing and unrelated: a stale `test/distribution-import-boundary.test.ts` entry, reproduced on a clean stash.++## Smell counts++- test/docs-cli-commands.test.ts: 0 unjustified src read sites before, 0 after (not in GRANDFATHERED)+- test/remediation-command-resolution.test.ts: 0 before, 0 after (not in GRANDFATHERED)+- test/helpers/cli-command-surface.ts: 0 (no file reads)+- No files deleted or renamed. The scripts/structural-suites.tsv row for remediation-command-resolution (3 readFileSync) is unchanged: `bun scripts/classify-tests.ts` produced no diff.++## Limitations / skips++- CLI_ONLY flags are validated per top-level command, not per subcommand. This is inherited from CLI_FLAG_REGISTRY and cannot be fixed without a production refactor.+- Verbs only (no flag check) for validator-exempt commands: `call`, `config`, `jobs submit`, `eval brainbench`. Also for routes main() dispatches before the validator (`search modes|stats|tune|diagnose`, `sources inspect|connect`, `sources demo company-brain`), which the helper mirrors from src/cli.ts main().+- Flags are checked only in docs/guides, docs/migrations and skills (the requested scope); README and the rest of docs/ get verb checks only. An informational scan outside that scope found 8 flag hits, left untouched: docs/architecture/RETRIEVAL.md:387 `eval --config`, frontmatter-scan-incremental.md:100,153 `frontmatter scan --incremental/--reconcile`, key-files/commands-4.md:34 `purge-deleted --older-than`, plus key-files/commands-4.md:22, a usage-grammar line whose `[--reranker auto|off|keep|<model>]` alternation the tokenizer reads as extra positionals (a tokenizer limitation, not a doc bug), docs/contradictions.md:120 `dream --slug`, docs/protocol/MEMORY_VERBS_v1.md:54 `recall --entity`, docs/what-schemas-unlock.md:136 `schema review-orphans --limit`.++## 1b. Class-3 per-file batch (sub-task; full evidence below)++Integration note: the `patterns subagent submission` test originally made a real (failing) Anthropic call with a fake key; it now stubs `fetch` offline. Re-probed after the change: `dream.patterns.output_slug_prefix` config read renamed → 1 fail.++### Class-3 source-grep rewrites — evidence (test-reduction wave, 2026-09-29)++Scope: lane report §3 "Per file" row + the conversation-facts row. All 10 files handled; no skips.+Executed tests (runtime counts): 224 → 176 (−48); `git diff --shortstat`: 16 files, +774 / −855.++## Files changed (uncommitted)++- Deleted: `test/backlinks-job-default.test.ts`, `test/cycle/cycle-lock-ttl.test.ts`, `test/phantom-redirect-per-source-lock.test.ts`, `test/extract-conversation-facts-workers.test.ts`+- Rewritten: `test/cycle-pack-gating.test.ts` (21→8), `test/cycle-patterns.test.ts` (16→11), `test/regression-strict-source-id.test.ts` (9→5), `test/asymmetric-encoding-contract.test.ts` (6→4), `test/cli.test.ts` (24→20), `test/upgrade.serial.test.ts` (30→25)+- New behavior owners added to: `test/handlers.test.ts` (10→12), `test/core/cycle.serial.test.ts` (39→41), `test/phantom-redirect.test.ts` (41→42; vacuous C4 test replaced by 2), `test/extract-conversation-facts-diagnostics.serial.test.ts` (4→8)+- Docs: `docs/architecture/key-files/core-utilities-1.md`, `docs/architecture/key-files/commands-3.md` (pointers from deleted test files to their new owners)+- No production code changed. No shared files (smell GRANDFATHERED, tsv, weights, CLAUDE.md, CHANGELOG, VERSION) touched.++## Smell ratchet (`bun test test/test-reads-source-smell.test.ts` — fails as expected, "stale ratchet entry")++All touched files now have 0 unjustified src/ read sites:+asymmetric-encoding-contract 3→0, backlinks-job-default 1→0 (deleted), cli.test 1→0 (read now tagged `[structural]`), cycle-pack-gating 1→0, cycle-patterns 1→0 (one tagged `[structural]` read kept), cycle/cycle-lock-ttl 1→0 (deleted), extract-conversation-facts-workers 1→0 (deleted), phantom-redirect-per-source-lock 1→0 (deleted), regression-strict-source-id 6→0, upgrade.serial 1→0.+Also reported stale but NOT from this slice (already stale at HEAD): `distribution-import-boundary.test.ts` 1→0.++## Shared-file edits the parent owns++- GRANDFATHERED: remove the 10 entries above (+ distribution-import-boundary if not handled elsewhere).+- `scripts/test-weights.json`, `scripts/ubicloud/weights.json`: remove the 4 deleted files. `scripts/structural-suites.tsv`: backlinks-job-default, cycle/cycle-lock-ttl, phantom-redirect-per-source-lock appear; regenerate with `bun scripts/classify-tests.ts`. No hits in `.github/`, `scripts/e2e-test-map.ts`, `test/fixtures/e2e-unmapped-baseline.txt`, `scripts/serial-weights.json`, `scripts/e2e-weights.json`.++## Commands run++- `bash ~/.capy/drive/user-garry-tan/skills/gstack/scripts/install.sh --check` → failed (not installed); installer run → "Claude skills, GPT-6 Astra skills, and Chromium are ready"+- `bun install --frozen-lockfile` → OK+- each touched file alone: handlers 12/0, core/cycle.serial 41/0, phantom-redirect 42/0, asymmetric-encoding-contract 4/0, regression-strict-source-id 5/0, cycle-pack-gating 8/0, cycle-patterns 11/0, cli 20/0, upgrade.serial 25/0, extract-conversation-facts-diagnostics.serial 8/0+- `bun run typecheck` → clean+- `bun run check:test-isolation` → OK (1988 non-serial unit files)+- `bun run check:doc-history` → ok+- every probe: mutation applied with a scripted exact-string replace, `bun test` new owner + a copy of the HEAD version of the old test, then `git checkout src` (final `git status --short src` clean)+++All probes were applied to production code, run, and reverted with `git checkout <file>`.+"new" = behavior test added in this slice. Counts are `bun test <file>` pass/fail.++## Retiring a test — evidence table++| Deleted test | Probe edit | Result | Surviving owner | Owner result |+|---|---|---|---|---|+| `test/backlinks-job-default.test.ts` › "default action is 'check'" + "inverted shape stays absent" + "block exists" (file deleted) | `src/commands/jobs.ts` backlinks handler: `job.data.action === 'fix' ? 'fix' : 'check'` → `=== 'check' ? 'check' : 'fix'` (fix-by-default) | deleted test fails (2 of 3) | `test/handlers.test.ts` › "no action in job.data → check: gap reported, target page untouched" (new) | fails (1 of 12) |+| ↳ coupling evidence | `jobs.ts`: behavior-preserving rewrite `job.data.action !== 'fix' ? 'check' : 'fix'` | deleted test fails (1 of 3) | same owner | passes (12 of 12) |+| `test/cycle/cycle-lock-ttl.test.ts` › "LOCK_TTL_MINUTES === 5" (file deleted) | `src/core/cycle.ts`: `LOCK_TTL_MINUTES = 5` → `30` (DB lock TTL) | deleted test fails (1 of 1) | `test/core/cycle.serial.test.ts` › "a held cycle lock expires 5 minutes out" (new) | fails (1 of 41) |+| ↳ same test, second literal | `src/core/cycle.ts`: `LOCK_TTL_MS = 5*60*1000` → `30*60*1000` (file-lock staleness) | deleted test fails (1 of 1) | `test/core/cycle.serial.test.ts` › "a live holder whose lock file is older than 5 minutes is treated as stale" (new) | fails (1 of 41) |+| `test/phantom-redirect-per-source-lock.test.ts` › "import line uses syncLockId" + "acquireLockWithRetry passes syncLockId(sourceId)" (file deleted) | `src/core/cycle/phantom-redirect.ts`: `acquireLockWithRetry(engine, syncLockId(sourceId), …)` → `acquireLockWithRetry(engine, SYNC_LOCK_ID, …)` (+ import) | deleted test fails (2 of 3) | `test/phantom-redirect.test.ts` › "lock contention (C4) — per-source sync lock" (2 new tests) | fails (2 of 42) |+| ↳ same, bare literal | `phantom-redirect.ts`: lock id → `'gbrain-sync'` | deleted test fails (1 of 3) — import pin blind | same owner | fails (2 of 42) |+| `test/phantom-redirect-per-source-lock.test.ts` › "helper sanity: syncLockId returns gbrain-sync:<source> shape" | `src/core/db-lock.ts`: `syncLockId` → `gbrain-sync/${sourceId}` | deleted test fails (1 of 3) | `test/phantom-redirect.test.ts` › "same-source sync lock held → lock_busy" (seeds the literal `gbrain-sync:src-b` row) | fails (1 of 42) |+| `test/phantom-redirect.test.ts` › "lock contention (C4)" — REPLACED (vacuous: asserted only the row it had just inserted, and seeded the pre-D16 bare `gbrain-sync` id) | any lock-id mutation above | old test passes (blind; it never called the pass) | replaced by the two per-source behavior tests in the same describe | fails (2 of 42) |+| `test/asymmetric-encoding-contract.test.ts` › "Source-text contract": "hybrid.ts imports embedQuery" + "hybrid.ts calls embedQuery" (describe deleted; file kept) | `src/core/search/hybrid.ts` `embedQueryBounded`: `embedQuery(text, {...})` → `embed(text)` (document encoding on the search path) | deleted tests: 1 of 3 fails (import pin blind — `embedQuery` still imported) | `test/asymmetric-encoding-contract.test.ts` › "embedQueryBounded sends input_type=query for Voyage" (new; both hybridSearch query-embed call sites, hybrid.ts:1880 and :2767, go through `embedQueryBounded`) | fails (1 of 4) |+| `test/asymmetric-encoding-contract.test.ts` › "embedding.ts re-exports both embed and embedQuery" | vacuous for behavior: `hybrid.ts` imports `{ embed, embedQuery }` from `../embedding.ts`, so dropping either export is a `tsc` error | — | `bun run typecheck` (verify battery) | see typecheck probe below |+| `test/regression-strict-source-id.test.ts` › "patterns.ts imports validateSourceId from utils.ts" + "patterns.ts calls validateSourceId before reverse-write join" (deleted; file kept) | `src/core/cycle/patterns.ts` `reverseWriteRefs`: move `validateSourceId(source_id)` after `writeFileSync` | old file 1 of 9 fails | `test/regression-strict-source-id.test.ts` › "patterns: snake_id and traversal ids throw and write nothing" (new, drives `patterns.__testing.reverseWriteRefs`) | fails (1 of 5) |+| `test/regression-strict-source-id.test.ts` › "synthesize.ts imports validateSourceId from utils.ts" + "synthesize.ts calls validateSourceId before reverse-write join" (deleted) | `src/core/cycle/synthesize.ts` `reverseWriteRefs`: delete `validateSourceId(source_id)` | old file 1 of 9 fails | `test/regression-strict-source-id.test.ts` › "synthesize: snake_id and traversal ids throw and write nothing" (new) | fails (1 of 5) |+| `test/regression-strict-source-id.test.ts` › "utils.ts source text contains no permissive regex" + "utils.ts re-exports assertValidSourceId as validateSourceId" (deleted) | `src/core/utils.ts`: replace the re-export with a permissive `/^[a-z0-9_./-]+$/` validator | old file 3 of 9 fail | kept behavior tests "validateSourceId from utils.ts IS assertValidSourceId…", "rejects underscores", plus both new reverse-write tests | fails (4 of 5) |+| `test/cycle-pack-gating.test.ts` (file rewritten: 21 → 8 tests; 14 source-grep pins over `cycle.ts` deleted, exported-constant ALL_PHASES/PHASE_SCOPE checks consolidated) › "packDeclaresPhase helper exists", "reads resolved.manifest.phases", "fail-open returns false" | `src/core/cycle.ts` `packDeclaresPhase`: `return phases.includes(phase)` → `… && false` (gate never opens) | old file passes 21/21 (blind) | new › "a pack that declares the phases (gbrain-creator) opens the gate" | fails (1 of 7) |+| ↳ "dispatch for synthesize_concepts calls packDeclaresPhase" + "not_in_active_pack uses the same marker" | `cycle.ts`: `else if (!(await packDeclaresPhase(engine,'synthesize_concepts')))` → `else if (false && …)` (gate dropped, string kept) | old file passes 21/21 (blind) | new › "a pack without the phases skips both…" + "pack gating is additive…" | fails (2 of 7) |+| ↳ "only extract_atoms + synthesize_concepts reference packDeclaresPhase" + "extract_facts / calibration_profile dispatch does NOT consult packDeclaresPhase" | `cycle.ts`: add a `packDeclaresPhase(engine,'extract_facts')` skip branch to the extract_facts dispatch | old 3 of 21 fail | new › "pack gating is additive: a full default-pack cycle pack-skips only the two lens phases" | fails (1 of 7) |+| ↳ "NEEDS_LOCK_PHASES includes extract_atoms / synthesize_concepts" | `cycle.ts`: drop `'extract_atoms'` from `NEEDS_LOCK_PHASES` | old 1 of 21 fail | new › "extract_atoms alone waits behind a live cycle-lock holder" | fails (1 of 7) |+| ↳ "#2117 both skip summaries name the phases: key and a lens pack" + "drain hint" | `cycle.ts`: synthesize_concepts skip summary → `'synthesize_concepts: skipped'` | old 1 of 21 fail | new › "a pack without the phases skips both with an actionable … summary" | fails (1 of 7) |+| ↳ "packDeclaresPhase reads phases from active pack manifest (NOT extends chain)" | `src/core/schema-pack/merge.ts` `mergeInheritedManifest`: inherit `phases` from the nearest ancestor that declares them | old passes 21/21 (blind) | new › "phases are not inherited through extends (D4-B)" (user pack under `$GBRAIN_HOME/.gbrain/schema-packs/`, verified to load: merged page_types include `atom`, `phases` undefined) | fails (1 of 8) |+| `test/cycle-patterns.test.ts` (file rewritten: 16 → 11 tests; module-level `patterns.ts` source read removed; 1 tagged structural pin kept — see "Kept pins") › "caps gather to 100 reflections" | `src/core/cycle/patterns.ts` gatherReflections: `LIMIT 100` → `LIMIT 1000` | old file 16/16 pass (blind: `'LIMIT 1000'` contains `'LIMIT 100'`) | new › "scoped to <prefix>/, newest first, capped at 100, bounded by lookback" | fails (1 of 10) |+| ↳ "orders by updated_at DESC" | `patterns.ts`: `ORDER BY updated_at DESC` → `ASC` | old 16/16 pass (blind: the DESC string survives in a comment) | same new test | fails (1 of 10) |+| ↳ "filters reflections by slug LIKE <prefix>/%" | `patterns.ts`: bind `${sourceSlugPrefix}%` (no slash; sibling trees leak in) | old 1 of 16 fails | same new test | fails (1 of 10) |+| ↳ "reads min_evidence + lookback_days config" | `patterns.ts` loadPatternsConfig: `Math.max(1, parseInt(minEvidenceStr)…)` → `Math.max(3, …)` | old 16/16 pass (blind) | new › "min_evidence: 2 reflections skip by default … run at min_evidence=2" | fails (1 of 10) |+| ↳ (same test, lookback half) | `patterns.ts`: `lookbackDays: lookbackStr ? 30 : 30` (config ignored) | old 16/16 pass (blind) | new › "lookback_days narrows the window" | fails (1 of 10) |+| ↳ "source slug prefix defaults to …/reflections" + scope-filter `dream.patterns.source_slug_prefix` | `patterns.ts`: read key `dream.patterns.source_slug_prefix_x` | old 16/16 pass (blind: substring) | new › "source_slug_prefix points the phase at another reflection tree" | fails (1 of 10) |+| ↳ "gates on gateway provider reachability, not ANTHROPIC_API_KEY" | `patterns.ts`: probe → `process.env.ANTHROPIC_API_KEY ? ok : fail` | old 1 of 16 fails | new › "a non-Anthropic model passes the gate with no ANTHROPIC_API_KEY" | fails (1 of 10) |+| ↳ (same test, `normalizeModelId`) | `patterns.ts`: `probeChatModel(normalizeModelId(config.model))` → `probeChatModel(config.model)` | old 16/16 pass (blind: import still present) | new › "a bare model id is normalized to its provider before probing" | fails (1 of 10) |+| ↳ "adds a configured output_slug_prefix to the subagent write allow-list" + "threads allowed_slug_prefixes from filing-rules JSON" | `patterns.ts`: `if (!allowedSlugPrefixes.includes(outputGlob))` → `if (allowedSlugPrefixes.includes(outputGlob))` | old 16/16 pass (blind) | new › "job carries filing-rule + configured output allow-list and prompt prefixes; no raw_data" | fails (1 of 10) |+| ↳ "output slug prefix is config-driven" | `patterns.ts`: read key `dream.patterns.output_slug_prefix_x` | old 16/16 pass (blind: substring) | same submission test | fails (1 of 10) |+| ↳ "does NOT use raw_data table (Codex #3)" | `patterns.ts`: `INSERT INTO raw_data …` right after `new MinionQueue(engine)` | old 16/16 pass (blind) | same submission test (asserts `raw_data` empty) | fails (1 of 10) |+| ↳ "reverse-writes pages to disk via serializeMarkdown" | `patterns.ts` renderPageToMarkdown: `return page.compiled_truth ?? ''` (frontmatter dropped) | old 16/16 pass (blind) | new › "writes the page back as markdown that round-trips title, type, tags and body" | fails (1 of 10) |+| ↳ "uses subagent_tool_executions for slug provenance" | `patterns.ts` collectChildPutPageSlugs: `tool_name = 'brain_put_page'` → `'put_page'` | old 1 of 16 fails | `test/cycle-patterns-source-scope.test.ts` › "collected refs carry the cycle source" (+4) | fails (5 of 6) |+| ↳ "runs after extract — does not call runAutoLink / extractPageLinks" (vacuous negative pin) | `src/core/cycle.ts` ALL_PHASES: move `'patterns'` before `'extract'` | old 16/16 pass (blind) | `test/core/cycle.serial.test.ts` › "default: all 6 phases run in order" | fails (1 of 41) |+| ↳ "imports … SubagentHandlerData" | vacuous: a type-only import, enforced by `tsc` | — | `bun run typecheck` | — |+| `test/cli.test.ts` › "reindex is in CLI_ONLY" (deleted) | `src/cli.ts`: drop `'reindex'` from `CLI_ONLY` | old file 2 of 24 fail (this pin + the census) | `test/cli.test.ts` › "CLI-only commands reach their handlers instead of \"Unknown command\"" (new, spawns `gbrain <cmd> --help` for reindex/import/export/embed/files) + kept census | fails (2 of 20) |+| `test/cli.test.ts` › "CLI_ONLY set contains expected commands" (deleted) | `cli.ts`: drop `'files'` from `CLI_ONLY` | old 1 of 24 fails — only the kept census; this pin is blind (`'files'` still appears in `case 'files':`) | same new spawn test | fails (2 of 20) |+| `test/cli.test.ts` › "ask alias maps to query in source" (replaced) | `cli.ts`: delete the `if (command === 'ask') command = 'query'` block | old 1 of 24 fails | `test/cli.test.ts` › "ask dispatches to the query op" (new, spawns `gbrain ask --help`, expects `Usage: gbrain query`) | fails (1 of 20) |+| ↳ coupling evidence | `cli.ts`: behavior-preserving `command = ({ ask: 'query' })[command] ?? command` | old 1 of 24 fails | same new test | passes (20 of 20) |+| `test/cli.test.ts` › "imports operations from operations.ts" + "builds cliOps map from operations" (deleted) | `cli.ts`: `cliOps` population guarded with `&& false` (map left empty) | old 1 of 24 fails — neither pin (strings survive) | existing `test/cli.test.ts` › "per-command --help prints usage without DB connection" + new "ask dispatches to the query op" | fails (2 of 20) |+| `test/cli.test.ts` › "has formatResult function for CLI output" (deleted) | vacuous: `formatResult` is imported and called by the kept "formatResult's default renderer is bigint-safe" test; removal is a `tsc` + runtime failure there | — | `test/cli.test.ts` › "formatResult's default renderer is bigint-safe" | — |+| `test/upgrade.serial.test.ts` › describe "detectInstallMethod heuristic (source analysis)" (13 source-grep tests deleted; replaced by 4 in-process + 4 PATH-shimmed behavior tests) › "checks node_modules before binary" | `src/commands/upgrade.ts` detectInstallMethod: `if (execPath.endsWith('/gbrain')) return 'binary'` inserted before the node_modules branch | old file 30/30 pass (blind: first `node_modules` hit is a comment) | new › "node_modules is checked before the compiled-binary execPath name" | fails (1 of 25) |+| ↳ "checks binary before clawhub" | `upgrade.ts`: clawhub probe inserted before the binary check | old 4 of 30 fail | existing › "binary self-update {smoke_failed,version_mismatch,replace_failed} records to_version" (run under a `gbrain`-named bun with a succeeding clawhub shim) | fails (3 of 25) |+| ↳ "uses clawhub --version, not which clawhub" | `upgrade.ts`: `execSync('which clawhub', …)` | old 2 of 30 fail | new › "clawhub is detected by running `clawhub --version`, not by PATH presence" (+ hung-probe test) | fails (2 of 25) |+| ↳ "has timeout on upgrade execSync calls" | `upgrade.ts`: drop `timeout: 5_000` from the clawhub detection probe | old 30/30 pass (blind: other `timeout:` literals keep the count ≥2) | new › "a hung `clawhub --version` probe times out instead of wedging upgrade" | fails (1 of 1 run with `-t hung`; hit the 60s test timeout) |+| ↳ "does not reference npm in case labels or messages" | covered by the same clawhub test: the `unknown` path's full stdout+stderr must not mention `npm` | — | new › "clawhub is detected by running `clawhub --version`…" | asserts on output |+| ↳ "bun-link signal walks .git/config for garrytan/gbrain match" (`toLowerCase`) | `upgrade.ts` detectBunLink: `cfg.includes(GBRAIN_GITHUB_REPO)` (case-sensitive) | old 30/30 pass (blind: `toLowerCase()` appears elsewhere) | new › "bun-link: case-insensitive .git/config marker; git pull + bun install run at the repo root without a shell" (config url `GarryTan/GBrain`) | fails (1 of 25) |+| ↳ "detectBunLink does not gate on isSymbolicLink" | `upgrade.ts` detectBunLink: `if (!lstatSync(argv1).isSymbolicLink()) return null` | old 1 of 30 fails | same new bun-link test (argv[1] is a real file) | fails (1 of 25) |+| ↳ "detectBunLink returns repoRoot" + "bun-link upgrade uses execFileSync for shell-injection safety" | `upgrade.ts`: `execSync(\`git -C ${linkInfo.repoRoot} pull --ff-only\`)` | old 1 of 30 fails | same new bun-link test (checkout path contains `$(touch INJECTED-…)`; the probe run created the marker, the test caught it) | fails (1 of 25) |+| ↳ "bun global upgrade passes cwd to bun update" | `upgrade.ts`: drop `cwd: bunGlobalRoot` from `bun update gbrain` | old 1 of 30 fails | new › "bun global install: `bun update gbrain` runs in the bun global root" | fails (1 of 25) |+| ↳ "classifyBunInstall checks repository.url AND src/cli.ts marker" | `upgrade.ts` classifyBunInstall: remove the repository.url check | old 30/30 pass (blind) | new › "canonical by repository.url: bun, no squatter warning" | fails (1 of 25) |+| ↳ (same test, marker half) | `upgrade.ts` classifyBunInstall: remove the `src/cli.ts` marker check | old 1 of 30 fails | new › "canonical by shipped src/cli.ts marker when repository is absent" | fails (1 of 25) |+| ↳ "squatter recovery message names both source-clone AND release-binary paths" | `upgrade.ts` printSquatterRecovery: drop the releases URL line | old 30/30 pass (blind: `releases` appears elsewhere in the file) | new › "npm squatter … warns with clone + release recovery (#658)" | fails (1 of 25) |+| ↳ "return type includes bun-link variant" | vacuous: the `switch (method)` has `case 'bun-link'`, so dropping the union member is a `tsc` error | — | `bun run typecheck` | — |+| `test/extract-conversation-facts-workers.test.ts` (file deleted; 17 tests: 12 source-grep + 3 exported-helper + 2 type-shape greps) › "LockUnavailableError caught + pages_lock_skipped incremented (D6)" | `src/commands/extract-conversation-facts.ts`: drop `state.result.pages_lock_skipped++` in the lock-busy catch | old file 1 of 17 fails | `test/extract-conversation-facts-diagnostics.serial.test.ts` › "a page locked by another worker is skipped and counted; the CLI exits 3; release lets it run" (new) | fails (1 of 8) |+| ↳ "per-page work wrapped in withRefreshingLock (D2 + D12)" | `extract-conversation-facts.ts`: replace `withRefreshingLock(engine, lockId, fn, …)` with a direct `fn()` call | old 1 of 17 fails | same new lock test | fails (1 of 8) |+| ↳ "exit 3 fires when lock-busy pages remain (codex #3)" | `extract-conversation-facts.ts`: delete `if (aggregate.pages_lock_skipped > 0 …) process.exit(3)` | old 1 of 17 fails | same new lock test (`process.exit` spied → expects `exit:3` and the "Skipped 1 page(s) held by another worker" summary) | fails (1 of 8) |+| ↳ "delete-orphans-first called BEFORE segment extraction (D11)" | `extract-conversation-facts.ts`: remove the delete-orphans-first call | old 17/17 pass (blind: `deleteOrphanFactsForPage(` still appears in the non-extractable path) | new › "replay deletes a prior partial run's facts before extracting, keeping the new ones (D11)" | fails (1 of 8) |+| ↳ (same test, ordering) | `extract-conversation-facts.ts`: move the delete from before the segment loop to after it | old 17/17 pass (blind) | same new D11 test (the late delete wipes the facts it just inserted) | fails (1 of 8) |+| ↳ "preflight fires … BEFORE work loop" + "imports assertFactsEmbeddingDimMatchesConfig" | `extract-conversation-facts.ts`: delete the D15 preflight call | old 1 of 17 fails | new › "embedding-width drift fails the run before any page is attempted (D15 preflight)" (engine view reporting `kind: 'postgres'` over the same PGLite DB; gateway reconfigured to 1024 dims vs the `halfvec(1536)` column) | fails (1 of 8) |+| ↳ (same, ordering) | `extract-conversation-facts.ts`: move the preflight from before the work loop to just before `return result` | old 1 of 17 fails | same new preflight test (asserts no page was attempted before the throw) | fails (1 of 8) |+| ↳ "parsedArgs.workers threaded into core opts" | `extract-conversation-facts.ts` runExtractConversationFacts: drop `workers: parsed.workers` from the core opts | old 17/17 pass (blind: the job-envelope copy of the string survives) | new › "--workers reaches the worker resolver and the --background job envelope" | fails (1 of 8) |+| ↳ "Minion job envelope includes workers (D9 round-trip)" | `extract-conversation-facts.ts` buildJobParams: drop `workers: parsed.workers` | old 17/17 pass (blind: the core-opts copy survives) | same new workers test (job row `data.workers === 20`) | fails (1 of 8) |+| ↳ "runExtractConversationFactsCore calls resolveWorkersWithClamp" + import pins (runSlidingPool, parseWorkers/resolveWorkersWithClamp, withRefreshingLock/LockUnavailableError) | import pins are vacuous (`tsc`); the resolver call is observed by the kept "three actual pool workers share exact counters…" (spied resolver; `maxActive === 3`) and the new workers test | — | existing + new diagnostics tests | — |+| ↳ "ExtractConversationFactsResult has pages_lock_skipped + orphan_facts_cleaned" + "initial result object literal initializes both counters to 0" | the counters are asserted as exact values (`pages_lock_skipped: 1/0`, `orphan_facts_cleaned: 1`) and via the CLI summary; an uninitialized counter becomes `NaN` and fails those | — | new lock + D11 tests | — |+| ↳ "extractConversationFactsLockId composes source + slug" + "lock id differs across sources" | `extract-conversation-facts.ts`: lock id → `extract-conversation-facts:${slug}` (source dropped) | old 2 of 17 fail | new lock test (the same slug in `speaker-b` must run while `speaker-a`'s is held) | fails (1 of 8) |+| ↳ "PER_PAGE_LOCK_TTL_MINUTES is short enough…" | `extract-conversation-facts.ts`: `PER_PAGE_LOCK_TTL_MINUTES = 2` → `30` | old 1 of 17 fails | new lock test (reads the live lock's TTL during the model call; must be ≤ 10 min) | fails (1 of 8) |++### Typecheck probes for vacuous pins++| Deleted pin | Probe edit | `bun run typecheck` |+|---|---|---|+| asymmetric › "embedding.ts re-exports both embed and embedQuery" | `src/core/embedding.ts`: un-export `embedQuery` | 10 errors (e.g. `src/commands/takes.ts(28,10): TS2459 … 'embedQuery' … not exported`; `hybrid.ts` imports it too) |+| upgrade › "return type includes bun-link variant" | `src/commands/upgrade.ts`: drop `'bun-link'` from `detectInstallMethod`'s return union | `upgrade.ts(48,10): TS2678` + `upgrade.ts(823,22): TS2322` |++## Kept pins (tagged, class-2, no cheap harness)++| File › test | Why kept | Probe |+|---|---|---|+| `test/cli.test.ts` › "every handleCliOnly top-level case label is reachable via CLI_ONLY" | A self-updating registry census: switch `case` labels in `handleCliOnly` cannot be enumerated at runtime, so a NEW case missing from CLI_ONLY can only be caught from source text. Now carries a `test-reads-source-ok[structural]` marker (shared module-level read). | drop `'reindex'`/`'files'` from CLI_ONLY → fails |+| `test/cli.test.ts` › "cli.ts no longer uses a replacer-less stringify on the normalize path" | The local-op normalize call site sits inline in `main()`; bigints only reach it from Postgres (PGLite returns int8/COUNT as JS numbers — verified with `SELECT 5::bigint, count(*)` → `number number`), so no unit-lane harness can drive a bigint through it without a production seam. Same tagged read. | not re-probed (unchanged test body) |+| `test/cycle-patterns.test.ts` › "the post-drain wait renews the private-queue lease through the shared throttled factory" | The lease only lapses after a >10-min post-drain wait with a live child; on the inline drain the child is terminal before the wait, so renewal is unobservable (verified: a `renewPrivateQueueLease` spy saw no call even on real code). Library behavior is owned by `test/wait-for-completion.test.ts` / `test/queue-child-done.test.ts`. Tagged `test-reads-source-ok[structural]`. Honest limits: blind to `import { waitForCompletion as waitForCompletionRenewing }` (passes), and trips on a behavior-preserving `(waitForCompletionRenewing as any)(…)` cast. `test/cycle-abort.test.ts` also pins the same call. | alias probe: passes (blind); cast probe: fails |++## Ratchets, manifests, commands++| Command | Result |+|---|---|+| focused: 34 touched/owner files each run alone (`(scratch) focused.txt`) | all pass |+| `bun run typecheck` | clean |+| `bun run verify` | 56/56 checks green (23 s) |+| `bun run check:test-placeholders` | OK (2622 files, 6 allowlisted sites) |+| `bun test test/test-reads-source-smell.test.ts` | 12/0 after removing 16 GRANDFATHERED entries (15 rewritten/deleted files → 0, plus the stale `distribution-import-boundary` entry left by slice 19) |+| `bun scripts/classify-tests.ts` | `scripts/structural-suites.tsv` regenerated (314 suites / 1339 cases / 182 files) |+| weights: 5 deleted files removed from `scripts/ubicloud/weights.json` and `scripts/test-weights.json` (none in serial/e2e weights, `.github`, `e2e-test-map.ts`, e2e baseline) | `run-serial-pool`, `ci-ubicloud-schedule`, `sharding`, `test-shard.slow` pass |+| `bun run check:orphan-modules` | OK (20 permitted test-only) |+| `bun run check:test-isolation` | OK |diff --git a/docs/test-audit/2026-09-29/implementation/security.md b/docs/test-audit/2026-09-29/implementation/security.mdnew file mode 100644index 0000000000..186f396e7d--- /dev/null+++ b/docs/test-audit/2026-09-29/implementation/security.md@@ -0,0 +1,56 @@+## Source-config secret exposure (security item of the test-reduction plan)++A stored `webhook_secret` leaked through two surfaces. Both now route through `redactSourceConfig()`, and every surface that reads and serializes `sources.config` has a behavioral test that stores a secret-bearing config and asserts the secret never appears in output. Stored config is never mutated by the fix or the tests (each leak test asserts the stored secret is still intact).++### Leaks found and fixed++| Surface | How it leaked | Fix |+|---|---|---|+| `sources_add` op result, printed by `gbrain call sources_add` | Attaching a path to an existing path-less source (#3903 attach path) returned the full `SourceRow`, including the raw `config` with `webhook_secret` | `src/core/ops/sources.ts`: return `config: redactSourceConfig(parseSourceConfig(row.config))` |+| Managed `gbrain sources add <id> --path` (attach), its idempotent replay, and the `source_lifecycle` administration op | Outcome carried `config: {...source.config, ...input.config}`; the same outcome is persisted in `persistence_topology_changes` and replayed on retry | `src/core/persistence/source-lifecycle.ts`: outcome `config` goes through `redactSourceConfig()`, so neither the receipt nor the retained journal row holds the secret |++Behavior change on an intentional reveal: `sources webhook set` printed the new secret twice (config summary + GitHub paste block). The summary line now reads `webhook_secret: (shown once below)`, and the paste block still prints it once. `sources webhook rotate` already printed it once and is unchanged.++### Secret-bearing keys++`SECRET_KEYS` stays `{webhook_secret}`. Every other key the codebase reads is a pointer, not a credential: `gh_token_env` / `g_token_env` name env vars, `gh_app_pem_path` names a key file, `g_token_command` names a mint command, `g_account` is a vault pointer, and `remote_url` with embedded credentials is rejected by `parseRemoteUrl`. Recorded in the header of `scripts/check-source-config-leak.sh`.++### New tests and mutation evidence++Every test passes on the real code. Each row applied one targeted production mutation (scripted in `(scratch) src-secret/mutate.py`, restored after each run) and ran the named test with `-t`.++| # | Mutation (production code) | File | Test (`-t`) | Result under mutation |+|---|---|---|---|---|+| M1 | `sources list --json` emits `config` | `src/commands/sources.ts` | source-config-secret-surfaces "list, status" | 0 pass / 1 fail |+| M2 | `webhook show` prints the stored secret | `src/commands/sources.ts` | "list, status" | 0 pass / 1 fail |+| M3 | `sources status --json` spreads config | `src/commands/sources.ts` | "list, status" | 0 pass / 1 fail |+| M4 | `archived --json` lists raw config | `src/commands/sources.ts` | "list, status" | 0 pass / 1 fail |+| M5 | `remove --dry-run` echoes config | `src/commands/sources.ts` | "list, status" | 0 pass / 1 fail |+| M6 | re-wrapped-config warning interpolates config | `src/core/sources-load.ts` | "re-wrapped" | 0 pass / 1 fail |+| M7 | `webhook set` prints the secret twice (pre-fix output) | `src/commands/sources.ts` | "webhook set" | 0 pass / 1 fail |+| M8 | `webhook rotate` prints the secret twice | `src/commands/sources.ts` | "webhook rotate" | 0 pass / 1 fail |+| M8b | `webhook rotate` also prints the old secret | `src/commands/sources.ts` | "webhook rotate" | 0 pass / 1 fail |+| M9 | `sources_add` returns raw config (pre-fix) | `src/core/ops/sources.ts` | "gbrain call" | 0 pass / 1 fail |+| M10 | `listSources` (remote `sources_list`) returns config | `src/core/sources-ops.ts` | "remote MCP" | 0 pass / 1 fail |+| M11 | `getSourceStatus` (remote `sources_status`) returns config | `src/core/sources-ops.ts` | "remote MCP" | 0 pass / 1 fail |+| M12 | sync report (remote `get_status_snapshot`) returns config | `src/core/sync-status-report.ts` | "remote MCP" | 0 pass / 1 fail |+| M13 | remote `run_doctor` federation_health message echoes configs | `src/commands/doctor/checks/routing-federation.ts` | "doctor" | 0 pass / 1 fail |+| M13c | local `doctor --json` source_config_shape message echoes configs | `src/commands/doctor/checks/core-health.ts` | "doctor" | 0 pass / 1 fail |+| M14 | managed add receipt returns raw config (pre-fix) | `src/core/persistence/source-lifecycle.ts` | "managed" | 0 pass / 1 fail |+| M15 | backup metadata inventories raw source config | `src/core/backup/snapshot.ts` | agent-install-backup.serial "full backup" | 0 pass / 1 fail (manifest assertion) |+| M16 | restore reconnect lines / receipt echo detached config | `src/core/backup/quarantine.ts` | agent-install-backup.serial "full backup" | 0 pass / 1 fail (reconnect assertion) |+| M17 | `GET /admin/api/sources` returns raw rows | `src/commands/serve-http.ts` | e2e/serve-http-oauth "admin source access" | 0 pass / 1 fail |++Pre-fix run of the new file on unmodified master: 5 pass / 3 fail (webhook set printed 2 occurrences; `gbrain call sources_add` and the managed receipt returned the raw secret). Post-fix: 8 pass / 0 fail.++A first doctor mutation that edited `checkFederationHealth` survived because local doctor never runs that check (only `run_doctor` does). The test was extended to cover remote `run_doctor` too, and both doctor mutations (M13, M13c) now fail it.++### Audited surfaces with no leak (explicit field projections, now pinned)++`sources list/status/webhook show/current/archived/remove --dry-run` (human and `--json`), parse warnings, remote MCP `sources_list` / `sources_status` / `get_status_snapshot` / `run_doctor`, local `doctor --json`, admin API `GET /admin/api/sources`, backup metadata, restore reconnect lines and `restore-receipt.json`, and `.jsonl`/`.log` files under `GBRAIN_HOME` after managed administration. The MCP request log stores caller params, never results. Internal readers (sync, autopilot, resolver, destructive guard, webhook HMAC check, connectors, minion authority digest, company brain) only use config as a predicate.++Kept by contract: the full-database backup archive (`sensitive-full-database-state`) and the private 0600 restore inventory `.gbrain/restore-detached.json`, which intentionally retains detached source configs so the operator can reconnect them.++### Deleted tests++None. `src/core/source-config-redact.ts` is kept, and it is now imported by two runtime serializers, so the orphan-module test-only count dropped from 45 to 44 (the ceiling of 46 is unchanged).diff --git a/docs/test-audit/2026-09-29/lane-doc-pins/doc-pins.md b/docs/test-audit/2026-09-29/lane-doc-pins/doc-pins.mdnew file mode 100644index 0000000000..2ff8a8f1b1--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-doc-pins/doc-pins.md@@ -0,0 +1,166 @@+# Test audit — lane `doc-pins` (read-only discovery)++Repo: garrytan/gbrain @ `2ede415` (v0.59.11.0), shallow clone (50 commits; history before `d9909cd` squashed).+Method: openclaw `test-audit` skill (audit mode, evidence-before-edit), gbrain `docs/TESTING.md` §"Coverage responsibilities before consolidation" (surviving owner must cover the same contract **and** boundary, and must execute).+Cost source: `scripts/ubicloud/weights.json` (ms per file). Lane totals for scale: unit 3,985 s, serial 1,930 s, slow 847 s, e2e 2,879 s.+Tree state: every probe reverted with `git checkout -- .`; `git status --short` empty at the end. `bun install --frozen-lockfile` was needed first (node_modules was absent; untracked).++## 1. Scope actually found++The "~157 files" estimate comes from a coarse grep (`CHANGELOG|README|SKILL.md|docs/...`). I reproduced it (152 files), but most of those hits are **temp-fixture trees** (tests that `mkdtemp` a workspace and write their own `README.md` / `SKILL.md` / `RESOLVER.md` / `AGENTS.md`, e.g. skillpack-*, shared-skills-*, sync*, bootstrap-* renders). Those test product behavior, not committed docs, and are out of this lane.++Tests that read **committed** repo docs / skills / templates / recipes / version files as text and assert on them: **~44 files** (list in §6). Of these, ~10 files carry prose-only pins; the rest are generated-artifact freshness, link/reference integrity, release/version sync, or shipped prompt/recipe contracts.++Compute is not the argument in this lane: the whole in-lane set costs ~83 s of per-file time (40 s of that is one e2e that executes a shipped script — keep). The value of cutting here is friction: prose pins make doc edits fail CI without protecting behavior.++## 2. Top candidates (full evidence)++### C1 — `test/readme-hero-anchors.test.ts` (whole file, 5 tests) → **delete**+- Tests: `README hero anchors (D9 regression guard) > mentions OpenClaw`, `> mentions Hermes`, `> leads with controlled memory and the two distinct setup paths`, `> includes at least one production number`, `> includes BrainBench framing (P@5 or R@5)`.+- Detects: exact marketing phrases in the first 50 README lines. **Probe P1:** meaning-preserving reword "Give the agent you already use a memory you control" → "Give your existing agent a memory you control": **FAIL** (`leads with controlled memory…`). No product behavior involved.+- Non-test callers of the seam: none. `grep src` for README reads finds only unrelated `README.md` files that shared-skills/template generators write themselves (`src/core/bootstrap/template-repo.ts:171`, `src/core/shared-skills/*`); nothing consumes the repo README.+- Surviving owner: none needed (no contract). README links are already checked by `test/docs-navigation.test.ts > local Markdown links and fragments resolve in README.md`; README commands by `test/docs-cli-commands.test.ts > every gbrain <verb> in README/docs/skills resolves`; privacy by `check:privacy`.+- History: rewritten at each headline rotation — `1fc8b6c` (#5026) replaced the "Search gives you raw pages…" anchor with the new headline; `db56c77` trimmed the comment again. The file's own header says "If yes [deliberate rotation]: update the anchors here". Pure lockstep churn; no evidence it ever caught a regression.+- Unlocks: 52 test LOC. No production seam.+- Cost: unit 154 ms. Risk: **low**.++### C2 — issue-fix doc-wording pins: `test/docs-bootstrap-persistence-table.test.ts` (2), `test/docs-timeline-extraction-guide.test.ts` (2) → **delete**+- Tests: `#4986 bootstrap.md scopes the Stop-push knobs… > per-turn row says the switch + debounce govern the Stop path only`, `> session-end row names no switch/debounce; crash-recovery push has its own row`; `#4987 timeline extraction docs describe the real trigger > system-of-record.md Timeline row…`, `> compiled-truth.md warns that compiled-truth citations mint timeline rows`.+- Detects: specific phrases in operator guides. They import no product code, so they cannot detect the doc drifting from behavior — only the doc drifting from its own past wording.+ - **Probe P2 (behavior break):** removed `if (process.env.GBRAIN_STOP_PUSH === '0') return 'push_disabled';` from `stopPushIfDue` (`src/commands/hook.ts:932`) — the exact behavior the doc describes. docs-bootstrap-persistence-table: **PASS (2/2)**, i.e. blind.+ - **Probe P2b (meaning-preserving doc reword):** "Stop path only" → "Stop hook alone": **FAIL**.+- Surviving behavior owner (same contract, real boundary): `test/hook-command.serial.test.ts > stop-hook per-turn push [D3] > GBRAIN_STOP_PUSH=0 disables the per-turn push (buffer append still runs)` — passes at baseline, **fails** under P2. Timeline trigger behavior: `test/extract.test.ts` (cited in the test's own header as the behavior pin).+- History: both added in `f1fbdfb` (v0.50.1.0 community fix wave) as doc fixes for #4986/#4987; single commit each.+- Unlocks: 53 test LOC. Cost: unit 189 + 227 = 416 ms. Risk: **low**.+- Note (environment): 10 other tests in `hook-command.serial.test.ts` fail at baseline on this machine (push-spawn tests; environment, not probe-related). The named owner test passes at baseline.++### C3 — `test/docs-mcp-deploy.test.ts` (9 tests) → **delete 7 doc-only pins; rewrite 1 at the CLI boundary; keep route anchor only if wanted**+- Doc-only pins (7): `DEPLOY.md documents the tailnet/LAN-only… > troubleshooting names the SDK issuer error…`, `> HTTP section states --source-guard is stdio-only…`, `> ALTERNATIVES.md distinguishes tailnet-only Serve…`, `DEPLOY.md documents dual-mode /mcp auth > troubleshooting covers "needsAuth…"`, `owner magic-link flow > warns against consuming the single-use nonce…`, `> preserves private delivery and protected-bootstrap requirements`, `> distinguishes login from client creation and states lifecycle limits`.+ - **Probe P8 (behavior break):** `NONCE_TTL_MS` 5 min → 60 min (`src/commands/serve-http.ts:1319`), making "expires after five minutes" false: **PASS 9/9** (blind).+ - **Probe P8b (meaning-preserving):** "expires after five minutes" → "is valid for five minutes": **FAIL**.+- `auth help points at the owner login flow…` reads `src/commands/auth.ts` source text (`test-reads-source-ok` exemption). Rewrite at the boundary: move the 3 help-text substrings into `test/cli-help-discoverability.test.ts > #4003 — gbrain auth --help reaches the detailed usage block`, which already spawns `gbrain auth --help`.+- `documents the owner request and the existing mint endpoint` anchors the documented route to `app.post('/admin/api/issue-magic-link'` in source. The route itself is behavior-tested in `test/e2e/serve-http-consent.test.ts` (POSTs to it) and `test/mcp-admin-http.test.ts`. Weak doc↔code check; drop or keep as a one-liner.+- History: single commit `f1fbdfb` (#4500, #4893, #5007 doc fixes).+- Unlocks: ~70 test LOC and 2 `test-reads-source-ok` exemptions. Cost: unit 251 ms. Risk: **low–med** (the privacy/secret-handling sentences are security guidance; if the owner wants them frozen, fold them into one "security guidance phrases" table row, see cluster K1).++### C4 — `test/skillopt/deadline-and-hermetic.test.ts` describe `#4741 — hermetic-config docs make no platform-survives-logout claim` (2 tests) → **delete**+- Tests: `docs/guides/skillopt.md does not promise the empty-dir form keeps macOS logged in`, `the provider doc comment does not promise it either`.+- Detects: only the literal regex `/keychain and survives/` coming back. The second test greps a **source code comment** (it says so: "comment text has no runtime surface to assert").+ - **Probe P5:** re-added the retracted claim reworded ("keeps the macOS keychain login, which survives logout") to the provider file: **PASS 2/2**.+- Surviving owner for behavior: same file, `#4119 — resolveHermeticConfigDir (opt-in)` tests (3) exercise the real function.+- Unlocks: 13 test LOC, one source-read exemption. Cost: marginal (file 315 ms stays). Risk: **low**.++### C5 — per-guard "wired into verify / package.json" pins (5 files, ~14 tests) → **delete; one assertion moves to `ci-gates`**+- Tests:+ - `test/tool-catalog.test.ts > freshness guard > check script exists and is wired into package.json + the verify chain`+ - `test/no-tracked-symlinks-guard.test.ts > check-no-tracked-symlinks.sh > exists and is executable`, `> is wired into the verify dispatcher`+ - `test/check-bootstrap-guards.test.ts > check-bootstrap-tag.sh > exists and is executable`, `check-bootstrap-templates.sh > exists and is executable`, `verify + workflow wiring > both guards are registered in the verify dispatcher`, `> package.json carries both check scripts`, `check-grok-pin.sh > verify wiring: run-verify-parallel CHECKS + package.json both carry check:grok-pin`+ - `test/privacy-script-wired.test.ts > check-privacy.sh CI wiring > exists and is executable`, `> package.json "verify" script delegates to run-verify-parallel.sh`, `> run-verify-parallel.sh dispatches check:privacy`, `> package.json "check:privacy" alias points at the script`, `> CI test.yml runs bun run verify…`+ - `test/scripts/check-engine-dynamic-import.test.ts > engine dynamic-import guard wiring > is wired into the verify registry…`, `> is listed by the authoritative verify dispatcher`, and `check-engine-dynamic-import.sh > exists`+- Surviving generic owner: `test/scripts/run-verify-parallel.test.ts > guard registration ⇒ execution coverage > every manifest guard is executed by verify or explicitly exempt` (with `scripts/guard-self-test.sh` requiring every `scripts/check-*` to be in `guards-manifest.tsv`; all 8 guards are registered there). Same contract, same boundary (the `--dry-list` of the real dispatcher plus `package.json` scripts).+ - **Probe P3a:** dropped `"check:tool-catalog"` from `CHECKS`: tool-catalog wiring test FAIL **and** generic owner FAIL.+ - **Probe P3c:** dropped 7 guards (`no-tracked-symlinks, bootstrap-tag, bootstrap-templates, grok-pin, opencode-pin, privacy, engine-dynamic-import`) from `CHECKS`: every per-file pin failed, **and** the generic owner failed naming all 7 by file. Complete duplication.+ - **Probe P3b (behavior-preserving rename):** renamed `check:tool-catalog` → `check:tool-catalog-fresh` in both `package.json` and `CHECKS`. The generic owner PASSES and the guard still runs (dry-list shows it), but the tool-catalog pin FAILS: implementation-coupled.+ - The "executable" bit: every guard is invoked as `bash scripts/<x>.sh` from package.json, so the mode bit has no effect on execution.+- The one non-duplicated assertion: "test.yml verify job runs `bun run verify`" (pinned twice, in privacy-script-wired and in check-bootstrap-guards `[C2]`). `test/scripts/ci-gates.test.ts` already loads `test.yml` and asserts the verify job's `needs`/`if`, but not its command. Move one assertion there (`unit.jobs.verify.steps.some(s => s.run === 'bun run verify')`) and delete both copies.+- Keep in those files: the fixture-driven guard behavior tests (e.g. `fails and names the offender when a symlink is tracked`, all `check-bootstrap-*` / grok / opencode / pin-doc fixture failure modes, the privacy scanner behavior tests, and the `.gitignore node_modules patterns` test).+- Unlocks: ~110 test LOC. Cost: small (~6 dry-list spawns at ≈10 ms each). Risk: **low**.+- Lane overlap: these read `package.json` and `run-verify-parallel.sh` as text, so the CI/tooling lane may report them too. Dedupe when merging.++### C6 — duplicated and vacuous real-repo `checkResolvable(skills/)` assertions → **delete 5, rewrite 2 at a fixture boundary**+- Owner test: `test/check-resolvable.test.ts > v0.22.4 regression — actual repo skills/ has 0 errors > repo skills/ pass check-resolvable cleanly (zero errors AND zero warnings)`. Every issue carries `severity: 'error'|'warning'` (`src/core/check-resolvable.ts:61`), so this test already requires `issues == []` for every type. `check:resolver` in verify (`check-resolvable --strict`) is the CLI-boundary owner.+- Subsumed (same boundary, same in-process call on the real tree): `test/resolver.test.ts > RESOLVER.md > references only existing skill files`, `> every manifest skill is reachable from resolver`; `test/check-resolvable.test.ts > checkResolvable — real skills directory > all manifest skills are reachable from RESOLVER.md`, `> no missing files referenced by RESOLVER.md`, `> no orphan triggers (in resolver but not manifest)`.+ - **Probe Q2:** pointed one RESOLVER row at a missing `skills/academic-verifyx/SKILL.md`. Failures: resolver.test ×2, check-resolvable.test `no missing files` **and** `repo skills/ pass … cleanly`, plus `check:resolver` rc=1. Four in-process copies plus a CLI gate for one regression.+ - Probe Q1 (removing academic-verify's row entirely) failed nothing, because frontmatter triggers union with RESOLVER rows by design (#1451). This confirms the reachability pins add nothing beyond the owner.+- **Vacuous (assertion-free on a clean repo):** `> action strings are specific (contain file paths)`, `> unreachable issues have structured fix objects`, `> whitelisted skills … don't trigger MECE overlap`. Each loops over `report.issues`, and the real tree reports `issues: 0` (verified: 75/75 skills reachable).+ - **Probe Q3:** changed the emitted fix type `add_trigger` → `add_row_PROBE` in `src/core/check-resolvable.ts:429`. check-resolvable.test + check-resolvable-cli.test + resolver.test: **231 pass / 0 fail**. No test anywhere asserts `add_trigger` (grep), so the fix-object and MECE-whitelist contracts are currently unguarded.+- Action: delete the 5 subsumed tests. Rewrite `unreachable issues have structured fix objects` and the MECE-whitelist test on a `makeSkillsFixture(...)` tree that actually produces the issue (the fixture helper already exists in the same file, around line 333). This rewrite *adds* real coverage.+- Unlocks: ~45 test LOC net. Cost: ≈130 ms (two `checkResolvable(skills/)` calls in resolver.test). Risk: **low** (for the deletions; the rewrite is net coverage gain).+- Keep: `resolver.test.ts` trigger round-trip (D5/C) and the example-name validator (D13). Those are distinct contracts.++### C7 — `test/ambient-recall-templates.test.ts > HEARTBEAT ambient-delta row > rendered template-repo HEARTBEAT.md carries the same row` → **delete**; CODEX.md and guide pins → **consolidate or delete**+- **Probe P4:** renamed the row only in the rendered `templates/bootstrap/template-repo/HEARTBEAT.md`. The pin FAILS, **and** `scripts/check-bootstrap-templates.sh` fails (rc=1, generator↔vendored `diff -r`), **and** so does `test/check-bootstrap-guards.test.ts > check-bootstrap-templates.sh > passes on this repo` (unit lane). The source-template pin plus the byte-diff guard fully cover the rendered copy.+- `docs surfaces > CODEX.md session-boundary instruction names both verbs`, `> ambient-recall guide exists and names both verbs`: prose pins. The guide's existence and inbound links are already checked by docs-navigation's link resolution (HEARTBEAT links to it). Low value; fold into K1 or delete.+- Keep: `source template points heartbeats at gbrain delta + context-pack`. Templates are rendered into users' workspaces, so this is a shipped prompt contract.+- Unlocks: ~22 LOC. Cost: unit 175 ms if the file shrinks to one test (no whole-file saving). Risk: **low**.++### C8 — `test/context-audit-skill.test.ts` → **rewrite (keep the contract, change the boundary)**+- Shipped skill, so this is a prompt-byte contract. But the arithmetic pin is implementation-coupled:+ - **Probe C1 (behavior-identical whitespace edit)** `* 10 + 27 ) / 28` → `* 10 + 27) / 28`: **FAIL**.+ - **Probe C2 (behavior break)** appended `* 0`, so every estimate becomes 0 tokens: **PASS 3/3**.+- Rewrite like `test/skillpack-check-report-only.test.ts` already does: extract the fenced bash pre-pass, run it on a fixture file of known size, and assert `ceil(bytes/2.8)`. Keep the `Estimate basis` / `/context` deferral phrase checks (they are the user-facing prompt contract).+- Cost: unit 203 ms. Risk: **low**. Net LOC ≈ 0.++## 3. Consolidation clusters (one generic contract instead of many one-off pins)++- **K1 — "doc claims" table.** Replace the one-off phrase pins (C2, C3's doc-only tests, C4, C7-docs, `mcp-registration-blocks > OpenClaw stdio registration docs (#4842)` ×2, `docs-navigation > active memory guidance keeps durable preferences separate…` and `> primary docs do not reinstate blanket graph or exclusivity promises`, `put-page-remote-autolink-hint > downstream-upgrade doc and enrich skill state the MCP skip…`) with **one** table-driven test: rows of `{file, mustContain[], mustNotContain[], reason/issue}`. Recommend keeping only **retracted-claim negatives** (honesty and privacy promises such as "no inline graph extraction", "not a full database backup", the retired `~/.openclaw/config.json` path), because AGENTS.md makes those a stated user-facing boundary. Drop the positive wording pins. ~15 tests → 1 table; about −90 LOC after adding the table.+- **K2 — guard wiring.** Covered by C5. The generic owner already exists; the per-guard copies are pure duplication.+- **K3 — `gbrain <verb>` scanners.** `docs-cli-commands.test.ts` (README/docs/skills) and `remediation-command-resolution.test.ts` (CHANGELOG top entry plus src strings) carry copy-pasted `validCommands()` / `commandPosition()` / fence-scanning code. Both are valuable (generic doc↔CLI contract). Extract one shared helper in `test/helpers/`. No coverage change, about −40 LOC. `canonical-migration-command.test.ts > docs/skills sweep` is a third hand-rolled markdown walker that could use the same helper.+- **K4 — recipe files.** `test/integrations.test.ts > twilio-voice-brain recipe` (5 per-file tests: parses, where-URLs are https, required secrets, semver version, requires resolve) sits beside `all recipes` (parses, typed health checks, no personal refs). Fold the generic properties (secret `where` is https, semver version, `requires` resolve) into the `all recipes` loop. That extends coverage to all 9 recipes. Keep only twilio's specific secret-name assertion. `features-recipe-secrets.test.ts` (entry↔recipe secrets) and `integrations-getstatus-anyof.test.ts` stay: they test runtime status resolution. About −40 LOC, with net coverage gain.+- **K5 — contributor-doc content pins in `build-llms.test.ts`.** `content contract: AGENTS.md mirrors README + INSTALL_FOR_AGENTS install path`, `CLAUDE.md keeps the inline ship IRON RULES`, `CLAUDE.md carries the resolver + cross-cutting invariants`, `AGENTS.md keeps its boot order…`, `llms.txt references required entry points`, `llms.txt indexes the relocated docs`. These pin agent-instruction files for contributors (not shipped product), and the llms-config paths are already guarded by `every configured path exists on disk` plus the freshness test. Low value, but CLAUDE.md is literally the prompt that coding agents on this repo read, so treat it as **owner's call**. If kept, move the rows into K1's table. ~40 LOC.++## 4. Retained false positives (looked like doc pins; they are the independent contract)++- `build-llms.test.ts > committed llms.txt + llms-full.txt match current generator output`, `every configured path exists`, `llmstxt spec shape`, `size budget`, `does NOT inline KEY_FILES.md`: generated-artifact freshness plus a bundle-shape contract that ships to LLM fetchers.+- `tool-catalog.test.ts > committed docs/TOOL_CATALOG.md matches a fresh render` (+ render-behavior tests): generated-artifact freshness for the public tool surface.+- `harness-onboarding.test.ts > published adapter facts and guide destinations match the runtime registry`: doc must equal `renderHarnessReference()` byte for byte; this is a generated-doc contract tied to the runtime registry.+- `docs-navigation.test.ts` link and fragment resolution (test.each over ~30 docs, 3.5 s): the only link checker. It is the lane's most expensive file; consider scoping or caching rather than deleting.+- `docs-cli-commands.test.ts`, `remediation-command-resolution.test.ts`, `canonical-migration-command.test.ts`: generic doc↔live-CLI contracts (they caught the real #3502 `gbrain install` and #3697 rot classes).+- `skillopt/error-code-docs.test.ts`: bijection between emitted remediation codes and doc anchors, a user-visible link contract emitted by product code.+- `release-workflow.test.ts`, `check-bootstrap-guards.test.ts` fixture tests, `template-repo-generator.test.ts`, `cli.test.ts > VERSION matches package.json`, `codex-plugin-manifest` / `openclaw-plugin-manifest` version lockstep: release, version-stamp and package contracts (self-update asset names, provenance, template publish).+- `skills-conformance.test.ts`, `resolver.test.ts` trigger round-trip and example-name validator, `check-resolvable … repo skills/ pass cleanly`, `openclaw-plugin-manifest > every skills/ path reference in a bundled SKILL.md resolves`: shipped skill-pack structural contracts.+- `canonical-writer-inventory.test.ts`: architecture contract (write-site census against a reviewed TSV).+- `skillpack-check-report-only.test.ts`: executes the skill's bash snippet against hostile input. This is a security contract and the model for rewriting C8.+- `pg-access-classify.test.ts > the marker literal appears in skills/db-repair frontmatter`: the `GBRAIN_DB_ACCESS` marker must route agents to the db-repair skill (routing contract).+- `put-page-remote-autolink-hint.test.ts > brain-ops skill Phase 2.5 states the MCP skip…`: agent-facing honesty in a shipped skill (remote=true behavior). Keep; the adjacent downstream-doc half can go to K1.+- `retrieval-reflex-recipe-routing.test.ts`: MECE trigger routing between the recipe skill and the query skill (routing behavior).+- `resolver.test.ts > has categorized sections`: `Brain operations` is the default section in check-resolvable's fix suggestion (`src/core/check-resolvable.ts:419`) and a mounts-cache field. Weak, but it has a consumer.+- `ambient-recall-templates > source template…`, `bootstrap-contract > the default skill bundle carries the memory loop contract`, `migrations-v0_12_0/v0_22_4` markdown-exists tests: shipped template, skill-bundle or migration pointers that product code emits.+- `integrations.test.ts > x-to-brain recipe > health check works with an app-only bearer token (#2343)`: credible regression on a runtime-parsed recipe.+- `e2e/qm-provisioning.test.ts`: executes a shipped script under `docs/integrations/` (behavior, not prose).++## 5. Category counts and sizing++| Category | Files | Tests (approx) | Verdict |+|---|---:|---:|---|+| Temp-fixture false hits in the coarse grep (not doc pins) | ~108 | n/a | out of lane |+| Generated-artifact freshness / link / reference integrity | 15 | ~110 (incl. per-doc/per-skill test.each) | keep |+| Release / version-stamp / package sync | 5 | ~70 | keep |+| Shipped skill / template / recipe prompt contracts | 13 | ~45 | keep (C8 rewrite, K4 merge) |+| Prose pins with no product consumer | 10 | ~31 | delete or fold into K1 |+| Duplicate verify-wiring pins (package.json / CHECKS text) | 5 | ~16 | delete (C5) |+| Real-repo checkResolvable duplicates + vacuous loops | 2 | 8 | delete 5, rewrite 2 (C6) |+| Redundant rendered-template pin | 1 | 1 | delete (C7) |++Estimated savings:+- **High-confidence batch** (C1, C2, C4, C5, C6, C7-rendered): ≈ **280 test LOC**, 3 whole files deleted, 0 production LOC (doc pins need no production seams; 2–3 `test-reads-source-ok` exemptions go away). Compute ≈ **0.7–0.9 s** of unit per-file time (whole files 154 + 189 + 227 ms, plus ≈130 ms of checkResolvable calls, plus ≈60 ms of dry-list spawns). That is ~0.02% of the unit lane.+- **Full lane** (adding C3, K1, K3, K4, K5): ≈ **450–500 test LOC**, ≈ 1.1 s compute. C6 and K4 add coverage (the fix-object and MECE contracts, and all-recipe properties).++## 6. In-lane file list (committed docs read as text) with weights (ms)++readme-hero-anchors 154 · docs-bootstrap-persistence-table 189 · docs-timeline-extraction-guide 227 · docs-mcp-deploy 251 · mcp-registration-blocks 287 · ambient-recall-templates 175 · skillopt/deadline-and-hermetic 315 · context-audit-skill 203 · build-llms 185 · docs-navigation 3525 · docs-cli-commands 558 · remediation-command-resolution 648 · canonical-migration-command 300 · skillopt/error-code-docs 168 · tool-catalog 572 · harness-onboarding 458 · release-workflow 173 · check-bootstrap-guards 3491 · template-repo-generator 243 · privacy-script-wired 534 · no-tracked-symlinks-guard 192 · scripts/check-engine-dynamic-import 5442 · scripts/check-key-files-current-state 890 · resolver 648 · check-resolvable 338 · skills-conformance 299 · codex-plugin-manifest 3181 · openclaw-plugin-manifest 175 · put-page-remote-autolink-hint 2839 · retrieval-reflex-recipe-routing 188 · skillpack-check-report-only 167 · pg-access-classify 243 · bootstrap-contract 380 · canonical-writer-inventory 297 · integrations 211 · features-recipe-secrets 227 · integrations-getstatus-anyof 337 · integrations-heartbeat-max-age 221 · migrations-v0_12_0 262 · migrations-v0_22_4 254 · upgrade-reference-sweep 501 · cli (VERSION test only) 8017 · scripts/run-verify-parallel 4653 · e2e/qm-provisioning 40319 (e2e). Total ≈ 83 s.++Out-of-lane pointers noticed (source/CI-text pins, for the other lanes): `check-bootstrap-guards > heavy-tests.yml carries the bootstrap Docker e2e placeholder [A7]`; `migrations-v0_12_0 > feature pitch includes the headline benchmark numbers` (marketing numbers in a src string); `mcp-registration-blocks > OAUTH_SECRET_NOTE text is unchanged by the move` (move-regression pin).++## 7. Probe log (all reverted; `git status` clean after each)++| # | Mutation | Target test(s) | Result |+|---|---|---|---|+| P1 | README hero reword (same meaning) | readme-hero-anchors | FAIL (coupled to prose) |+| P2 | drop `GBRAIN_STOP_PUSH` check in `stopPushIfDue` | docs-bootstrap-persistence-table | PASS (blind) |+| P2 | same | hook-command.serial `GBRAIN_STOP_PUSH=0 disables…` | FAIL (real owner) |+| P2b | doc reword "Stop path only" → "Stop hook alone" | docs-bootstrap-persistence-table | FAIL |+| P3a | drop `check:tool-catalog` from CHECKS | tool-catalog wiring / run-verify-parallel generic | FAIL / FAIL |+| P3b | rename script key in package.json + CHECKS (still runs) | tool-catalog wiring / generic | FAIL / PASS |+| P3c | drop 7 guards from CHECKS | 4 per-guard files / generic | all FAIL / FAIL naming all 7 |+| P4 | rename row in rendered template-repo only | ambient rendered pin / check-bootstrap-templates.sh / check-bootstrap-guards "passes on this repo" | FAIL / rc=1 / FAIL |+| P5 | re-add retracted keychain claim, reworded | deadline-and-hermetic #4741 | PASS (blind) |+| P8 | nonce TTL 5 → 60 min | docs-mcp-deploy | PASS 9/9 (blind) |+| P8b | "expires after" → "is valid for" five minutes | docs-mcp-deploy | FAIL |+| Q1 | delete academic-verify RESOLVER row | resolver / check-resolvable | PASS (frontmatter union, by design) |+| Q2 | RESOLVER row → missing SKILL.md | resolver ×2, check-resolvable ×2, check:resolver | all FAIL (4 in-process duplicates + CLI) |+| Q3 | fix type `add_trigger` → `add_row_PROBE` | check-resolvable, check-resolvable-cli, resolver | 231 pass / 0 fail (unguarded) |+| C1 | whitespace-only edit to skill arithmetic | context-audit-skill | FAIL (coupled) |+| C2 | `* 0` breaks the estimate | context-audit-skill | PASS (blind) |++Focused validation commands for a future edit PR: `bun test test/scripts/run-verify-parallel.test.ts test/scripts/ci-gates.test.ts test/check-resolvable.test.ts test/resolver.test.ts test/check-bootstrap-guards.test.ts test/ambient-recall-templates.test.ts test/cli-help-discoverability.test.ts`, plus `bun run check:resolver`, `bash scripts/check-bootstrap-templates.sh`, `bun run verify`.diff --git a/docs/test-audit/2026-09-29/lane-e2e/attendance-repair-postgres.log b/docs/test-audit/2026-09-29/lane-e2e/attendance-repair-postgres.lognew file mode 100644index 0000000000..c0c39ed4b0--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-e2e/attendance-repair-postgres.log@@ -0,0 +1,187 @@+bun test v1.3.14 (0d9b296a)++test/e2e/attendance-repair-postgres.test.ts:+ Setting up brain schema (v166)...+ 161 migration(s) applied+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > preview is read-only, omits source text, and exact delta preserves unrelated IDs and evidence [137.38ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > repair never approves or persists inline-commented attendance: "Attendees: [Alice Example](../people/alice-example.md) <!-- [Hidden](../people/hidden-example.md) -->" [85.74ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > repair never approves or persists inline-commented attendance: "## Attendees\n- [Alice Example](../people/alice-example.md) <!-- [Hidden](../people/hidden-example.md) -->" [50.86ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > second request and new preview are row-identity idempotent [107.91ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > receipts are credential-independent while cloned endpoint and brain pins remain distinct [107.57ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > global seven-day pruning expires replay proof and requires a fresh preview without changing graph rows [75.53ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > retained expired proof refuses changed replay and fresh approval recovers without renewing old proof [127.98ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > pruned expired proof refuses changed replay and fresh approval recovers without renewing old proof [122.37ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > retained expired proof refuses no-op replay and fresh approval recovers without renewing old proof [130.25ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > pruned expired proof refuses no-op replay and fresh approval recovers without renewing old proof [142.97ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > retained expired proof refuses report-only replay and fresh approval recovers without renewing old proof [183.32ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > pruned expired proof refuses report-only replay and fresh approval recovers without renewing old proof [166.53ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > valid replay never refreshes durable proof age or row content [63.39ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > expired first approval refuses before writes or cursor progress with zero origins=false [60.29ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > expired first approval refuses before writes or cursor progress with zero origins=true [57.34ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > fresh approvals recover a pruned no-op window and continue into the next window [157.28ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > approval lifetime is rechecked inside every origin transaction before advancing its cursor [45.54ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > approval identity and issuance validation rejects malformed, future and legacy receipts without writes [44.79ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > preserves NULL producer [42.13ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > preserves manual producer [39.74ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > preserves custom-producer producer [33.08ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > unproven legacy evidence is report-only: Mentioned [Alice](../people/alice-example.md). [39.85ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > unproven legacy evidence is report-only: Invited [Alice](../people/alice-example.md). [35.66ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > unproven legacy evidence is report-only: Attendees: [Alice](../people/alice-example.md) did not attend [34.82ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > unproven legacy evidence is report-only: No evidence [94.60ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > frontmatter paths are report-only and never remove an existing frontmatter claim [76.48ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > ambiguous hinted slug forms skip the origin without removing legacy rows [44.84ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > title-only references remain report-only without a full-source resolver [17.37ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > same-slug foreign endpoints and other-origin attendance remain unchanged [61.63ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > missing and non-person body targets are counted and never guessed [20.35ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > ambiguous bare body evidence never deletes an owned claim [47.05ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > hinted frontmatter names do not authorize a claim before or after another candidate appears [80.48ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > slash-containing frontmatter with a conflicting title never bypasses A1 uniqueness [45.95ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > slash-containing frontmatter with a conflicting aliases never bypasses A1 uniqueness [42.48ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > pack-owned outgoing semantics are excluded and pinned [31.95ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > unavailable pack is not treated as permission for legacy fallback [39.11ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > gbrain-base shipped outgoing attendance is report-only [58.36ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > company-brain shipped outgoing attendance is report-only [51.98ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > origin-edit refuses stale preview without additional writes or checkpoint advance [55.53ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > endpoint-edit refuses stale preview without additional writes or checkpoint advance [28.60ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > origin-delete refuses stale preview without additional writes or checkpoint advance [55.46ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > endpoint-delete refuses stale preview without additional writes or checkpoint advance [43.13ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > origin-recreate refuses stale preview without additional writes or checkpoint advance [24.23ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > endpoint-recreate refuses stale preview without additional writes or checkpoint advance [49.24ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > source-recreate refuses stale preview without additional writes or checkpoint advance [21.78ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > source-archive refuses stale preview without additional writes or checkpoint advance [13.37ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > source-archive-flag refuses stale preview without additional writes or checkpoint advance [14.65ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > ontology refuses stale preview without additional writes or checkpoint advance [31.53ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > ontology-file refuses stale preview without additional writes or checkpoint advance [30.00ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > edge-edit refuses stale preview without additional writes or checkpoint advance [42.40ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > edge-insert refuses stale preview without additional writes or checkpoint advance [33.21ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > edge-delete refuses stale preview without additional writes or checkpoint advance [33.83ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > edge-resolution refuses stale preview without additional writes or checkpoint advance [29.29ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > endpoint-type refuses stale preview without additional writes or checkpoint advance [26.88ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > flag-only archived repair-fixture refuses preview without writes or checkpoint advance [17.25ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > flag-only archived repair-fixture refuses apply without writes or checkpoint advance [18.96ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > flag-only archived default refuses preview without writes or checkpoint advance [17.65ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > flag-only archived default refuses apply without writes or checkpoint advance [16.62ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > ordinary archive and restore lifecycle refuses repair while archived and permits a fresh preview after restore [44.12ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > parser and digest mismatch refuse before any transaction [13.87ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > failed insertion rolls back deletion and durable receipt [48.36ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > database read-only permissions refuse apply without a checkpoint or row changes [34.17ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > interruption after commit before cursor safely replays the committed origin [63.30ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > report-only pack_semantics_preserved with existing edges replays a commit before private checkpoint progress [79.48ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > report-only pack_unavailable with existing edges replays a commit before private checkpoint progress [42.75ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > report-only origin_size_limit with existing edges replays a commit before private checkpoint progress [53.41ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > report-only edge_limit with existing edges replays a commit before private checkpoint progress [75.07ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > report-only edge_size_limit with existing edges replays a commit before private checkpoint progress [59.97ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > report-only reference_limit with existing edges replays a commit before private checkpoint progress [67.57ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > mixed person and non-person explicit attendees leave the entire origin report-only [72.53ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > interruption after cursor and failure at next origin never advances past failure [50.51ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > source recreation invalidates an already committed cursor [37.94ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > committed edge recreation is not accepted as idempotent replay [57.00ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > owned obsolete attendance alone is removed and its committed replay stays stable [92.48ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > authority, source, confirmation and backup refusals happen without mutation [13.17ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > bounds reject invalid batches and cap retained diagnostics and source metadata [147.46ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > oversized origins and reference sets are report-only [34.96ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > oversized bodies and edge evidence never cross the DB boundary, and frontmatter is not materialized [101.12ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > large non-attendance adjacency cannot force an unbounded attendance scan [57.62ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > sparse windows include soft-deleted and nonmeeting pages before eligibility filtering [1215.62ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > cursor covers skipped prefixes but never crosses a failed origin or skipped tail [103.61ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > zero-origin window refuses a stale source before cursor advancement [15.73ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > zero-origin window refuses a stale ontology before cursor advancement [12.26ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > zero-origin window refuses a stale skipped-page before cursor advancement [38.68ms]+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > one-row slug windows traverse punctuation and Unicode in database order without duplicates [94.90ms]+{"fixture":"attendance-repair-scale","engine":"pglite","sourcePages":11002,"previewedOrigins":1250,"endpointQueries":1250,"endpointRows":1250,"largestLookup":1,"elapsedMs":3721,"rssBytes":1675251712}+(pass) preview-bound attendance repair (pglite; repair-fixture non-overridden person_to_meeting) > default 250 and maximum 1000 page windows keep lookup work independent of a 10000-page source [16576.60ms]+ Setting up brain schema (v166)...+ 161 migration(s) applied+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > preview is read-only, omits source text, and exact delta preserves unrelated IDs and evidence [69.55ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > repair never approves or persists inline-commented attendance: "Attendees: [Alice Example](../people/alice-example.md) <!-- [Hidden](../people/hidden-example.md) -->" [55.69ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > repair never approves or persists inline-commented attendance: "## Attendees\n- [Alice Example](../people/alice-example.md) <!-- [Hidden](../people/hidden-example.md) -->" [48.09ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > second request and new preview are row-identity idempotent [79.91ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > receipts are credential-independent while cloned endpoint and brain pins remain distinct [45.17ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > global seven-day pruning expires replay proof and requires a fresh preview without changing graph rows [77.10ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > retained expired proof refuses changed replay and fresh approval recovers without renewing old proof [82.76ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > pruned expired proof refuses changed replay and fresh approval recovers without renewing old proof [87.50ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > retained expired proof refuses no-op replay and fresh approval recovers without renewing old proof [100.81ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > pruned expired proof refuses no-op replay and fresh approval recovers without renewing old proof [86.00ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > retained expired proof refuses report-only replay and fresh approval recovers without renewing old proof [113.66ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > pruned expired proof refuses report-only replay and fresh approval recovers without renewing old proof [103.01ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > valid replay never refreshes durable proof age or row content [42.74ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > expired first approval refuses before writes or cursor progress with zero origins=false [31.89ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > expired first approval refuses before writes or cursor progress with zero origins=true [25.97ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > fresh approvals recover a pruned no-op window and continue into the next window [88.64ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > approval lifetime is rechecked inside every origin transaction before advancing its cursor [32.14ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > approval identity and issuance validation rejects malformed, future and legacy receipts without writes [38.98ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > preserves NULL producer [27.15ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > preserves manual producer [32.86ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > preserves custom-producer producer [30.82ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > unproven legacy evidence is report-only: Mentioned [Alice](../people/alice-example.md). [35.22ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > unproven legacy evidence is report-only: Invited [Alice](../people/alice-example.md). [36.92ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > unproven legacy evidence is report-only: Attendees: [Alice](../people/alice-example.md) did not attend [33.12ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > unproven legacy evidence is report-only: No evidence [33.42ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > frontmatter paths are report-only and never remove an existing frontmatter claim [72.52ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > ambiguous hinted slug forms skip the origin without removing legacy rows [42.09ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > title-only references remain report-only without a full-source resolver [15.51ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > same-slug foreign endpoints and other-origin attendance remain unchanged [62.84ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > missing and non-person body targets are counted and never guessed [17.79ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > ambiguous bare body evidence never deletes an owned claim [47.02ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > hinted frontmatter names do not authorize a claim before or after another candidate appears [44.07ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > slash-containing frontmatter with a conflicting title never bypasses A1 uniqueness [38.07ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > slash-containing frontmatter with a conflicting aliases never bypasses A1 uniqueness [39.32ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > pack-owned outgoing semantics are excluded and pinned [26.13ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > unavailable pack is not treated as permission for legacy fallback [25.92ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > gbrain-base shipped outgoing attendance is report-only [34.84ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > company-brain shipped outgoing attendance is report-only [43.34ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > origin-edit refuses stale preview without additional writes or checkpoint advance [19.75ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > endpoint-edit refuses stale preview without additional writes or checkpoint advance [29.29ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > origin-delete refuses stale preview without additional writes or checkpoint advance [22.30ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > endpoint-delete refuses stale preview without additional writes or checkpoint advance [26.72ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > origin-recreate refuses stale preview without additional writes or checkpoint advance [23.80ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > endpoint-recreate refuses stale preview without additional writes or checkpoint advance [27.23ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > source-recreate refuses stale preview without additional writes or checkpoint advance [22.61ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > source-archive refuses stale preview without additional writes or checkpoint advance [13.95ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > source-archive-flag refuses stale preview without additional writes or checkpoint advance [14.48ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > ontology refuses stale preview without additional writes or checkpoint advance [14.65ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > ontology-file refuses stale preview without additional writes or checkpoint advance [13.77ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > edge-edit refuses stale preview without additional writes or checkpoint advance [19.64ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > edge-insert refuses stale preview without additional writes or checkpoint advance [19.89ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > edge-delete refuses stale preview without additional writes or checkpoint advance [21.32ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > edge-resolution refuses stale preview without additional writes or checkpoint advance [22.12ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > endpoint-type refuses stale preview without additional writes or checkpoint advance [29.41ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > flag-only archived repair-fixture refuses preview without writes or checkpoint advance [19.61ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > flag-only archived repair-fixture refuses apply without writes or checkpoint advance [18.06ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > flag-only archived default refuses preview without writes or checkpoint advance [17.18ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > flag-only archived default refuses apply without writes or checkpoint advance [14.67ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > ordinary archive and restore lifecycle refuses repair while archived and permits a fresh preview after restore [40.79ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > parser and digest mismatch refuse before any transaction [12.50ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > failed insertion rolls back deletion and durable receipt [50.53ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > database read-only permissions refuse apply without a checkpoint or row changes [17.94ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > a separate PostgreSQL reader sees a consistent graph while the repair holds write fences [48.38ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > interruption after commit before cursor safely replays the committed origin [47.82ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > report-only pack_semantics_preserved with existing edges replays a commit before private checkpoint progress [70.07ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > report-only pack_unavailable with existing edges replays a commit before private checkpoint progress [42.11ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > report-only origin_size_limit with existing edges replays a commit before private checkpoint progress [46.68ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > report-only edge_limit with existing edges replays a commit before private checkpoint progress [55.84ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > report-only edge_size_limit with existing edges replays a commit before private checkpoint progress [97.48ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > report-only reference_limit with existing edges replays a commit before private checkpoint progress [52.40ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > mixed person and non-person explicit attendees leave the entire origin report-only [54.82ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > interruption after cursor and failure at next origin never advances past failure [46.78ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > source recreation invalidates an already committed cursor [37.49ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > committed edge recreation is not accepted as idempotent replay [43.55ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > owned obsolete attendance alone is removed and its committed replay stays stable [66.76ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > authority, source, confirmation and backup refusals happen without mutation [10.93ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > bounds reject invalid batches and cap retained diagnostics and source metadata [137.87ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > oversized origins and reference sets are report-only [27.90ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > oversized bodies and edge evidence never cross the DB boundary, and frontmatter is not materialized [131.56ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > large non-attendance adjacency cannot force an unbounded attendance scan [54.34ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > sparse windows include soft-deleted and nonmeeting pages before eligibility filtering [1365.04ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > cursor covers skipped prefixes but never crosses a failed origin or skipped tail [97.87ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > zero-origin window refuses a stale source before cursor advancement [14.67ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > zero-origin window refuses a stale ontology before cursor advancement [13.02ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > zero-origin window refuses a stale skipped-page before cursor advancement [21.41ms]+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > one-row slug windows traverse punctuation and Unicode in database order without duplicates [72.31ms]+{"fixture":"attendance-repair-scale","engine":"postgres","sourcePages":11002,"previewedOrigins":1250,"endpointQueries":1250,"endpointRows":1250,"largestLookup":1,"elapsedMs":11677,"rssBytes":253120512}+(pass) preview-bound attendance repair (postgres; repair-fixture non-overridden person_to_meeting) > default 250 and maximum 1000 page windows keep lookup work independent of a 10000-page source [19307.31ms]++ 173 pass+ 0 fail+ 925 expect() calls+Ran 173 tests across 1 file. [51.91s]diff --git a/docs/test-audit/2026-09-29/lane-e2e/attendance-retrieval-postgres.log b/docs/test-audit/2026-09-29/lane-e2e/attendance-retrieval-postgres.lognew file mode 100644index 0000000000..42af52db33--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-e2e/attendance-retrieval-postgres.log@@ -0,0 +1,1728 @@+bun test v1.3.14 (0d9b296a)++test/e2e/attendance-retrieval-postgres.test.ts:+ Setting up brain schema (v166)...+ 161 migration(s) applied+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: ordinary meeting links are replaced like put_page [236.25ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: unchanged DB-only attendance survives and real evidence removal retracts it [190.99ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: ordinary meeting links are replaced like put_page [144.87ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 1/2 (50%) done+[extract.incremental] start+[extract.incremental] 1/2 (50%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: unchanged DB-only attendance survives and real evidence removal retracts it [130.76ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: ordinary meeting links keep additive filesystem handling [101.56ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 1/1 (100%)+[extract.links_fs] 1/1 (100%) done+[extract.links_fs] start+[extract.links_fs] 1/1 (100%)+[extract.links_fs] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: unchanged DB-only attendance survives and real evidence removal retracts it [108.16ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: source-selected gbrain-base overrides global attendance-fixture [63.74ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: source-selected attendance-fixture overrides global gbrain-base [59.67ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: source-selected attendance-fixture overrides global missing-example-pack [89.76ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: unavailable source-selected ontology preserves graph and watermark [109.69ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: inline commented people do not become attendees [137.19ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: unavailable ontology cannot reverse existing pack-owned attendance [89.31ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [140.17ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: HTML-commented attendance retracts the claim without asserting hidden evidence [118.84ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: missing display-label slugs do not make actual attendance incomplete [65.14ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: explicit foreign attendance survives complete resolution [170.97ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: federated-default foreign attendance survives complete resolution [109.15ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: unresolved attendance cannot retract owned graph or mark success [95.16ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: section-nested ~~~ examples never persist attendance [62.29ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: section-nested ``` examples never persist attendance [65.99ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: source-selected gbrain-base overrides global attendance-fixture [113.29ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: source-selected attendance-fixture overrides global gbrain-base [68.16ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: source-selected attendance-fixture overrides global missing-example-pack [82.94ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.incremental] start+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: unavailable source-selected ontology preserves graph and watermark [79.93ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: inline commented people do not become attendees [77.90ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: unavailable ontology cannot reverse existing pack-owned attendance [99.45ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [149.64ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: HTML-commented attendance retracts the claim without asserting hidden evidence [101.03ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: missing display-label slugs do not make actual attendance incomplete [88.57ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 1/2 (50%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: explicit foreign attendance survives complete resolution [109.36ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 1/2 (50%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: federated-default foreign attendance survives complete resolution [99.26ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 1/2 (50%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: unresolved attendance cannot retract owned graph or mark success [111.82ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: section-nested ~~~ examples never persist attendance [72.11ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: section-nested ``` examples never persist attendance [61.34ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: source-selected gbrain-base overrides global attendance-fixture [53.94ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: source-selected attendance-fixture overrides global gbrain-base [55.97ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: source-selected attendance-fixture overrides global missing-example-pack [56.38ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: unavailable source-selected ontology preserves graph and watermark [99.41ms]+[extract.links_fs] start+[extract.links_fs] 3/3 (100%)+[extract.links_fs] 3/3 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 3/3 (100%)+[extract.timeline_fs] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: inline commented people do not become attendees [96.66ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: unavailable ontology cannot reverse existing pack-owned attendance [95.06ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [167.68ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: HTML-commented attendance retracts the claim without asserting hidden evidence [103.86ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: missing display-label slugs do not make actual attendance incomplete [62.89ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 1/2 (50%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: explicit foreign attendance survives complete resolution [103.23ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 1/2 (50%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: federated-default foreign attendance survives complete resolution [90.48ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 1/2 (50%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: unresolved attendance cannot retract owned graph or mark success [88.24ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: section-nested ~~~ examples never persist attendance [50.26ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: section-nested ``` examples never persist attendance [75.35ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: source-selected gbrain-base overrides global attendance-fixture [82.38ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: source-selected attendance-fixture overrides global gbrain-base [83.85ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: source-selected attendance-fixture overrides global missing-example-pack [105.69ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: unavailable source-selected ontology preserves graph and watermark [65.40ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: inline commented people do not become attendees [97.82ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: unavailable ontology cannot reverse existing pack-owned attendance [103.42ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [209.31ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: HTML-commented attendance retracts the claim without asserting hidden evidence [109.03ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: missing display-label slugs do not make actual attendance incomplete [66.76ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: explicit foreign attendance survives complete resolution [95.28ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: federated-default foreign attendance survives complete resolution [94.90ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: unresolved attendance cannot retract owned graph or mark success [90.45ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: section-nested ~~~ examples never persist attendance [61.90ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: section-nested ``` examples never persist attendance [67.24ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: source-selected gbrain-base overrides global attendance-fixture [100.73ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: source-selected attendance-fixture overrides global gbrain-base [55.29ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: source-selected attendance-fixture overrides global missing-example-pack [71.54ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: unavailable source-selected ontology preserves graph and watermark [87.29ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: inline commented people do not become attendees [92.79ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: unavailable ontology cannot reverse existing pack-owned attendance [106.35ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [167.36ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: HTML-commented attendance retracts the claim without asserting hidden evidence [118.45ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: missing display-label slugs do not make actual attendance incomplete [88.60ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: explicit foreign attendance survives complete resolution [91.80ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: federated-default foreign attendance survives complete resolution [101.92ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: unresolved attendance cannot retract owned graph or mark success [99.00ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: section-nested ~~~ examples never persist attendance [57.78ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: section-nested ``` examples never persist attendance [56.78ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: source-selected gbrain-base overrides global attendance-fixture [53.13ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: source-selected attendance-fixture overrides global gbrain-base [58.84ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: source-selected attendance-fixture overrides global missing-example-pack [60.62ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: unavailable source-selected ontology preserves graph and watermark [63.52ms]+[extract.links_db] start+[extract.links_db] 3/3 (100%)+[extract.links_db] 3/3 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 3/3 (100%)+[extract.timeline_db] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: inline commented people do not become attendees [91.46ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: unavailable ontology cannot reverse existing pack-owned attendance [84.10ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [150.97ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: HTML-commented attendance retracts the claim without asserting hidden evidence [99.07ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: missing display-label slugs do not make actual attendance incomplete [59.59ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 1/2 (50%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: explicit foreign attendance survives complete resolution [94.91ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 1/2 (50%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: federated-default foreign attendance survives complete resolution [91.94ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 1/2 (50%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: unresolved attendance cannot retract owned graph or mark success [90.83ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: section-nested ~~~ examples never persist attendance [60.00ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: section-nested ``` examples never persist attendance [55.18ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: source-selected gbrain-base overrides global attendance-fixture [61.65ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: source-selected attendance-fixture overrides global gbrain-base [58.85ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: source-selected attendance-fixture overrides global missing-example-pack [61.77ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.stale] start+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: unavailable source-selected ontology preserves graph and watermark [59.83ms]+[extract.stale] start+[extract.stale] 3/3 (100%)+[extract.stale] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: inline commented people do not become attendees [83.58ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.stale] start+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: unavailable ontology cannot reverse existing pack-owned attendance [130.33ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+[extract.stale] start+[extract.stale] 1/1 (100%)+[extract.stale] 1/1 (100%) done+[extract.stale] start+[extract.stale] 1/1 (100%)+[extract.stale] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [133.98ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+[extract.stale] start+[extract.stale] 1/1 (100%)+[extract.stale] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: HTML-commented attendance retracts the claim without asserting hidden evidence [117.85ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: missing display-label slugs do not make actual attendance incomplete [64.80ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+[extract.stale] start+[extract.stale] done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: explicit foreign attendance survives complete resolution [98.50ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+[extract.stale] start+[extract.stale] done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: federated-default foreign attendance survives complete resolution [84.75ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.stale] start+[extract.stale] 1/2 (50%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: unresolved attendance cannot retract owned graph or mark success [87.55ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: section-nested ~~~ examples never persist attendance [74.04ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: section-nested ``` examples never persist attendance [56.75ms]+[extract.incremental] start+[extract.incremental] 1/1 (100%)+[extract.incremental] 1/1 (100%) done+[extract.incremental] start+[extract.incremental] 1/1 (100%)+[extract.incremental] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: imported hidden meetings get guarded canonical attendance [83.61ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: imported hidden meetings get guarded canonical attendance [85.75ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: an ordinary missing target does not discard later links or processed status [56.31ms]+[extract.incremental] start+[extract.incremental] 1/1 (100%)+[extract.incremental] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: file-only meeting declarations cannot bypass the database origin type [49.72ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: file-only meeting declarations cannot bypass the database origin type [49.47ms]+[extract.links_db] start+[extract.links_db] 3/3 (100%)+[extract.links_db] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: display-label person slugs do not assert extra attendees [87.43ms]+[extract.links_db] start+[extract.links_db] 3/4 (75%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: ambiguous bare references do not assert either attendee [107.68ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: actual extraction persists, queries and removes meeting-owned Markdown [141.95ms]+[extract.stale] start+[extract.stale] 3/3 (100%)+[extract.stale] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: display-label person slugs do not assert extra attendees [83.60ms]+[extract.stale] start+[extract.stale] 3/4 (75%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: ambiguous bare references do not assert either attendee [95.40ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+[extract.stale] start+[extract.stale] 1/1 (100%)+[extract.stale] 1/1 (100%) done+[extract.stale] start+[extract.stale] 1/1 (100%)+[extract.stale] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: actual extraction persists, queries and removes meeting-owned Markdown [122.66ms]+[extract.links_fs] start+[extract.links_fs] 3/3 (100%)+[extract.links_fs] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: display-label person slugs do not assert extra attendees [72.71ms]+[extract.links_fs] start+[extract.links_fs] 3/4 (75%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: ambiguous bare references do not assert either attendee [87.67ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: actual extraction persists, queries and removes meeting-owned Markdown [120.04ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: display-label person slugs do not assert extra attendees [78.01ms]+[extract.incremental] start+[extract.incremental] 1/2 (50%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: ambiguous bare references do not assert either attendee [90.46ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: actual extraction persists, queries and removes meeting-owned Markdown [145.30ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: display-label person slugs do not assert extra attendees [83.44ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: ambiguous bare references do not assert either attendee [95.41ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: actual extraction persists, queries and removes meeting-owned Markdown [156.64ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: display-label person slugs do not assert extra attendees [122.32ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: ambiguous bare references do not assert either attendee [107.49ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare: actual extraction persists, queries and removes meeting-owned Markdown [174.45ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: display-label person slugs do not assert extra attendees [143.88ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: ambiguous bare references do not assert either attendee [162.51ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep: actual extraction persists, queries and removes meeting-owned Markdown [140.77ms]+[extract.links_db] start+[extract.links_db] 4/4 (100%)+[extract.links_db] 4/4 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 4/4 (100%)+[extract.timeline_db] 4/4 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: mixed-source extraction resolves each origin's pack for identical slugs [153.45ms]+[extract.stale] start+[extract.stale] 4/4 (100%)+[extract.stale] 4/4 (100%) done+[extract.stale] start+[extract.stale] 1/1 (100%)+[extract.stale] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: mixed-source extraction resolves each origin's pack for identical slugs [176.51ms]+[extract.links_db] start+[extract.links_db] 1/3 (33%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > db: type-filtered extraction does not load an unrelated source pack [58.90ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > db: unavailable selected source fails preflight before any healthy graph or combined watermark changes [71.23ms]+[extract.stale] start+[extract.stale] 2/4 (50%) done+[extract.stale] start+[extract.stale] 1/3 (33%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > stale: an unavailable first source does not starve healthy later batches or become successful [146.56ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication: source-selected attendance-fixture/gbrain-base overrides global attendance-fixture [407.70ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication: source-selected attendance-fixture/attendance-fixture overrides global gbrain-base [143.37ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication: source-selected attendance-fixture/attendance-fixture overrides global missing-example-pack [190.08ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication: unavailable source-selected attendance-fixture pack saves the note but preserves the graph [272.51ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication: source-selected default/gbrain-base overrides global attendance-fixture [154.60ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication: source-selected default/attendance-fixture overrides global gbrain-base [154.24ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication: source-selected default/attendance-fixture overrides global missing-example-pack [147.79ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication: unavailable source-selected default pack saves the note but preserves the graph [266.73ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication discovers typed pack frontmatter before admitting edges and preserves unchanged row identity [262.76ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication keeps the note and prior graph when an endpoint changes after preparation: edit [152.03ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication keeps the note and prior graph when an endpoint changes after preparation: retype [163.56ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication keeps the note and prior graph when an endpoint changes after preparation: delete [156.95ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication does not swallow unrelated graph storage failures [149.81ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication admits the visible attendee but not a live person inside an inline comment [136.99ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication preserves pack-owned attendance and reports unavailable ontology without losing the note [160.89ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication does not admit a non-person into typed pack attendance [126.47ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local publication retains typed pack attendance when resolved endpoint metadata is unavailable [151.96ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > typed pack attendance preserves prior edges when the new target cannot be resolved [58.42ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > local put_page and remote deferred sweep preserve the actual Markdown producer [247.91ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > local put_page commits unresolved attendance content while preserving retryable graph [141.13ms]+[gbrain] vector search unavailable (missing_env) — results are keyword-only. Run `gbrain doctor` to diagnose.+(pass) non-overridden canonical attendance lifecycle (pglite) > actual put_page and query operations retain and remove the supported attendee [528.56ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+Links: created 2 from 2 pages (db source)++Done: 2 links, 0 timeline entries from 2 pages+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+Links: created 0 from 2 pages (db source)++Done: 0 links, 0 timeline entries from 2 pages+(pass) non-overridden canonical attendance lifecycle (pglite) > canonical frontmatter and body keep distinct provenance without duplicate people [102.06ms]+[extract.links_db] start+[extract.links_db] 3/4 (75%) done+Links: created 0 from 3 pages (db source)+Skipped 1 page(s) with unresolved attendance; prior links and extraction watermarks were preserved.+Unresolved frontmatter refs: 2 total+ 1× attendees:Shared name+ 1× attendees:people/company-example++Done: 0 links, 0 timeline entries from 3 pages+(pass) non-overridden canonical attendance lifecycle (pglite) > ambiguous or non-person canonical frontmatter stays unresolved [103.03ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: canonical frontmatter persists and removes under its meeting origin [178.96ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: canonical frontmatter persists and removes under its meeting origin [150.11ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > private attendees and unsealed projections remain excluded from remote retrieval [99.52ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > single and batch writers round-trip Markdown origin without exposing an ungranted origin [73.33ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > failed filesystem attendance replacement stays retryable and preserves the last good graph [106.04ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: failed attendance replacement does not advance its watermark [121.29ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+ link replacement error for people/alice-example (0 rows not written): Injected replacement failure+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: failed attendance replacement does not advance its watermark [130.54ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+Links: created 2 from 2 pages (db source)++Done: 2 links, 0 timeline entries from 2 pages+(pass) non-overridden canonical attendance lifecycle (pglite) > gbrain-base: pack_semantics_preserved [82.47ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+Links: created 2 from 2 pages (db source)++Done: 2 links, 0 timeline entries from 2 pages+(pass) non-overridden canonical attendance lifecycle (pglite) > company-brain: pack_semantics_preserved [76.51ms]+[extract.links_db] start+[extract.links_db] 3/3 (100%)+[extract.links_db] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > manual and other-origin rows survive exact meeting removal [129.62ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare/attendance-fixture: retained link identities refresh their evidence [119.37ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > prepare/gbrain-base: retained link identities refresh their evidence [104.88ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > sweep/attendance-fixture: retained link identities refresh their evidence [150.53ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch/attendance-fixture: retained link identities refresh their evidence [101.63ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental/attendance-fixture: retained link identities refresh their evidence [100.41ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync/attendance-fixture: retained link identities refresh their evidence [95.88ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-batch: unknown legacy producers survive attendance reconciliation [93.73ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-incremental: unknown legacy producers survive attendance reconciliation [125.13ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > fs-sync: unknown legacy producers survive attendance reconciliation [146.77ms]+(pass) non-overridden canonical attendance lifecycle (pglite) > reversed Markdown validation requires matching origin, types and captured endpoint revisions [95.92ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > source identities are resolved before reversing qualified Markdown [120.51ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > DB does not promote unsupported evidence: [Alice](../people/alice-example.md) did not attend. [77.41ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > DB does not promote unsupported evidence: Invited [Alice](../people/alice-example.md) for next month. [60.91ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > DB does not promote unsupported evidence: Discussed a proposal from [Alice](../people/alice-example.md). [77.69ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > DB does not promote unsupported evidence: Attendees: [Alice](../people/alice-example.md) (absent) [77.93ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > DB does not promote unsupported evidence: ## Attendees+- [Alice](../people/alice-example.md) was invited [63.64ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (pglite) > DB does not promote unsupported evidence: ```md+Attendees: [Alice](../people/alice-example.md)+``` [69.10ms]+ Setting up brain schema (v166)...+ 161 migration(s) applied+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: ordinary meeting links are replaced like put_page [273.43ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: unchanged DB-only attendance survives and real evidence removal retracts it [187.59ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: ordinary meeting links are replaced like put_page [162.66ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 1/2 (50%) done+[extract.incremental] start+[extract.incremental] 1/2 (50%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: unchanged DB-only attendance survives and real evidence removal retracts it [155.74ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: ordinary meeting links keep additive filesystem handling [108.95ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 1/1 (100%)+[extract.links_fs] 1/1 (100%) done+[extract.links_fs] start+[extract.links_fs] 1/1 (100%)+[extract.links_fs] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: unchanged DB-only attendance survives and real evidence removal retracts it [152.21ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: source-selected gbrain-base overrides global attendance-fixture [81.77ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: source-selected attendance-fixture overrides global gbrain-base [82.43ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: source-selected attendance-fixture overrides global missing-example-pack [89.54ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: unavailable source-selected ontology preserves graph and watermark [106.92ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: inline commented people do not become attendees [115.61ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: unavailable ontology cannot reverse existing pack-owned attendance [125.22ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [191.72ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: HTML-commented attendance retracts the claim without asserting hidden evidence [130.38ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: missing display-label slugs do not make actual attendance incomplete [95.47ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: explicit foreign attendance survives complete resolution [130.31ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: federated-default foreign attendance survives complete resolution [133.58ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: unresolved attendance cannot retract owned graph or mark success [123.65ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: section-nested ~~~ examples never persist attendance [81.69ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: section-nested ``` examples never persist attendance [79.01ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: source-selected gbrain-base overrides global attendance-fixture [82.55ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: source-selected attendance-fixture overrides global gbrain-base [78.24ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: source-selected attendance-fixture overrides global missing-example-pack [81.83ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.incremental] start+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: unavailable source-selected ontology preserves graph and watermark [93.54ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: inline commented people do not become attendees [106.76ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: unavailable ontology cannot reverse existing pack-owned attendance [106.69ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [167.68ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: HTML-commented attendance retracts the claim without asserting hidden evidence [145.32ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: missing display-label slugs do not make actual attendance incomplete [72.32ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 1/2 (50%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: explicit foreign attendance survives complete resolution [135.00ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 1/2 (50%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: federated-default foreign attendance survives complete resolution [125.91ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 1/2 (50%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: unresolved attendance cannot retract owned graph or mark success [113.39ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: section-nested ~~~ examples never persist attendance [78.40ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: section-nested ``` examples never persist attendance [72.67ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: source-selected gbrain-base overrides global attendance-fixture [67.98ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: source-selected attendance-fixture overrides global gbrain-base [85.34ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: source-selected attendance-fixture overrides global missing-example-pack [69.61ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: unavailable source-selected ontology preserves graph and watermark [76.55ms]+[extract.links_fs] start+[extract.links_fs] 3/3 (100%)+[extract.links_fs] 3/3 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 3/3 (100%)+[extract.timeline_fs] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: inline commented people do not become attendees [106.96ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: unavailable ontology cannot reverse existing pack-owned attendance [87.20ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [167.39ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: HTML-commented attendance retracts the claim without asserting hidden evidence [96.43ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: missing display-label slugs do not make actual attendance incomplete [60.08ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 1/2 (50%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: explicit foreign attendance survives complete resolution [93.41ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 1/2 (50%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: federated-default foreign attendance survives complete resolution [100.75ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 1/2 (50%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: unresolved attendance cannot retract owned graph or mark success [86.50ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: section-nested ~~~ examples never persist attendance [54.30ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: section-nested ``` examples never persist attendance [51.09ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: source-selected gbrain-base overrides global attendance-fixture [75.07ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: source-selected attendance-fixture overrides global gbrain-base [71.88ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: source-selected attendance-fixture overrides global missing-example-pack [92.37ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: unavailable source-selected ontology preserves graph and watermark [80.66ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: inline commented people do not become attendees [103.09ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: unavailable ontology cannot reverse existing pack-owned attendance [102.85ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [185.08ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: HTML-commented attendance retracts the claim without asserting hidden evidence [121.56ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: missing display-label slugs do not make actual attendance incomplete [70.99ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: explicit foreign attendance survives complete resolution [112.35ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: federated-default foreign attendance survives complete resolution [115.32ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: unresolved attendance cannot retract owned graph or mark success [110.36ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: section-nested ~~~ examples never persist attendance [70.04ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: section-nested ``` examples never persist attendance [69.14ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: source-selected gbrain-base overrides global attendance-fixture [67.21ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: source-selected attendance-fixture overrides global gbrain-base [62.86ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: source-selected attendance-fixture overrides global missing-example-pack [67.90ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: unavailable source-selected ontology preserves graph and watermark [61.96ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: inline commented people do not become attendees [92.53ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: unavailable ontology cannot reverse existing pack-owned attendance [78.76ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [129.26ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: HTML-commented attendance retracts the claim without asserting hidden evidence [99.49ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: missing display-label slugs do not make actual attendance incomplete [79.62ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: explicit foreign attendance survives complete resolution [112.44ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: federated-default foreign attendance survives complete resolution [108.92ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: unresolved attendance cannot retract owned graph or mark success [107.44ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: section-nested ~~~ examples never persist attendance [65.90ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: section-nested ``` examples never persist attendance [66.65ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: source-selected gbrain-base overrides global attendance-fixture [67.65ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: source-selected attendance-fixture overrides global gbrain-base [78.19ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: source-selected attendance-fixture overrides global missing-example-pack [65.80ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: unavailable source-selected ontology preserves graph and watermark [66.77ms]+[extract.links_db] start+[extract.links_db] 3/3 (100%)+[extract.links_db] 3/3 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 3/3 (100%)+[extract.timeline_db] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: inline commented people do not become attendees [95.96ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: unavailable ontology cannot reverse existing pack-owned attendance [95.47ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [171.69ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: HTML-commented attendance retracts the claim without asserting hidden evidence [118.20ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: missing display-label slugs do not make actual attendance incomplete [64.06ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 1/2 (50%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: explicit foreign attendance survives complete resolution [130.96ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 1/2 (50%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: federated-default foreign attendance survives complete resolution [119.41ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 1/2 (50%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: unresolved attendance cannot retract owned graph or mark success [99.73ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: section-nested ~~~ examples never persist attendance [56.78ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: section-nested ``` examples never persist attendance [58.80ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: source-selected gbrain-base overrides global attendance-fixture [73.05ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: source-selected attendance-fixture overrides global gbrain-base [77.56ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: source-selected attendance-fixture overrides global missing-example-pack [75.57ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.stale] start+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: unavailable source-selected ontology preserves graph and watermark [81.51ms]+[extract.stale] start+[extract.stale] 3/3 (100%)+[extract.stale] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: inline commented people do not become attendees [110.36ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.stale] start+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: unavailable ontology cannot reverse existing pack-owned attendance [101.42ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+[extract.stale] start+[extract.stale] 1/1 (100%)+[extract.stale] 1/1 (100%) done+[extract.stale] start+[extract.stale] 1/1 (100%)+[extract.stale] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: a unique bare attendee resolves, survives re-extraction, and retracts with its evidence [150.81ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+[extract.stale] start+[extract.stale] 1/1 (100%)+[extract.stale] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: HTML-commented attendance retracts the claim without asserting hidden evidence [111.73ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: missing display-label slugs do not make actual attendance incomplete [73.08ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+[extract.stale] start+[extract.stale] done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: explicit foreign attendance survives complete resolution [94.23ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+[extract.stale] start+[extract.stale] done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: federated-default foreign attendance survives complete resolution [99.96ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.stale] start+[extract.stale] 1/2 (50%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: unresolved attendance cannot retract owned graph or mark success [102.34ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: section-nested ~~~ examples never persist attendance [68.13ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: section-nested ``` examples never persist attendance [72.43ms]+[extract.incremental] start+[extract.incremental] 1/1 (100%)+[extract.incremental] 1/1 (100%) done+[extract.incremental] start+[extract.incremental] 1/1 (100%)+[extract.incremental] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: imported hidden meetings get guarded canonical attendance [95.98ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: imported hidden meetings get guarded canonical attendance [105.93ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: an ordinary missing target does not discard later links or processed status [60.06ms]+[extract.incremental] start+[extract.incremental] 1/1 (100%)+[extract.incremental] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: file-only meeting declarations cannot bypass the database origin type [56.15ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: file-only meeting declarations cannot bypass the database origin type [44.78ms]+[extract.links_db] start+[extract.links_db] 3/3 (100%)+[extract.links_db] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: display-label person slugs do not assert extra attendees [90.00ms]+[extract.links_db] start+[extract.links_db] 3/4 (75%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: ambiguous bare references do not assert either attendee [110.00ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: actual extraction persists, queries and removes meeting-owned Markdown [159.36ms]+[extract.stale] start+[extract.stale] 3/3 (100%)+[extract.stale] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: display-label person slugs do not assert extra attendees [99.61ms]+[extract.stale] start+[extract.stale] 3/4 (75%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: ambiguous bare references do not assert either attendee [118.53ms]+[extract.stale] start+[extract.stale] 2/2 (100%)+[extract.stale] 2/2 (100%) done+[extract.stale] start+[extract.stale] 1/1 (100%)+[extract.stale] 1/1 (100%) done+[extract.stale] start+[extract.stale] 1/1 (100%)+[extract.stale] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: actual extraction persists, queries and removes meeting-owned Markdown [156.41ms]+[extract.links_fs] start+[extract.links_fs] 3/3 (100%)+[extract.links_fs] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: display-label person slugs do not assert extra attendees [85.38ms]+[extract.links_fs] start+[extract.links_fs] 3/4 (75%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: ambiguous bare references do not assert either attendee [91.25ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: actual extraction persists, queries and removes meeting-owned Markdown [138.71ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: display-label person slugs do not assert extra attendees [88.92ms]+[extract.incremental] start+[extract.incremental] 1/2 (50%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: ambiguous bare references do not assert either attendee [95.05ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: actual extraction persists, queries and removes meeting-owned Markdown [170.07ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: display-label person slugs do not assert extra attendees [88.45ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: ambiguous bare references do not assert either attendee [104.68ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: actual extraction persists, queries and removes meeting-owned Markdown [156.55ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: display-label person slugs do not assert extra attendees [99.54ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: ambiguous bare references do not assert either attendee [115.41ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare: actual extraction persists, queries and removes meeting-owned Markdown [161.40ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: display-label person slugs do not assert extra attendees [101.16ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: ambiguous bare references do not assert either attendee [135.37ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep: actual extraction persists, queries and removes meeting-owned Markdown [154.00ms]+[extract.links_db] start+[extract.links_db] 4/4 (100%)+[extract.links_db] 4/4 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 4/4 (100%)+[extract.timeline_db] 4/4 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.timeline_db] start+[extract.timeline_db] 2/2 (100%)+[extract.timeline_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: mixed-source extraction resolves each origin's pack for identical slugs [147.86ms]+[extract.stale] start+[extract.stale] 4/4 (100%)+[extract.stale] 4/4 (100%) done+[extract.stale] start+[extract.stale] 1/1 (100%)+[extract.stale] 1/1 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: mixed-source extraction resolves each origin's pack for identical slugs [138.44ms]+[extract.links_db] start+[extract.links_db] 1/3 (33%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > db: type-filtered extraction does not load an unrelated source pack [74.15ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > db: unavailable selected source fails preflight before any healthy graph or combined watermark changes [59.20ms]+[extract.stale] start+[extract.stale] 2/4 (50%) done+[extract.stale] start+[extract.stale] 1/3 (33%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > stale: an unavailable first source does not starve healthy later batches or become successful [102.41ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication: source-selected attendance-fixture/gbrain-base overrides global attendance-fixture [167.91ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication: source-selected attendance-fixture/attendance-fixture overrides global gbrain-base [148.28ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication: source-selected attendance-fixture/attendance-fixture overrides global missing-example-pack [143.96ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication: unavailable source-selected attendance-fixture pack saves the note but preserves the graph [498.76ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication: source-selected default/gbrain-base overrides global attendance-fixture [147.61ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication: source-selected default/attendance-fixture overrides global gbrain-base [144.99ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication: source-selected default/attendance-fixture overrides global missing-example-pack [149.30ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication: unavailable source-selected default pack saves the note but preserves the graph [482.66ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication discovers typed pack frontmatter before admitting edges and preserves unchanged row identity [544.69ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication keeps the note and prior graph when an endpoint changes after preparation: edit [228.43ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication keeps the note and prior graph when an endpoint changes after preparation: retype [194.98ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication keeps the note and prior graph when an endpoint changes after preparation: delete [190.22ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication does not swallow unrelated graph storage failures [184.10ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication admits the visible attendee but not a live person inside an inline comment [181.27ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication preserves pack-owned attendance and reports unavailable ontology without losing the note [194.03ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication does not admit a non-person into typed pack attendance [166.51ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local publication retains typed pack attendance when resolved endpoint metadata is unavailable [171.56ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > typed pack attendance preserves prior edges when the new target cannot be resolved [80.10ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > local put_page and remote deferred sweep preserve the actual Markdown producer [520.49ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > local put_page commits unresolved attendance content while preserving retryable graph [196.48ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > actual put_page and query operations retain and remove the supported attendee [545.02ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+Links: created 2 from 2 pages (db source)++Done: 2 links, 0 timeline entries from 2 pages+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+Links: created 0 from 2 pages (db source)++Done: 0 links, 0 timeline entries from 2 pages+(pass) non-overridden canonical attendance lifecycle (postgres) > canonical frontmatter and body keep distinct provenance without duplicate people [173.09ms]+[extract.links_db] start+[extract.links_db] 3/4 (75%) done+Links: created 0 from 3 pages (db source)+Skipped 1 page(s) with unresolved attendance; prior links and extraction watermarks were preserved.+Unresolved frontmatter refs: 2 total+ 1× attendees:Shared name+ 1× attendees:people/company-example++Done: 0 links, 0 timeline entries from 3 pages+(pass) non-overridden canonical attendance lifecycle (postgres) > ambiguous or non-person canonical frontmatter stays unresolved [108.52ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: canonical frontmatter persists and removes under its meeting origin [158.04ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: canonical frontmatter persists and removes under its meeting origin [162.21ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > private attendees and unsealed projections remain excluded from remote retrieval [117.83ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > single and batch writers round-trip Markdown origin without exposing an ungranted origin [65.34ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > failed filesystem attendance replacement stays retryable and preserves the last good graph [128.27ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.timeline_fs] start+[extract.timeline_fs] 2/2 (100%)+[extract.timeline_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: failed attendance replacement does not advance its watermark [124.00ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+ link replacement error for people/alice-example (0 rows not written): Injected replacement failure+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: failed attendance replacement does not advance its watermark [124.22ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+Links: created 2 from 2 pages (db source)++Done: 2 links, 0 timeline entries from 2 pages+(pass) non-overridden canonical attendance lifecycle (postgres) > gbrain-base: pack_semantics_preserved [65.67ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+Links: created 2 from 2 pages (db source)++Done: 2 links, 0 timeline entries from 2 pages+(pass) non-overridden canonical attendance lifecycle (postgres) > company-brain: pack_semantics_preserved [65.83ms]+[extract.links_db] start+[extract.links_db] 3/3 (100%)+[extract.links_db] 3/3 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > manual and other-origin rows survive exact meeting removal [140.08ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare/attendance-fixture: retained link identities refresh their evidence [120.99ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > prepare/gbrain-base: retained link identities refresh their evidence [113.90ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > sweep/attendance-fixture: retained link identities refresh their evidence [92.94ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch/attendance-fixture: retained link identities refresh their evidence [95.60ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental/attendance-fixture: retained link identities refresh their evidence [100.62ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync/attendance-fixture: retained link identities refresh their evidence [100.28ms]+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+[extract.links_fs] start+[extract.links_fs] 2/2 (100%)+[extract.links_fs] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-batch: unknown legacy producers survive attendance reconciliation [90.97ms]+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+[extract.incremental] start+[extract.incremental] 2/2 (100%)+[extract.incremental] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-incremental: unknown legacy producers survive attendance reconciliation [108.79ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > fs-sync: unknown legacy producers survive attendance reconciliation [98.72ms]+(pass) non-overridden canonical attendance lifecycle (postgres) > reversed Markdown validation requires matching origin, types and captured endpoint revisions [88.14ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > source identities are resolved before reversing qualified Markdown [98.24ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > DB does not promote unsupported evidence: [Alice](../people/alice-example.md) did not attend. [56.00ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > DB does not promote unsupported evidence: Invited [Alice](../people/alice-example.md) for next month. [61.80ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > DB does not promote unsupported evidence: Discussed a proposal from [Alice](../people/alice-example.md). [58.20ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > DB does not promote unsupported evidence: Attendees: [Alice](../people/alice-example.md) (absent) [59.09ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > DB does not promote unsupported evidence: ## Attendees+- [Alice](../people/alice-example.md) was invited [57.91ms]+[extract.links_db] start+[extract.links_db] 2/2 (100%)+[extract.links_db] 2/2 (100%) done+(pass) non-overridden canonical attendance lifecycle (postgres) > DB does not promote unsupported evidence: ```md+Attendees: [Alice](../people/alice-example.md)+``` [57.40ms]+(pass) shared and filesystem canonical attendance grammar > large malformed lists are bounded and never accept a valid prefix [6.95ms]+(pass) shared and filesystem canonical attendance grammar > nonmatching constrained attendance rules preserve pack ownership and outgoing mentions [1.73ms]+(pass) shared and filesystem canonical attendance grammar > ambiguous bare attendance names stay nonassertive without changing ordinary expansion [1.99ms]+(pass) shared and filesystem canonical attendance grammar > a canonical mention does not reverse a separate pack-owned edge to the same target [1.71ms]+(pass) shared and filesystem canonical attendance grammar > Attendees: [Alice](../people/alice-example.md) [0.66ms]+(pass) shared and filesystem canonical attendance grammar > Attendees: [Alice](people/alice-example.md) [0.45ms]+(pass) shared and filesystem canonical attendance grammar > Attendees: [[people/alice-example]] [0.26ms]+(pass) shared and filesystem canonical attendance grammar > Attendees: [Alice](/people/alice-example.md) [0.26ms]+(pass) shared and filesystem canonical attendance grammar > ## Attendees+- [Alice](../people/alice-example.md)++## Notes+Discussed work. [0.39ms]+(pass) shared and filesystem canonical attendance grammar > not evidence: Attendees: [Company](../people/company-example.md) [0.73ms]+(pass) shared and filesystem canonical attendance grammar > not evidence: Attendees: [Missing](../people/missing.md) [0.30ms]+(pass) shared and filesystem canonical attendance grammar > not evidence: Attendees: [Alice](../people/alice-example.md) maybe [0.25ms]+(pass) shared and filesystem canonical attendance grammar > not evidence: Attendees: `not` [Alice](../people/alice-example.md) [0.38ms]+(pass) shared and filesystem canonical attendance grammar > not evidence: ~~~md+Attendees: [Alice](../people/alice-example.md)+~~~ [0.23ms]+(pass) shared and filesystem canonical attendance grammar > not evidence: Attendees: [Alice](../people/alice-example.md) [0.23ms]+(pass) shared and filesystem canonical attendance grammar > not evidence: ## Attendees+- [Alice](../people/alice-example.md)+Nobody attended. [0.31ms]+(pass) shared and filesystem canonical attendance grammar > not evidence: Reference to [Alice](../people/alice-example.md).+## Attendees+Nobody attended. [0.30ms]++ 387 pass+ 0 fail+ 1475 expect() calls+Ran 387 tests across 1 file. [47.21s]diff --git a/docs/test-audit/2026-09-29/lane-e2e/e2e-files.json b/docs/test-audit/2026-09-29/lane-e2e/e2e-files.jsonnew file mode 100644index 0000000000..cc97da3d67--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-e2e/e2e-files.json@@ -0,0 +1,3581 @@+[+ {+ "f": "test/e2e/anomalies-pglite.test.ts",+ "loc": 105,+ "ms": 2886,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/attendance-repair-postgres.test.ts",+ "loc": 1,+ "ms": 47886,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/attendance-retrieval-postgres.test.ts",+ "loc": 1,+ "ms": 49195,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/auth-permissions.test.ts",+ "loc": 172,+ "ms": 1084,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/auth-takes-holders-pglite.test.ts",+ "loc": 269,+ "ms": 1478,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/autopilot-cooldown-parity.test.ts",+ "loc": 62,+ "ms": 1649,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/autopilot-fanout-postgres.test.ts",+ "loc": 358,+ "ms": 1091,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/autopilot-linux-lifecycle.serial.test.ts",+ "loc": 378,+ "ms": 10888,+ "pg": true,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "GOOGLE_API_KEY",+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/backfill-perf-pglite.test.ts",+ "loc": 60,+ "ms": 10437,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/backup-coverage-parity.test.ts",+ "loc": 75,+ "ms": 2317,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/bootstrap-attach.serial.test.ts",+ "loc": 390,+ "ms": 5768,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/bootstrap-compiled-binary.serial.test.ts",+ "loc": 186,+ "ms": 5164,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/bootstrap-degraded-modes.serial.test.ts",+ "loc": 309,+ "ms": 5146,+ "pg": true,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "GOOGLE_GENERATIVE_AI_API_KEY",+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/bootstrap-harness-lifecycle.serial.test.ts",+ "loc": 300,+ "ms": 10390,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/bootstrap-hook-under-serve.serial.test.ts",+ "loc": 473,+ "ms": 14450,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/bootstrap-keyed-postgres.serial.test.ts",+ "loc": 371,+ "ms": 2967,+ "pg": true,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/bootstrap-lifecycle.serial.test.ts",+ "loc": 497,+ "ms": 8510,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/bootstrap-magic-moment.serial.test.ts",+ "loc": 259,+ "ms": 4771,+ "pg": true,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "GOOGLE_GENERATIVE_AI_API_KEY",+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/bootstrap-persistence.serial.test.ts",+ "loc": 254,+ "ms": 1365,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/bootstrap-real-claude.serial.test.ts",+ "loc": 310,+ "ms": 547,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "skip-only-in-e2e-lane"+ },+ {+ "f": "test/e2e/bootstrap-real-codex.serial.test.ts",+ "loc": 673,+ "ms": 680,+ "pg": true,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "skip-only-in-e2e-lane"+ },+ {+ "f": "test/e2e/brainstorm-resume.test.ts",+ "loc": 478,+ "ms": 2833,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/cache-gate-pglite.test.ts",+ "loc": 262,+ "ms": 2796,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/calibration-profile-write.test.ts",+ "loc": 176,+ "ms": 2241,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/capture-generation-regression.test.ts",+ "loc": 165,+ "ms": 2043,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/chronicle-event-projection-parity.test.ts",+ "loc": 193,+ "ms": 2214,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/chronicle-last-seen-postgres.test.ts",+ "loc": 77,+ "ms": 790,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/chunk-canonical-text-privacy.test.ts",+ "loc": 204,+ "ms": 2169,+ "pg": true,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/chunker-takes-strip.test.ts",+ "loc": 106,+ "ms": 1073,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/cjk-roundtrip.test.ts",+ "loc": 119,+ "ms": 1740,+ "pg": false,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/claude-plugin-install-real.serial.test.ts",+ "loc": 194,+ "ms": 523,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "skip-only-in-e2e-lane"+ },+ {+ "f": "test/e2e/claw-test.test.ts",+ "loc": 439,+ "ms": 82480,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/cli-source-scoping-pglite.test.ts",+ "loc": 98,+ "ms": 1931,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/client-grants.test.ts",+ "loc": 176,+ "ms": 2180,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/code-edges-jsonb-postgres.test.ts",+ "loc": 148,+ "ms": 807,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/code-edges-read-parity.test.ts",+ "loc": 260,+ "ms": 1811,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/code-indexing.test.ts",+ "loc": 536,+ "ms": 4269,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/code-intel-mcp-ops-pglite.test.ts",+ "loc": 396,+ "ms": 3382,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/codex-plugin-install-real.serial.test.ts",+ "loc": 383,+ "ms": 532,+ "pg": false,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "skip-only-in-e2e-lane"+ },+ {+ "f": "test/e2e/company-brain-receipts.test.ts",+ "loc": 17,+ "ms": 1058,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/compile-context-pglite.test.ts",+ "loc": 329,+ "ms": 2354,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/concurrent-embed-race.test.ts",+ "loc": 203,+ "ms": 1926,+ "pg": false,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/connect-bearer.test.ts",+ "loc": 238,+ "ms": 11278,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/connector-sync-handler-pglite.test.ts",+ "loc": 84,+ "ms": 1560,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/connectors-sync-pglite.test.ts",+ "loc": 430,+ "ms": 7247,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/contextual-retrieval-pglite.test.ts",+ "loc": 303,+ "ms": 3912,+ "pg": false,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/conversation-parser-pglite.test.ts",+ "loc": 163,+ "ms": 5083,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/cross-modal-eval.test.ts",+ "loc": 241,+ "ms": 427,+ "pg": false,+ "pglite": false,+ "keys": [+ "ANTHROPIC_API_KEY",+ "GOOGLE_GENERATIVE_AI_API_KEY",+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/cycle-consolidate-postgres.test.ts",+ "loc": 129,+ "ms": 736,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/cycle-recompute-emotional-weight-pglite.test.ts",+ "loc": 111,+ "ms": 2139,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/cycle.test.ts",+ "loc": 228,+ "ms": 2496,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/db-guard.test.ts",+ "loc": 65,+ "ms": 332,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/db-lock-acquisition-token.test.ts",+ "loc": 46,+ "ms": 710,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/db-singleton-shared-recovery.test.ts",+ "loc": 136,+ "ms": 385,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/deep-research-http.test.ts",+ "loc": 111,+ "ms": 2801,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/deep-research-source-id.test.ts",+ "loc": 19,+ "ms": 3558,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/delegated-grants-withdrawal.test.ts",+ "loc": 114,+ "ms": 1451,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/delegated-http-worker.test.ts",+ "loc": 180,+ "ms": 2872,+ "pg": true,+ "pglite": false,+ "keys": [+ "ANTHROPIC_API_KEY"+ ],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/doctor-connectors-pglite.test.ts",+ "loc": 79,+ "ms": 1973,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/doctor-progress.test.ts",+ "loc": 141,+ "ms": 8018,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/doctor-silent-death-parity.test.ts",+ "loc": 194,+ "ms": 3438,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/dream-allow-list-pglite.test.ts",+ "loc": 159,+ "ms": 3262,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/dream-cycle-phase-order-pglite.test.ts",+ "loc": 254,+ "ms": 3772,+ "pg": true,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/dream-patterns-pglite.test.ts",+ "loc": 217,+ "ms": 3699,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/dream-synthesize-chunking.test.ts",+ "loc": 646,+ "ms": 10544,+ "pg": false,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/dream-synthesize-concurrency-postgres.test.ts",+ "loc": 116,+ "ms": 12664,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/dream-synthesize-pglite.test.ts",+ "loc": 1262,+ "ms": 12146,+ "pg": false,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/dream-triage-postgres.test.ts",+ "loc": 80,+ "ms": 955,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/dream.test.ts",+ "loc": 141,+ "ms": 1853,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/embed-stale-pagination.test.ts",+ "loc": 290,+ "ms": 1031,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/embedding-column-pglite.test.ts",+ "loc": 369,+ "ms": 1805,+ "pg": true,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/embedding-column-postgres.test.ts",+ "loc": 230,+ "ms": 714,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/embedding-recovery-parity.test.ts",+ "loc": 3,+ "ms": null,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/engine-content-privacy.test.ts",+ "loc": 447,+ "ms": 7684,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/engine-parity-cjk.test.ts",+ "loc": 190,+ "ms": 2482,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/engine-parity-salience.test.ts",+ "loc": 347,+ "ms": 6102,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/engine-parity.test.ts",+ "loc": 2594,+ "ms": 26264,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/enrich-pglite.test.ts",+ "loc": 625,+ "ms": 7536,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/eval-capture.test.ts",+ "loc": 146,+ "ms": 718,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/eval-contradictions-postgres.test.ts",+ "loc": 331,+ "ms": 881,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/eval-loop.test.ts",+ "loc": 275,+ "ms": 1952,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/eval-replay-column.test.ts",+ "loc": 115,+ "ms": 1436,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/eval-takes-quality.test.ts",+ "loc": 217,+ "ms": 663,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/export-snapshot-postgres.test.ts",+ "loc": 3,+ "ms": null,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/extract-atoms-discovery-sql.test.ts",+ "loc": 149,+ "ms": 1002,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/extract-atoms-page-state.test.ts",+ "loc": 160,+ "ms": 2150,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/extract-timeline-attendance-postgres.test.ts",+ "loc": 1,+ "ms": 4675,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/extraction-review-postgres.test.ts",+ "loc": 110,+ "ms": 1362,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/fact-backfill-resident.test.ts",+ "loc": 204,+ "ms": 7921,+ "pg": true,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/fact-embedding-backfill-parity.test.ts",+ "loc": 347,+ "ms": 7052,+ "pg": true,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/fact-vector-repair-parity.test.ts",+ "loc": 169,+ "ms": 5977,+ "pg": true,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/facts-context-injection-postgres.test.ts",+ "loc": 71,+ "ms": 929,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/facts-cross-source-isolation.test.ts",+ "loc": 55,+ "ms": 687,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/facts-fence-reconcile-postgres.test.ts",+ "loc": 452,+ "ms": 1367,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/facts-forget.test.ts",+ "loc": 53,+ "ms": 1275,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/facts-notability-roundtrip.test.ts",+ "loc": 135,+ "ms": 652,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/facts-recall-event-time-postgres.test.ts",+ "loc": 89,+ "ms": 758,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/facts-recall-render.test.ts",+ "loc": 45,+ "ms": 908,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/facts-separation-postgres.test.ts",+ "loc": 211,+ "ms": 868,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/facts-worker-config.test.ts",+ "loc": 11,+ "ms": 2423,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/fixture-reset-postgres.test.ts",+ "loc": 112,+ "ms": 4246,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/fresh-install-pglite.test.ts",+ "loc": 372,+ "ms": 29181,+ "pg": false,+ "pglite": true,+ "keys": [+ "GOOGLE_GENERATIVE_AI_API_KEY",+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/frontmatter-migration.test.ts",+ "loc": 195,+ "ms": 3738,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/global-basename-pglite.test.ts",+ "loc": 349,+ "ms": 3967,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/google-attachments-postgres.test.ts",+ "loc": 8,+ "ms": null,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/grandfather-projection-postgres.test.ts",+ "loc": 259,+ "ms": 4645,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/graph-quality.test.ts",+ "loc": 389,+ "ms": 4440,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/graph-signals-engine.test.ts",+ "loc": 177,+ "ms": 1793,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/graph-signals-eval.test.ts",+ "loc": 302,+ "ms": 5931,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/harness-access.test.ts",+ "loc": 7,+ "ms": 5967,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/health-parity-postgres.test.ts",+ "loc": 165,+ "ms": 2262,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/http-transport.test.ts",+ "loc": 347,+ "ms": 1378,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/import-credential-preflight.test.ts",+ "loc": 74,+ "ms": 2277,+ "pg": false,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "GOOGLE_GENERATIVE_AI_API_KEY",+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/ingestion-roundtrip.test.ts",+ "loc": 334,+ "ms": 4097,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/init-fresh-pglite.test.ts",+ "loc": 377,+ "ms": 35927,+ "pg": false,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/install-real-grok.serial.test.ts",+ "loc": 489,+ "ms": 542,+ "pg": true,+ "pglite": true,+ "keys": [+ "GBRAIN_REAL_GROK_E",+ "XAI_API_KEY"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "skip-only-in-e2e-lane"+ },+ {+ "f": "test/e2e/install-real-hermes.serial.test.ts",+ "loc": 345,+ "ms": 508,+ "pg": true,+ "pglite": true,+ "keys": [+ "GBRAIN_REAL_HERMES_E"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "skip-only-in-e2e-lane"+ },+ {+ "f": "test/e2e/install-real-opencode.serial.test.ts",+ "loc": 512,+ "ms": 544,+ "pg": true,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "GBRAIN_REAL_OPENCODE_E",+ "GBRAIN_REAL_OPENCODE_PAID_E"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "skip-only-in-e2e-lane"+ },+ {+ "f": "test/e2e/integrity-batch.test.ts",+ "loc": 169,+ "ms": 836,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/job-isolation.test.ts",+ "loc": 133,+ "ms": 2089,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/jobs-agent-scope-postgres.test.ts",+ "loc": 103,+ "ms": 1120,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/jobs-watch-readsnapshot.test.ts",+ "loc": 86,+ "ms": 2072,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/jsonb-batch-poison-postgres.test.ts",+ "loc": 186,+ "ms": 1051,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/jsonb-roundtrip.test.ts",+ "loc": 137,+ "ms": 777,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/legacy-chunk-privacy.test.ts",+ "loc": 399,+ "ms": 7966,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/legacy-fact-extraction-dedup-postgres.test.ts",+ "loc": 3,+ "ms": null,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/legacy-vector-compatibility-postgres.test.ts",+ "loc": 3,+ "ms": null,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/link-source-check-repair-postgres.test.ts",+ "loc": 131,+ "ms": 968,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/list-all-sources-postgres.test.ts",+ "loc": 193,+ "ms": 724,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/list-pages-regression.test.ts",+ "loc": 94,+ "ms": 1733,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/managed-atom-compaction.test.ts",+ "loc": 16,+ "ms": 8574,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/managed-atom-regressions.test.ts",+ "loc": 27,+ "ms": 17589,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/managed-connector-fencing.test.ts",+ "loc": 3,+ "ms": 12497,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/managed-connector-recovery.test.ts",+ "loc": 3,+ "ms": 31154,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/managed-connector-retry.test.ts",+ "loc": 3,+ "ms": 69715,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/managed-connector-routing.test.ts",+ "loc": 6,+ "ms": 62805,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/managed-extract-atoms.test.ts",+ "loc": 16,+ "ms": 17096,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/managed-facts-backstop.test.ts",+ "loc": 11,+ "ms": 13715,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/managed-facts-compaction.test.ts",+ "loc": 10,+ "ms": 35825,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/managed-facts-embedding.test.ts",+ "loc": 10,+ "ms": 37909,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/managed-maintenance.test.ts",+ "loc": 3,+ "ms": 46505,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/managed-sync-failures.test.ts",+ "loc": 3,+ "ms": 31428,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/managed-synthesis-postprocess.test.ts",+ "loc": 3,+ "ms": 12231,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/mcp-budget-reservation-postgres.test.ts",+ "loc": 77,+ "ms": 804,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/mcp-search-transport-matrix.test.ts",+ "loc": 406,+ "ms": null,+ "pg": true,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/mcp.test.ts",+ "loc": 70,+ "ms": 1201,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/mechanical.test.ts",+ "loc": 1600,+ "ms": 60319,+ "pg": true,+ "pglite": true,+ "keys": [+ "VOYAGE_API_KEY"+ ],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/memory-safety-wave-postgres.test.ts",+ "loc": 3,+ "ms": null,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/migrate-chain.test.ts",+ "loc": 221,+ "ms": 2978,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migrate-embeddings-postgres.test.ts",+ "loc": 248,+ "ms": 1883,+ "pg": true,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migrate-engine-pglite-to-postgres.test.ts",+ "loc": 393,+ "ms": 9641,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migrate-engine-sources-postgres.test.ts",+ "loc": 44,+ "ms": 2074,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-drop-invalid-concurrent-index.test.ts",+ "loc": 121,+ "ms": 1118,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-flow.test.ts",+ "loc": 299,+ "ms": 4277,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-preview-safety.test.ts",+ "loc": 94,+ "ms": 11358,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-v35-auto-rls.test.ts",+ "loc": 264,+ "ms": 1146,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-v35-event-trigger.test.ts",+ "loc": 104,+ "ms": 1053,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-v47-notability.test.ts",+ "loc": 217,+ "ms": 920,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-v50-ingest-log-source-id.test.ts",+ "loc": 137,+ "ms": 1063,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-vector-replay-postgres.test.ts",+ "loc": 3,+ "ms": null,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/migration-wave-budget-crash.test.ts",+ "loc": 47,+ "ms": null,+ "pg": true,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY"+ ],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-wave-healing-fence.test.ts",+ "loc": 61,+ "ms": null,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-wave-intermediate-retrieval.test.ts",+ "loc": 83,+ "ms": null,+ "pg": true,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-wave-phase-leases.test.ts",+ "loc": 79,+ "ms": null,+ "pg": true,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-wave-prepared-withdrawal.test.ts",+ "loc": 71,+ "ms": null,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/migration-wave-provider-outcomes.test.ts",+ "loc": 83,+ "ms": null,+ "pg": true,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/minions-authority-parity.test.ts",+ "loc": 80,+ "ms": 954,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/minions-budget-cathedral.test.ts",+ "loc": 126,+ "ms": 1820,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/minions-concurrency.test.ts",+ "loc": 149,+ "ms": 1456,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/minions-controller-bounce-only.test.ts",+ "loc": 98,+ "ms": 1873,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/minions-field-report-repro.test.ts",+ "loc": 101,+ "ms": 27667,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/minions-prefix-strip-smoke.test.ts",+ "loc": 83,+ "ms": 1753,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/minions-resilience.test.ts",+ "loc": 405,+ "ms": 12390,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/minions-self-fix-flow.test.ts",+ "loc": 144,+ "ms": 1661,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/minions-shell-pglite.test.ts",+ "loc": 393,+ "ms": 2274,+ "pg": true,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY"+ ],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/minions-shell.test.ts",+ "loc": 149,+ "ms": 1161,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/mounts-routing-pglite.test.ts",+ "loc": 291,+ "ms": 44757,+ "pg": true,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/multi-source-bug-class.test.ts",+ "loc": 344,+ "ms": 3606,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/multi-source-emotional-weight-pglite.test.ts",+ "loc": 114,+ "ms": 1437,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/multi-source.test.ts",+ "loc": 689,+ "ms": 2870,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/multimodal-postgres.test.ts",+ "loc": 342,+ "ms": 2387,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/non-tty-output.serial.test.ts",+ "loc": 61,+ "ms": 7693,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/oauth-grant-transactions.test.ts",+ "loc": 175,+ "ms": 1412,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/onboard-full-flow.test.ts",+ "loc": 181,+ "ms": 2035,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/ontology-merge-parity.test.ts",+ "loc": 279,+ "ms": 2081,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/op-checkpoint-jsonb-parity.test.ts",+ "loc": 82,+ "ms": 703,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/openclaw-context-engine-plugin.test.ts",+ "loc": 168,+ "ms": 825,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/openclaw-plugin-load-real.test.ts",+ "loc": 397,+ "ms": 331,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "skip-only-in-e2e-lane"+ },+ {+ "f": "test/e2e/openclaw-reference-compat.test.ts",+ "loc": 150,+ "ms": 1168,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/openrouter-anthropic-subagent-replay.live.test.ts",+ "loc": 168,+ "ms": 1464,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "skip-only-in-e2e-lane"+ },+ {+ "f": "test/e2e/openrouter-deepseek-subagent-replay.live.test.ts",+ "loc": 168,+ "ms": 1913,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "skip-only-in-e2e-lane"+ },+ {+ "f": "test/e2e/orphan-reduction.test.ts",+ "loc": 174,+ "ms": 6818,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/persistence-admin-intent.test.ts",+ "loc": 94,+ "ms": 9254,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/persistence-chaos.test.ts",+ "loc": 571,+ "ms": 35877,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/persistence-embedding-effects.test.ts",+ "loc": 6,+ "ms": 94110,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/persistence-http-liveness.test.ts",+ "loc": 408,+ "ms": 53500,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/persistence-phase-liveness.test.ts",+ "loc": 457,+ "ms": 18258,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/persistence-publication-parity.test.ts",+ "loc": 8,+ "ms": 5530,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/persistence-recovery.test.ts",+ "loc": 6,+ "ms": 11255,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/persistence-runtime-matrix.test.ts",+ "loc": 16,+ "ms": 45396,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/persistence-skill-bundles-postgres.test.ts",+ "loc": 27,+ "ms": 21508,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/persistence-sync-company-parity.test.ts",+ "loc": 8,+ "ms": 13668,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/persistence-sync-options-parity.test.ts",+ "loc": 8,+ "ms": 123842,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/persistence-sync-origin-parity.test.ts",+ "loc": 8,+ "ms": 16895,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/pgbouncer-teardown.test.ts",+ "loc": 159,+ "ms": 2508,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/pglite-cli-exit.serial.test.ts",+ "loc": 540,+ "ms": 38745,+ "pg": true,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "GOOGLE_API_KEY",+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/phantom-redirect.test.ts",+ "loc": 285,+ "ms": 31881,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/postgres-bootstrap.test.ts",+ "loc": 436,+ "ms": 2462,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/postgres-driver-install.test.ts",+ "loc": 84,+ "ms": 306,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/postgres-engine-disconnect-idempotency.test.ts",+ "loc": 133,+ "ms": 459,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/postgres-jsonb.test.ts",+ "loc": 174,+ "ms": 713,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/postgres-reconnect-singleton.test.ts",+ "loc": 98,+ "ms": 400,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/projection-readiness-currency.test.ts",+ "loc": 81,+ "ms": 1345,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/projection-recovery-parity.test.ts",+ "loc": 9,+ "ms": 18230,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/projection-statistics-postgres.test.ts",+ "loc": 79,+ "ms": 585,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/propose-takes-jsonb-postgres.test.ts",+ "loc": 138,+ "ms": 930,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/purge-deleted-dryrun-postgres.test.ts",+ "loc": 73,+ "ms": 726,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/put-page-persistence-postgres.test.ts",+ "loc": 215,+ "ms": 13045,+ "pg": true,+ "pglite": false,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/qm-provisioning.test.ts",+ "loc": 345,+ "ms": 40319,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/quarantine-search-exclusion.test.ts",+ "loc": 154,+ "ms": 3283,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/read-enrichment-privacy.test.ts",+ "loc": 435,+ "ms": 6533,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/reconcile-crash-unactivated.test.ts",+ "loc": 15,+ "ms": 101348,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/reconcile-crash.test.ts",+ "loc": 15,+ "ms": 102209,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/reconcile-pgbouncer.test.ts",+ "loc": 106,+ "ms": 4541,+ "pg": true,+ "pglite": false,+ "keys": [+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/remote-privacy-journeys.test.ts",+ "loc": 272,+ "ms": 24236,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/restore-source-config-jsonb-postgres.test.ts",+ "loc": 68,+ "ms": 1076,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/salience-anomalies-source-isolation-pglite.test.ts",+ "loc": 127,+ "ms": 2123,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/salience-llm-routing.test.ts",+ "loc": 186,+ "ms": 320,+ "pg": false,+ "pglite": false,+ "keys": [+ "ANTHROPIC_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/salience-pglite.test.ts",+ "loc": 138,+ "ms": 3246,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/schema-cathedral.test.ts",+ "loc": 176,+ "ms": 4680,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/schema-drift.test.ts",+ "loc": 316,+ "ms": 6071,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/search-exclude.test.ts",+ "loc": 236,+ "ms": 2067,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/search-quality.test.ts",+ "loc": 231,+ "ms": 1862,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/search-query-contract-postgres.test.ts",+ "loc": 64,+ "ms": 2042,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/search-readiness-http.test.ts",+ "loc": 197,+ "ms": 12483,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/search-swamp.test.ts",+ "loc": 149,+ "ms": 1861,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/self-upgrade-binary-swap.test.ts",+ "loc": 266,+ "ms": 521,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/self-upgrade-marker.test.ts",+ "loc": 125,+ "ms": 4124,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/serve-http-consent.test.ts",+ "loc": 219,+ "ms": 6124,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/serve-http-ingest-webhook.test.ts",+ "loc": 687,+ "ms": 31742,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/serve-http-meta.test.ts",+ "loc": 60,+ "ms": 1141,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/serve-http-multi-agent.test.ts",+ "loc": 830,+ "ms": 22098,+ "pg": true,+ "pglite": false,+ "keys": [+ "GOOGLE_API_KEY",+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/serve-http-oauth.test.ts",+ "loc": 1735,+ "ms": 23362,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/serve-http-source-grant.test.ts",+ "loc": 305,+ "ms": 4308,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/serve-http-surface-ceiling.test.ts",+ "loc": 277,+ "ms": 18357,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/serve-http-takes-holders.test.ts",+ "loc": 189,+ "ms": 3038,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/serve-stdio-roundtrip.test.ts",+ "loc": 354,+ "ms": 23374,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/shared-skills-rls.test.ts",+ "loc": 42,+ "ms": 2079,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/shared-skills-transports.test.ts",+ "loc": 13,+ "ms": 17308,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/skill-brain-first.test.ts",+ "loc": 246,+ "ms": 770,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/skillopt-loop.serial.test.ts",+ "loc": 989,+ "ms": 4338,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/skillopt-models-strict.serial.test.ts",+ "loc": 390,+ "ms": 2857,+ "pg": false,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/skillopt-models-used.serial.test.ts",+ "loc": 236,+ "ms": 2212,+ "pg": false,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/skillopt-outcome.serial.test.ts",+ "loc": 443,+ "ms": 3927,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/skillopt-pglite.serial.test.ts",+ "loc": 233,+ "ms": 2111,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/skillpack-flow.test.ts",+ "loc": 419,+ "ms": 12999,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/skillpack-third-party.test.ts",+ "loc": 243,+ "ms": 7636,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/skills.test.ts",+ "loc": 195,+ "ms": 397,+ "pg": true,+ "pglite": false,+ "keys": [+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY"+ ],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/source-boundary-mutation-postgres.test.ts",+ "loc": 121,+ "ms": 863,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/source-isolation-pglite.test.ts",+ "loc": 287,+ "ms": 4965,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/source-routing.test.ts",+ "loc": 234,+ "ms": 2030,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/sources-remote-mcp.test.ts",+ "loc": 477,+ "ms": 14567,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/status-pglite.test.ts",+ "loc": 208,+ "ms": 2406,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/storage-tiering.test.ts",+ "loc": 273,+ "ms": 1288,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/subagent-crash-replay-multi-provider.test.ts",+ "loc": 540,+ "ms": 3814,+ "pg": false,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/subagent-gateway-path.test.ts",+ "loc": 726,+ "ms": 3757,+ "pg": false,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/subagent-gateway-resume-reconciliation.test.ts",+ "loc": 308,+ "ms": 2598,+ "pg": false,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/symbol-resolver-pglite.test.ts",+ "loc": 220,+ "ms": 3079,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/sync-cjk-git.test.ts",+ "loc": 95,+ "ms": 750,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/sync-credential-preflight.test.ts",+ "loc": 127,+ "ms": 2970,+ "pg": false,+ "pglite": true,+ "keys": [+ "ANTHROPIC_API_KEY",+ "GOOGLE_GENERATIVE_AI_API_KEY",+ "OPENAI_API_KEY",+ "VOYAGE_API_KEY"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/sync-delegation-under-serve.serial.test.ts",+ "loc": 257,+ "ms": 154568,+ "pg": true,+ "pglite": true,+ "keys": [+ "VOYAGE_API_KEY"+ ],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/sync-lock-overlap-postgres.test.ts",+ "loc": 132,+ "ms": 9872,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/sync-lock-recovery.test.ts",+ "loc": 261,+ "ms": 5313,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/sync-parallel.test.ts",+ "loc": 283,+ "ms": 9071,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/sync-reconcile-postgres.test.ts",+ "loc": 169,+ "ms": 2138,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/sync-sigkill-resume-postgres.test.ts",+ "loc": 448,+ "ms": 13332,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/sync-status-pglite.test.ts",+ "loc": 322,+ "ms": 1774,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/sync.test.ts",+ "loc": 681,+ "ms": 4601,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/synthesize-bigint-job-id-postgres.test.ts",+ "loc": 80,+ "ms": 1003,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/system-of-record-invariant.test.ts",+ "loc": 466,+ "ms": 4161,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/takes-postgres.test.ts",+ "loc": 426,+ "ms": 1112,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/takes-scorecard-parity.test.ts",+ "loc": 202,+ "ms": 2583,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/takes-weight-rounding-postgres.test.ts",+ "loc": 137,+ "ms": 818,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/takes-write-ops-postgres.test.ts",+ "loc": 352,+ "ms": 16358,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/thin-client.test.ts",+ "loc": 457,+ "ms": 14918,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/think-source-isolation-pglite.test.ts",+ "loc": 141,+ "ms": 2118,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/think-trajectory-pglite.test.ts",+ "loc": 302,+ "ms": 2485,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/transcripts-ingest-pglite.test.ts",+ "loc": 843,+ "ms": 7956,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/transcripts-writeback-fidelity.test.ts",+ "loc": 126,+ "ms": 4103,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/type-unification-full-flow.test.ts",+ "loc": 265,+ "ms": 3159,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/unsupported-embedding-identity-postgres.test.ts",+ "loc": 9,+ "ms": 49264,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/upgrade-bun-link-arc.serial.test.ts",+ "loc": 443,+ "ms": 10048,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/upgrade.test.ts",+ "loc": 106,+ "ms": 3798,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/upsert-chunks-registry-column.test.ts",+ "loc": 587,+ "ms": 3093,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/v030_1-integration-pglite.test.ts",+ "loc": 222,+ "ms": 26038,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/v0_28_5-fix-wave.test.ts",+ "loc": 292,+ "ms": 15254,+ "pg": false,+ "pglite": true,+ "keys": [+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/v0_29-mcp-dispatch-pglite.test.ts",+ "loc": 247,+ "ms": 1709,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/v0_30_3-fix-wave.test.ts",+ "loc": 201,+ "ms": 13153,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/vector-candidate-safety-postgres.test.ts",+ "loc": 188,+ "ms": 26307,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/vector-ef-search-postgres.test.ts",+ "loc": 78,+ "ms": 4882,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/volunteer-context-postgres.test.ts",+ "loc": 97,+ "ms": 1025,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/voyage-multimodal.test.ts",+ "loc": 44,+ "ms": 270,+ "pg": false,+ "pglite": false,+ "keys": [+ "VOYAGE_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "skip-only-in-e2e-lane"+ },+ {+ "f": "test/e2e/voyage-rerank-live.test.ts",+ "loc": 132,+ "ms": 297,+ "pg": false,+ "pglite": false,+ "keys": [+ "VOYAGE_API_KEY"+ ],+ "spawn": false,+ "cls": "no-pg",+ "cat": "skip-only-in-e2e-lane"+ },+ {+ "f": "test/e2e/whoknows.test.ts",+ "loc": 236,+ "ms": 2951,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/withdrawal-bounded-safety-postgres.test.ts",+ "loc": 2,+ "ms": null,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/withdrawal-crash-postgres.test.ts",+ "loc": 2,+ "ms": null,+ "pg": false,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg-wrapper",+ "cat": "pg-wrapper"+ },+ {+ "f": "test/e2e/worker-abort-recovery.test.ts",+ "loc": 178,+ "ms": 5266,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/worker-configuration-release.test.ts",+ "loc": 201,+ "ms": 33879,+ "pg": true,+ "pglite": false,+ "keys": [+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY"+ ],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/worker-lock-renewal-starvation.test.ts",+ "loc": 164,+ "ms": 3648,+ "pg": true,+ "pglite": false,+ "keys": [],+ "spawn": false,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/worker-readiness-cli.test.ts",+ "loc": 132,+ "ms": 4058,+ "pg": true,+ "pglite": false,+ "keys": [+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY"+ ],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ },+ {+ "f": "test/e2e/workspace-generic-compat.test.ts",+ "loc": 154,+ "ms": 835,+ "pg": false,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "no-pg",+ "cat": "pglite-or-pure (no Postgres)"+ },+ {+ "f": "test/e2e/zombie-reaping.test.ts",+ "loc": 240,+ "ms": 9405,+ "pg": true,+ "pglite": true,+ "keys": [],+ "spawn": true,+ "cls": "pg",+ "cat": "pg"+ }+]\ No newline at end of filediff --git a/docs/test-audit/2026-09-29/lane-e2e/e2e.md b/docs/test-audit/2026-09-29/lane-e2e/e2e.mdnew file mode 100644index 0000000000..f989638d7b--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-e2e/e2e.md@@ -0,0 +1,152 @@+# Test audit — LANE=e2e (test/e2e)++Read-only discovery. Checkout at `2ede415` (v0.59.11.0). The tree was left clean after every probe (`git status --short` came back empty). Method: the openclaw test-audit skill, AGENTS.md/CLAUDE.md, and TESTING.md §"Coverage responsibilities before consolidation". Costs come from `scripts/ubicloud/weights.json` (`e2e:<path>` ms per file). 16 newer files have no weight entry.++## CI routing facts that shape every verdict++- **Unit shards exclude `test/e2e/*`** (`scripts/test-shard.sh:93`). A PGLite-only e2e file executes only in the e2e lanes.+- **The e2e lanes:**+ - **PR/push `selected-e2e`**: diff-selected via `select-e2e.ts`. Escape-hatch paths (`operations.ts`, `src/core/ops/`, `skills/`, workflows, `package.json`, …) select ALL files, minus `E2E_EXCLUSIONS`. Runs sequentially per shard through `run-e2e.sh` with `DATABASE_URL`. **No provider keys** are passed.+ - **Named jobs**: `jsonb-parity`, `tier1`, and `tier2` (skills.test.ts, with keys).+ - **Nightly `coverage-full-e2e`**: the whole `test/e2e/*.test.ts` glob, 4 shards, with coverage, plus OPENAI/ANTHROPIC keys (no VOYAGE/OPENROUTER/GOOGLE).+- **`run-e2e.sh` scrubs `GBRAIN_REAL_*` / `HERMES_` / `GROK_` / `OPENCODE_`**, so the real-agent door files structurally skip in every e2e lane. Their venue is `heavy-tests.yml`.+- **`persistence-validation.yml`** is `workflow_call`ed from `test.yml` on every PR. By name it runs `test/e2e/reconcile-crash*.test.ts` (postgres × Bun 1.3.11/1.3.13), `reconcile-pgbouncer`, `extract-atoms-page-state`, and `scripts/persistence/matrix.ts`.+- **No PgBouncer service in `e2e.yml`**, so files gated on `GBRAIN_PGBOUNCER_URL` are skip-only in GitHub e2e. They execute only under `ci:local`/`ci:ubicloud`.++## Category counts (312 files, 71,361 LOC, 2,877 s)++| Category | Files | LOC | ms (weights) | Verdict |+|---|---:|---:|---:|---|+| Real Postgres (setupDB / PostgresEngine / engine loops / fixtures) | 165 | 36,930 | 1,449,559 | Postgres owner; keep by default |+| Postgres wrappers of shared scenarios (`registerPostgresTests` / `import '../x.test.ts'`) | 22 | 78 | 491,686 | Parity arms, NOT duplicates. **Exception: 3 attendance wrappers re-run the PGLite arm (Candidate 2)** |+| PGLite-only or pure (never touch Postgres) | 113 | 30,538 | 927,437 | Lane-misplaced. They hold the Postgres runner sequentially and run on PRs only when selected. Move-lane candidates, not deletions. Inventory: `pglite-files.txt` |+| Skip-only in every e2e lane (door binaries / never-provided keys) | 12 | 3,815 | 8,151 | Doors owned by heavy-tests; 4 live files never execute in any CI |++Key-gated behaviour: on PR `selected-e2e`, every OPENAI/ANTHROPIC-gated describe skips (no secrets are passed). Nightly executes them. VOYAGE/OPENROUTER-gated tests execute nowhere in CI.++## Top candidates (full evidence)++### 1. `test/e2e/mcp.test.ts`: delete (HIGH confidence)+- **Tests:** "E2E: MCP Tool Generation > operations generate valid MCP tool definitions" and "> MCP server module can be imported".+- **What it can detect:** only that `operations` has at least 30 entries with truthy name/description and contains 9 names, plus that `server.ts` exports two functions. The first test *re-implements* the ParamDef→JSON-Schema mapping inline. Its copy has already drifted: it lacks the `default` key and recursive `items` that the real `src/mcp/tool-defs.ts:paramDefToSchema` emits. So it asserts properties of its own copy.+- **Mutation probe:** I set `buildToolDefs` to emit `required: []` and made `paramDefToSchema` drop `description`.+ - `bun test test/e2e/mcp.test.ts` → **2 pass, 0 fail** (detects nothing).+ - The owner `test/mcp-tool-defs.test.ts` → **4 fail**: "output equals pre-extraction inline mapping byte-for-byte", "put_page warns…", "strictParams… real dry_run", "paramDefToSchema preserves description on nested items".+- **Non-test callers of the seam:** none needed. It reads the public `operations` array and `server.ts` exports.+- **Surviving owners:**+ - `test/mcp-tool-defs.test.ts`: `buildToolDefs` byte-equality, "preserves operation count", "every def has object inputSchema with properties + required array".+ - `test/mcp-stdio-gate-list.test.ts`: the live stdio tools/list.+ - Op-name presence: e.g. `test/operations-trust-boundary.test.ts` (find_orphans etc.).+ - Module import is exercised by `test/mcp-stdio-source-preflight.test.ts` and `test/checkpoint-harvest.serial.test.ts` (`handleToolCall`).+ - All of these are the same boundary: pure/in-process.+- **History:** added in a86f99588 (v0.3.0, 2026-04-08), before `tool-defs.ts` was extracted as the single source (v0.34). Last touched 9c2c91188.+- **Deletion unlocks:** 70 test LOC. Plus edits to the `tier1` run line in `e2e.yml`, `E2E_EXCLUSIONS` in `scripts/e2e-matrix.ts:12`, the map entry `src/mcp/**` in `scripts/e2e-test-map.ts:346` (still covered by http-transport + mcp-search-transport-matrix), and the `test/select-e2e.test.ts:32` fixture list. No production seam.+- **Cost:** 1,201 ms. It also runs inside a required job.+- **Risk:** low. **Validation:** `bun test test/mcp-tool-defs.test.ts test/select-e2e.test.ts test/scripts/*e2e*`.++### 2. Attendance wrappers re-run the PGLite arm already run by the unit lane: rewrite at the wrapper (HIGH confidence)+- **Files:** `test/e2e/attendance-retrieval-postgres.test.ts`, `test/e2e/attendance-repair-postgres.test.ts`, `test/e2e/extract-timeline-attendance-postgres.test.ts`. Each is one line, `import '../X.test.ts'`.+- **Mechanism:** the imported scenarios use `for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])])`. They don't use `testBackends()`, so under the e2e `DATABASE_URL` they register **both** arms. The unit lane (URL stripped) already runs the PGLite arm. All 19 other wrappers use `registerPostgresTests` + `testBackends()`/connector-fixture, which honour `GBRAIN_TEST_BACKEND=postgres`.+- **Measured against local pgvector pg16:**+ - `attendance-retrieval-postgres`: 387 tests, **183 PGLite (20.1 s) + 183 Postgres (21.9 s)**.+ - `attendance-repair-postgres`: 173 tests, **86 PGLite (22.7 s) + 87 Postgres (24.4 s)**.+ - `extract-timeline-attendance-postgres`: 22 tests, 11 `(pglite)` + 11 `(postgres)` describes.+- **Surviving owner of the PGLite arm:** the unit-lane runs of `test/attendance-retrieval.test.ts` (unit weight 26.6 s), `test/attendance-repair.test.ts` (24.2 s) and `test/extract-timeline-attendance.test.ts` (3.0 s). Same contract, same PGLite boundary. The Postgres arm stays in e2e.+- **History:** a610db7b7 (v0.58.0.0, 2026-09-25, #5458), a recent wave predating/omitting the `testBackends` convention.+- **Action:** switch the three scenario loops to `testBackends()` and the wrappers to `registerPostgresTests(() => import(...))`. The shape is identical to `managed-maintenance.test.ts`. This removes only the duplicated PGLite execution.+- **Saves:** ~45 s per execution (PGLite arms 20.1 + 22.7 + ~2.5 s). Net LOC ~0. No production seam.+- **Cost now:** 47,886 + 49,195 + 4,675 ms. **Risk:** low.+- **Validation:** run each wrapper with `DATABASE_URL` and confirm only `(postgres)` describes; unit files unchanged.++### 3. `test/e2e/v030_1-integration-pglite.test.ts`: delete, keeping 2 registry assertions in a unit file (HIGH confidence)+- **Tests:** 14 tests across Lanes B/C/D/E + "Cross-lane integration".+- **Why slow:** `beforeEach` does a cold `initSchema` (the file deletes `GBRAIN_PGLITE_SNAPSHOT`). Every test, including pure checkpoint helpers, pays about 2 s. Measured locally: 14 pass, each test 1.97–2.68 s, 30.3 s wall.+- **Mutation probe:** I made `validateCheckpoint` return `resumeAt: 'pull'`. The e2e file fails 1 test; the owner `test/upgrade-checkpoint.serial.test.ts` fails "partial completion → resumeAt = next un-completed step" in **0.42 ms**.+- **Per-lane surviving owners (same PGLite/pure boundary):**+ - **Lane E** (round-trip, resumeAt, brain_mismatch, all_complete): `upgrade-checkpoint.serial.test.ts` "writes and reads a complete checkpoint", "partial completion…", "X2: brain mismatch…", "all steps complete…".+ - **Lane D:** `test/vector-index-lifecycle.test.ts` "checkActiveBuild > PGLite returns active: false" and "dropZombieIndexes > PGLite: no-op returns dropped: []". Same `kind==='pglite'` branch.+ - **Lane B:** `test/bootstrap.test.ts` "fresh install regression: initSchema on empty DB produces LATEST" (cold path, snapshot deleted). `test/schema-bootstrap-coverage.test.ts` pins `pages.emotional_weight_recomputed_at`.+ - **"connectionManager in engine" and "schema_version optional":** no product contract. The first asserts that a property is absent; the second accepts undefined or '1'.+ - **Only unique assertions:** "listBackfills returns the canonical registry entries" and "embedding_voyage is declared-only". No other test imports `backfill-registry`; `src/commands/backfill.ts` and `src/core/cycle/patterns.ts` consume it. **Move these two into `test/backfill-base.test.ts`** (no engine needed). The empty-brain `runBackfill` checks are low value; optional.+- **History:** dffb607ef (v0.30.1, #750). Last touched aa820c7f9 (snapshot opt-out).+- **Deletion unlocks:** ~200 test LOC; entries in `test/fixtures/e2e-unmapped-baseline.txt`. No production seam.+- **Saves:** ~26 s (weight 26,038 ms). **Risk:** low.++### 4. `test/e2e/v0_30_3-fix-wave.test.ts`: delete (MEDIUM confidence), dominated by schema-bootstrap-coverage+- **Tests:** "pre-v39 brain…", "pre-v40 brain…", "pre-v41 PGLite brain…", "pre-v34 brain (compounded…)". Each rewinds a LATEST PGLite brain by dropping columns and re-runs `initSchema`.+- **Mutation A** (dropped the `effective_date` ALTER from `applyForwardReferenceBootstrap`, `src/core/pglite-engine.ts`):+ - v0_30_3 fails 2 of 4.+ - `test/schema-bootstrap-coverage.test.ts` fails 3: "covers every forward reference declared in REQUIRED_BOOTSTRAP_COVERAGE", "after bootstrap, PGLITE_SCHEMA_SQL replays…", "every ALTER TABLE ADD COLUMN in MIGRATIONS is covered…".+ - `test/bootstrap.test.ts`: 0 fail.+- **Mutation B** (dropped the `modality` ALTER):+ - **v0_30_3: 4 pass**, so its "pre-v39 (missing modality…)" test does not detect the loss of the column it names.+ - schema-bootstrap-coverage fails 1.+- **Surviving owners:** `schema-bootstrap-coverage.test.ts` (every column v0_30_3 names is in `REQUIRED_BOOTSTRAP_COVERAGE`, lines ~90–118). Full-initSchema-from-old-shape is covered generically by `bootstrap.test.ts` "full path: pre-v0.18 brain reaches LATEST_VERSION via initSchema" and "pre-v121 timeline shape reaches LATEST through full initSchema". All PGLite.+- **Why MEDIUM:** v0_30_3 is the only test running this exact set of rewinds through the full `initSchema` + migration chain. Its unique value is the "compounded pre-v34" arc. Consider merging that one case into `bootstrap.test.ts`.+- **History:** ff53a4c9b (v0.31.1.1 fix-wave, #776).+- **Unlocks:** 201 LOC. **Saves:** 13,153 ms. **Risk:** low–med.+- **Sibling:** `test/e2e/v0_28_5-fix-wave.test.ts` (15,254 ms, 292 LOC) is the same pattern. Its A4 tests duplicate `test/embedding-dim-check.test.ts` "Postgres branch inlines all four recipe steps…" and "…skips HNSW recreate when requested dims exceed pgvector cap". Cluster A overlaps schema-bootstrap-coverage. Cluster B (dim templating at 768 / >2000) needs an owner check before removal. Not probed; secondary candidate.++### 5. `test/e2e/reconcile-crash.test.ts` + `reconcile-crash-unactivated.test.ts`: add to `E2E_EXCLUSIONS` (HIGH confidence, lane dedupe, no test deletion)+- **Tests:** "Postgres reconciliation survives SIGKILL/<boundary>, activation=true|false" over `CRASH_BOUNDARIES`.+- **Duplicate execution:** `persistence-validation.yml` (called from `test.yml` on every PR) already runs exactly these two files, by name, on postgres × Bun {1.3.11, 1.3.13} with pg16, and uploads crash manifests. The step is "Require all reconciliation crash boundaries before and after activation". The `selected-e2e` run is Bun 1.3.13 + pg16, which is **the same contract on the same boundary** as the persistence-validation postgres/1.3.13 arm. They are selected on any escape-hatch PR and through `e2e-test-map.ts:229,235,238`.+- **Action:** add both files to `E2E_EXCLUSIONS` (the "named-job lane" mechanism). That removes only the PR `selected-e2e` duplicate. Nightly `coverage-full-e2e` still runs them, so coverage artifacts and cadence are unchanged, per TESTING.md.+- **History:** b272cf234 (#5361, 2026-09-22) added the files and the persistence-validation step together.+- **Saves:** ~203 s per PR where selected (102,209 + 101,348 ms). **Risk:** low.+- **Validation:** `bun test test/scripts/*e2e-matrix*` (if pinned) and `bun scripts/select-e2e.ts | bun scripts/e2e-matrix.ts prepare`.++### 6. `test/e2e/minions-field-report-repro.test.ts`: keep, rewrite for a smaller workload (HIGH confidence it is the sole owner)+- **Test:** "v0.41 field-report repro > subagent batch under lease pressure completes; zero dead-from-lease-pressure".+- **Mutation probe:** I set `isLeaseFull = false && …` in `src/core/minions/worker.ts:1659`, which breaks the worker's lease-full routing.+ - This file **fails**.+ - `test/minions-lease-full-retry.test.ts` (7 pass), `test/e2e/minions-controller-bounce-only.test.ts` (2 pass), `test/job-isolation-protocol.test.ts` (22 pass) and `test/child-job-runner.test.ts` (15 pass) **all still pass**.+ - So this is the only worker-boundary owner. Retained.+- **Waste:** a fixed `await new Promise(r => setTimeout(r, 25_000))` with 12 jobs.+- **Action:** poll until all jobs settle (with a timeout), or use 2–3 jobs. Move to the unit/slow lane; it is PGLite-only.+- **Saves:** ~20+ s of 27,667 ms. **Risk:** low.++### 7. Never-executing live files: exclude from the e2e glob (MEDIUM; opt-in dev tools, not CI coverage)+- **Files:**+ - `openrouter-anthropic-subagent-replay.live.test.ts` (1,464 ms / 168 LOC)+ - `openrouter-deepseek-subagent-replay.live.test.ts` (1,913 / 168)+ - `voyage-rerank-live.test.ts` (297 / 132)+ - `voyage-multimodal.test.ts` (270 / 44)+- **Evidence:** no workflow provides `OPENROUTER_API_KEY` or `VOYAGE_API_KEY` (the only secrets are ANTHROPIC, OPENAI, XAI, TEMPLATE_REPO_PAT). The openrouter files still boot PGLite in `beforeAll` before skipping every test. The voyage files are excluded from `selected-e2e` but still hit by the nightly glob.+- **TESTING.md says** "a missing key … is not live-provider evidence". Keep them as documented opt-in commands, but rename or exclude them from `run-e2e.sh`'s glob so they stop counting as discovered coverage.+- **Saves:** ~3.9 s nightly. **Risk:** low.+- The 7 real-agent door files (≈3.9 s) are skip-only in e2e lanes by design (env scrub) and owned by `heavy-tests.yml`. Excluding them from the glob is optional.++## Category-level opportunity: lane misplacement (not deletions)+113 files / 30.5K LOC / 927 s never touch Postgres. Examples: `claw-test` 82 s, `mounts-routing-pglite` 45 s, `qm-provisioning` 40 s, `pglite-cli-exit.serial` 39 s, `init-fresh-pglite` 36 s, `fresh-install-pglite` 29 s, `remote-privacy-journeys` 24 s, `serve-stdio-roundtrip` 23 s, plus ~39 `*-pglite*` files.++In the e2e lane they occupy a Postgres-provisioned runner, execute strictly sequentially (`run-e2e.sh`), and run on PRs only when selected. Moving them to unit/serial/slow lanes (by suffix) would *increase* PR coverage and cut Postgres-lane wall time. Their tests are the sole owners in most cases, so this is re-homing, not reduction.++TODOS.md:6806 ("Non-tier-1 e2e files run in no required CI lane") is the same finding, and partly stale now that `selected-e2e` exists. Exceptions that must stay put:+- `sync-delegation-under-serve.serial` and `dream-synthesize-pglite`: dedicated tier1 steps.+- `db-guard.test.ts`: fine to move, but keep it.++## Retained false positives+- **22 Postgres wrappers** (491 s, 78 LOC; e.g. `persistence-embedding-effects`, `managed-connector-retry`, `projection-recovery-parity`, `google-attachments-postgres`). Tiny files, but each is the Postgres arm of a shared scenario gated by `requirePostgresTestDatabase` + `GBRAIN_TEST_BACKEND=postgres`. A PGLite pass doesn't establish JSONB, locking or pool behaviour (TESTING.md). Only the 3 attendance wrappers double-run (Candidate 2).+- **`db-guard.test.ts`** (332 ms): a pure unit test sitting in e2e, but the only direct truth table for `assertSafeE2eDatabaseUrl`, the destructive-DB safety guard. `db-guard-coverage.test.ts` tests the scanner, not the predicate. Security contract. Keep; lane-move it.+- **`persistence-runtime-matrix.test.ts`** (45 s weight): skip-only in GitHub e2e (no PgBouncer). Under `ci:local`/`ci:ubicloud` it is the local stand-in for persistence-validation's "Execute all 24 deployment cases", which ci:local does not otherwise run.+- **`minions-field-report-repro`**: the probe showed it is the sole worker-routing owner (shrink it, don't delete).+- **`minions-controller-bounce-only`**: covers `controllerTick` over populated audit/dead-job SQL windows. `lease-cap-controller.test.ts` covers the pure `nextLeaseCap` and only the empty-brain tick.+- **`claw-test`** (82 s): drives the real harness subprocess, oracles, phase-timeout kill and charset guard. `claw-test-cli.test.ts` covers only the registry, detection and argv. Process boundary. Keep (slow-lane candidate).+- **`sync-delegation-under-serve.serial`** (155 s), **`serve-http-multi-agent`**, **`postgres-bootstrap`**: process/IPC/SIGKILL/bootstrap boundaries with dedicated jobs.+- **Tier1 named files are also in the nightly glob**, so they run twice nightly. That is deliberate, for coverage LCOV, so no action.++## Est. savings if candidates 1–7 land+| # | Action | Test LOC removed | ms saved per run where it executes |+|---|---|---:|---:|+| 1 | delete mcp.test.ts | 70 | 1,201 |+| 2 | attendance wrappers → Postgres-only | ~0 | ~45,000 |+| 3 | delete v030_1 (move 2 asserts) | ~200 | ~26,000 |+| 4 | delete v0_30_3 (+ v0_28_5 follow-up) | 201 (+~292) | 13,153 (+15,254) |+| 5 | reconcile-crash → E2E_EXCLUSIONS | 0 | ~203,000 per selected PR |+| 6 | field-report poll instead of 25 s sleep | ~0 | ~20,000 |+| 7 | exclude never-run live files | 0 (rename) | ~3,900 nightly |+| | **Total (1–7, excl. v0_28_5)** | **~470** | **~312 s** (≈11% of e2e compute) |++Plus the category move of 927 s from the sequential Postgres lane to parallel unit/serial lanes.++Probes run (all reverted; `git status` clean): tool-defs mutation, worker lease-full routing, PGLite bootstrap effective_date / modality, upgrade-checkpoint resumeAt. Attendance arm timings came from a local `pgvector/pgvector:pg16` container, since removed. No full-suite runs.diff --git a/docs/test-audit/2026-09-29/lane-e2e/pglite-files.txt b/docs/test-audit/2026-09-29/lane-e2e/pglite-files.txtnew file mode 100644index 0000000000..3dd2dd7251--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-e2e/pglite-files.txt@@ -0,0 +1,113 @@+154568 257 test/e2e/sync-delegation-under-serve.serial.test.ts+82480 439 test/e2e/claw-test.test.ts+44757 291 test/e2e/mounts-routing-pglite.test.ts+40319 345 test/e2e/qm-provisioning.test.ts+35927 377 test/e2e/init-fresh-pglite.test.ts+29181 372 test/e2e/fresh-install-pglite.test.ts+27667 101 test/e2e/minions-field-report-repro.test.ts+26038 222 test/e2e/v030_1-integration-pglite.test.ts+24236 272 test/e2e/remote-privacy-journeys.test.ts+23374 354 test/e2e/serve-stdio-roundtrip.test.ts+18357 277 test/e2e/serve-http-surface-ceiling.test.ts+15254 292 test/e2e/v0_28_5-fix-wave.test.ts+14450 473 test/e2e/bootstrap-hook-under-serve.serial.test.ts+13153 201 test/e2e/v0_30_3-fix-wave.test.ts+12999 419 test/e2e/skillpack-flow.test.ts+12483 197 test/e2e/search-readiness-http.test.ts+12146 1262 test/e2e/dream-synthesize-pglite.test.ts+11278 238 test/e2e/connect-bearer.test.ts+10544 646 test/e2e/dream-synthesize-chunking.test.ts+10437 60 test/e2e/backfill-perf-pglite.test.ts+10390 300 test/e2e/bootstrap-harness-lifecycle.serial.test.ts+10048 443 test/e2e/upgrade-bun-link-arc.serial.test.ts+8510 497 test/e2e/bootstrap-lifecycle.serial.test.ts+7956 843 test/e2e/transcripts-ingest-pglite.test.ts+7921 204 test/e2e/fact-backfill-resident.test.ts+7693 61 test/e2e/non-tty-output.serial.test.ts+7636 243 test/e2e/skillpack-third-party.test.ts+7536 625 test/e2e/enrich-pglite.test.ts+7247 430 test/e2e/connectors-sync-pglite.test.ts+6818 174 test/e2e/orphan-reduction.test.ts+6124 219 test/e2e/serve-http-consent.test.ts+5931 302 test/e2e/graph-signals-eval.test.ts+5768 390 test/e2e/bootstrap-attach.serial.test.ts+5164 186 test/e2e/bootstrap-compiled-binary.serial.test.ts+5146 309 test/e2e/bootstrap-degraded-modes.serial.test.ts+5083 163 test/e2e/conversation-parser-pglite.test.ts+4965 287 test/e2e/source-isolation-pglite.test.ts+4771 259 test/e2e/bootstrap-magic-moment.serial.test.ts+4680 176 test/e2e/schema-cathedral.test.ts+4440 389 test/e2e/graph-quality.test.ts+4338 989 test/e2e/skillopt-loop.serial.test.ts+4269 536 test/e2e/code-indexing.test.ts+4161 466 test/e2e/system-of-record-invariant.test.ts+4124 125 test/e2e/self-upgrade-marker.test.ts+4103 126 test/e2e/transcripts-writeback-fidelity.test.ts+4097 334 test/e2e/ingestion-roundtrip.test.ts+3967 349 test/e2e/global-basename-pglite.test.ts+3927 443 test/e2e/skillopt-outcome.serial.test.ts+3912 303 test/e2e/contextual-retrieval-pglite.test.ts+3814 540 test/e2e/subagent-crash-replay-multi-provider.test.ts+3798 106 test/e2e/upgrade.test.ts+3772 254 test/e2e/dream-cycle-phase-order-pglite.test.ts+3757 726 test/e2e/subagent-gateway-path.test.ts+3738 195 test/e2e/frontmatter-migration.test.ts+3699 217 test/e2e/dream-patterns-pglite.test.ts+3606 344 test/e2e/multi-source-bug-class.test.ts+3382 396 test/e2e/code-intel-mcp-ops-pglite.test.ts+3283 154 test/e2e/quarantine-search-exclusion.test.ts+3262 159 test/e2e/dream-allow-list-pglite.test.ts+3246 138 test/e2e/salience-pglite.test.ts+3159 265 test/e2e/type-unification-full-flow.test.ts+3079 220 test/e2e/symbol-resolver-pglite.test.ts+2970 127 test/e2e/sync-credential-preflight.test.ts+2951 236 test/e2e/whoknows.test.ts+2886 105 test/e2e/anomalies-pglite.test.ts+2857 390 test/e2e/skillopt-models-strict.serial.test.ts+2833 478 test/e2e/brainstorm-resume.test.ts+2796 262 test/e2e/cache-gate-pglite.test.ts+2598 308 test/e2e/subagent-gateway-resume-reconciliation.test.ts+2406 208 test/e2e/status-pglite.test.ts+2354 329 test/e2e/compile-context-pglite.test.ts+2277 74 test/e2e/import-credential-preflight.test.ts+2212 236 test/e2e/skillopt-models-used.serial.test.ts+2139 111 test/e2e/cycle-recompute-emotional-weight-pglite.test.ts+2123 127 test/e2e/salience-anomalies-source-isolation-pglite.test.ts+2118 141 test/e2e/think-source-isolation-pglite.test.ts+2111 233 test/e2e/skillopt-pglite.serial.test.ts+2072 86 test/e2e/jobs-watch-readsnapshot.test.ts+2067 236 test/e2e/search-exclude.test.ts+2043 165 test/e2e/capture-generation-regression.test.ts+2035 181 test/e2e/onboard-full-flow.test.ts+2030 234 test/e2e/source-routing.test.ts+1973 79 test/e2e/doctor-connectors-pglite.test.ts+1952 275 test/e2e/eval-loop.test.ts+1931 98 test/e2e/cli-source-scoping-pglite.test.ts+1926 203 test/e2e/concurrent-embed-race.test.ts+1873 98 test/e2e/minions-controller-bounce-only.test.ts+1862 231 test/e2e/search-quality.test.ts+1861 149 test/e2e/search-swamp.test.ts+1820 126 test/e2e/minions-budget-cathedral.test.ts+1805 369 test/e2e/embedding-column-pglite.test.ts+1793 177 test/e2e/graph-signals-engine.test.ts+1774 322 test/e2e/sync-status-pglite.test.ts+1753 83 test/e2e/minions-prefix-strip-smoke.test.ts+1740 119 test/e2e/cjk-roundtrip.test.ts+1733 94 test/e2e/list-pages-regression.test.ts+1709 247 test/e2e/v0_29-mcp-dispatch-pglite.test.ts+1661 144 test/e2e/minions-self-fix-flow.test.ts+1560 84 test/e2e/connector-sync-handler-pglite.test.ts+1478 269 test/e2e/auth-takes-holders-pglite.test.ts+1437 114 test/e2e/multi-source-emotional-weight-pglite.test.ts+1436 115 test/e2e/eval-replay-column.test.ts+1365 254 test/e2e/bootstrap-persistence.serial.test.ts+1201 70 test/e2e/mcp.test.ts+1168 150 test/e2e/openclaw-reference-compat.test.ts+835 154 test/e2e/workspace-generic-compat.test.ts+825 168 test/e2e/openclaw-context-engine-plugin.test.ts+770 246 test/e2e/skill-brain-first.test.ts+750 95 test/e2e/sync-cjk-git.test.ts+521 266 test/e2e/self-upgrade-binary-swap.test.ts+427 241 test/e2e/cross-modal-eval.test.ts+332 65 test/e2e/db-guard.test.ts+320 186 test/e2e/salience-llm-routing.test.tsdiff --git a/docs/test-audit/2026-09-29/lane-patterns/neardup.txt b/docs/test-audit/2026-09-29/lane-patterns/neardup.txtnew file mode 100644index 0000000000..de86c6c5cc--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-patterns/neardup.txt@@ -0,0 +1,28 @@+0.89 41 test/e2e/openrouter-anthropic-subagent-replay.live.test.ts test/e2e/openrouter-deepseek-subagent-replay.live.test.ts+0.77 24 test/chronicle-timeline-reads.test.ts test/e2e/chronicle-last-seen-postgres.test.ts+0.77 23 test/facts-engine.test.ts test/e2e/facts-recall-event-time-postgres.test.ts+0.70 23 test/e2e/import-credential-preflight.test.ts test/e2e/sync-credential-preflight.test.ts+0.70 16 test/search-multimodal-no-embed.serial.test.ts test/unified-multimodal.serial.test.ts+0.62 24 test/delete-write-through-commit.serial.test.ts test/write-through-commit.serial.test.ts+0.57 34 test/sync-rename-reconcile.serial.test.ts test/e2e/sync-reconcile-postgres.test.ts+0.57 17 test/oauth-refresh-invalid-grant.test.ts test/oauth.test.ts+0.56 18 test/cycle-patterns-completed-outcome.serial.test.ts test/cycle-patterns-evidence-gate.serial.test.ts+0.56 47 test/links-timeline-jsonb-poison.test.ts test/e2e/jsonb-batch-poison-postgres.test.ts+0.55 16 test/extract-facts-embed-unavailable.serial.test.ts test/extract-facts-embed-warn.serial.test.ts+0.55 23 test/brain-repo-durability.serial.test.ts test/filing-rules-resolution.serial.test.ts+0.53 39 test/code-callers-pin.serial.test.ts test/code-def-refs-pin.serial.test.ts+0.53 17 test/cycle-start-recovery.test.ts test/jobs-worker-startup-recovery.test.ts+0.53 27 test/facts-separation-pglite.test.ts test/e2e/facts-separation-postgres.test.ts+0.50 24 test/hybrid-adaptive-dedup-cache-plane.serial.test.ts test/hybrid-types-cache-skip.serial.test.ts+0.50 15 test/oauth-dcr-ttl.test.ts test/oauth-refresh-invalid-grant.test.ts+0.49 18 test/e2e/vector-candidate-safety-postgres.test.ts test/search/vector-candidate-safety.test.ts+0.48 11 test/reindex-code-model-source.serial.test.ts test/reindex-code-nudge.serial.test.ts+0.46 25 test/migrate-embeddings-boundary.serial.test.ts test/migrate-embeddings-flow.serial.test.ts+0.45 10 test/subagent-handler.test.ts test/e2e/minions-prefix-strip-smoke.test.ts+0.45 17 test/checkpoint-harvest.serial.test.ts test/context-pack-wb-lane.serial.test.ts+0.43 10 test/cross-modal-hybrid-integration.serial.test.ts test/search-multimodal-no-embed.serial.test.ts+0.43 23 test/migrate-embeddings-boundary.serial.test.ts test/migrate-embeddings-hardening.serial.test.ts+0.42 22 test/context/resolve-ipc-sweep-kinds.test.ts test/context/resolve-ipc-sync-kinds.test.ts+0.41 21 test/hybrid-adaptive-dedup-cache-plane.serial.test.ts test/hybrid-cached-hit-budget-meta.serial.test.ts+0.41 29 test/e2e/claude-plugin-install-real.serial.test.ts test/e2e/codex-plugin-install-real.serial.test.ts+0.41 11 test/ai/recipe-dashscope-rerank.test.ts test/ai/recipe-nan.test.tsdiff --git a/docs/test-audit/2026-09-29/lane-patterns/patterns.md b/docs/test-audit/2026-09-29/lane-patterns/patterns.mdnew file mode 100644index 0000000000..0b3ad2efdc--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-patterns/patterns.md@@ -0,0 +1,169 @@+# Test audit — LANE=patterns (cross-cutting sweep over `test/**`)++Repo: garrytan/gbrain @ `2ede415` (v0.59.11.0). Read-only lane; no edits committed. All mutation+probes were reverted with `git checkout -- .`; `git status --short` was empty after every batch.++Method: openclaw `test-audit` skill (value bar, retention bar, candidate-evidence fields), gbrain+`AGENTS.md`/`docs/TESTING.md` "Coverage responsibilities before consolidation" (shared PGLite/Postgres+scenarios are NOT duplicate coverage; name a surviving owner for the same contract AND boundary).+Scanners: `~/.capy/work/test-audit/scan.py`, `scan2.py` (raw output `scan.json`, `scan2.json`,+`neardup.txt`); probe log `probes.log`. Cost = `scripts/ubicloud/weights.json` ms per file (per-file,+so a per-test deletion saves only a fraction of the file number; I say so where it matters).++History caveat: the checkout has only 50 commits; most test files trace to the squash/graft commit+`d9909cd` (v0.47.5.0, 2026-08-28), so `git log -S` cannot recover original intent before that.++Corpus: 2,644 `*.test.ts` files (357 serial, 20 slow, ~315 in `test/e2e`); weights cover 2,591 files.++---++## Top candidates (full evidence)++### C1. `test/regressions/v0.36.1.0-iron-rule.test.ts` — whole file (6 tests)+- **Tests:** R1 ×2 (`user message default path…`, `system prompt: no anti-bias section…`), R2 (`null profile → null tag…`),+ R3 (`deriveResolutionTuple operates without any grade_takes imports`), R4 (`this regression is covered by existing v0.34.1 source-isolation suite`),+ R5 (`this regression is covered by existing search-mode test suite`), `IRON RULE inventory > all 5 regressions have an addressed status`.+- **What it can detect:** R4, R5 are `expect(true).toBe(true)` with no production import → detect nothing.+ The inventory test asserts a local object literal contains the word `covered` → self-comparison, detects nothing.+ R3's comment claims it "will fail to compile" if takes-resolution couples to grade_takes — false; it just calls a pure function.+ R1/R2 are line-for-line copies of owner tests.+- **Probe A:** mutated `tagFindingWithCalibration` so a null profile returns a tag → BOTH+ `eval-contradictions-calibration-join.test.ts > tagFindingWithCalibration — R2 regression > null profile returns null tag` and the iron-rule R2 copy failed (18 pass / 2 fail). The copy adds no detection.+- **Surviving owners (same contract, same in-process boundary):**+ R1 → `test/think-with-calibration.test.ts` `withCalibration:false omits the anti-bias section (R1 regression guard)`, `withCalibration omitted entirely → same as false (R1)`, `without calibration: question first, then retrieval, then instruction (regression R1)` (stricter: also checks takes + instruction order).+ R2 → `test/eval-contradictions-calibration-join.test.ts` (probe-proven).+ R3 → `test/takes-resolution.test.ts` (`deriveResolutionTuple({quality:'correct'…})` toEqual full tuple) + `test/e2e/takes-postgres.test.ts`.+ R4/R5 → the file names `test/source-isolation-pglite.test.ts`, which **does not exist** (only `test/e2e/source-isolation-pglite.test.ts`); `test/search-mode.test.ts` exists.+- **Non-test callers of seams:** none needed (only public functions).+- **History:** introduced as a "D26 IRON RULE index" marker; traced to `d9909cd`.+- **Unlocks:** −156 test LOC, −1 unit file. **Cost:** 159 ms (unit).+- **Risk:** low. **Action:** delete. Validate: `bun test test/think-with-calibration.test.ts test/eval-contradictions-calibration-join.test.ts test/takes-resolution.test.ts`.++### C2. Migration `__testing` typeof probes + the dead exports they keep alive+- **Tests:** `phase functions exported for unit testing` in `test/migrations-v0_12_0.test.ts`, `test/migrations-v0_12_2.test.ts`,+ `test/migrations-v0_13_0.test.ts`, `test/migration-orchestrator-v0_21_0.test.ts`.+- **What it can detect:** only that an object property is a function. **Probe B1:** made v0_12_0 `phaseASchema` throw → the probe still passed (the real dry-run test failed instead).+ **Probe B2 (behavior-preserving):** un-exported `__testing` → the probe FAILED. It detects nothing behavioral and breaks on a no-op refactor: textbook implementation coupling.+- **Non-test callers of the seam:** none. `grep "__testing.phase|__testing.readStats"` shows zero callers for these four modules anywhere in `src/` or `test/` besides the typeof lines (other migration versions — v0_16_0, v0_22_4, v0_31_0, v0_32_2, v0_29_1 — do call their own `__testing` for real; not candidates).+- **Surviving owner:** each file's orchestrator tests (e.g. v0_12_0 `dry-run skips all side-effect phases`, proven by B1) plus `test/migration-resume.test.ts`.+- **Unlocks:** −4 tests (~30 test LOC) and **−27 production LOC** (four `export const __testing = {…}` blocks: 6+9+6+6 lines incl. doc comment) — net-negative prod.+- **Cost:** files are 262/286/245/239 ms; the probe itself is ~0 ms (savings are maintenance, not time).+- **Risk:** low. **Action:** delete tests + delete the four `__testing` exports.++### C3. typeof-export / "module can be imported" probes (≈36 tests in 18 files)+Pure probes whose every assertion is `typeof X === 'function'` or `toBeDefined()` on an import. An import failure or missing export+already fails `bun run typecheck` (tsconfig includes `src` and `test`) and every behavior test that calls the export.+| File | Test(s) | Surviving behavioral owner | File ms |+|---|---|---|---|+| test/features.test.ts | `exports runFeatures`, `exports featuresTeaserForDoctor`, **`covers all 7 recipes`** (asserts only `runFeatures` defined) | **NONE** — see gap below | 223 |+| test/enrichment-service.test.ts | 3× `module exports …`, `enrichment result includes tier fields` (asserts only `toBeDefined`) | test/e2e/extraction-review-postgres.test.ts calls `enrichEntity` | 202 |+| test/transcription.test.ts | `module exports transcribe function`, `TranscriptionResult interface shape`, `detects provider from env vars` (body: "We just verify the function is callable") | same file `rejects unsupported audio format`, `rejects missing API key…` (probe E) | 187 |+| test/doctor.test.ts | `doctor module exports runDoctor`, `LATEST_VERSION is importable from migrate`, `takesWeightGridCheck is exported as a pure function` | same file L636/664 call `takesWeightGridCheck(engine)`; doctor CLI tests | 8723 (file) |+| test/code-callers-cli.test.ts | `code-callers module exports runCodeCallers`, `code-callees module exports runCodeCallees` (whole file) | test/code-callers-pin.serial.test.ts, test/e2e/cli-source-scoping-pglite.test.ts | 191 |+| test/cycle-abort.test.ts | `signal field exists on CycleOpts interface` (asserts `typeof runCycle`; never touches `signal`) | same file `runCycle accepts signal in opts without error` | 480 |+| test/eval-whoknows.test.ts | `module exports WhoknowsFn type alias` (asserts `typeof runEvalWhoknows`) | same file `runEvalWhoknows accepts null engine…` | 297 |+| test/whoknows.test.ts | `public surface: rankCandidates / findExperts / runWhoknows are functions` | test/e2e/read-enrichment-privacy.test.ts `findExperts` | 241 |+| test/salience.test.ts | `computeAnomaliesFromBuckets is exported and pure` | test/anomalies.test.ts | 172 |+| test/extract.test.ts | `is a function` (walkMarkdownFiles) | test/sync-walker-submodule.test.ts, test/notability-eval.test.ts | 222 |+| test/migrate.test.ts | `runMigrations is exported and callable` | rest of migrate.test.ts | 8243 (file) |+| test/v0_37_fix_wave.serial.test.ts | `reinit-pglite module exports runReinitPglite` | test/v0_37_gap_fill.serial.test.ts calls `runReinitPglite` | 591 |+| test/ai/gateway-chat.test.ts | `chat() function is exported…`, `ChatBlock + ChatMessage + ChatResult types are exported` (`expect(mod).toBeDefined()`) | gateway chat behavior tests | 187 |+| test/e2e/mcp.test.ts | `MCP server module can be imported` (in the **E2E** lane) | rest of mcp.test.ts | e2e |+| test/operations-embedding-column.test.ts | 2× `exists` | subsequent tests in the same describes dereference the op | 719 |+| test/search/query-op-autocut.test.ts, query-op-adaptive-return.test.ts | `query op exists` | same files | 346/395 |+| test/helpers/agent-harness.unit.test.ts | `resolve*Binary returns a string or null`, `hasHermesAuth returns a boolean` (tautological unions) | none needed (helper smoke) | 448 |+- **Probe F (key finding):** made `runFeatures` throw at entry → `test/features.test.ts` + `test/features-recipe-secrets.test.ts` **19 pass / 0 fail**. `gbrain features` has no behavioral test at all; the three probes give false confidence (one is literally named "covers all 7 recipes").+- **Probe E:** `transcribe` throwing → the 3 typeof probes passed; the 2 real tests failed.+- **Unlocks:** ≈36 tests, ≈180–220 test LOC, one whole file (`code-callers-cli.test.ts`). ms: small (per-test ~0; whole-file deletion of code-callers-cli saves ~191 ms).+- **Risk:** low, except `features`: **action there = rewrite at boundary** (a real `runFeatures(engine, ['--json'])` PGLite test) before deleting the probes. Everywhere else: delete.++### C4. `test/v0_37_fix_wave.serial.test.ts` › `GBrainConfig type includes voyage_api_key field (TS compile guard)`+- **What it can detect:** nothing. The body never references `voyage_api_key` (it does `import(...).then(m => ({type: undefined}))` then `expect(true).toBe(true)`), so neither bun nor tsc can fail on it.+- **Probe C:** deleted `voyage_api_key?: string;` from `GBrainConfig` → test **1 pass / 0 fail**. `tsc --noEmit` reported 9 errors in `src/core/advisor/collect-setup-smells.ts`, `src/core/ai/provider-env.ts`, `src/core/config-db-merge.ts` and 3 real tests — i.e. the typecheck gate over real consumers is the owner.+- **Blame:** L248 test name `db56c778` 2026-09-24; body from `d9909cd`.+- **Unlocks:** −7 LOC. **Cost:** within 591 ms serial file (~0 for this test). **Risk:** low. **Action:** delete.++### C5. `test/schema-pack-manifest-v041_2.test.ts` › `AggregatorKind type union covers exactly the enum values`+- **Identity copier:** `type AggregatorKind = typeof AGGREGATOR_KINDS[number]` (src/core/schema-pack/manifest-v1.ts:200), so `const typed: AggregatorKind = k` for `k of AGGREGATOR_KINDS` is a tautology and `typeof typed === 'string'` is always true.+- **Probe D:** renamed `count_based` → `exposes exactly 4 v1 aggregator kinds` and `accepts all 4 aggregator kinds` failed; the tautology test passed.+- **Owner:** the two tests above in the same file. **Unlocks:** −7 LOC. **Risk:** low. **Action:** delete.++### C6. `test/e2e/mechanical.test.ts` › `describeE2E('E2E: Performance Baselines')` › `import + search + link performance`+- **What it can detect:** only a thrown error from import/search/add_link; it computes p50/p99 and **only `console.log`s** them — no thresholds, no expects.+- **Owner:** the 22 other describes in the same file exercise import, search, add_link and get_backlinks on the same Postgres boundary with assertions (the file is the `e2e.yml` L266 named job).+- **Cost:** file 60,319 ms over 23 describes, each with its own `setupDB()` → **~2.6 s est.** per describe (estimate; not measured — needs Postgres). This one pays a full `setupDB` + 13-fixture import for zero assertions.+- **Unlocks:** −33 LOC, ~2.6 s off a named PR-critical E2E job. **Risk:** low. **Action:** delete (or, if baselines matter, move to a bench script — `test/e2e/bench-vs-openclaw/` already exists).++### C7. Exact cross-file duplicate test bodies+- `test/link-extraction-relative-path.test.ts` › `flat layout unchanged: verb inference still fires on the resolved slug` is byte-identical to+ `test/link-extraction-dir-whitelist-2576.test.ts` › `verb inference works for non-whitelisted dirs (typed edge, not just mentions)` (same input, same asserts, same pure boundary). Delete one (−9 LOC). Risk low.+- `test/e2e/schema-cathedral.test.ts` › `v0.39 T22d — artifact-type routing` (2 tests: `detectArtifactKind dispatches by extension`, `validateManifestByKind rejects cross-kind manifests`) duplicate pure-function assertions in `test/artifact-abstraction.test.ts` (`detectArtifactKind by extension`, and the cross-kind `toThrow(/api_version/)` cases at L38/42). They sit in an E2E-lane file (4,680 ms) that deliberately cold-builds the PGLite schema, but these two never touch the engine. Delete the describe (−12 LOC). Risk low.++### C8. `test/e2e/openrouter-{anthropic,deepseek}-subagent-replay.live.test.ts` — one-parameter clone pair+- `diff` shows the files differ **only** in comments, `MODEL`, and the describe name (168 LOC each, 0.89 line-overlap).+- Gate: `OPENROUTER_API_KEY`; **no workflow sets it** (grep of `.github/workflows`), so CI only ever sees skips, yet the E2E lane charges 1,464 + 1,913 ms for two skip-only files.+- **Action:** merge into one table-driven file over `[MODEL…]` (−~165 LOC, −1 E2E file slot ≈1.5 s). Keep the live contract (it is the opt-in live-provider owner per TESTING.md). Risk low.++### C9. Unconditionally skipped tests that no longer execute anywhere+- `test/e2e/sync-lock-recovery.test.ts` › `pipe through \`head -5\` exits cleanly, next sync runs without lock-busy` — `test.skip` since "v0.41.7+ follow-up" (36 LOC). Its comment defers to `test/process-cleanup.test.ts`, whose header in turn cites **`E2E sync-pipe-sigpipe.test.ts` — which does not exist**. So the SIGPIPE→lock-release path has no real-process owner; only the unit registry test. **Action:** rewrite deterministically or delete and fix the stale reference; do not count it as coverage. Risk **med** (real gap either way).+- `test/e2e/skillpack-third-party.test.ts` › `search returns the local fixture; info shows full details` — `test.skip` (~73 LOC); comment names the owner `test/skillpack-registry-client.test.ts` (exists; 25 `fetchImpl` uses). **Action:** delete. Risk low.++### C10. No-op tests with no production reference+- `test/e2e/cjk-roundtrip.test.ts` › `vector path skip-gracefully without OPENAI_API_KEY`: logs a line if the key is missing, then `expect(true).toBe(true)` unconditionally; imports nothing. Delete (−10 LOC). Risk low.++---++## Category counts (raw scanner hit → confirmed low-value after reading)++| Pattern | Raw hits | Confirmed candidates | Examples |+|---|---|---|---|+| Assertion-free tests (no expect/assert/throw in body) | 208 tests | **2** (mechanical perf, cjk vector no-op) | 190+ are helper-delegated (`expectCode`, `expectUsageExit`, `exerciseX(engine…)` shared scenarios) or no-throw contracts |+| Files with zero `expect` | 46 | **0** | all delegate to `test/helpers/*` scenarios (PGLite + Postgres arms) — retained |+| `expect(true)`/`expect(1)` trivial asserts | 28 sites / 16 tests | **5** (iron-rule R4, R5; v0_37 TS guard; cjk vector; plus 2 E2E "skipped" placeholder markers — harmless) | 13 `expect(1).toBe(1)` sites are fixture strings inside lint/runner tests |+| Self-comparison / identity copier | 1 inventory self-check + 1 type tautology | **2** (iron-rule inventory; AggregatorKind) | |+| typeof-export-is-function / "module imports" probes | 78 typeof sites; 122 "typeof/defined-only" tests | **≈36 tests / 18 files** (+4 `__testing` exports) | C2, C3 |+| Copied inventories / restated constants (`expect(CONST).toEqual([...literal])`) | 32 | **1 delete** (AggregatorKind), 2–3 weak change-detectors (see below); rest retained | |+| Tests of mocks | 0 (no mock-return-then-assert; no test mocks its own module-under-test among 70 `mock.module` files) | **0** | |+| Exact duplicate bodies across files | 6 groups | **2** (C7) + 1 clone pair (C8); 3 are PGLite↔Postgres parity (retained) | |+| Near-duplicate files (≥40% line overlap) | 28 pairs | **1** (openrouter pair); ~10 are PGLite/Postgres parity, rest share setup boilerplate but test different contracts | `neardup.txt` |+| Version-stamped files (`*v0_xx*`, `*-regression*`) | 45 files | **1** (iron-rule); migrations-v* are the migration contract (retained) | |+| Unconditional `test.skip` | 14 literal sites | **2** executable-but-skipped (C9); 9 are else-branch visibility markers; 3 are fixture strings | |+| Env-gated with no CI job setting the gate | 7 gates / 8 files | **move-lane**, not delete | below |++Orphan opt-in gates (skip-only in every CI lane; per TESTING.md a skip is not evidence): `GBRAIN_TRIAGE_CALIBRATION_LIVE` (test/cycle-synthesize-triage-calibration.test.ts, 339 ms), `GBRAIN_TEST_SHARED_SKILLS_BENCHMARK` (test/shared-skills-catalog-performance.test.ts, 385 ms), `GBRAIN_TEST_PACKAGE_SMOKE` (test/e2e/postgres-driver-install.test.ts, 306 ms, 1 day old), `VOYAGE_API_KEY` (test/e2e/voyage-multimodal.test.ts, 270 ms), `OPENROUTER_API_KEY` (2 files, 3,377 ms), `GBRAIN_SELFUPDATE_COMPILE_SMOKE` (test/binary-self-update-compiled.serial.test.ts, 345 ms; owned by `bun run test:compile-smoke`, not in any workflow). ≈5.0 s of lane time for zero executed assertions. Recommendation: exclude `*.live.test.ts`/opt-in files from CI discovery or give them a named opt-in job; do not delete (they are the live-provider owners).++---++## Retained false positives (looked low-value, are the independent contract)++- **Shared-scenario file pairs** (`test/managed-*.test.ts` ↔ `test/e2e/managed-*.test.ts`, `persistence-*`, `facts-separation-pglite` ↔ `facts-separation-postgres`, `links-timeline-jsonb-poison` ↔ `e2e/jsonb-batch-poison-postgres`, `list-all-sources` ↔ `e2e/list-all-sources-postgres`, `chronicle-timeline-reads` ↔ `e2e/chronicle-last-seen-postgres`, `sync-rename-reconcile` ↔ `e2e/sync-reconcile-postgres`, `vector-candidate-safety`): same helper, different engine boundary (JSONB, locking, pooler). TESTING.md rule: not duplicate coverage.+- **`test/operation-context-sourceid-required.test.ts`** (`expect(true)` tests): the assertion is `// @ts-expect-error`, enforced by `bun run typecheck` in `verify` (tsconfig includes `test`). Independent type contract.+- **No-throw tests on empty/idempotent inputs** (`extract-stale` `markPagesExtractedBatch: empty input is a no-op`, `storage` `delete is idempotent`, `pglite-engine` `skipExistenceCheck=true: silent no-op`, `oauth` `revoking already-revoked token is a no-op`, `migrations-v0_27_1` idempotent): credible regression (empty-array SQL, double-delete). Optional tightening: `seed-pglite.serial` `creates parent directories when needed` could assert `existsSync` instead of `expect(true)`.+- **`test/e2e/sync-credential-preflight.test.ts` early return** when `sync-failures.jsonl` is absent: absence is the correct post-fix outcome, not a skip.+- **`test/e2e/graph-signals-eval.test.ts` Gate 1** ends in `expect(true)` but gates via `throw` above it.+- **`test/e2e/jsonb-roundtrip.test.ts` source grep** for `${JSON.stringify(x)}::jsonb`: cheapest independent guard for a known Postgres JSONB double-encode bug class.+- **Restated constants that are wire/security/prompt contracts:** `ALLOWED_SCOPES_LIST` (scope.test.ts, wire drift), `GIT_SSRF_FLAGS` (security), `SOURCE_TIER_NAMES` order, `JUDGE_ERROR_CLASSES` closed vocabulary, `RUBRIC_DIMENSIONS` (LLM JSON schema/prompt), `AGGREGATOR_KINDS` (manifest public API), migration column sets (v94/v126), `Object.keys(...)` envelope shapes (regression-v0_16_4, get-agent-job trimmed keys = privacy), `envelope-to-gbrain` frontmatter-injection key sets (security), `PHASES` vs `BOOTSTRAP_PHASE_IDS` (two constants in lockstep). Weak change-detectors I would *not* prioritize: `CJK_CLAUSE_DELIMITERS covers ;:,、`, `LINKABLE_ENTITY_TYPES exposes the hardcoded contract`, `AGENT_IDS exposes the five supported agents`.+- **Else-branch `test.skip('… requires PostgreSQL')` markers** (persistence-*-parity, storage-tiering, unsupported-embedding-identity, voyage): visibility only, zero cost; keep.+- **Migration version-stamped files** (`migrations-v0_*`, `migrations-v1xx`): each owns one migration's contract.++---++## Sizing++| Bucket | Tests | Test LOC | Prod LOC | CI ms |+|---|---|---|---|---|+| C1 iron-rule file | 6 | 156 | 0 | 159 |+| C2 migration `__testing` probes | 4 | ~30 | −27 | ~0 |+| C3 typeof probes (excl. features until rewritten) | ~33 | ~170 | 0 | ~191 (whole code-callers-cli file) + ~0 |+| C4 + C5 + C10 no-op/tautology | 3 | ~24 | 0 | ~0 |+| C6 mechanical perf describe | 1 | 33 | 0 | ~2,600 (est., Postgres E2E) |+| C7 exact duplicates | 3 | ~21 | 0 | ~0 |+| C8 openrouter merge | (merge) | ~165 | 0 | ~1,500 (one skip-only E2E file) |+| C9 dead skipped tests | 2 | ~109 | 0 | 0 (already skipped) |+| **Total (delete/merge)** | **~52** | **~710** | **−27** | **~4.5 s** |+| Move-lane (orphan opt-in gates) | 8 files | 0 | 0 | ~5.0 s of skip-only slots (overlaps C8 by 3.4 s) |++Bottom line: the pattern sweep finds a modest, high-confidence batch (~700 test LOC, ~27 prod LOC, a few seconds of+CI) rather than a large one — gbrain's "zero-expect" and "duplicate" files are overwhelmingly deliberate shared-scenario+engine parity. The most valuable finding is not a deletion: `gbrain features` has no behavioral test (probe F), and+the SIGPIPE lock-release path points at a nonexistent E2E owner (C9).diff --git a/docs/test-audit/2026-09-29/lane-patterns/probes.log b/docs/test-audit/2026-09-29/lane-patterns/probes.lognew file mode 100644index 0000000000..972fb84307--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-patterns/probes.log@@ -0,0 +1,57 @@+### A calibration-join: null profile returns non-null+ src/core/eval-contradictions/calibration-join.ts | 2 +-+ 1 file changed, 1 insertion(+), 1 deletion(-)+error: expect(received).toBeNull()+(fail) tagFindingWithCalibration — R2 regression > null profile returns null tag (contradictions output unchanged) [4.39ms]+error: expect(received).toBeNull()+(fail) R2: contradictions probe UNCHANGED when no calibration profile > null profile → null tag (output byte-identical to v0.32.6) [0.10ms]+ 18 pass+ 2 fail+### B1 v0_12_0 phaseASchema throws+ src/commands/migrations/v0_12_0.ts | 2 +-+ 1 file changed, 1 insertion(+), 1 deletion(-)+async function phaseASchema(opts: OrchestratorOpts): Promise<OrchestratorPhaseResult> { throw new Error("PROBE");+error: PROBE+(fail) v0.12.0 — Knowledge Graph auto-wire migration > dry-run skips all side-effect phases [0.61ms]+ 4 pass+ 1 fail+### B2 v0_12_0 remove __testing export (behavior-preserving)+ src/commands/migrations/v0_12_0.ts | 2 +-+ 1 file changed, 1 insertion(+), 1 deletion(-)+(fail) v0.12.0 — Knowledge Graph auto-wire migration > phase functions exported for unit testing [0.17ms]+ 4 pass+ 1 fail+### C remove voyage_api_key from GBrainConfig+- voyage_api_key?: string;+ 1 pass+ 0 fail+tsc errors: 9+src/core/advisor/collect-setup-smells.ts+src/core/ai/provider-env.ts+src/core/config-db-merge.ts+test/brain-score-recommendations.test.ts+test/config-db-merge.test.ts+test/provider-env.test.ts+### D rename AGGREGATOR_KINDS member+ src/core/schema-pack/manifest-v1.ts | 2 +-+ 1 file changed, 1 insertion(+), 1 deletion(-)+error: expect(received).toEqual(expected)+(fail) v0.41 T3: AggregatorKind closed registry > exposes exactly 4 v1 aggregator kinds [0.82ms]+(fail) v0.41 T3: SchemaPackManifestSchema calibration_domains field > accepts all 4 aggregator kinds [0.46ms]+ 18 pass+ 2 fail+### E transcribe throws+ src/core/transcription.ts | 2 +-+ 1 file changed, 1 insertion(+), 1 deletion(-)+error: expect(received).toContain(expected)+(fail) transcription > rejects unsupported audio format [0.71ms]+error: expect(received).toContain(expected)+(fail) transcription > rejects missing API key with helpful error [0.75ms]+ 4 pass+ 2 fail+### F runFeatures throws+ src/commands/features.ts | 2 +-+ 1 file changed, 1 insertion(+), 1 deletion(-)+ 19 pass+ 0 fail+clean-check donediff --git a/docs/test-audit/2026-09-29/lane-patterns/scan.json b/docs/test-audit/2026-09-29/lane-patterns/scan.jsonnew file mode 100644index 0000000000..a60c4c119d--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-patterns/scan.json@@ -0,0 +1,2387 @@+{+ "not_toThrow": [+ [+ "test/core/budget/budget-tracker.test.ts",+ 19+ ],+ [+ "test/sources-mcp.test.ts",+ 18+ ],+ [+ "test/file-upload-security.test.ts",+ 14+ ],+ [+ "test/ai/gateway-chat.test.ts",+ 13+ ],+ [+ "test/ingestion/test-harness.test.ts",+ 9+ ],+ [+ "test/skillpack-manifest-v1.test.ts",+ 6+ ],+ [+ "test/sync-json-stdout-clean.test.ts",+ 6+ ],+ [+ "test/jobs-child-readiness.serial.test.ts",+ 5+ ],+ [+ "test/skillpack-registry-schema.test.ts",+ 5+ ],+ [+ "test/e2e/multi-source-bug-class.test.ts",+ 5+ ],+ [+ "test/search/embedding-column.serial.test.ts",+ 5+ ],+ [+ "test/progress.test.ts",+ 4+ ],+ [+ "test/ai/recipe-openrouter.test.ts",+ 4+ ],+ [+ "test/budget/free-local-chat-pricing.test.ts",+ 4+ ],+ [+ "test/auth-register-client-args.test.ts",+ 3+ ]+ ],+ "expect_true_any": [+ [+ "test/backoff.test.ts",+ "concurrent process limit blocks when exceeded"+ ],+ [+ "test/backoff.test.ts",+ "complete decrements active process count"+ ],+ [+ "test/extract-stale.test.ts",+ "markPagesExtractedBatch: empty input is a no-op"+ ],+ [+ "test/operation-context-sourceid-required.test.ts",+ "omitting sourceId from an OperationContext literal is a type error"+ ],+ [+ "test/operation-context-sourceid-required.test.ts",+ "passing undefined for sourceId is a type error"+ ],+ [+ "test/real-home-guard-preload.test.ts",+ "detects writes to ${path} without blaming subsequent tests"+ ],+ [+ "test/seed-pglite.serial.test.ts",+ "creates parent directories when needed"+ ],+ [+ "test/v0_37_fix_wave.serial.test.ts",+ "GBrainConfig type includes voyage_api_key field (TS compile guard)"+ ],+ [+ "test/core/background-work.test.ts",+ "empty registry (no test drainers) resolves fast"+ ],+ [+ "test/e2e/cjk-roundtrip.test.ts",+ "vector path skip-gracefully without OPENAI_API_KEY"+ ],+ [+ "test/e2e/embedding-column-postgres.test.ts",+ "skipped"+ ],+ [+ "test/e2e/graph-signals-eval.test.ts",+ "Gate 1 (QUALITY): no statistically significant regression in wrong direction"+ ],+ [+ "test/e2e/sync-credential-preflight.test.ts",+ "does NOT write 565 identical entries to sync-failures.jsonl"+ ],+ [+ "test/e2e/upsert-chunks-registry-column.test.ts",+ "skipped"+ ],+ [+ "test/regressions/v0.36.1.0-iron-rule.test.ts",+ "this regression is covered by existing v0.34.1 source-isolation suite"+ ],+ [+ "test/regressions/v0.36.1.0-iron-rule.test.ts",+ "this regression is covered by existing search-mode test suite"+ ]+ ],+ "self_compare": [+ [+ "test/backoff.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/backoff.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/backoff.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/extract-stale.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/operation-context-sourceid-required.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/operation-context-sourceid-required.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/real-home-guard-preload.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/seed-pglite.serial.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/skillpack-rubric-doctor.test.ts",+ "expect(1).toBe(1)"+ ],+ [+ "test/skillpack-rubric-doctor.test.ts",+ "expect(1).toBe(1)"+ ],+ [+ "test/v0_37_fix_wave.serial.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/core/background-work.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/e2e/cjk-roundtrip.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/e2e/embedding-column-postgres.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/e2e/graph-signals-eval.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/e2e/sync-credential-preflight.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/e2e/upsert-chunks-registry-column.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/regressions/v0.36.1.0-iron-rule.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/regressions/v0.36.1.0-iron-rule.test.ts",+ "expect(true).toBe(true)"+ ],+ [+ "test/scripts/check-test-isolation.test.ts",+ "expect(1).toBe(1)"+ ],+ [+ "test/scripts/check-test-isolation.test.ts",+ "expect(1).toBe(1)"+ ],+ [+ "test/scripts/check-test-isolation.test.ts",+ "expect(1).toBe(1)"+ ],+ [+ "test/scripts/classify-tests.test.ts",+ "expect(1).toBe(1)"+ ],+ [+ "test/scripts/classify-tests.test.ts",+ "expect(1).toBe(1)"+ ],+ [+ "test/scripts/e2e-runner.test.ts",+ "expect(1).toBe(1)"+ ],+ [+ "test/scripts/e2e-runner.test.ts",+ "expect(1).toBe(1)"+ ],+ [+ "test/scripts/run-serial-pool.test.ts",+ "expect(1).toBe(1)"+ ],+ [+ "test/scripts/run-unit-parallel.test.ts",+ "expect(1).toBe(1)"+ ]+ ],+ "test_no_assert": [+ [+ "test/bootstrap-interview.serial.test.ts",+ "newer state version \u2192 typed error naming the upgrade path",+ 6,+ [+ "expectErr",+ "interviewStatePath",+ "makeWs",+ "mkdirSync",+ "readInterviewState",+ "stringify",+ "writeFileSync"+ ]+ ],+ [+ "test/bootstrap-interview.serial.test.ts",+ "unknown key \u2192 typed error",+ 4,+ [+ "expectErr",+ "makeWs",+ "setAnswer"+ ]+ ],+ [+ "test/bootstrap-uninstall.serial.test.ts",+ "missing home entirely \u2192 NO_RECEIPT refusal",+ 3,+ [+ "expectRefusal",+ "uninstallWorkspace"+ ]+ ],+ [+ "test/bootstrap-uninstall.serial.test.ts",+ "GBRAIN_HOME + homeExplicit but home outside the workspace \u2192 HOME_GUARD",+ 5,+ [+ "expectRefusal",+ "seedHome",+ "uninstallWorkspace"+ ]+ ],+ [+ "test/bootstrap-uninstall.serial.test.ts",+ "GBRAIN_HOME + homeExplicit but missing gbrain-home signature \u2192 HOME_GUARD",+ 18,+ [+ "expectRefusal",+ "mkdirSync",+ "uninstallWorkspace",+ "writeReceipt"+ ]+ ],+ [+ "test/candidate-audit.test.ts",+ "best-effort: unwritable audit dir warns but does not throw",+ 10,+ [+ "logCandidate",+ "withEnv",+ "writeFileSync"+ ]+ ],+ [+ "test/child-worker-supervisor.test.ts",+ "settles the run loop instead of hanging, and counts each failure as a crash",+ 1,+ []+ ],+ [+ "test/company-brain-policy.test.ts",+ "malformed or valid changed policy never broadens the approved one-page selection after plan GC",+ 1,+ []+ ],+ [+ "test/company-brain-policy.test.ts",+ "explicit federation preserves keyless import approval and cannot enqueue automatic enrichment",+ 3,+ []+ ],+ [+ "test/company-brain-policy.test.ts",+ "old extractor approval refuses same-commit, changed-commit, and full sync without a new receipt",+ 1,+ []+ ],+ [+ "test/company-brain-policy.test.ts",+ "preview replays only the exact prior request, source incarnation, principal, repository and approval",+ 1,+ []+ ],+ [+ "test/company-brain-runtime.test.ts",+ "admission is local-only, atomic and replayable without repository or host schema edits",+ 1,+ []+ ],+ [+ "test/company-brain-runtime.test.ts",+ "connect verifies content and ownership, preserves history, and ordinary sync reconciles new targets",+ 1,+ []+ ],+ [+ "test/company-brain-runtime.test.ts",+ "graph failure retains real cursors beyond GC and zero-diff resume completes only missing phases",+ 1,+ []+ ],+ [+ "test/company-brain-runtime.test.ts",+ "interrupted content reads the approved commit after detached HEAD and missing working files",+ 1,+ []+ ],+ [+ "test/company-brain-runtime.test.ts",+ "verification catches missing explicit edges and repairs them on zero-diff retry",+ 1,+ []+ ],+ [+ "test/company-brain-runtime.test.ts",+ "same-source frontmatter reattribution cannot cross the completion fence",+ 1,+ []+ ],+ [+ "test/company-brain-runtime.test.ts",+ "canonical tag overlays refuse source writeback instead of changing approved bytes",+ 1,+ []+ ],+ [+ "test/company-brain-runtime.test.ts",+ "private audience and incompatible destination schema never register a source",+ 1,+ []+ ],+ [+ "test/company-brain-runtime.test.ts",+ "unchanged origins gain newly resolvable edges and lose edges after target retyping or deletion",+ 1,+ []+ ],+ [+ "test/contextual-synopsis-model.serial.test.ts",+ "handler registers canonical native synopsis model before service gateway chat",+ 6,+ [+ "expectHandlerRegistersNativeSynopsisRoute"+ ]+ ],+ [+ "test/contextual-synopsis-model.serial.test.ts",+ "handler registers deprecated native synopsis model before service gateway chat",+ 6,+ [+ "expectHandlerRegistersNativeSynopsisRoute"+ ]+ ],+ [+ "test/contextual-synopsis-model.serial.test.ts",+ "handler registers env native synopsis model before service gateway chat",+ 5,+ [+ "expectHandlerRegistersNativeSynopsisRoute"+ ]+ ],+ [+ "test/creds-relay-client.test.ts",+ "a malformed (non-conformant) response \u2192 relay_unreachable",+ 8,+ [+ "createSession",+ "expectCode",+ "json"+ ]+ ],+ [+ "test/creds-relay-client.test.ts",+ "an expired/unknown session \u2192 relay_session_expired (404)",+ 8,+ [+ "expectCode",+ "instantSleep",+ "pollClaim",+ "relay"+ ]+ ],+ [+ "test/creds-relay-client.test.ts",+ "a network-refused base URL \u2192 relay_unreachable",+ 15,+ [+ "Response",+ "expectCode",+ "instantSleep",+ "pollClaim",+ "serve",+ "stop"+ ]+ ],+ [+ "test/creds-relay-client.test.ts",+ "200 with a malformed claim body \u2192 relay_unreachable (fail closed, no partial claim)",+ 14,+ [+ "expectCode",+ "instantSleep",+ "json",+ "pollClaim"+ ]+ ],+ [+ "test/creds-relay-client.test.ts",+ "401 from the relay \u2192 invalid_grant_revoked",+ 4,+ [+ "expectCode",+ "refreshViaRelay",+ "relay",+ "relayEntry"+ ]+ ],+ [+ "test/cycle-pack-gating.test.ts",+ "only extract_atoms + synthesize_concepts dispatch sites reference packDeclaresPhase",+ 6,+ [+ "exec",+ "match"+ ]+ ],+ [+ "test/detached-stderr.test.ts",+ "closeDetachedStderrSink is idempotent and ignore-safe",+ 6,+ [+ "closeDetachedStderrSink",+ "openDetachedStderrSink"+ ]+ ],+ [+ "test/embed-backfill-submit.test.ts",+ "allows re-submission after cooldown elapses",+ 15,+ [+ "MinionQueue",+ "NOW",+ "add",+ "executeRaw",+ "expectStatus",+ "submitWithWorker"+ ]+ ],+ [+ "test/embed-backfill-submit.test.ts",+ "config-overridable cooldown (via embed.backfill_cooldown_min)",+ 12,+ [+ "MinionQueue",+ "NOW",+ "add",+ "executeRaw",+ "expectStatus",+ "setConfig",+ "submitWithWorker"+ ]+ ],+ [+ "test/embed-backfill-submit.test.ts",+ "admits when spend24hFn returns < cap",+ 8,+ [+ "expectStatus",+ "submitWithWorker"+ ]+ ],+ [+ "test/embed-backfill-submit.test.ts",+ "cap \"off\" \u2192 submits even at huge spend (Infinity cap never tripped)",+ 8,+ [+ "expectStatus",+ "setConfig",+ "submitWithWorker"+ ]+ ],+ [+ "test/embed-backfill-submit.test.ts",+ "tokenmax does NOT bypass the cooldown (axis split \u2014 churn protection stays)",+ 15,+ [+ "MinionQueue",+ "NOW",+ "add",+ "executeRaw",+ "expectStatus",+ "submitWithWorker"+ ]+ ],+ [+ "test/embed-backfill-submit.test.ts",+ "cooldown is per-source, not global",+ 12,+ [+ "CONFLICT",+ "MinionQueue",+ "VALUES",+ "add",+ "executeRaw",+ "expectStatus",+ "sources",+ "submitWithWorker"+ ]+ ],+ [+ "test/eval-prune.test.ts",+ "accepts multiple duration units",+ 6,+ [+ "runEvalPrune",+ "withSilencedStdout"+ ]+ ],+ [+ "test/file-upload-remote-default.test.ts",+ "remote: true takes the same strict path (undefined \u2261 untrusted, not a third mode)",+ 6,+ [+ "ctxWithRemote",+ "expectInvalidParams",+ "handler"+ ]+ ],+ [+ "test/file-upload-remote-default.test.ts",+ "final-component symlink is rejected in BOTH modes \u2014 loose mode relaxes confinement only",+ 16,+ [+ "ctxWithRemote",+ "expectInvalidParams",+ "handler",+ "rmSync",+ "symlinkSync"+ ]+ ],+ [+ "test/google-auth.test.ts",+ "rejects a Web-application client with client_json_wrong_type",+ 9,+ [+ "expectCodeSync",+ "parseClientJson",+ "stringify"+ ]+ ],+ [+ "test/google-auth.test.ts",+ "rejects garbage with client_json_unreadable",+ 3,+ [+ "expectCodeSync",+ "parseClientJson"+ ]+ ],+ [+ "test/google-auth.test.ts",+ "rejects a missing client_id with client_json_unreadable",+ 6,+ [+ "expectCodeSync",+ "parseClientJson",+ "stringify"+ ]+ ],+ [+ "test/google-auth.test.ts",+ "rejects bad shapes with client_shape_invalid",+ 5,+ [+ "expectCodeSync",+ "validateClientPair"+ ]+ ],+ [+ "test/google-auth.test.ts",+ "200 WITHOUT a refresh_token \u2192 no_refresh_token",+ 4,+ [+ "exchangeCode",+ "expectCode",+ "fakeFetch",+ "jsonResponse"+ ]+ ],+ [+ "test/google-auth.test.ts",+ "400 invalid_grant with a Date header skewed >60s \u2192 invalid_grant_clock_skew",+ 5,+ [+ "Date",+ "exchangeCode",+ "expectCode",+ "fakeFetch",+ "jsonResponse",+ "now",+ "toUTCString"+ ]+ ],+ [+ "test/google-auth.test.ts",+ "400 invalid_grant with an accurate Date header \u2192 code_reused",+ 5,+ [+ "Date",+ "exchangeCode",+ "expectCode",+ "fakeFetch",+ "jsonResponse",+ "toUTCString"+ ]+ ],+ [+ "test/google-auth.test.ts",+ "401 invalid_client \u2192 invalid_client",+ 4,+ [+ "exchangeCode",+ "expectCode",+ "fakeFetch",+ "jsonResponse"+ ]+ ],+ [+ "test/google-auth.test.ts",+ "7 days stale + consent_publish_state unknown \u2192 invalid_grant_testing_expiry",+ 9,+ [+ "expectCode",+ "invalidGrant",+ "makeEntry",+ "refreshAccessToken"+ ]+ ],+ [+ "test/google-auth.test.ts",+ "7 days stale but consent_publish_state production \u2192 invalid_grant_revoked",+ 13,+ [+ "expectCode",+ "invalidGrant",+ "makeEntry",+ "refreshAccessToken"+ ]+ ],+ [+ "test/google-auth.test.ts",+ "fresh proof-of-life (1 day ago) \u2192 invalid_grant_revoked even in unknown state",+ 9,+ [+ "expectCode",+ "invalidGrant",+ "makeEntry",+ "refreshAccessToken"+ ]+ ],+ [+ "test/google-auth.test.ts",+ "unknown credential id \u2192 not_connected",+ 4,+ [+ "GoogleTokenProvider",+ "MemoryVault",+ "expectCode",+ "fakeFetch",+ "getAccessToken"+ ]+ ],+ [+ "test/google-redirect.test.ts",+ "the consent-page URL (accounts.google.com) \u2192 pasted_wrong_url",+ 9,+ [+ "expectCodeSync",+ "parsePastedRedirect"+ ]+ ],+ [+ "test/google-redirect.test.ts",+ "a consent-page URL carrying a stray code= param is still rejected by host, not sniffed as legit",+ 11,+ [+ "expectCodeSync",+ "parsePastedRedirect"+ ]+ ],+ [+ "test/google-redirect.test.ts",+ "a scheme-less consent-page URL (address bar without https://) \u2192 pasted_wrong_url",+ 13,+ [+ "expectCodeSync",+ "parsePastedRedirect"+ ]+ ],+ [+ "test/google-redirect.test.ts",+ "consent-host anchor: a port or userinfo on the consent host is still the consent page",+ 22,+ [+ "expectCodeSync",+ "parsePastedRedirect"+ ]+ ],+ [+ "test/google-redirect.test.ts",+ "state mismatch \u2192 state_mismatch",+ 6,+ [+ "expectCodeSync",+ "parsePastedRedirect"+ ]+ ],+ [+ "test/google-redirect.test.ts",+ "error=access_denied in the query \u2192 access_denied_test_user",+ 6,+ [+ "expectCodeSync",+ "parsePastedRedirect"+ ]+ ],+ [+ "test/google-redirect.test.ts",+ "empty paste \u2192 pasted_wrong_url",+ 3,+ [+ "expectCodeSync",+ "parsePastedRedirect"+ ]+ ],+ [+ "test/google-redirect.test.ts",+ "rejects with consent_timeout when nothing arrives within timeoutMs",+ 8,+ [+ "close",+ "expectRejectsCode",+ "startLoopback"+ ]+ ],+ [+ "test/google-redirect.test.ts",+ "a busy port \u2192 CredentialError port_in_use (thrown synchronously)",+ 9,+ [+ "Response",+ "expectCodeSync",+ "serve",+ "startLoopback",+ "stop"+ ]+ ],+ [+ "test/grandfather-managed.test.ts",+ "managed grandfathering publishes metadata without changing vectors or spending on derived effects",+ 1,+ []+ ],+ [+ "test/grandfather-managed.test.ts",+ "a concurrent explicit validation choice is not overwritten by grandfathering",+ 1,+ []+ ],+ [+ "test/grandfather-managed.test.ts",+ "human file edits abort managed grandfathering without replacing either version",+ 1,+ []+ ],+ [+ "test/grandfather-managed.test.ts",+ "pending grandfathering reuses its admitted request and its original rollback snapshot",+ 1,+ []+ ],+ [+ "test/grandfather-managed.test.ts",+ "archived sources and non-Markdown artifacts are not rewritten by managed grandfathering",+ 1,+ []+ ],+ [+ "test/harness-access.serial.test.ts",+ "PGLite live server: private handoff, recovery, seven verbs, live grants and atomic delegation",+ 3,+ [+ "harnessAccessJourney"+ ]+ ],+ [+ "test/import-abort-error.test.ts",+ "missing dir arg \u2192 typed abort, not process death",+ 3,+ [+ "expectAbort"+ ]+ ],+ [+ "test/import-abort-error.test.ts",+ "invalid --workers \u2192 typed abort",+ 3,+ [+ "expectAbort"+ ]+ ],+ [+ "test/import-abort-error.test.ts",+ "unreadable import target \u2192 typed abort",+ 3,+ [+ "expectAbort"+ ]+ ],+ [+ "test/jobs-lifecycle-ops.test.ts",+ "unknown id \u2192 invalid_params \"Job not found\"",+ 3,+ [+ "ctxOf",+ "expectOpError"+ ]+ ],+ [+ "test/legacy-fact-extraction-dedup.test.ts",+ "legacy extraction deduplicates exact old facts without inferring their vector identity or crossing visibility",+ 4,+ []+ ],+ [+ "test/legacy-vector-compatibility.test.ts",+ "legacy same-model NULL hashes stay searchable through failed migrations without trusting wrong generations or stale hashes",+ 4,+ []+ ],+ [+ "test/managed-atom-regressions.test.ts",+ "atom retry fault stays scoped while an older source retry drains",+ 3,+ [+ "exerciseAtomRetryFence",+ "test"+ ]+ ],+ [+ "test/managed-atom-regressions.test.ts",+ "atom retry ${state} preserves reviewed target ${edit}",+ 3,+ [+ "exerciseAtomWriteThroughPolicy",+ "test"+ ]+ ],+ [+ "test/managed-atom-regressions.test.ts",+ "atom write-through ${value} with ${owner} owner",+ 3,+ [+ "exerciseAtomDisabledAuthority",+ "test"+ ]+ ],+ [+ "test/managed-extract-atoms.test.ts",+ "managed atom ${scenario}",+ 1,+ []+ ],+ [+ "test/managed-extract-atoms.test.ts",+ "managed atom batch ${scenario}",+ 1,+ []+ ],+ [+ "test/memory-safety-wave.serial.test.ts",+ "sync, remember, withdraw, metadata repair, migration, export and HTTP MCP retain source and privacy boundaries",+ 4,+ []+ ],+ [+ "test/migrations-v0_27_1.test.ts",+ "handler is idempotent \u2014 running twice on a clean brain does not error",+ 9,+ [+ "find"+ ]+ ],+ [+ "test/minions-submission-authority.test.ts",+ "controlled migration drains active work, preserves legacy rows and excludes old binaries",+ 4,+ [+ "import",+ "rehearseMinionAuthorityUpgrade"+ ]+ ],+ [+ "test/oauth-dcr-scope-ceiling.test.ts",+ "agent scope keeps the specific operator-approved wording",+ 4,+ [+ "authCodeMetadata",+ "expectRejected",+ "makeProvider"+ ]+ ],+ [+ "test/oauth-dcr-scope-ceiling.test.ts",+ "client_credentials + \"read write\" \u2192 rejected naming write",+ 4,+ [+ "expectRejected",+ "machineMetadata",+ "makeProvider"+ ]+ ],+ [+ "test/oauth-dcr-scope-ceiling.test.ts",+ "client_credentials + \"admin\" \u2192 rejected naming admin",+ 4,+ [+ "expectRejected",+ "machineMetadata",+ "makeProvider"+ ]+ ],+ [+ "test/oauth-dcr-scope-ceiling.test.ts",+ "client_credentials + \"read\" (inside the machine ceiling) is still refused for the same reason",+ 7,+ [+ "expectRejected",+ "machineMetadata",+ "makeProvider"+ ]+ ],+ [+ "test/oauth.test.ts",+ "revoking already-revoked token is a no-op",+ 8,+ [+ "getClient"+ ]+ ],+ [+ "test/operations-source-isolation-matrix.test.ts",+ "BRAIN-WIDE ${row.name} \u2014 ${row.rationale}",+ 3,+ [+ "handler",+ "scopedScalar"+ ]+ ],+ [+ "test/page-projection-code-recovery.test.ts",+ "managed reindex uses a durable guarded receipt without canonical writes or paid effects",+ 1,+ []+ ],+ [+ "test/persistence-commit-durability.test.ts",+ "recovery, cancellation, transfer drain and successor epoch force durable commits under an async session",+ 1,+ []+ ],+ [+ "test/persistence-effect-recovery-fairness.test.ts",+ "mirror recovery passes held roots and revisits them after cursor wrap",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "managed schema restart preserves source and brain identities without triggering a seed write",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "imports files without rewriting bytes and checkpoints only committed page receipts",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "interrupted cursor resumes its pinned target before a newer HEAD and never advances early",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "attached working-tree changes require opt-in and delete retains exact physical identity",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "repeated slices reuse one manifest and still reject an intervening page identity change",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "managed discovery unions persisted hidden-path waivers with explicit patterns",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "subpath exclusions and unsupported code/pull paths refuse before canonical writes",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "a write between batches cannot be overwritten by an older enumerated Git page",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "remote sync keeps submit_job authority and rejects option upgrades and current grant revocation",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "raw bytes changing after preparation conflict without publishing and the same request replays",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "managed terminal receipts survive a missing ledger and corrected retry uses a new ID (CRLF=%s)",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "pending durable sync retries keep the same request ID and do not claim committed imports",+ 1,+ []+ ],+ [+ "test/persistence-managed-sync.test.ts",+ "continuous foreground arrivals cannot starve a bounded sync batch",+ 1,+ []+ ],+ [+ "test/persistence-onboarding.test.ts",+ "read-only preflight identifies both blocked states and explicit onboarding restores writes and sync",+ 1,+ []+ ],+ [+ "test/persistence-recovery-capacity.test.ts",+ "standalone page and withdrawal recovery respect occupied pool capacity and retain a control connection",+ 1,+ []+ ],+ [+ "test/persistence-recovery-fairness.test.ts",+ "sixteen blocked recovery roots cannot starve a later recoverable root or release a blocked FIFO head",+ 1,+ []+ ],+ [+ "test/persistence-root-refresh.test.ts",+ "unchanged bound roots retain their durable records without replacement",+ 1,+ []+ ],+ [+ "test/persistence-root-refresh.test.ts",+ "unbound and moved source paths remain fenced alongside the original bound root",+ 1,+ []+ ],+ [+ "test/persistence-staging.test.ts",+ "journaled flush failure removes owned stage and releases accounting only after rollback",+ 1,+ []+ ],+ [+ "test/persistence-staging.test.ts",+ "blocked file ancestor settles failed publication and releases its worktree (${index})",+ 1,+ []+ ],+ [+ "test/persistence-staging.test.ts",+ "unexpected/partial staging is retained without releasing recovery capacity (${index})",+ 1,+ []+ ],+ [+ "test/persistence-staging.test.ts",+ "terminal recovery survives index upgrade and fences its worktree until staging cleanup completes",+ 1,+ []+ ],+ [+ "test/persistence-staging.test.ts",+ "legacy recovery gains durable restoration staging before rewriting the old file",+ 1,+ []+ ],+ [+ "test/persistence-staging.test.ts",+ "withdrawal mirror staging preserves unexpected bytes and only finishes forward",+ 1,+ []+ ],+ [+ "test/persistence-sync-failures.serial.test.ts",+ "local single and all-source CLI JSON carry durable diagnostics and fail the exit verdict",+ 1,+ []+ ],+ [+ "test/persistence-sync-options.serial.test.ts",+ "fresh processes resume persisted pending opt-outs under the original request and persist synthetic vectors only for opt-in",+ 1,+ []+ ],+ [+ "test/persistence-topology-recovery-fairness.test.ts",+ "bounded topology recovery rotates past a persistent conflict, wraps, and releases only settled reservations",+ 1,+ []+ ],+ [+ "test/persistence-topology-recovery.test.ts",+ "clone recovery rejects malformed staging tokens and target prefix collisions",+ 8,+ [+ "basename",+ "expectValidation",+ "slice",+ "toUpperCase"+ ]+ ],+ [+ "test/persistence-topology-recovery.test.ts",+ "clone recovery retains parent, canonical path, aside prefix and owner checks",+ 14,+ [+ "basename",+ "expectValidation",+ "randomUUID",+ "toUpperCase"+ ]+ ],+ [+ "test/persistence-withdrawal-retry.test.ts",+ "${boundary}: retry releases the whole transaction and commits one withdrawal, quota reservation and receipt",+ 1,+ []+ ],+ [+ "test/persistence-withdrawal-retry.test.ts",+ "Postgres withdrawal retries a real source lock timeout with its original request ID",+ 1,+ []+ ],+ [+ "test/pg-access-classify.test.ts",+ "run_command argv[0] is always gbrain",+ 8,+ [+ "classifyPgAccessError",+ "diagnoseDbConfig",+ "everyFix"+ ]+ ],+ [+ "test/pglite-engine.test.ts",+ "skipExistenceCheck=true: silent no-op on missing page",+ 9,+ [+ "addTimelineEntry"+ ]+ ],+ [+ "test/put-page-dedup-fence.test.ts",+ "delegated subagent (allow-list, NO auth) cannot rewrite an out-of-fence page",+ 10,+ [+ "expectFenced",+ "makeCtx",+ "putEchoingVictimId"+ ]+ ],+ [+ "test/put-page-dedup-fence.test.ts",+ "legacy sandbox subagent (namespace fence, no allow-list) cannot either",+ 4,+ [+ "expectFenced",+ "makeCtx",+ "putEchoingVictimId"+ ]+ ],+ [+ "test/put-page-dedup-fence.test.ts",+ "slug-bound OAuth client cannot (the v0.42.72.0 case, still fenced)",+ 4,+ [+ "boundAuth",+ "expectFenced",+ "makeCtx",+ "putEchoingVictimId"+ ]+ ],+ [+ "test/put-page-dedup-fence.test.ts",+ "a caller under BOTH confinements is fenced (requested slug satisfies both)",+ 9,+ [+ "boundAuth",+ "expectFenced",+ "makeCtx",+ "putEchoingVictimId"+ ]+ ],+ [+ "test/real-home-guard-preload.test.ts",+ "mutating probe",+ 1,+ [+ "stringify"+ ]+ ],+ [+ "test/real-home-guard-preload.test.ts",+ "innocent probe",+ 1,+ []+ ],+ [+ "test/real-home-guard-preload.test.ts",+ "create",+ 1,+ []+ ],+ [+ "test/real-home-guard-preload.test.ts",+ "isolated",+ 1,+ []+ ],+ [+ "test/real-home-guard-preload.test.ts",+ "deliberate",+ 1,+ []+ ],+ [+ "test/remote-ping-status-field.test.ts",+ "unpack generics type the lifecycle field as status",+ 4,+ [+ "match"+ ]+ ],+ [+ "test/remote-privacy-sweep.test.ts",+ "${op.name} [${shape}]",+ 3,+ [+ "runCase"+ ]+ ],+ [+ "test/remote-privacy-sweep.test.ts",+ "${op.name} [${shape}]",+ 3,+ [+ "runCase"+ ]+ ],+ [+ "test/schema-bootstrap-coverage.test.ts",+ "after bootstrap, PGLITE_SCHEMA_SQL replays without crashing on missing forward references",+ 76,+ [+ "PGLiteEngine",+ "UNIQUE",+ "WP4",+ "applyForwardReferenceBootstrap",+ "columns",+ "connect",+ "disconnect",+ "exec"+ ]+ ],+ [+ "test/schema-engine-isolation.serial.test.ts",+ "all engine-backed loaders use the selected brain without changing host config",+ 1,+ []+ ],+ [+ "test/schema-engine-isolation.serial.test.ts",+ "absent brain and source keys still permit ordinary file fallback",+ 1,+ []+ ],+ [+ "test/schema-engine-isolation.serial.test.ts",+ "failed ${failedKey} lookup never uses host vocabulary in typed reads",+ 1,+ []+ ],+ [+ "test/schema-engine-isolation.serial.test.ts",+ "general CLI/env precedence remains intact while strict approval rejects conflicts",+ 1,+ []+ ],+ [+ "test/schema-engine-isolation.serial.test.ts",+ "strict approval proposes only a selected-DB binding and fails closed on unreadable config",+ 1,+ []+ ],+ [+ "test/schema-engine-isolation.serial.test.ts",+ "per-source overrides are read from the selected DB and mixed-schema reads refuse",+ 1,+ []+ ],+ [+ "test/schema-engine-isolation.serial.test.ts",+ "strict approval detects parent changes within the registry TTL without child or alias changes",+ 1,+ []+ ],+ [+ "test/schema-engine-isolation.serial.test.ts",+ "CLI import honors target schema after resolving the source flag",+ 1,+ []+ ],+ [+ "test/schema-engine-isolation.serial.test.ts",+ "CLI-selected source schema is resolved after argument precedence",+ 1,+ []+ ],+ [+ "test/schema-engine-isolation.serial.test.ts",+ "first and incremental legacy sync use the target schema",+ 1,+ []+ ],+ [+ "test/schema-engine-isolation.serial.test.ts",+ "typed query closure uses the target pack in keyword and hybrid reads",+ 1,+ []+ ],+ [+ "test/schema-engine-isolation.serial.test.ts",+ "managed prepared import retains target types and leaves committed source bytes unchanged",+ 1,+ []+ ],+ [+ "test/shared-content-freshness.test.ts",+ "receipt-proven content roots are explicitly writer-owned without inventing sync timestamps",+ 1,+ []+ ],+ [+ "test/shared-content-freshness.test.ts",+ "external roots and absent, incomplete, unowned or mismatched receipts still fail never-synced health",+ 1,+ []+ ],+ [+ "test/shared-content-freshness.test.ts",+ "source incarnation and canonical host-binding changes invalidate the owned-root proof",+ 1,+ []+ ],+ [+ "test/shared-content-freshness.test.ts",+ "pending and recovering canonical writes remain visible separately and remote checks never read filesystem paths",+ 1,+ []+ ],+ [+ "test/skillpack-brain-resident-locate.test.ts",+ "boundary: a 64-char slug passes the shape gate (fails later as not_found)",+ 9,+ [+ "ctxFor",+ "expectOpError",+ "fakeEngine",+ "getResidentSkillDetail",+ "repeat"+ ]+ ],+ [+ "test/skillpack-brain-resident-locate.test.ts",+ "federated-array scope pointing away from the source \u2192 not_found",+ 5,+ [+ "ctxFor",+ "expectOpError",+ "fakeEngine",+ "getResidentSkillDetail"+ ]+ ],+ [+ "test/skillpack-brain-resident-locate.test.ts",+ "scalar ctx.sourceId pointing away from the source \u2192 not_found",+ 5,+ [+ "ctxFor",+ "expectOpError",+ "fakeEngine",+ "getResidentSkillDetail"+ ]+ ],+ [+ "test/skillpack-rubric-doctor.test.ts",+ "x",+ 1,+ []+ ],+ [+ "test/skillpack-rubric-doctor.test.ts",+ "e2e",+ 1,+ []+ ],+ [+ "test/sources-mcp.test.ts",+ "bound by a federated grant with NO write source: nothing is removable",+ 8,+ [+ "base",+ "ctxRemote",+ "notFound",+ "withoutSourceId"+ ]+ ],+ [+ "test/sources-mcp.test.ts",+ "the __all__ sentinel is never a write source for an untrusted caller",+ 5,+ [+ "base",+ "notFound"+ ]+ ],+ [+ "test/storage.test.ts",+ "delete is idempotent (missing file is ok)",+ 4,+ [+ "delete"+ ]+ ],+ [+ "test/supervisor-configuration-blocked.test.ts",+ "startup timeout also reaps an unready direct worker without tini",+ 1,+ []+ ],+ [+ "test/supervisor-configuration-blocked.test.ts",+ "managed spawns leave GBRAIN_SUPERVISED to the owner and always hand off the status channel",+ 1,+ []+ ],+ [+ "test/thin-client-launcher-routing.test.ts",+ "thin launcher preserves explicit arguments without pinning the grant write source: %j",+ 1,+ []+ ],+ [+ "test/thin-client-routing.test.ts",+ "takes search with no query",+ 3,+ [+ "expectUsageExit"+ ]+ ],+ [+ "test/thin-client-routing.test.ts",+ "takes add missing --claim/--kind/--who",+ 3,+ [+ "expectUsageExit"+ ]+ ],+ [+ "test/thin-client-routing.test.ts",+ "takes update missing --row",+ 3,+ [+ "expectUsageExit"+ ]+ ],+ [+ "test/thin-client-routing.test.ts",+ "takes resolve missing --quality and --outcome",+ 3,+ [+ "expectUsageExit"+ ]+ ],+ [+ "test/thin-client-routing.test.ts",+ "takes resolve with a non-boolean --outcome",+ 3,+ [+ "expectUsageExit"+ ]+ ],+ [+ "test/thin-client-routing.test.ts",+ "takes supersede missing --claim",+ 3,+ [+ "expectUsageExit"+ ]+ ],+ [+ "test/upgrade-reference-sweep.test.ts",+ "zero drift (skills present but identical) \u2192 silent",+ 12,+ [+ "postUpgradeReferenceSweep",+ "scratchHostWithSkill",+ "withEnv"+ ]+ ],+ [+ "test/upgrade-reference-sweep.test.ts",+ "errors swallowed silently \u2014 never blocks post-upgrade",+ 11,+ [+ "postUpgradeReferenceSweep",+ "withEnv"+ ]+ ],+ [+ "test/worker-renewal-configuration.test.ts",+ "$name preserves configuration provenance and execution ownership",+ 1,+ []+ ],+ [+ "test/brainstorm/eval-brainstorm.test.ts",+ "_cleanup_",+ 3,+ [+ "rmSync"+ ]+ ],+ [+ "test/e2e/jsonb-roundtrip.test.ts",+ "no ${JSON.stringify(x)}::jsonb pattern remains in fixed sites",+ 6,+ []+ ],+ [+ "test/e2e/managed-atom-regressions.test.ts",+ "retry fault stays scoped while an older source retry drains",+ 5,+ [+ "close",+ "exerciseAtomRetrySourceIsolation",+ "isolatedPersistencePostgres"+ ]+ ],+ [+ "test/e2e/managed-atom-regressions.test.ts",+ "retry ${state} preserves reviewed target ${edit}",+ 3,+ [+ "exerciseAtomWriteThroughPolicy",+ "test"+ ]+ ],+ [+ "test/e2e/managed-atom-regressions.test.ts",+ "write-through ${value} with ${owner} owner",+ 3,+ [+ "exerciseAtomDisabledAuthority",+ "test"+ ]+ ],+ [+ "test/e2e/managed-extract-atoms.test.ts",+ "batch ${scenario}",+ 1,+ []+ ],+ [+ "test/e2e/mechanical.test.ts",+ "import + search + link performance",+ 24,+ [+ "callOp",+ "floor",+ "sort",+ "time",+ "toFixed"+ ]+ ],+ [+ "test/e2e/minions-authority-parity.test.ts",+ "controlled queue protocol cutover matches PGLite",+ 4,+ [+ "getEngine",+ "import",+ "rehearseMinionAuthorityUpgrade"+ ]+ ],+ [+ "test/e2e/mounts-routing-pglite.test.ts",+ "(2) unflagged read routes by cwd: mount path-prefix (tier 4) vs host fallback (tier 6)",+ 6,+ [+ "expectServedBy",+ "gbrain"+ ]+ ],+ [+ "test/e2e/mounts-routing-pglite.test.ts",+ "(3) .gbrain-mount dotfile in an UNRELATED cwd routes to the named mount (tier 3)",+ 4,+ [+ "dirWithDotfile",+ "expectServedBy",+ "gbrain"+ ]+ ],+ [+ "test/e2e/mounts-routing-pglite.test.ts",+ "(4) dotfile BEATS path-prefix: content `host` inside the mount opts back to host",+ 11,+ [+ "dirWithDotfile",+ "expectServedBy",+ "gbrain",+ "mkdirSync"+ ]+ ],+ [+ "test/e2e/mounts-routing-pglite.test.ts",+ "(5) upper tiers: GBRAIN_BRAIN_ID (tier 2) beats dotfile; --brain flag (tier 1) beats env",+ 20,+ [+ "dirWithDotfile",+ "expectServedBy",+ "gbrain"+ ]+ ],+ [+ "test/e2e/openclaw-plugin-load-real.test.ts",+ "${flagged.stdout}\\n${flagged.stderr}`)) {\n return runOpenclaw(['plugins', 'inspect', id, '--json'], { timeoutMs: 30_000 });\n }\n return flagged;\n}\n\nfunction cleanup() {\n if (!OPENCLAW) return;\n\n\n try {\n runOpenclaw(['plugins', 'uninstall', '--force', PLUGIN_ID], { timeoutMs: 30_000 });\n } catch { }\n try {\n if (existsSync(PROFILE_DIR)) rmSync(PROFILE_DIR, { recursive: true, force: true });\n } catch { }\n try {\n if (fixtureDir && existsSync(fixtureDir)) rmSync(fixtureDir, { recursive: true, force: true });\n } catch { }\n}\n\ndescribe('openclaw-plugin-load-real (Tier 2 e2e)', () => {\n beforeAll(async () => {\n if (SKIP) {\n console.warn(SKIP_MSG);\n return;\n }\n\n repoRoot = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' })\n .stdout.trim();\n if (!repoRoot) throw new Error('not in a git repo \u2014 cannot resolve plugin source path');\n\n fixtureDir = mkdtempSync(join(tmpdir(), 'gbrain-ctx-plugin-real-'));\n\n const fixtureTemplate = join(repoRoot, 'test', 'fixtures', 'openclaw-plugin-real');\n writeFileSync(\n join(fixtureDir, 'package.json'),\n readFileSync(join(fixtureTemplate, 'package.json.template'), 'utf8'),\n );\n writeFileSync(\n join(fixtureDir, 'openclaw.plugin.json'),\n readFileSync(join(fixtureTemplate, 'openclaw.plugin.json.template'), 'utf8'),\n );\n\n\n\n\n\n\n\n\n\n\n\n\n\n const buildResult = spawnSync(\n 'bun',\n [\n 'build',\n join(repoRoot, 'src', 'openclaw-context-engine.ts'),\n '--target=bun',\n '--outdir',\n fixtureDir,\n '--entry-naming',\n '[dir]/entry.[ext]',\n ],\n { encoding: 'utf8', timeout: 60_000 },\n );\n if (buildResult.status !== 0) {\n throw new Error(`bun build failed (exit ${buildResult.status}): ${buildResult.stderr}`);\n }\n if (!existsSync(join(fixtureDir, 'entry.js'))) {\n throw new Error('bun build did not produce entry.js');\n }\n\n\n\n\n\n const install = runOpenclaw([\n 'plugins', 'install',\n '--link',\n '--dangerously-force-unsafe-install',\n fixtureDir,\n ], { timeoutMs: 60_000 });\n if (install.exitCode !== 0) {\n throw new Error(\n `openclaw plugins install failed (exit ${install.exitCode}).\\n` +\n `stdout: ${install.stdout}\\nstderr: ${install.stderr}",+ 3,+ [+ "cleanup"+ ]+ ],+ [+ "test/e2e/persistence-phase-liveness.test.ts",+ "stopping before driver dispatch recognizes its prefixed cancellation error",+ 1,+ []+ ],+ [+ "test/e2e/persistence-phase-liveness.test.ts",+ "stopping during reservation recognizes an earlier abort without reporting a storage failure",+ 1,+ []+ ],+ [+ "test/e2e/persistence-phase-liveness.test.ts",+ "a slow PostgreSQL receipt read cannot hide an independently committed request",+ 1,+ []+ ],+ [+ "test/e2e/persistence-phase-liveness.test.ts",+ "an expired locked head does not stall independent roots or skip its own follower",+ 1,+ []+ ],+ [+ "test/e2e/persistence-phase-liveness.test.ts",+ "${phase} stopping cancels its blocked query without reporting a storage failure",+ 1,+ []+ ],+ [+ "test/e2e/persistence-phase-liveness.test.ts",+ "${phase} cancels a real table-lock wait and retains fail-closed scheduling",+ 1,+ []+ ],+ [+ "test/e2e/persistence-phase-liveness.test.ts",+ "a blocked recovery operation keeps reservations and retries after its SQL bound",+ 1,+ []+ ],+ [+ "test/e2e/persistence-phase-liveness.test.ts",+ "ordinary pool saturation cancels queued scheduler reads without accumulating work",+ 1,+ []+ ],+ [+ "test/e2e/persistence-phase-liveness.test.ts",+ "capacity marking names and cancels its real row-lock wait before shutdown",+ 1,+ []+ ],+ [+ "test/e2e/persistence-phase-liveness.test.ts",+ "a queued direct-pool BEGIN stays tracked and cannot prepare after shutdown",+ 1,+ []+ ],+ [+ "test/e2e/persistence-phase-liveness.test.ts",+ "a ${outcome} cold direct initialization remains observed until settlement",+ 1,+ []+ ],+ [+ "test/e2e/persistence-phase-liveness.test.ts",+ "claim renewal cancels its actual SQL wait without a late lease extension",+ 1,+ []+ ],+ [+ "test/ingestion/test-harness.test.ts",+ "stop() before run() is a no-op",+ 4,+ [+ "IngestionTestHarness",+ "stop"+ ]+ ],+ [+ "test/ingestion/sources/file-watcher.test.ts",+ "resolves start() on chokidar ready",+ 12,+ [+ "IngestionTestHarness",+ "createFileWatcherSource",+ "fireReady",+ "makeStubWatcher",+ "run",+ "stop"+ ]+ ],+ [+ "test/scripts/ci-gates.test.ts",+ "DATABASE_URL=$database E2E exit=$e2eExit",+ 1,+ []+ ],+ [+ "test/scripts/ci-local-rendering.test.ts",+ "required=${required}, executed=${passes}, Bun exit=${testExit}, parent coverage exists=${parentCoverageExists}${outputBytes ? ",+ 1,+ []+ ],+ [+ "test/scripts/e2e-runner.test.ts",+ "failure",+ 1,+ [+ "rmSync"+ ]+ ],+ [+ "test/scripts/e2e-runner.test.ts",+ "failure",+ 1,+ []+ ],+ [+ "test/scripts/e2e-runner.test.ts",+ "child",+ 1,+ []+ ],+ [+ "test/scripts/run-serial-pool.test.ts",+ "hangs forever",+ 1,+ []+ ],+ [+ "test/scripts/run-serial-pool.test.ts",+ "keeps a child alive",+ 5,+ [+ "setInterval",+ "spawn",+ "stringify",+ "writeFileSync"+ ]+ ],+ [+ "test/scripts/run-serial-pool.test.ts",+ "allows exclusive registration cleanup to finish",+ 20,+ [+ "existsSync",+ "exit",+ "kill",+ "on",+ "readFileSync",+ "stringify",+ "writeFileSync"+ ]+ ],+ [+ "test/scripts/run-unit-parallel.test.ts",+ "sleeps past the shard cap",+ 1,+ [+ "sleep"+ ]+ ],+ [+ "test/search/attribution-stamping.test.ts",+ "empty results \u2192 no-op (no stamping)",+ 6,+ [+ "runPostFusionStages"+ ]+ ]+ ],+ "typeof_function": [+ [+ "test/bootstrap-status.serial.test.ts",+ "p.detect"+ ],+ [+ "test/code-callers-cli.test.ts",+ "mod.runCodeCallers"+ ],+ [+ "test/code-callers-cli.test.ts",+ "mod.runCodeCallees"+ ],+ [+ "test/cycle-abort.test.ts",+ "mod.runCycle"+ ],+ [+ "test/db-pool-max-lifetime.test.ts",+ "v"+ ],+ [+ "test/db-pool-max-lifetime.test.ts",+ "v"+ ],+ [+ "test/db-pool-max-lifetime.test.ts",+ "v"+ ],+ [+ "test/db-pool-max-lifetime.test.ts",+ "v"+ ],+ [+ "test/distribution-import-boundary.test.ts",+ "dist.extractTarball"+ ],+ [+ "test/distribution-import-boundary.test.ts",+ "dist.packTarball"+ ],+ [+ "test/distribution-import-boundary.test.ts",+ "dist.askTrust"+ ],+ [+ "test/distribution-import-boundary.test.ts",+ "dist.loadRegistry"+ ],+ [+ "test/distribution-import-boundary.test.ts",+ "dist.resolveSource"+ ],+ [+ "test/distribution-import-boundary.test.ts",+ "dist.classifySpec"+ ],+ [+ "test/distribution-import-boundary.test.ts",+ "dist.effectiveTier"+ ],+ [+ "test/distribution-import-boundary.test.ts",+ "dist.validateRegistryCatalog"+ ],+ [+ "test/distribution-import-boundary.test.ts",+ "dist.runScaffoldThirdParty"+ ],+ [+ "test/doctor.test.ts",+ "runDoctor"+ ],+ [+ "test/doctor.test.ts",+ "mod.takesWeightGridCheck"+ ],+ [+ "test/enrichment-service.test.ts",+ "mod.enrichEntity"+ ],+ [+ "test/enrichment-service.test.ts",+ "mod.enrichEntities"+ ],+ [+ "test/enrichment-service.test.ts",+ "mod.extractAndEnrich"+ ],+ [+ "test/eval-whoknows.test.ts",+ "mod.runEvalWhoknows"+ ],+ [+ "test/extract.test.ts",+ "walkMarkdownFiles"+ ],+ [+ "test/features.test.ts",+ "mod.runFeatures"+ ],+ [+ "test/features.test.ts",+ "mod.featuresTeaserForDoctor"+ ],+ [+ "test/migrate.test.ts",+ "runMigrations"+ ],+ [+ "test/migration-orchestrator-v0_21_0.test.ts",+ "__testing.phaseASchema"+ ],+ [+ "test/migration-orchestrator-v0_21_0.test.ts",+ "__testing.phaseBBackfillPrompt"+ ],+ [+ "test/migration-orchestrator-v0_21_0.test.ts",+ "__testing.phaseCVerify"+ ],+ [+ "test/migrations-registry.test.ts",+ "m.orchestrator"+ ],+ [+ "test/migrations-v0_12_0.test.ts",+ "__testing.phaseASchema"+ ],+ [+ "test/migrations-v0_12_0.test.ts",+ "__testing.phaseBConfigCheck"+ ],+ [+ "test/migrations-v0_12_0.test.ts",+ "__testing.phaseCBackfillLinks"+ ],+ [+ "test/migrations-v0_12_0.test.ts",+ "__testing.phaseDBackfillTimeline"+ ],+ [+ "test/migrations-v0_12_0.test.ts",+ "__testing.phaseEVerify"+ ],+ [+ "test/migrations-v0_12_0.test.ts",+ "__testing.readStats"+ ],+ [+ "test/migrations-v0_12_2.test.ts",+ "__testing.phaseASchema"+ ],+ [+ "test/migrations-v0_12_2.test.ts",+ "__testing.phaseBRepair"+ ],+ [+ "test/migrations-v0_12_2.test.ts",+ "__testing.phaseCVerify"+ ],+ [+ "test/migrations-v0_13_0.test.ts",+ "__testing.phaseASchema"+ ],+ [+ "test/migrations-v0_13_0.test.ts",+ "__testing.phaseBBackfill"+ ],+ [+ "test/migrations-v0_13_0.test.ts",+ "__testing.phaseCVerify"+ ],+ [+ "test/migrations-v0_22_4.test.ts",+ "v0_22_4.orchestrator"+ ],+ [+ "test/oauth.test.ts",+ "store.getClient"+ ],+ [+ "test/oauth.test.ts",+ "dcrOn.clientsStore.registerClient"+ ],+ [+ "test/parity.test.ts",+ "op.handler"+ ],+ [+ "test/postgres-driver-vendor.test.ts",+ "postgres"+ ],+ [+ "test/postgres-engine-rls-scope.test.ts",+ "received"+ ],+ [+ "test/salience.test.ts",+ "computeAnomaliesFromBuckets"+ ],+ [+ "test/serve-http-cors.test.ts",+ "fn"+ ],+ [+ "test/sql-ranking.test.ts",+ "topLevelEscapeLikePattern"+ ],+ [+ "test/think-embed-question-wiring.serial.test.ts",+ "embedQuestion"+ ],+ [+ "test/transcription.test.ts",+ "mod.transcribe"+ ],+ [+ "test/transcription.test.ts",+ "mod.transcribe"+ ],+ [+ "test/transcripts-claude-code-workflow-drift.test.ts",+ "isArtifact"+ ],+ [+ "test/v0_37_fix_wave.serial.test.ts",+ "EmbeddingDimMismatchError"+ ],+ [+ "test/v0_37_fix_wave.serial.test.ts",+ "mod.runReinitPglite"+ ],+ [+ "test/whoknows.test.ts",+ "rankCandidates"+ ],+ [+ "test/whoknows.test.ts",+ "findExperts"+ ],+ [+ "test/whoknows.test.ts",+ "runWhoknows"+ ],+ [+ "test/ai/build-gateway-config.test.ts",+ "mod.buildGatewayConfig"+ ],+ [+ "test/ai/gateway-chat.test.ts",+ "mod.chat"+ ],+ [+ "test/ai/recipe-azure-openai.test.ts",+ "cfg.fetch"+ ],+ [+ "test/ai/recipe-azure-openai.test.ts",+ "result.fetch"+ ],+ [+ "test/ai/recipe-llama-server.test.ts",+ "r.probe"+ ],+ [+ "test/ai/recipe-lmstudio.test.ts",+ "recipe.probe"+ ],+ [+ "test/ai/recipe-ollama-thinking.test.ts",+ "chat.thinking_by_default"+ ],+ [+ "test/ai/recipe-openrouter.test.ts",+ "loop"+ ],+ [+ "test/cycle/yield-during-phase-refresh.test.ts",+ "fn"+ ],+ [+ "test/cycle/yield-during-phase-refresh.test.ts",+ "fn"+ ],+ [+ "test/e2e/mcp.test.ts",+ "mod.startMcpServer"+ ],+ [+ "test/e2e/mcp.test.ts",+ "mod.handleToolCall"+ ],+ [+ "test/e2e/openclaw-context-engine-plugin.test.ts",+ "entry.register"+ ],+ [+ "test/e2e/openclaw-plugin-load-real.test.ts",+ "registerContextEngine"+ ],+ [+ "test/e2e/openclaw-plugin-load-real.test.ts",+ "engine.ingest"+ ],+ [+ "test/e2e/openclaw-plugin-load-real.test.ts",+ "engine.assemble"+ ],+ [+ "test/e2e/openclaw-plugin-load-real.test.ts",+ "engine.compact"+ ]+ ],+ "file_no_expect": [+ "test/company-brain-receipts.test.ts",+ "test/facts-worker-config.test.ts",+ "test/harness-access.serial.test.ts",+ "test/managed-atom-compaction.test.ts",+ "test/managed-atom-regressions.test.ts",+ "test/managed-facts-compaction.test.ts",+ "test/managed-facts-embedding.test.ts",+ "test/shared-skills-transports.test.ts",+ "test/e2e/attendance-repair-postgres.test.ts",+ "test/e2e/attendance-retrieval-postgres.test.ts",+ "test/e2e/deep-research-source-id.test.ts",+ "test/e2e/embedding-recovery-parity.test.ts",+ "test/e2e/export-snapshot-postgres.test.ts",+ "test/e2e/extract-timeline-attendance-postgres.test.ts",+ "test/e2e/facts-worker-config.test.ts",+ "test/e2e/google-attachments-postgres.test.ts",+ "test/e2e/harness-access.test.ts",+ "test/e2e/legacy-fact-extraction-dedup-postgres.test.ts",+ "test/e2e/legacy-vector-compatibility-postgres.test.ts",+ "test/e2e/managed-atom-compaction.test.ts",+ "test/e2e/managed-atom-regressions.test.ts",+ "test/e2e/managed-connector-fencing.test.ts",+ "test/e2e/managed-connector-recovery.test.ts",+ "test/e2e/managed-connector-retry.test.ts",+ "test/e2e/managed-connector-routing.test.ts",+ "test/e2e/managed-extract-atoms.test.ts",+ "test/e2e/managed-facts-backstop.test.ts",+ "test/e2e/managed-facts-compaction.test.ts",+ "test/e2e/managed-facts-embedding.test.ts",+ "test/e2e/managed-maintenance.test.ts",+ "test/e2e/managed-sync-failures.test.ts",+ "test/e2e/managed-synthesis-postprocess.test.ts",+ "test/e2e/memory-safety-wave-postgres.test.ts",+ "test/e2e/migration-vector-replay-postgres.test.ts",+ "test/e2e/persistence-embedding-effects.test.ts",+ "test/e2e/persistence-publication-parity.test.ts",+ "test/e2e/persistence-recovery.test.ts",+ "test/e2e/persistence-sync-company-parity.test.ts",+ "test/e2e/persistence-sync-options-parity.test.ts",+ "test/e2e/persistence-sync-origin-parity.test.ts",+ "test/e2e/projection-recovery-parity.test.ts",+ "test/e2e/shared-skills-transports.test.ts",+ "test/e2e/unsupported-embedding-identity-postgres.test.ts",+ "test/e2e/withdrawal-bounded-safety-postgres.test.ts",+ "test/e2e/withdrawal-crash-postgres.test.ts",+ "test/search/search-query-contract.test.ts"+ ],+ "expect_true_only": [+ [+ "test/extract-stale.test.ts",+ "markPagesExtractedBatch: empty input is a no-op"+ ],+ [+ "test/operation-context-sourceid-required.test.ts",+ "omitting sourceId from an OperationContext literal is a type error"+ ],+ [+ "test/operation-context-sourceid-required.test.ts",+ "passing undefined for sourceId is a type error"+ ],+ [+ "test/seed-pglite.serial.test.ts",+ "creates parent directories when needed"+ ],+ [+ "test/v0_37_fix_wave.serial.test.ts",+ "GBrainConfig type includes voyage_api_key field (TS compile guard)"+ ],+ [+ "test/core/background-work.test.ts",+ "empty registry (no test drainers) resolves fast"+ ],+ [+ "test/e2e/cjk-roundtrip.test.ts",+ "vector path skip-gracefully without OPENAI_API_KEY"+ ],+ [+ "test/e2e/embedding-column-postgres.test.ts",+ "skipped"+ ],+ [+ "test/e2e/graph-signals-eval.test.ts",+ "Gate 1 (QUALITY): no statistically significant regression in wrong direction"+ ],+ [+ "test/e2e/upsert-chunks-registry-column.test.ts",+ "skipped"+ ],+ [+ "test/regressions/v0.36.1.0-iron-rule.test.ts",+ "this regression is covered by existing v0.34.1 source-isolation suite"+ ],+ [+ "test/regressions/v0.36.1.0-iron-rule.test.ts",+ "this regression is covered by existing search-mode test suite"+ ]+ ],+ "dup_bodies_crossfile": [+ [+ [+ "test/artifact-abstraction.test.ts",+ "detectArtifactKind by extension"+ ],+ [+ "test/e2e/schema-cathedral.test.ts",+ "detectArtifactKind dispatches by extension"+ ]+ ],+ [+ [+ "test/link-extraction-dir-whitelist-2576.test.ts",+ "verb inference works for non-whitelisted dirs (typed edge, not just mentions)"+ ],+ [+ "test/link-extraction-relative-path.test.ts",+ "flat layout unchanged: verb inference still fires on the resolved slug"+ ]+ ],+ [+ [+ "test/links-timeline-jsonb-poison.test.ts",+ "strips embedded NUL but preserves the rest"+ ],+ [+ "test/e2e/jsonb-batch-poison-postgres.test.ts",+ "strips embedded NUL in link context"+ ]+ ],+ [+ [+ "test/links-timeline-jsonb-poison.test.ts",+ "round-trips free-text summary/detail/source without throwing"+ ],+ [+ "test/e2e/jsonb-batch-poison-postgres.test.ts",+ "addTimelineEntriesBatch round-trips poison summary/detail/source"+ ]+ ],+ [+ [+ "test/list-all-sources.test.ts",+ "filters archived by default"+ ],+ [+ "test/e2e/list-all-sources-postgres.test.ts",+ "filters archived by default"+ ]+ ],+ [+ [+ "test/e2e/openrouter-anthropic-subagent-replay.live.test.ts",+ "persisted tool-call ids stay byte-identical across resume"+ ],+ [+ "test/e2e/openrouter-deepseek-subagent-replay.live.test.ts",+ "persisted tool-call ids stay byte-identical across resume"+ ]+ ]+ ]+}\ No newline at end of filediff --git a/docs/test-audit/2026-09-29/lane-patterns/scan2.json b/docs/test-audit/2026-09-29/lane-patterns/scan2.jsonnew file mode 100644index 0000000000..0180f01b2b--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-patterns/scan2.json@@ -0,0 +1,808 @@+{+ "only_typeof": [+ [+ "test/advisor-core.test.ts",+ "reports stalled jobs and stale sync",+ 2+ ],+ [+ "test/advisor-core.test.ts",+ "embeddings disabled \u2192 warn",+ 1+ ],+ [+ "test/brain-allowlist.serial.test.ts",+ "execute() names a missing required parameter instead of crashing",+ 1+ ],+ [+ "test/brain-allowlist.serial.test.ts",+ "execute() normalizes optional absent idioms (null / \"\") before validation and the handler (wave review)",+ 1+ ],+ [+ "test/budget-meter.test.ts",+ "Anthropic pricing map covers the alias resolution targets",+ 3+ ],+ [+ "test/cli-should-force-exit.test.ts",+ "uses process.argv.slice(2) by default when called with no args",+ 1+ ],+ [+ "test/code-callers-cli.test.ts",+ "code-callers module exports runCodeCallers",+ 1+ ],+ [+ "test/code-callers-cli.test.ts",+ "code-callees module exports runCodeCallees",+ 1+ ],+ [+ "test/code-def-refs.test.ts",+ "ranks by slug + line number (deterministic)",+ 1+ ],+ [+ "test/content-sanity.test.ts",+ "null/undefined title does not throw and yields a normal result",+ 2+ ],+ [+ "test/cross-modal-default-slots.test.ts",+ "every default slot model has a canonical pricing entry",+ 1+ ],+ [+ "test/cycle-abort.test.ts",+ "signal field exists on CycleOpts interface",+ 1+ ],+ [+ "test/cycle-pack-gating.test.ts",+ "every ALL_PHASES entry has a PHASE_SCOPE entry (exhaustive map)",+ 1+ ],+ [+ "test/db-pacer.test.ts",+ "dispose releases blocked acquirers with a no-op permit",+ 1+ ],+ [+ "test/db-pool-max-lifetime.test.ts",+ "empty string falls through to the default (function)",+ 1+ ],+ [+ "test/db-pool-max-lifetime.test.ts",+ "wiring: the default reaches a real pool as a FUNCTION (per-connection jitter)",+ 1+ ],+ [+ "test/default-alias-liveness.test.ts",+ "every default target has a canonical pricing entry",+ 1+ ],+ [+ "test/default-model-panels.test.ts",+ "every default panel model prices via canonical AND the takes-quality allowlist",+ 2+ ],+ [+ "test/default-model-panels.test.ts",+ "every model the google recipe offers is priced",+ 1+ ],+ [+ "test/degraded-engine.test.ts",+ "covers the full PostgresEngine method surface (a new engine method can never miss the degraded path)",+ 1+ ],+ [+ "test/dispatch-response-meta.serial.test.ts",+ "metaHook failure never drops the retrieval key (per-key isolation)",+ 1+ ],+ [+ "test/doctor.test.ts",+ "doctor module exports runDoctor",+ 1+ ],+ [+ "test/doctor.test.ts",+ "LATEST_VERSION is importable from migrate",+ 1+ ],+ [+ "test/doctor.test.ts",+ "takesWeightGridCheck is exported as a pure function",+ 1+ ],+ [+ "test/dry-fix.test.ts",+ "skips when pattern matches more than once",+ 1+ ],+ [+ "test/embedding-recovery.serial.test.ts",+ "retained vector guard fails closed on unreadable registry or unknown counts",+ 1+ ],+ [+ "test/enrichment-service.test.ts",+ "module exports enrichEntity function",+ 1+ ],+ [+ "test/enrichment-service.test.ts",+ "module exports enrichEntities for batch processing",+ 1+ ],+ [+ "test/enrichment-service.test.ts",+ "module exports extractAndEnrich for text processing",+ 1+ ],+ [+ "test/enrichment-service.test.ts",+ "enrichment result includes tier fields",+ 1+ ],+ [+ "test/eval-takes-quality-pricing.test.ts",+ "returns pricing for the default 3-model panel",+ 3+ ],+ [+ "test/eval-v041_2-scaffolds.test.ts",+ "details carry the planned-evaluator pointer",+ 1+ ],+ [+ "test/eval-whoknows.test.ts",+ "module exports WhoknowsFn type alias",+ 1+ ],+ [+ "test/extract.test.ts",+ "is a function",+ 1+ ],+ [+ "test/facts-meta-cache.test.ts",+ "different allow-lists produce distinct cache entries",+ 2+ ],+ [+ "test/features.test.ts",+ "exports runFeatures",+ 1+ ],+ [+ "test/features.test.ts",+ "exports featuresTeaserForDoctor",+ 1+ ],+ [+ "test/features.test.ts",+ "covers all 7 recipes",+ 1+ ],+ [+ "test/find-experts-op.test.ts",+ "registered in the operations array",+ 1+ ],+ [+ "test/founder-scorecard.test.ts",+ "high drift score (>=0.5) fires a narrative_drift flag",+ 1+ ],+ [+ "test/frontmatter-non-string-fields.test.ts",+ "numeric type is coerced to a string (never crashes downstream)",+ 1+ ],+ [+ "test/get-brain-identity.test.ts",+ "is registered in operationsByName",+ 1+ ],+ [+ "test/get-status-snapshot-op.test.ts",+ "exists and is registered in the operations array",+ 2+ ],+ [+ "test/get-timeline-op.test.ts",+ "threads after/before/limit with federated source scope",+ 1+ ],+ [+ "test/link-extraction.test.ts",+ "extracts bare slug references in text",+ 1+ ],+ [+ "test/lint-content-sanity.test.ts",+ "respects custom bytes_warn override",+ 1+ ],+ [+ "test/lint-content-sanity.test.ts",+ "fires on access_denied body pattern",+ 1+ ],+ [+ "test/lint-content-sanity.test.ts",+ "junk_patterns_enabled=false suppresses operator literals AND built-ins via consumer wiring",+ 1+ ],+ [+ "test/lint-content-sanity.test.ts",+ "LLM preamble rule still fires",+ 1+ ],+ [+ "test/markdown-validation.test.ts",+ "opens but never closes, no heading",+ 1+ ],+ [+ "test/memory-verbs-conformance.test.ts",+ "timeline dates honor the string|null card contract in-process (PGLite returns Date objects)",+ 3+ ],+ [+ "test/metric-glossary.test.ts",+ "every retrieval-IR metric is present",+ 1+ ],+ [+ "test/metric-glossary.test.ts",+ "every stability metric is present",+ 1+ ],+ [+ "test/metric-glossary.test.ts",+ "every stat-significance metric is present",+ 1+ ],+ [+ "test/metric-glossary.test.ts",+ "every operational metric is present",+ 1+ ],+ [+ "test/migrate.test.ts",+ "runMigrations is exported and callable",+ 1+ ],+ [+ "test/migration-orchestrator-v0_21_0.test.ts",+ "phase functions exported for unit testing",+ 3+ ],+ [+ "test/migrations-v0_12_0.test.ts",+ "phase functions exported for unit testing",+ 6+ ],+ [+ "test/migrations-v0_12_2.test.ts",+ "phase functions exported for unit testing",+ 3+ ],+ [+ "test/migrations-v0_13_0.test.ts",+ "phase functions exported for unit testing",+ 3+ ],+ [+ "test/model-config.serial.test.ts",+ "cycle in aliases breaks at depth 2",+ 1+ ],+ [+ "test/model-pricing.test.ts",+ "cross-modal panel models are all priced from canonical",+ 1+ ],+ [+ "test/oauth.test.ts",+ "clientsStore exposes registerClient when dcrDisabled is false/unset",+ 1+ ],+ [+ "test/oauth.test.ts",+ "explicit client_secret_post \u2192 confidential client with secret",+ 1+ ],+ [+ "test/oauth.test.ts",+ "explicit client_secret_basic \u2192 confidential client with secret",+ 1+ ],+ [+ "test/ollama-recipe.test.ts",+ "declares a chat touchpoint",+ 2+ ],+ [+ "test/openrouter-reranker-recipe.test.ts",+ "declares a reranker touchpoint",+ 2+ ],+ [+ "test/operations-descriptions.test.ts",+ "all v0.29 ops in the allow-list resolve to a registered Operation",+ 1+ ],+ [+ "test/operations-descriptions.test.ts",+ "list_pages has new sort + updated_after params surfaced to MCP",+ 2+ ],+ [+ "test/operations-embedding-column.test.ts",+ "exists",+ 1+ ],+ [+ "test/operations-embedding-column.test.ts",+ "exists",+ 1+ ],+ [+ "test/operations-trust-boundary.test.ts",+ "every op declares a scope annotation",+ 1+ ],+ [+ "test/operations-trust-boundary.test.ts",+ "submit_job rejects shell with ctx.remote=true (HTTP MCP shell-job RCE class)",+ 1+ ],+ [+ "test/provider-fixture-env.test.ts",+ "covers every recipe credential and compatibility endpoint",+ 1+ ],+ [+ "test/public-exports.test.ts",+ "${entry.subpath} imports without throwing",+ 2+ ],+ [+ "test/salience.test.ts",+ "SalienceResult is a stable contract",+ 1+ ],+ [+ "test/salience.test.ts",+ "computeAnomaliesFromBuckets is exported and pure",+ 1+ ],+ [+ "test/schema-pack-manifest-v041_2.test.ts",+ "AggregatorKind type union covers exactly the enum values",+ 1+ ],+ [+ "test/schema-pack-registry.test.ts",+ "warn callback is optional (no opts arg works)",+ 1+ ],+ [+ "test/search-op-source-id.test.ts",+ "the op contract carries source_id (parity with query)",+ 2+ ],+ [+ "test/sources-mcp.test.ts",+ "include_archived: true returns archived sources",+ 1+ ],+ [+ "test/sources.test.ts",+ "orders default source first, then alphabetical",+ 1+ ],+ [+ "test/spawn-helpers.test.ts",+ "returns a string (smoke test only \u2014 actual presence depends on machine)",+ 1+ ],+ [+ "test/sync-repo-source-routing.test.ts",+ "explicit source_id param wins over the repo-derived source",+ 1+ ],+ [+ "test/sync-repo-source-routing.test.ts",+ "no conflict when ctx.sourceId matches the repo-derived source",+ 1+ ],+ [+ "test/sync.test.ts",+ "SyncResult exposes embedded count field",+ 1+ ],+ [+ "test/takes-holder-validation.test.ts",+ "users/garry \u2192 warning emitted",+ 1+ ],+ [+ "test/think-pipeline.serial.test.ts",+ "C3: remote caller with explicit bad model \u2192 op throws (modelExplicit wired)",+ 1+ ],+ [+ "test/transcription.test.ts",+ "module exports transcribe function",+ 1+ ],+ [+ "test/transcription.test.ts",+ "TranscriptionResult interface shape",+ 1+ ],+ [+ "test/transcription.test.ts",+ "detects provider from env vars",+ 1+ ],+ [+ "test/v0_37_fix_wave.serial.test.ts",+ "reinit-pglite module exports runReinitPglite",+ 1+ ],+ [+ "test/v81-v82-smoke.test.ts",+ "v82 accepts JSONB shape for per-source snapshot",+ 1+ ],+ [+ "test/whoknows.test.ts",+ "public surface: rankCandidates / findExperts / runWhoknows are functions",+ 3+ ],+ [+ "test/ai/build-gateway-config.test.ts",+ "importing buildGatewayConfig does NOT trigger main() (no help on stdout)",+ 2+ ],+ [+ "test/ai/gateway-chat.test.ts",+ "chat() function is exported with the expected signature",+ 1+ ],+ [+ "test/ai/gateway-chat.test.ts",+ "ChatBlock + ChatMessage + ChatResult types are exported",+ 1+ ],+ [+ "test/ai/recipe-llama-server.test.ts",+ "declares a probe function",+ 1+ ],+ [+ "test/ai/recipe-ollama-thinking.test.ts",+ "declares thinking_by_default as a per-model predicate",+ 1+ ],+ [+ "test/chunkers/code.test.ts",+ "large chunk stays independent",+ 1+ ],+ [+ "test/code-intel/scope-walker-resolution.test.ts",+ "Pattern 2: this.m() inside a class resolves to Class::m",+ 1+ ],+ [+ "test/code-intel/scope-walker-resolution.test.ts",+ "Pattern 3: new C().m() resolves to C::m via top-level binding",+ 1+ ],+ [+ "test/code-intel/scope-walker-resolution.test.ts",+ "Pattern 1: imported symbol resolves to module::method",+ 1+ ],+ [+ "test/code-intel/scope-walker-resolution.test.ts",+ "bare function call stays bare-token",+ 1+ ],+ [+ "test/code-intel/scope-walker-resolution.test.ts",+ "unresolvable member call falls back to bare token (no crash)",+ 1+ ],+ [+ "test/code-intel/scope-walker-resolution.test.ts",+ "Pattern 2: self.m() inside a class resolves to Class::m",+ 1+ ],+ [+ "test/code-intel/scope-walker-resolution.test.ts",+ "Pattern 1: from pkg import obj resolves to pkg::method",+ 1+ ],+ [+ "test/code-intel/scope-walker-resolution.test.ts",+ "Pattern 3: obj = ClassName() resolves to ClassName::method",+ 1+ ],+ [+ "test/cycle/nightly-probe-adapters.test.ts",+ "missing summary file \u2192 throws with paste-ready hint",+ 1+ ],+ [+ "test/cycle/nightly-probe-adapters.test.ts",+ "malformed summary JSON \u2192 throws with content prefix",+ 1+ ],+ [+ "test/cycle/yield-during-phase-refresh.test.ts",+ "returns a function when lock is present",+ 1+ ],+ [+ "test/cycle/yield-during-phase-refresh.test.ts",+ "returns a function when only outer is present",+ 1+ ],+ [+ "test/e2e/mcp.test.ts",+ "MCP server module can be imported",+ 2+ ],+ [+ "test/e2e/schema-drift.test.ts",+ "regression #588: ${sentinel} columns match across engines",+ 2+ ],+ [+ "test/e2e/salience-anomalies-source-isolation-pglite.test.ts",+ "sourceIds=[default,src-b] surfaces both cohorts",+ 2+ ],+ [+ "test/helpers/agent-harness.unit.test.ts",+ "resolveClaudeBinary returns a string or null",+ 1+ ],+ [+ "test/helpers/agent-harness.unit.test.ts",+ "resolveCodexBinary returns a string or null",+ 1+ ],+ [+ "test/helpers/agent-harness.unit.test.ts",+ "resolveHermesBinary returns a string or null",+ 1+ ],+ [+ "test/helpers/agent-harness.unit.test.ts",+ "hasHermesAuth returns a boolean",+ 1+ ],+ [+ "test/search/modes-report-coverage.test.ts",+ "the previously-hardcoded-out knobs now resolve (reranker + relational)",+ 1+ ],+ [+ "test/search/query-op-adaptive-return.test.ts",+ "query op exists",+ 1+ ],+ [+ "test/search/query-op-autocut.test.ts",+ "query op exists",+ 1+ ]+ ],+ "restate": [+ [+ "test/bootstrap-status.serial.test.ts",+ "PHASES matches BOOTSTRAP_PHASE_IDS exactly, in order",+ "BOOTSTRAP_PHASE_IDS",+ 8+ ],+ [+ "test/brainbench-fixtures.test.ts",+ "toPublicTurn picks exactly the public fields \u2014 smuggled keys dropped",+ "Object.keys(pub).sort()",+ 4+ ],+ [+ "test/by-mention.test.ts",+ "LINKABLE_ENTITY_TYPES exposes the hardcoded contract",+ "LINKABLE_ENTITY_TYPES",+ 4+ ],+ [+ "test/cjk.test.ts",+ "CJK_CLAUSE_DELIMITERS covers \uff1b\uff1a\uff0c\u3001",+ "CJK_CLAUSE_DELIMITERS",+ 4+ ],+ [+ "test/codex-plugin-manifest.test.ts",+ "deny-unknown-fields: only observed codex keys",+ "Object.keys(server).sort()",+ 4+ ],+ [+ "test/connect.test.ts",+ "exposes the five supported agents",+ "AGENT_IDS",+ 5+ ],+ [+ "test/envelope-to-gbrain.test.ts",+ "a provider string carrying a newline cannot inject frontmatter keys",+ "Object.keys(parsed).sort()",+ 7+ ],+ [+ "test/envelope-to-gbrain.test.ts",+ "a created_at that %s cannot alter the frontmatter",+ "Object.keys(parsed).sort()",+ 7+ ],+ [+ "test/envelope-to-gbrain.test.ts",+ "hostile message ids cannot inject frontmatter keys or break the page",+ "Object.keys(frontmatter).sort()",+ 7+ ],+ [+ "test/envelope-to-gbrain.test.ts",+ "a hostile non-string ts cannot break the frontmatter",+ "Object.keys(frontmatter).sort()",+ 7+ ],+ [+ "test/eval-takes-quality-rubric.test.ts",+ "dim names match plan + docs (codex review #5 strict-required-dim contract)",+ "RUBRIC_DIMENSIONS",+ 5+ ],+ [+ "test/get-agent-job.test.ts",+ "returns only the trimmed keys \u2014 never data/prompt",+ "Object.keys(r).sort()",+ 7+ ],+ [+ "test/git-remote.test.ts",+ "exact shape \u2014 global -c config flags only (spread BEFORE the verb)",+ "[...GIT_SSRF_FLAGS]",+ 6+ ],+ [+ "test/longmemeval-judge.test.ts",+ "unpriced judge model \u2192 cost_usd null (never 0); the vocabulary is closed",+ "JUDGE_ERROR_CLASSES",+ 6+ ],+ [+ "test/longmemeval-judge.test.ts",+ "denominators and sub-blocks",+ "Object.keys(qa.by_type)",+ 4+ ],+ [+ "test/migrate-engine-completeness.serial.test.ts",+ "every row copies except denylisted keys, which are reported as skipped",+ "[...result.skipped].sort()",+ 4+ ],+ [+ "test/migration-ledger.test.ts",+ "migrations block carries the four ledger keys",+ "Object.keys(body.migrations).sort()",+ 4+ ],+ [+ "test/migrations-v0_11_0.test.ts",+ "includes exactly the seven v0.11.0 builtins",+ "[...BUILTIN_HANDLERS].sort()",+ 7+ ],+ [+ "test/migrations-v126.test.ts",+ "table has expected columns with expected types and defaults",+ "Object.keys(byName).sort()",+ 8+ ],+ [+ "test/migrations-v94.test.ts",+ "table has expected columns with expected types",+ "Object.keys(byName).sort()",+ 6+ ],+ [+ "test/minions-shell.test.ts",+ "result shape includes all declared keys",+ "Object.keys(res).sort()",+ 5+ ],+ [+ "test/regression-v0_16_4.test.ts",+ "JSON envelope shape is stable (keys unchanged from v0.16.4)",+ "Object.keys(report).sort()",+ 5+ ],+ [+ "test/regression-v0_16_4.test.ts",+ "JSON envelope shape is stable (keys unchanged from v0.16.4)",+ "Object.keys(report.summary).sort()",+ 5+ ],+ [+ "test/replay-autocut-floor.test.ts",+ "validate-live passes on a consistent capture and fails (exit 1) on a tampered one",+ "Object.keys(out._meta.metric_glossary).sort()",+ 4+ ],+ [+ "test/resolvers.test.ts",+ "x_handle_to_tweet candidates declares full item shape with required + additionalProperties:false",+ "Object.keys(props).sort()",+ 5+ ],+ [+ "test/schema-pack-manifest-v041_2.test.ts",+ "exposes exactly 4 v1 aggregator kinds",+ "AGGREGATOR_KINDS",+ 4+ ],+ [+ "test/scope.test.ts",+ "list is sorted alphabetically (deterministic for wire/drift check)",+ "[...ALLOWED_SCOPES_LIST]",+ 9+ ],+ [+ "test/source-resolver-with-tier.test.ts",+ "canonical order is 1=flag \u2192 7=seed_default with sole_non_default at 5.5",+ "SOURCE_TIER_NAMES",+ 7+ ],+ [+ "test/sync-isSyncable-shape.test.ts",+ "SYNC_SKIP_FILES export contains the canonical structural metafiles",+ "[...SYNC_SKIP_FILES]",+ 5+ ],+ [+ "test/workspace-push.serial.test.ts",+ "the deny list covers the documented classes",+ "PUSH_DENY_GLOBS",+ 5+ ],+ [+ "test/context/sync-ipc-validation.test.ts",+ "field table and options interface stay in lockstep",+ "Object.keys(DELEGATED_SYNC_OPTION_FIELDS).sort()",+ 11+ ],+ [+ "test/e2e/client-grants.test.ts",+ "legacy admin output stays compatible and raw incomplete agent grants return 400",+ "Object.keys(body).sort()",+ 4+ ]+ ]+}\ No newline at end of filediff --git a/docs/test-audit/2026-09-29/lane-seams/bundled-src.txt b/docs/test-audit/2026-09-29/lane-seams/bundled-src.txtnew file mode 100644index 0000000000..5c634ad2c0--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-seams/bundled-src.txt@@ -0,0 +1,1402 @@+src/admin-embedded.ts+src/cli.ts+src/commands/advisor.ts+src/commands/agent-logs.ts+src/commands/agent-register.ts+src/commands/agent.ts+src/commands/anomalies.ts+src/commands/apply-migrations.ts+src/commands/auth.ts+src/commands/autopilot-fanout.ts+src/commands/autopilot-remediation-policy.ts+src/commands/autopilot-timeout.ts+src/commands/autopilot.ts+src/commands/backfill.ts+src/commands/backlinks.ts+src/commands/backup.ts+src/commands/bench-publish.ts+src/commands/book-mirror.ts+src/commands/bootstrap.ts+src/commands/brainstorm.ts+src/commands/cache.ts+src/commands/calibration.ts+src/commands/call.ts+src/commands/capture.ts+src/commands/check-resolvable.ts+src/commands/check-update.ts+src/commands/claw-test.ts+src/commands/code-callees.ts+src/commands/code-callers.ts+src/commands/code-def.ts+src/commands/code-refs.ts+src/commands/code-scope.ts+src/commands/company-brain-connect.ts+src/commands/company-brain-demo.ts+src/commands/company-brain-inspect.ts+src/commands/compile-context.ts+src/commands/config.ts+src/commands/connect.ts+src/commands/connectors/auth.ts+src/commands/connectors/index.ts+src/commands/connectors/status.ts+src/commands/connectors/sync.ts+src/commands/conversation-parser.ts+src/commands/creds.ts+src/commands/db-repair.ts+src/commands/doctor-asset-paths.ts+src/commands/doctor.ts+src/commands/doctor/bootstrap-checks.ts+src/commands/doctor/checks/backup-coverage.ts+src/commands/doctor/checks/calibration.ts+src/commands/doctor/checks/canonical-content.ts+src/commands/doctor/checks/connectors.ts+src/commands/doctor/checks/consolidation-cycle.ts+src/commands/doctor/checks/conversation-coverage.ts+src/commands/doctor/checks/core-health.ts+src/commands/doctor/checks/default-source-path.ts+src/commands/doctor/checks/engine-fit.ts+src/commands/doctor/checks/extraction-sync.ts+src/commands/doctor/checks/fts-reindex.ts+src/commands/doctor/checks/google-oauth.ts+src/commands/doctor/checks/graph-embedding.ts+src/commands/doctor/checks/home-worktree.ts+src/commands/doctor/checks/integrations-memorable.ts+src/commands/doctor/checks/memory-writeback.ts+src/commands/doctor/checks/pglite-worker.ts+src/commands/doctor/checks/postgres-cancellation.ts+src/commands/doctor/checks/projection-readiness.ts+src/commands/doctor/checks/queue-jobs.ts+src/commands/doctor/checks/routing-federation.ts+src/commands/doctor/checks/search-eval.ts+src/commands/doctor/checks/stale-mentions.ts+src/commands/doctor/checks/sync-failures.ts+src/commands/doctor/checks/verbs-reflex.ts+src/commands/doctor/report-remote.ts+src/commands/doctor/schema-pack-checks.ts+src/commands/doctor/skill-checks.ts+src/commands/dream-retriage-constants.ts+src/commands/dream-retriage.ts+src/commands/dream.ts+src/commands/edges-backfill.ts+src/commands/embed-facts-delegate.ts+src/commands/embed.ts+src/commands/engine-status.ts+src/commands/enrich.ts+src/commands/eval-brainbench.ts+src/commands/eval-brainstorm.ts+src/commands/eval-chronicle.ts+src/commands/eval-code-retrieval.ts+src/commands/eval-compare.ts+src/commands/eval-conversation-parser.ts+src/commands/eval-cross-modal.ts+src/commands/eval-export.ts+src/commands/eval-gate.ts+src/commands/eval-longmemeval.ts+src/commands/eval-prune.ts+src/commands/eval-replay.ts+src/commands/eval-retrieval-quality.ts+src/commands/eval-run-all.ts+src/commands/eval-suspected-contradictions.ts+src/commands/eval-synthesize-concepts.ts+src/commands/eval-takes-quality.ts+src/commands/eval-trajectory.ts+src/commands/eval-whoknows.ts+src/commands/eval.ts+src/commands/export.ts+src/commands/extract-attendance-repair.ts+src/commands/extract-benchmark.ts+src/commands/extract-conversation-facts.ts+src/commands/extract-explain.ts+src/commands/extract-status.ts+src/commands/extract.ts+src/commands/features.ts+src/commands/files.ts+src/commands/founder-scorecard.ts+src/commands/friction.ts+src/commands/frontmatter-install-hook.ts+src/commands/frontmatter.ts+src/commands/google-attachments.ts+src/commands/google-setup-tail.ts+src/commands/google-setup.ts+src/commands/google.ts+src/commands/graph-query.ts+src/commands/harness-connect.ts+src/commands/hook.ts+src/commands/import.ts+src/commands/init-mode-picker.ts+src/commands/init-prefer-postgres.ts+src/commands/init-provider-picker.ts+src/commands/init.ts+src/commands/integrations.ts+src/commands/integrity.ts+src/commands/jobs-readiness.ts+src/commands/jobs-watch.ts+src/commands/jobs.ts+src/commands/lint.ts+src/commands/loops.ts+src/commands/maintain.ts+src/commands/mcp-admin-http.ts+src/commands/mcp-admin.ts+src/commands/mcp-expose-probe.ts+src/commands/mcp-expose.ts+src/commands/mcp-provision.ts+src/commands/mcp.ts+src/commands/migrate-embeddings.ts+src/commands/migrate-engine.ts+src/commands/migrations/in-process.ts+src/commands/migrations/index.ts+src/commands/migrations/shared-content.ts+src/commands/migrations/v0_11_0.ts+src/commands/migrations/v0_12_0.ts+src/commands/migrations/v0_12_2.ts+src/commands/migrations/v0_13_0.ts+src/commands/migrations/v0_13_1.ts+src/commands/migrations/v0_14_0.ts+src/commands/migrations/v0_16_0.ts+src/commands/migrations/v0_18_0-storage-backfill.ts+src/commands/migrations/v0_18_0.ts+src/commands/migrations/v0_18_1.ts+src/commands/migrations/v0_21_0.ts+src/commands/migrations/v0_22_4.ts+src/commands/migrations/v0_28_0.ts+src/commands/migrations/v0_29_1.ts+src/commands/migrations/v0_31_0.ts+src/commands/migrations/v0_32_2.ts+src/commands/migrations/v0_43_0.ts+src/commands/migrations/v0_46_3.ts+src/commands/models.ts+src/commands/mounts.ts+src/commands/notability-eval.ts+src/commands/onboard.ts+src/commands/orphans.ts+src/commands/pages.ts+src/commands/persistence-admin.ts+src/commands/persistence-delegate.ts+src/commands/pglite-repair.ts+src/commands/protocol.ts+src/commands/providers.ts+src/commands/publish.ts+src/commands/quarantine.ts+src/commands/recall.ts+src/commands/reconcile-links.ts+src/commands/reindex-aliases.ts+src/commands/reindex-code-delegate.ts+src/commands/reindex-code.ts+src/commands/reindex-frontmatter.ts+src/commands/reindex-multimodal.ts+src/commands/reindex-search-vector.ts+src/commands/reindex.ts+src/commands/reinit-pglite.ts+src/commands/remote.ts+src/commands/repair-jsonb.ts+src/commands/report.ts+src/commands/resolvers.ts+src/commands/routing-eval.ts+src/commands/salience.ts+src/commands/schema.ts+src/commands/search-diagnose.ts+src/commands/search.ts+src/commands/self-upgrade.ts+src/commands/serve-http-admin-limits.ts+src/commands/serve-http-clients.ts+src/commands/serve-http-grants.ts+src/commands/serve-http-metrics.ts+src/commands/serve-http-oauth.ts+src/commands/serve-http-registration.ts+src/commands/serve-http.ts+src/commands/serve.ts+src/commands/skillify-check.ts+src/commands/skillify.ts+src/commands/skillopt.ts+src/commands/skillpack-check.ts+src/commands/skillpack.ts+src/commands/skillpack/harness.ts+src/commands/skillpack/reference.ts+src/commands/skillpack/scaffold.ts+src/commands/skillpack/shared.ts+src/commands/source-reconcile.ts+src/commands/sources-demo.ts+src/commands/sources-harden.ts+src/commands/sources-lifecycle-args.ts+src/commands/sources-lifecycle.ts+src/commands/sources-set-path.ts+src/commands/sources.ts+src/commands/status.ts+src/commands/storage.ts+src/commands/sweep-delegate.ts+src/commands/sweep.ts+src/commands/sync-delegate.ts+src/commands/sync-diagnostics.ts+src/commands/sync-persistence-delegate.ts+src/commands/sync.ts+src/commands/takes-mutation.ts+src/commands/takes.ts+src/commands/thin-client-routing.ts+src/commands/think.ts+src/commands/tools-json.ts+src/commands/transcripts.ts+src/commands/upgrade.ts+src/commands/watch.ts+src/commands/whoknows.ts+src/core/abort-check.ts+src/core/advisor/apply.ts+src/core/advisor/collect-backup-coverage.ts+src/core/advisor/collect-chronicle.ts+src/core/advisor/collect-mcp-client-fit.ts+src/core/advisor/collect-migration.ts+src/core/advisor/collect-schema-pack.ts+src/core/advisor/collect-setup-smells.ts+src/core/advisor/collect-stalled-jobs.ts+src/core/advisor/collect-uninstalled-brain-pack.ts+src/core/advisor/collect-uninstalled-bundled.ts+src/core/advisor/collect-usage-shape.ts+src/core/advisor/collect-version.ts+src/core/advisor/collect-writeback-consent.ts+src/core/advisor/history.ts+src/core/advisor/recommended-set.ts+src/core/advisor/render.ts+src/core/advisor/run.ts+src/core/agent-install/entry.ts+src/core/agent-install/environment.ts+src/core/agent-install/init-state.ts+src/core/agent-install/launcher.ts+src/core/agent-install/setup.ts+src/core/agent-install/shared-skills.ts+src/core/agent-install/state.ts+src/core/ai/anthropic-key.ts+src/core/ai/anthropic-model-ids.ts+src/core/ai/base-url-probe.ts+src/core/ai/budget-record.ts+src/core/ai/build-gateway-config.ts+src/core/ai/capabilities.ts+src/core/ai/chat-usage.ts+src/core/ai/defaults.ts+src/core/ai/dims.ts+src/core/ai/errors.ts+src/core/ai/gateway-model-sources.ts+src/core/ai/gateway.ts+src/core/ai/guarded-generation.ts+src/core/ai/invocation-guard.ts+src/core/ai/model-resolver.ts+src/core/ai/openai-latest.ts+src/core/ai/openrouter-families.ts+src/core/ai/probes.ts+src/core/ai/provider-env.ts+src/core/ai/providers/claude-cli-language-model.ts+src/core/ai/providers/claude-cli-scratch.ts+src/core/ai/recipes/anthropic.ts+src/core/ai/recipes/azure-openai.ts+src/core/ai/recipes/claude-cli.ts+src/core/ai/recipes/dashscope-rerank.ts+src/core/ai/recipes/dashscope.ts+src/core/ai/recipes/deepseek.ts+src/core/ai/recipes/google.ts+src/core/ai/recipes/groq.ts+src/core/ai/recipes/index.ts+src/core/ai/recipes/litellm-proxy.ts+src/core/ai/recipes/llama-server-reranker.ts+src/core/ai/recipes/llama-server.ts+src/core/ai/recipes/lmstudio.ts+src/core/ai/recipes/minimax.ts+src/core/ai/recipes/mistral.ts+src/core/ai/recipes/moonshot.ts+src/core/ai/recipes/nan.ts+src/core/ai/recipes/nvidia.ts+src/core/ai/recipes/ollama.ts+src/core/ai/recipes/openai.ts+src/core/ai/recipes/openrouter.ts+src/core/ai/recipes/perplexity.ts+src/core/ai/recipes/together.ts+src/core/ai/recipes/voyage.ts+src/core/ai/recipes/zhipu.ts+src/core/ai/reranker-readiness-engine.ts+src/core/ai/reranker-readiness.ts+src/core/anthropic-pricing.ts+src/core/atomic-write.ts+src/core/attendance-repair.ts+src/core/audit-parser-probe.ts+src/core/audit-quality-probe.ts+src/core/audit-skill-brain-first.ts+src/core/audit-slug-fallback.ts+src/core/audit-synopsis.ts+src/core/audit-week-file.ts+src/core/audit/audit-writer.ts+src/core/audit/batch-retry-audit.ts+src/core/audit/content-sanity-audit.ts+src/core/audit/db-disconnect-audit.ts+src/core/audit/lock-renewal-audit.ts+src/core/audit/pool-recovery-audit.ts+src/core/audit/redact-connection-info.ts+src/core/audit/self-upgrade-audit.ts+src/core/autopilot-lock.ts+src/core/autopilot-paths.ts+src/core/backfill-base.ts+src/core/backfill-effective-date.ts+src/core/backfill-registry.ts+src/core/background-work.ts+src/core/backoff.ts+src/core/backup/archive.ts+src/core/backup/coverage.ts+src/core/backup/private-path.ts+src/core/backup/quarantine.ts+src/core/backup/repository.ts+src/core/backup/snapshot.ts+src/core/backup/status-file.ts+src/core/batch-rows.ts+src/core/bench/baseline-file.ts+src/core/bench/correctness-gate.ts+src/core/bench/qrels-file.ts+src/core/binary-self-update.ts+src/core/bootstrap/assets.ts+src/core/bootstrap/atomic-write.ts+src/core/bootstrap/attach.ts+src/core/bootstrap/codex-hooks.ts+src/core/bootstrap/codex-toml.ts+src/core/bootstrap/contract.ts+src/core/bootstrap/format.ts+src/core/bootstrap/harness.ts+src/core/bootstrap/hooks.ts+src/core/bootstrap/host-specs.ts+src/core/bootstrap/instructions-block.ts+src/core/bootstrap/interview.ts+src/core/bootstrap/lock.ts+src/core/bootstrap/opencode-json.ts+src/core/bootstrap/render.ts+src/core/bootstrap/repo.ts+src/core/bootstrap/serve-health.ts+src/core/bootstrap/status.ts+src/core/bootstrap/uninstall.ts+src/core/bootstrap/verify.ts+src/core/brain-registry.ts+src/core/brain-repo-durability.ts+src/core/brain-resolver.ts+src/core/brain-score-recommendations.ts+src/core/brain-writer.ts+src/core/brainstorm/checkpoint.ts+src/core/brainstorm/domain-bank.ts+src/core/brainstorm/error-classify.ts+src/core/brainstorm/judges.ts+src/core/brainstorm/orchestrator.ts+src/core/budget/budget-tracker.ts+src/core/budget/models-used.ts+src/core/budget/reservation-cost.ts+src/core/by-mention.ts+src/core/calibration/domain-aggregators.ts+src/core/calibration/gstack-coupling.ts+src/core/calibration/svg-renderer.ts+src/core/calibration/templates.ts+src/core/calibration/think-ab.ts+src/core/calibration/undo-wave.ts+src/core/calibration/voice-gate.ts+src/core/capability.ts+src/core/capture-content.ts+src/core/check-resolvable.ts+src/core/chronicle/config.ts+src/core/chronicle/eligibility.ts+src/core/chronicle/extract-events.ts+src/core/chronicle/last-seen.ts+src/core/chronicle/narrative.ts+src/core/chronicle/ontology.ts+src/core/chunkers/code.ts+src/core/chunkers/component-markup.ts+src/core/chunkers/def-types.ts+src/core/chunkers/edge-extractor.ts+src/core/chunkers/qualified-names.ts+src/core/chunkers/recursive.ts+src/core/chunkers/symbol-resolver.ts+src/core/chunkers/token-estimate.ts+src/core/cjk.ts+src/core/claw-test/agent-runner.ts+src/core/claw-test/progress-tail.ts+src/core/claw-test/runners/grok.ts+src/core/claw-test/runners/hermes.ts+src/core/claw-test/runners/openclaw.ts+src/core/claw-test/runners/opencode.ts+src/core/claw-test/scenarios.ts+src/core/claw-test/seed-pglite.ts+src/core/claw-test/transcript-capture.ts+src/core/cli-flag-registry.generated.ts+src/core/cli-force-exit.ts+src/core/cli-options.ts+src/core/cli-preflight.ts+src/core/cli-util.ts+src/core/code-chunks.ts+src/core/code-graph-readiness.ts+src/core/code-intel/read-scope.ts+src/core/code-intel/recursive-walk.ts+src/core/code-intel/sinks/index.ts+src/core/code-intel/sinks/py.ts+src/core/code-intel/sinks/ts.ts+src/core/code-intel/traversal-cache.ts+src/core/company-brain/admission.ts+src/core/company-brain/demo.ts+src/core/company-brain/evidence.ts+src/core/company-brain/inspection.ts+src/core/company-brain/policy.ts+src/core/company-brain/profile.ts+src/core/company-brain/receipt-schema.ts+src/core/company-brain/receipts.ts+src/core/company-brain/revision.ts+src/core/company-brain/runtime.ts+src/core/company-brain/sample.ts+src/core/company-brain/status.ts+src/core/company-brain/types.ts+src/core/company-brain/verification.ts+src/core/config-db-merge.ts+src/core/config-snapshot.ts+src/core/config.ts+src/core/confirm-prompt.ts+src/core/connect-probe.ts+src/core/connection-audit.ts+src/core/connection-manager.ts+src/core/connectors/classify.ts+src/core/connectors/client.ts+src/core/connectors/config-keys.ts+src/core/connectors/credentials.ts+src/core/connectors/oauth-pkce.ts+src/core/connectors/providers/chatgpt.ts+src/core/connectors/providers/claude.ts+src/core/connectors/registry.ts+src/core/connectors/spool.ts+src/core/connectors/sync.ts+src/core/console-prefix.ts+src/core/content-sanity-literals.ts+src/core/content-sanity.ts+src/core/context-engine.ts+src/core/context/checkpoint-harvest.ts+src/core/context/chronicle-context.ts+src/core/context/compile-view.ts+src/core/context/corpus-segments.ts+src/core/context/entity-salience.ts+src/core/context/hook-heartbeat.ts+src/core/context/ipc-path.ts+src/core/context/reflex-rationale.ts+src/core/context/reflex.ts+src/core/context/resolve-ipc.ts+src/core/context/retrieval-reflex.ts+src/core/context/sensitivity-scan.ts+src/core/context/session-state.ts+src/core/context/sweep-ipc.ts+src/core/context/sync-ipc.ts+src/core/context/turn-context.ts+src/core/context/volunteer-events.ts+src/core/context/volunteer.ts+src/core/context/windows-ipc.ts+src/core/contextual-retrieval-resolver.ts+src/core/contextual-retrieval-service.ts+src/core/conversation-parser/body.ts+src/core/conversation-parser/builtins.ts+src/core/conversation-parser/eval.ts+src/core/conversation-parser/llm-base.ts+src/core/conversation-parser/llm-fallback.ts+src/core/conversation-parser/nightly-probe.ts+src/core/conversation-parser/normalize-block.ts+src/core/conversation-parser/parse.ts+src/core/conversation-parser/transcript-signals.ts+src/core/creds/errors.ts+src/core/creds/export.ts+src/core/creds/providers/google.ts+src/core/creds/redirect.ts+src/core/creds/relay-client.ts+src/core/creds/vault.ts+src/core/cross-modal-eval/aggregate.ts+src/core/cross-modal-eval/json-repair.ts+src/core/cross-modal-eval/receipt-name.ts+src/core/cross-modal-eval/receipt-write.ts+src/core/cross-modal-eval/runner.ts+src/core/cycle.ts+src/core/cycle/anomaly.ts+src/core/cycle/base-phase.ts+src/core/cycle/budget-meter.ts+src/core/cycle/calibration-profile.ts+src/core/cycle/conversation-facts-backfill.ts+src/core/cycle/cycle-date.ts+src/core/cycle/drift.ts+src/core/cycle/emotional-weight.ts+src/core/cycle/enrich-thin.ts+src/core/cycle/extract-atoms-cost-gate.ts+src/core/cycle/extract-atoms-drain.ts+src/core/cycle/extract-atoms-page-state.ts+src/core/cycle/extract-atoms.ts+src/core/cycle/extract-facts.ts+src/core/cycle/extract-takes.ts+src/core/cycle/filing-rules.ts+src/core/cycle/grade-takes.ts+src/core/cycle/inline-drain.ts+src/core/cycle/link-manifest.ts+src/core/cycle/nightly-probe-adapters.ts+src/core/cycle/nightly-probe-search-config.ts+src/core/cycle/nightly-quality-probe.ts+src/core/cycle/patterns.ts+src/core/cycle/phantom-redirect.ts+src/core/cycle/phase-scope.ts+src/core/cycle/phases/consolidate.ts+src/core/cycle/propose-takes.ts+src/core/cycle/recompute-emotional-weight.ts+src/core/cycle/schema-suggest.ts+src/core/cycle/synthesize-concepts.ts+src/core/cycle/synthesize-postprocess.ts+src/core/cycle/synthesize-verify.ts+src/core/cycle/synthesize.ts+src/core/cycle/transcript-discovery.ts+src/core/cycle/triage-rescue.ts+src/core/data-frontmatter.ts+src/core/db-lock.ts+src/core/db-pacer.ts+src/core/db-repair-receipts.ts+src/core/db.ts+src/core/deep-research-id.ts+src/core/default-source-path-check.ts+src/core/degraded-engine.ts+src/core/degraded-marker.ts+src/core/derived-links.ts+src/core/destructive-guard.ts+src/core/disk-walk.ts+src/core/docker-postgres.ts+src/core/doctor-categories.ts+src/core/doctor-cause-rank.ts+src/core/doctor-remote.ts+src/core/dry-fix.ts+src/core/effective-date.ts+src/core/embed-backfill-lock.ts+src/core/embed-backfill-submit.ts+src/core/embed-facts-options.ts+src/core/embed-facts.ts+src/core/embed-oversize-heal.ts+src/core/embed-preflight.ts+src/core/embed-retry.ts+src/core/embed-reuse.ts+src/core/embed-skip.ts+src/core/embed-stale.ts+src/core/embed-stall.ts+src/core/embed-takes.ts+src/core/embedding-context.ts+src/core/embedding-dim-check.ts+src/core/embedding-input-limit.ts+src/core/embedding-invalidation.ts+src/core/embedding-migration-budget.ts+src/core/embedding-migration-cli.ts+src/core/embedding-migration-retention.ts+src/core/embedding-migration.ts+src/core/embedding-pricing.ts+src/core/embedding-readiness.ts+src/core/embedding.ts+src/core/engine-constants.ts+src/core/engine-errors.ts+src/core/engine-factory.ts+src/core/engine.ts+src/core/enrich/thin.ts+src/core/enrichment-service.ts+src/core/entities/resolve-on-save.ts+src/core/entities/resolve.ts+src/core/entity-identity.ts+src/core/entity-name-quality.ts+src/core/env-number.ts+src/core/env-trust.ts+src/core/errors.ts+src/core/eval-capture-scrub.ts+src/core/eval-capture.ts+src/core/eval-contradictions/auto-supersession.ts+src/core/eval-contradictions/cache.ts+src/core/eval-contradictions/calibration.ts+src/core/eval-contradictions/cost-prompt.ts+src/core/eval-contradictions/cost-tracker.ts+src/core/eval-contradictions/cross-source.ts+src/core/eval-contradictions/date-filter.ts+src/core/eval-contradictions/judge-errors.ts+src/core/eval-contradictions/judge.ts+src/core/eval-contradictions/run-health.ts+src/core/eval-contradictions/runner.ts+src/core/eval-contradictions/severity-classify.ts+src/core/eval-contradictions/trends.ts+src/core/eval-contradictions/types.ts+src/core/eval-shared/json-repair.ts+src/core/eval/cycle-default.ts+src/core/eval/drift-watch.ts+src/core/eval/metric-glossary.ts+src/core/eval/ranked-docs.ts+src/core/execution-env.ts+src/core/export-publish.ts+src/core/export-snapshot.ts+src/core/export-stage.ts+src/core/extract-frontmatter.ts+src/core/extract-ner.ts+src/core/extract-takes-from-pages.ts+src/core/extract-timeline-from-meetings.ts+src/core/extract/receipt-writer.ts+src/core/extract/rollup-writer.ts+src/core/extraction-review.ts+src/core/facts-fence.ts+src/core/facts/absorb-log.ts+src/core/facts/audit-sources.ts+src/core/facts/backstop.ts+src/core/facts/classify.ts+src/core/facts/cli-process-mode.ts+src/core/facts/conversation-types.ts+src/core/facts/decay.ts+src/core/facts/eligibility.ts+src/core/facts/embedding-identity.ts+src/core/facts/extract-from-fence.ts+src/core/facts/extract.ts+src/core/facts/fence-write.ts+src/core/facts/forget.ts+src/core/facts/meta-hook.ts+src/core/facts/phantom-audit.ts+src/core/facts/queue.ts+src/core/facts/single-prepare.ts+src/core/facts/stub-guard-audit.ts+src/core/facts/supersede-resolve.ts+src/core/facts/ttl-parse.ts+src/core/facts/visibility.ts+src/core/facts/withdrawal-discovery.ts+src/core/facts/withdrawal-overlay.ts+src/core/facts/withdrawal-schema.ts+src/core/facts/withdrawal.ts+src/core/facts/write-single.ts+src/core/facts/writeback-audience.ts+src/core/facts/writeback-config.ts+src/core/facts/writeback-gate.ts+src/core/facts/writeback-instructions.ts+src/core/feature-flags.ts+src/core/fence-scan.ts+src/core/fence-shared.ts+src/core/file-resolver.ts+src/core/filing-audit.ts+src/core/friction.ts+src/core/frontmatter-inference.ts+src/core/fts-language.ts+src/core/gbrain-env-file.ts+src/core/gbrain-home.ts+src/core/git-head.ts+src/core/git-remote.ts+src/core/git-visible-files.ts+src/core/github-source.ts+src/core/google/access.ts+src/core/google/attachment-backfill.ts+src/core/google/attachment-receipts.ts+src/core/google/google-clients.ts+src/core/google/google-render.ts+src/core/google/google-source.ts+src/core/google/loop-detect.ts+src/core/google/loops-extract.ts+src/core/google/types.ts+src/core/grants/cli.ts+src/core/grants/encoding.ts+src/core/grants/lifecycle.ts+src/core/grants/migration.ts+src/core/grants/model.ts+src/core/grants/profiles.ts+src/core/grants/rescope.ts+src/core/grants/schema.ts+src/core/grants/service.ts+src/core/guarded-http.ts+src/core/guardrails.ts+src/core/harness/arguments.ts+src/core/harness/capabilities.ts+src/core/harness/client-setup.ts+src/core/harness/credentials.ts+src/core/harness/delivery.ts+src/core/harness/install.ts+src/core/harness/native-router.ts+src/core/harness/oauth-setup.ts+src/core/harness/registry.ts+src/core/harness/shared-skills.ts+src/core/harness/status.ts+src/core/harness/verify.ts+src/core/import-checkpoint.ts+src/core/import-file.ts+src/core/import-identity.ts+src/core/index.ts+src/core/ingestion/index.ts+src/core/ingestion/test-harness.ts+src/core/ingestion/types.ts+src/core/init-embed-check.ts+src/core/init-schema-retry.ts+src/core/last-retrieved.ts+src/core/latin-fold.ts+src/core/lease-schema.ts+src/core/legacy-token-scope.ts+src/core/levenshtein.ts+src/core/link-extraction.ts+src/core/link-reconciliation.ts+src/core/link-source-check-repair.ts+src/core/llm-json.ts+src/core/loops/loops-store.ts+src/core/markdown-chunks.ts+src/core/markdown-code.ts+src/core/markdown.ts+src/core/mcp-client.ts+src/core/mcp-registration.ts+src/core/mcp-usage.ts+src/core/migrate.ts+src/core/migration-ledger.ts+src/core/minion-spend.ts+src/core/minions/admission.ts+src/core/minions/agent-audit.ts+src/core/minions/attachments.ts+src/core/minions/authorize-legacy.ts+src/core/minions/backoff.ts+src/core/minions/backpressure-audit.ts+src/core/minions/budget-meter.ts+src/core/minions/child-job-runner.ts+src/core/minions/child-readiness.ts+src/core/minions/child-worker-supervisor.ts+src/core/minions/configuration-error.ts+src/core/minions/db-probe.ts+src/core/minions/delegated-admission.ts+src/core/minions/delegated-policy.ts+src/core/minions/delegated-spend.ts+src/core/minions/delegated-tools.ts+src/core/minions/detached-stderr.ts+src/core/minions/embed-backfill-admission.ts+src/core/minions/error-classify.ts+src/core/minions/errors.ts+src/core/minions/exit-classification.ts+src/core/minions/handler-timeouts.ts+src/core/minions/handlers/connector-sync.ts+src/core/minions/handlers/contextual-reindex-per-chunk.ts+src/core/minions/handlers/embed-backfill.ts+src/core/minions/handlers/ingest-capture.ts+src/core/minions/handlers/shell-audit.ts+src/core/minions/handlers/shell-inherit.ts+src/core/minions/handlers/shell-redact.ts+src/core/minions/handlers/shell-validate.ts+src/core/minions/handlers/shell.ts+src/core/minions/handlers/subagent-aggregator.ts+src/core/minions/handlers/subagent-audit.ts+src/core/minions/handlers/subagent-oneshot.ts+src/core/minions/handlers/subagent-persistence.ts+src/core/minions/handlers/subagent.ts+src/core/minions/handlers/supervisor-audit.ts+src/core/minions/index.ts+src/core/minions/job-context.ts+src/core/minions/job-isolation.ts+src/core/minions/lease-pressure-audit.ts+src/core/minions/llm-halt-cooldown.ts+src/core/minions/lock-renewal-tick.ts+src/core/minions/niceness.ts+src/core/minions/plugin-loader.ts+src/core/minions/processing-state.ts+src/core/minions/protected-names.ts+src/core/minions/queue.ts+src/core/minions/quiet-hours.ts+src/core/minions/rate-leases.ts+src/core/minions/reconnect.ts+src/core/minions/rss-default.ts+src/core/minions/run-child.ts+src/core/minions/source-filesystem.ts+src/core/minions/spawn-helpers.ts+src/core/minions/submission-authority.ts+src/core/minions/supervisor-pid.ts+src/core/minions/supervisor.ts+src/core/minions/system-prompt.ts+src/core/minions/tool-write-identity.ts+src/core/minions/tools/brain-allowlist.ts+src/core/minions/tools/put-page-result.ts+src/core/minions/transcript.ts+src/core/minions/types.ts+src/core/minions/wait-for-completion.ts+src/core/minions/worker-exit-codes.ts+src/core/minions/worker-registry.ts+src/core/minions/worker.ts+src/core/model-config.ts+src/core/model-id.ts+src/core/model-pricing.ts+src/core/mounts-cache.ts+src/core/multi-source-drift.ts+src/core/npm-squat-check.ts+src/core/oauth-grants.ts+src/core/oauth-provider.ts+src/core/onboard/checks.ts+src/core/onboard/init-nudge.ts+src/core/onboard/render.ts+src/core/onboard/writeback-nudge.ts+src/core/op-checkpoint.ts+src/core/operations-descriptions.ts+src/core/operations.ts+src/core/ops/admin.ts+src/core/ops/brain-membership.ts+src/core/ops/calibration.ts+src/core/ops/chronicle.ts+src/core/ops/chunks.ts+src/core/ops/code-intel.ts+src/core/ops/connectors.ts+src/core/ops/context.ts+src/core/ops/contract.ts+src/core/ops/embedding-migration.ts+src/core/ops/entity-identity.ts+src/core/ops/extraction.ts+src/core/ops/facts.ts+src/core/ops/files.ts+src/core/ops/image.ts+src/core/ops/ingest-log.ts+src/core/ops/insights.ts+src/core/ops/jobs.ts+src/core/ops/links.ts+src/core/ops/loops.ts+src/core/ops/orphans.ts+src/core/ops/pages.ts+src/core/ops/persistence.ts+src/core/ops/raw-data.ts+src/core/ops/request-tools.ts+src/core/ops/salience.ts+src/core/ops/schema-packs.ts+src/core/ops/search.ts+src/core/ops/skillopt.ts+src/core/ops/skills-catalog.ts+src/core/ops/sources.ts+src/core/ops/sync-status.ts+src/core/ops/tags.ts+src/core/ops/takes.ts+src/core/ops/timeline.ts+src/core/ops/transcripts.ts+src/core/ops/usage.ts+src/core/orphan-policy.ts+src/core/output/post-write.ts+src/core/output/scaffold.ts+src/core/output/slug-registry.ts+src/core/output/validators/back-link.ts+src/core/output/validators/citation.ts+src/core/output/validators/index.ts+src/core/output/validators/link.ts+src/core/output/validators/triple-hr.ts+src/core/output/writer.ts+src/core/owner-holder.ts+src/core/pace-mode.ts+src/core/page-lock.ts+src/core/page-state/guards.ts+src/core/page-state/import-guard.ts+src/core/page-state/materialize.ts+src/core/page-state/projection-schema.ts+src/core/page-state/projections.ts+src/core/page-state/rename-alias.ts+src/core/page-state/schema.ts+src/core/page-state/snapshot.ts+src/core/page-state/tags.ts+src/core/page-state/transactions.ts+src/core/page-state/types.ts+src/core/page-state/versions.ts+src/core/page-summary.ts+src/core/pages-upsert-arbiter.ts+src/core/parallel.ts+src/core/path-confine.ts+src/core/persistence/activation.ts+src/core/persistence/admin-contract.ts+src/core/persistence/admin-intent.ts+src/core/persistence/administration.ts+src/core/persistence/admission-retry.ts+src/core/persistence/atom-maintenance.ts+src/core/persistence/atom-retry.ts+src/core/persistence/authority.ts+src/core/persistence/bundle-files.ts+src/core/persistence/canonical-projections.ts+src/core/persistence/connector-google-receipts.ts+src/core/persistence/connector-sync.ts+src/core/persistence/consumer.ts+src/core/persistence/context.ts+src/core/persistence/control.ts+src/core/persistence/coordinator.ts+src/core/persistence/diagnostics.ts+src/core/persistence/digest.ts+src/core/persistence/effect-facts.ts+src/core/persistence/effect-git.ts+src/core/persistence/effect-journal.ts+src/core/persistence/effect-recovery-scan.ts+src/core/persistence/effect-recovery.ts+src/core/persistence/effect-retry.ts+src/core/persistence/effect-schema.ts+src/core/persistence/effect-targets.ts+src/core/persistence/effects.ts+src/core/persistence/embed-facts-administration.ts+src/core/persistence/facts-maintenance.ts+src/core/persistence/facts-prepare.ts+src/core/persistence/filesystem-guard.ts+src/core/persistence/grandfather.ts+src/core/persistence/health.ts+src/core/persistence/identity.ts+src/core/persistence/import-mutations.ts+src/core/persistence/import-prepare.ts+src/core/persistence/ipc.ts+src/core/persistence/journal.ts+src/core/persistence/legacy-locks.ts+src/core/persistence/limits.ts+src/core/persistence/links-preparation.ts+src/core/persistence/local-client.ts+src/core/persistence/maintenance.ts+src/core/persistence/managed-sources.ts+src/core/persistence/memory-mutations.ts+src/core/persistence/memory-prepare.ts+src/core/persistence/model.ts+src/core/persistence/native-file-target.ts+src/core/persistence/native-lock.ts+src/core/persistence/onboarding.ts+src/core/persistence/ownership.ts+src/core/persistence/page-advisories.ts+src/core/persistence/page-input.ts+src/core/persistence/page-mutations.ts+src/core/persistence/page-prepare.ts+src/core/persistence/page-visibility.ts+src/core/persistence/params.ts+src/core/persistence/physical-root-record.ts+src/core/persistence/physical-root-recovery.ts+src/core/persistence/physical-root.ts+src/core/persistence/pool-capacity.ts+src/core/persistence/preconditions.ts+src/core/persistence/prepared-maintenance.ts+src/core/persistence/projection-reindex.ts+src/core/persistence/protected-takes.ts+src/core/persistence/protocol.ts+src/core/persistence/provider.ts+src/core/persistence/purge-params.ts+src/core/persistence/reconcile-audit.ts+src/core/persistence/reconcile-backup.ts+src/core/persistence/reconcile-merge.ts+src/core/persistence/reconcile-prepare.ts+src/core/persistence/reconcile-safety.ts+src/core/persistence/reconcile-state.ts+src/core/persistence/reconcile.ts+src/core/persistence/reindex-administration.ts+src/core/persistence/root-registry.ts+src/core/persistence/schema.ts+src/core/persistence/semantic-pages.ts+src/core/persistence/semantic.ts+src/core/persistence/service.ts+src/core/persistence/skill-activation.ts+src/core/persistence/source-lifecycle.ts+src/core/persistence/staging.ts+src/core/persistence/sync-administration.ts+src/core/persistence/sync-authority.ts+src/core/persistence/sync-discovery.ts+src/core/persistence/sync-failures.ts+src/core/persistence/sync-origin.ts+src/core/persistence/sync-prepare.ts+src/core/persistence/sync-run.ts+src/core/persistence/sync-wire.ts+src/core/persistence/takes-prepare.ts+src/core/persistence/topology-clone.ts+src/core/persistence/topology-filesystem.ts+src/core/persistence/topology-locks.ts+src/core/persistence/topology-receipts.ts+src/core/persistence/topology-recovery.ts+src/core/persistence/topology-schema.ts+src/core/persistence/topology-transaction.ts+src/core/persistence/types.ts+src/core/persistence/verb-errors.ts+src/core/persistence/writer-guard-schema.ts+src/core/pg-access-classify.ts+src/core/pglite-embedded-asset-paths.ts+src/core/pglite-embedded-assets.ts+src/core/pglite-engine.ts+src/core/pglite-engine/cjk-search.ts+src/core/pglite-engine/code-edges.ts+src/core/pglite-engine/facts.ts+src/core/pglite-engine/salience.ts+src/core/pglite-engine/takes.ts+src/core/pglite-leftovers-check.ts+src/core/pglite-lifecycle.ts+src/core/pglite-lock.ts+src/core/pglite-repair.ts+src/core/pglite-resetwal.ts+src/core/pglite-schema.ts+src/core/pid1-reaper.ts+src/core/pool-budget.ts+src/core/pool-gauge.ts+src/core/post-upgrade-reembed.ts+src/core/postgres-engine.ts+src/core/postgres-engine/cancellation.ts+src/core/postgres-engine/cjk-search.ts+src/core/postgres-engine/code-edges.ts+src/core/postgres-engine/facts.ts+src/core/postgres-engine/forward-reference-bootstrap.ts+src/core/postgres-engine/init-schema-lock.ts+src/core/postgres-engine/salience.ts+src/core/postgres-engine/takes.ts+src/core/preferences.ts+src/core/process-cleanup.ts+src/core/process-watchdog.ts+src/core/progress.ts+src/core/progressive-batch/audit.ts+src/core/quarantine.ts+src/core/recall-cursor-state.ts+src/core/remediation-checkpoint.ts+src/core/remediation-step.ts+src/core/remediation/context.ts+src/core/remediation/index.ts+src/core/remediation/plan.ts+src/core/remediation/run.ts+src/core/remote-body.ts+src/core/remote-mcp-probe.ts+src/core/repo-root.ts+src/core/repo-visibility.ts+src/core/rerank-audit.ts+src/core/resolver-filenames.ts+src/core/resolvers/builtin/url-reachable.ts+src/core/resolvers/builtin/x-api/handle-to-tweet.ts+src/core/resolvers/index.ts+src/core/resolvers/interface.ts+src/core/resolvers/registry.ts+src/core/retry-matcher.ts+src/core/retry.ts+src/core/routing-eval.ts+src/core/runtime-version.ts+src/core/schema-embedded.generated.ts+src/core/schema-events.ts+src/core/schema-pack/best-effort.ts+src/core/schema-pack/bundled-assets.ts+src/core/schema-pack/bundled.ts+src/core/schema-pack/candidate-audit.ts+src/core/schema-pack/closure.ts+src/core/schema-pack/detect.ts+src/core/schema-pack/engine-resolution.ts+src/core/schema-pack/enrichable.ts+src/core/schema-pack/expert-types.ts+src/core/schema-pack/extractable.ts+src/core/schema-pack/index.ts+src/core/schema-pack/link-inference.ts+src/core/schema-pack/lint-rules.ts+src/core/schema-pack/load-active.ts+src/core/schema-pack/loader.ts+src/core/schema-pack/manifest-v1.ts+src/core/schema-pack/merge.ts+src/core/schema-pack/mutate-audit.ts+src/core/schema-pack/mutate.ts+src/core/schema-pack/op-trust-gate.ts+src/core/schema-pack/pack-lock.ts+src/core/schema-pack/page-to-alias.ts+src/core/schema-pack/page-to-link.ts+src/core/schema-pack/per-source.ts+src/core/schema-pack/primitives.ts+src/core/schema-pack/query-cache-invalidator.ts+src/core/schema-pack/query-types.ts+src/core/schema-pack/redos-guard.ts+src/core/schema-pack/registry.ts+src/core/schema-pack/retype.ts+src/core/schema-pack/review.ts+src/core/schema-pack/scaffold-extractable.ts+src/core/schema-pack/stats.ts+src/core/schema-pack/suggest.ts+src/core/schema-pack/sync.ts+src/core/schema-pack/type-usage.ts+src/core/schema-pack/unify-types-handler.ts+src/core/schema-pack/write-vocabulary.ts+src/core/schema-verify.ts+src/core/schema-version-health.ts+src/core/scope.ts+src/core/search/alias-normalize.ts+src/core/search/arm-confidence.ts+src/core/search/autocut.ts+src/core/search/by-image.ts+src/core/search/cjk-keyword-sql.ts+src/core/search/crag.ts+src/core/search/date-bounds.ts+src/core/search/dedup.ts+src/core/search/embedding-column.ts+src/core/search/eval.ts+src/core/search/evidence.ts+src/core/search/exact-lookup.ts+src/core/search/expansion.ts+src/core/search/explain-formatter.ts+src/core/search/fusion-lists.ts+src/core/search/graph-signals.ts+src/core/search/hybrid.ts+src/core/search/image-loader.ts+src/core/search/intent-weights.ts+src/core/search/llm-intent.ts+src/core/search/metadata-boost-gate.ts+src/core/search/mode-switch-ux.ts+src/core/search/mode.ts+src/core/search/modes-report.ts+src/core/search/output-redaction.ts+src/core/search/private-visibility.ts+src/core/search/projection-readiness.ts+src/core/search/projection-statistics.ts+src/core/search/query-cache-gate.ts+src/core/search/query-cache.ts+src/core/search/query-intent.ts+src/core/search/read-enrichment.ts+src/core/search/read-policy-sql.ts+src/core/search/recency-decay.ts+src/core/search/relational-intent.ts+src/core/search/relational-recall.ts+src/core/search/relational-rerank-pin.ts+src/core/search/rerank.ts+src/core/search/return-policy.ts+src/core/search/safe-chunks.ts+src/core/search/snippet-cap.ts+src/core/search/source-boost.ts+src/core/search/sql-ranking.ts+src/core/search/telemetry.ts+src/core/search/title-match.ts+src/core/search/token-budget.ts+src/core/search/tune-recommendations.ts+src/core/search/two-pass.ts+src/core/search/vector-pool.ts+src/core/search/vector-settings.ts+src/core/secret-scan.ts+src/core/self-upgrade.ts+src/core/semver.ts+src/core/serve-service.ts+src/core/serve-sweep-runner.ts+src/core/serve-sync-runner.ts+src/core/shared-skills/access-schema.ts+src/core/shared-skills/adapter.ts+src/core/shared-skills/catalog.ts+src/core/shared-skills/compatibility.ts+src/core/shared-skills/content-freshness.ts+src/core/shared-skills/knowledge-guard.ts+src/core/shared-skills/manifest.ts+src/core/shared-skills/membership-authority.ts+src/core/shared-skills/membership-schema.ts+src/core/shared-skills/membership-types.ts+src/core/shared-skills/membership.ts+src/core/shared-skills/migration-export.ts+src/core/shared-skills/migration-members.ts+src/core/shared-skills/migration-projection.ts+src/core/shared-skills/migration.ts+src/core/shared-skills/model.ts+src/core/shared-skills/optimizer.ts+src/core/shared-skills/persistence-schema.ts+src/core/shared-skills/policy.ts+src/core/shared-skills/publication.ts+src/core/shared-skills/restore.ts+src/core/shared-skills/retention.ts+src/core/shared-skills/schema-all.ts+src/core/shared-skills/schema.ts+src/core/shared-skills/setup-bundle.ts+src/core/shared-skills/setup-files.ts+src/core/shared-skills/setup-source-policy.ts+src/core/shared-skills/setup.ts+src/core/shared-skills/tool-access.ts+src/core/skill-brain-first.ts+src/core/skill-catalog.ts+src/core/skill-fix-gates.ts+src/core/skill-frontmatter.ts+src/core/skill-manifest.ts+src/core/skill-trigger-index.ts+src/core/skillify/generator.ts+src/core/skillify/templates.ts+src/core/skillopt/apply-edits.ts+src/core/skillopt/audit.ts+src/core/skillopt/batch.ts+src/core/skillopt/benchmark.ts+src/core/skillopt/bootstrap-benchmark.ts+src/core/skillopt/bootstrap-run.ts+src/core/skillopt/bundled-skill-gate.ts+src/core/skillopt/checkpoint.ts+src/core/skillopt/cycle-phase.ts+src/core/skillopt/held-out.ts+src/core/skillopt/help.ts+src/core/skillopt/index.ts+src/core/skillopt/job.ts+src/core/skillopt/lock.ts+src/core/skillopt/lr-schedule.ts+src/core/skillopt/models-plan.ts+src/core/skillopt/must-abort.ts+src/core/skillopt/orchestrator.ts+src/core/skillopt/output-cap.ts+src/core/skillopt/preflight.ts+src/core/skillopt/reflect.ts+src/core/skillopt/rejected-buffer.ts+src/core/skillopt/remediation.ts+src/core/skillopt/rollout.ts+src/core/skillopt/run-outcome.ts+src/core/skillopt/score.ts+src/core/skillopt/types.ts+src/core/skillopt/validate-gate.ts+src/core/skillopt/version-store.ts+src/core/skillopt/write-capture.ts+src/core/skillpack/apply-hunks.ts+src/core/skillpack/audit.ts+src/core/skillpack/bootstrap-display.ts+src/core/skillpack/brain-pack-advisory.ts+src/core/skillpack/brain-resident-locate.ts+src/core/skillpack/bridge-state.ts+src/core/skillpack/bundle.ts+src/core/skillpack/copy.ts+src/core/skillpack/diff-text.ts+src/core/skillpack/doctor.ts+src/core/skillpack/endorse.ts+src/core/skillpack/harness-bridge.ts+src/core/skillpack/harvest-lint.ts+src/core/skillpack/harvest.ts+src/core/skillpack/init-brain-pack.ts+src/core/skillpack/init-scaffold.ts+src/core/skillpack/installer.ts+src/core/skillpack/manifest-v1.ts+src/core/skillpack/migrate-fence.ts+src/core/skillpack/nag-state.ts+src/core/skillpack/pack-publish.ts+src/core/skillpack/personas.ts+src/core/skillpack/post-install-advisory.ts+src/core/skillpack/preconditions.ts+src/core/skillpack/reference.ts+src/core/skillpack/registry-client.ts+src/core/skillpack/registry-schema.ts+src/core/skillpack/remote-source.ts+src/core/skillpack/rubric.ts+src/core/skillpack/scaffold-third-party.ts+src/core/skillpack/scaffold.ts+src/core/skillpack/scrub-legacy.ts+src/core/skillpack/shared-brain-bridge.ts+src/core/skillpack/skill-currency.ts+src/core/skillpack/state.ts+src/core/skillpack/tarball.ts+src/core/skillpack/trust-prompt.ts+src/core/skillpack/writer-guard.ts+src/core/skills-integrity.ts+src/core/sort-newest-first.ts+src/core/source-config-sql.ts+src/core/source-health.ts+src/core/source-id.ts+src/core/source-local-reference-index.ts+src/core/source-resolver.ts+src/core/sources-load.ts+src/core/sources-ops.ts+src/core/spend-log.ts+src/core/spend-posture.ts+src/core/sql-query.ts+src/core/ssrf-validate.ts+src/core/stall-env.ts+src/core/storage-config.ts+src/core/storage.ts+src/core/storage/local.ts+src/core/storage/s3.ts+src/core/storage/supabase.ts+src/core/stored-embedding-identity.ts+src/core/supabase-admin.ts+src/core/surface-audit.ts+src/core/sweep.ts+src/core/sync-anchor.ts+src/core/sync-concurrency.ts+src/core/sync-cost-gate.ts+src/core/sync-delta.ts+src/core/sync-embed-backfill.ts+src/core/sync-failure-ledger.ts+src/core/sync-git.ts+src/core/sync-lock.ts+src/core/sync-policy.ts+src/core/sync-reconcile.ts+src/core/sync-status-report.ts+src/core/sync.ts+src/core/tailscale.ts+src/core/take-proposals.ts+src/core/takes-fence.ts+src/core/takes-quality-eval/aggregate.ts+src/core/takes-quality-eval/pricing.ts+src/core/takes-quality-eval/receipt-name.ts+src/core/takes-quality-eval/receipt-write.ts+src/core/takes-quality-eval/regress.ts+src/core/takes-quality-eval/replay.ts+src/core/takes-quality-eval/rubric.ts+src/core/takes-quality-eval/runner.ts+src/core/takes-quality-eval/trend.ts+src/core/takes-resolution.ts+src/core/takes-write.ts+src/core/text-safe.ts+src/core/thin-client-upgrade-prompt.ts+src/core/think/cite-render.ts+src/core/think/entity-extract.ts+src/core/think/gather.ts+src/core/think/index.ts+src/core/think/intent.ts+src/core/think/persist-take.ts+src/core/think/prompt.ts+src/core/think/sanitize.ts+src/core/think/temporal-window.ts+src/core/timeline-citations.ts+src/core/timeline-dedup-repair.ts+src/core/timeline-extract.ts+src/core/timeline-write-through.ts+src/core/timeout.ts+src/core/timing-safe.ts+src/core/token-mint.ts+src/core/trajectory-format.ts+src/core/trajectory.ts+src/core/transcription.ts+src/core/transcripts.ts+src/core/transcripts/capture-spec.ts+src/core/transcripts/chatgpt-export.ts+src/core/transcripts/claude-code-jsonl.ts+src/core/transcripts/claude-code.ts+src/core/transcripts/claude-export.ts+src/core/transcripts/codex-hook-lane.ts+src/core/transcripts/codex.ts+src/core/transcripts/detect.ts+src/core/transcripts/discover.ts+src/core/transcripts/export-json.ts+src/core/transcripts/grok.ts+src/core/transcripts/hermes.ts+src/core/transcripts/ingest-facts.ts+src/core/transcripts/ingest.ts+src/core/transcripts/openclaw.ts+src/core/transcripts/render.ts+src/core/transcripts/types.ts+src/core/types.ts+src/core/url-redact.ts+src/core/url-safety.ts+src/core/utils.ts+src/core/vector-index.ts+src/core/verbs.ts+src/core/verbs/conformance-fixtures.ts+src/core/verbs/conformance.ts+src/core/verbs/entity-card.ts+src/core/verbs/usage-log.ts+src/core/worker-pool.ts+src/core/workspace-push.ts+src/core/write-through.ts+src/core/wsl-paths.ts+src/core/yaml-lite.ts+src/core/zombie-reap.ts+src/eval/brainbench/adapters/claude-code.ts+src/eval/brainbench/adapters/codex.ts+src/eval/brainbench/adapters/openclaw.ts+src/eval/brainbench/adapters/shared.ts+src/eval/brainbench/fixtures.ts+src/eval/brainbench/harness.ts+src/eval/brainbench/metrics/continuity.ts+src/eval/brainbench/metrics/know-to-ask.ts+src/eval/brainbench/metrics/push.ts+src/eval/brainbench/metrics/write-back.ts+src/eval/brainbench/scoreboard.ts+src/eval/brainbench/seed.ts+src/eval/brainbench/types.ts+src/eval/chronicle/harness.ts+src/eval/code-retrieval/harness.ts+src/eval/code-retrieval/strategies.ts+src/eval/deterministic-embed.ts+src/eval/longmemeval/adapter.ts+src/eval/longmemeval/capture.ts+src/eval/longmemeval/emit.ts+src/eval/longmemeval/extract.ts+src/eval/longmemeval/gateway-client.ts+src/eval/longmemeval/harness.ts+src/eval/longmemeval/intent.ts+src/eval/longmemeval/judge-lane.ts+src/eval/longmemeval/judge.ts+src/eval/longmemeval/metrics.ts+src/eval/longmemeval/qa-accuracy.ts+src/eval/longmemeval/reader.ts+src/eval/longmemeval/resume.ts+src/eval/longmemeval/run-config.ts+src/eval/longmemeval/sanitize.ts+src/eval/longmemeval/trajectory-route.ts+src/eval/retrieval-quality/harness.ts+src/eval/shared/bootstrap.ts+src/eval/shared/embed-cache.ts+src/eval/shared/judge-runner.ts+src/fixtures/github-demo.ts+src/mcp/capabilities.ts+src/mcp/context-pack-handler.ts+src/mcp/dispatch.ts+src/mcp/instructions.ts+src/mcp/publish-gates.ts+src/mcp/rate-limit.ts+src/mcp/resolve-ipc-binding.ts+src/mcp/server.ts+src/mcp/skill-resources.ts+src/mcp/source-preflight.ts+src/mcp/surface.ts+src/mcp/tool-defs.ts+src/mcp/validate-params.ts+src/openclaw-context-engine.ts+src/version.tsdiff --git a/docs/test-audit/2026-09-29/lane-seams/dead-modules.txt b/docs/test-audit/2026-09-29/lane-seams/dead-modules.txtnew file mode 100644index 0000000000..d57adf0803--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-seams/dead-modules.txt@@ -0,0 +1,42 @@+src/commands/eval-schema-authoring.ts+src/core/archive-crawler-config.ts+src/core/artifact/index.ts+src/core/calibration/cross-brain.ts+src/core/calibration/nudge.ts+src/core/calibration/recall-footer.ts+src/core/calibration/take-forecast.ts+src/core/chronicle/backstop.ts+src/core/chunkers/llm.ts+src/core/chunkers/semantic.ts+src/core/conversation-parser/llm-polish.ts+src/core/data-research.ts+src/core/diarize/payload-fitter.ts+src/core/distribution/index.ts+src/core/enrichment/budget.ts+src/core/enrichment/completeness.ts+src/core/eval-capture-graph.ts+src/core/eval-contradictions/calibration-join.ts+src/core/fail-improve.ts+src/core/ingestion/daemon.ts+src/core/ingestion/dedup.ts+src/core/ingestion/skillpack-load.ts+src/core/ingestion/sources/file-watcher.ts+src/core/ingestion/sources/gstack-learnings.ts+src/core/ingestion/sources/inbox-folder.ts+src/core/ingestion/sources/markdown-greenfield.ts+src/core/minions/batch-projection.ts+src/core/minions/budget-tracker.ts+src/core/minions/lease-cap-controller.ts+src/core/minions/self-fix.ts+src/core/minions/stagger.ts+src/core/onboard/impact-capture.ts+src/core/progressive-batch/orchestrator.ts+src/core/progressive-batch/retrofit-wrap.ts+src/core/progressive-batch/stage-report.ts+src/core/schema-pack/expand-type-filter.ts+src/core/schema-pack/rewrite-links-batch.ts+src/core/search/keyword.ts+src/core/search/vector.ts+src/core/skillpack/brain-pack-lint.ts+src/core/source-config-redact.ts+src/core/upgrade-checkpoint.tsdiff --git a/docs/test-audit/2026-09-29/lane-seams/dead-tests.txt b/docs/test-audit/2026-09-29/lane-seams/dead-tests.txtnew file mode 100644index 0000000000..98d6addf27--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-seams/dead-tests.txt@@ -0,0 +1,48 @@+test/archive-crawler-config.test.ts+test/artifact-abstraction.test.ts+test/batch-projection.test.ts+test/budget-tracker.test.ts+test/chronicle-extract.test.ts+test/code-intel/eval-capture-graph.test.ts+test/company-brain-schema.test.ts+test/conversation-parser/llm-polish.test.ts+test/core/diarize/payload-fitter-summarize.test.ts+test/core/diarize/payload-fitter.test.ts+test/cross-brain-calibration.test.ts+test/data-research.test.ts+test/distribution-import-boundary.test.ts+test/e2e/ingestion-roundtrip.test.ts+test/e2e/jobs-watch-readsnapshot.test.ts+test/e2e/minions-budget-cathedral.test.ts+test/e2e/minions-controller-bounce-only.test.ts+test/e2e/minions-self-fix-flow.test.ts+test/e2e/onboard-full-flow.test.ts+test/e2e/schema-cathedral.test.ts+test/e2e/v030_1-integration-pglite.test.ts+test/enrichment.test.ts+test/eval-contradictions-calibration-join.test.ts+test/eval-schema-authoring.test.ts+test/fail-improve.test.ts+test/ingestion/daemon.test.ts+test/ingestion/dedup.test.ts+test/ingestion/gstack-learnings.test.ts+test/ingestion/markdown-greenfield.test.ts+test/ingestion/migration-mode.test.ts+test/ingestion/skillpack-load.test.ts+test/ingestion/sources/file-watcher.test.ts+test/ingestion/sources/inbox-folder.test.ts+test/lease-cap-controller.test.ts+test/minions-quiet-hours.test.ts+test/nudge.test.ts+test/progressive-batch/orchestrator.test.ts+test/progressive-batch/retrofit-wrap.test.ts+test/recall-footer.test.ts+test/regressions/v0.36.1.0-iron-rule.test.ts+test/schema-pack-expand-type-filter.test.ts+test/schema-pack-rewrite-links-batch.test.ts+test/self-fix.test.ts+test/skillopt/silent-abort-3516.test.ts+test/skillpack-init-brain-pack.test.ts+test/source-config-redact.test.ts+test/take-forecast.test.ts+test/upgrade-checkpoint.serial.test.tsdiff --git a/docs/test-audit/2026-09-29/lane-seams/seam-callers.tsv b/docs/test-audit/2026-09-29/lane-seams/seam-callers.tsvnew file mode 100644index 0000000000..c24c640cf9--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-seams/seam-callers.tsv@@ -0,0 +1,165 @@+1 1 0 src/cli.ts:1029 _clearIdentityCacheForTest+42 1 52 src/cli.ts:1558 __testing+0 1 4 src/cli.ts:1694 resetRetrievalMetaForTests+42 1 52 src/commands/agent-logs.ts:182 __testing+42 1 52 src/commands/agent.ts:519 __testing+42 1 52 src/commands/apply-migrations.ts:636 __testing+42 1 52 src/commands/calibration.ts:275 __testing+42 1 52 src/commands/capture.ts:447 __testing+42 2 52 src/commands/dream.ts:566 __testing+0 1 1 src/commands/embed.ts:109 _resetEmbedQuarantineForTest+0 1 1 src/commands/extract-conversation-facts.ts:656 _resetLockBusyLogCacheForTest+42 1 52 src/commands/migrations/v0_11_0.ts:499 __testing+42 1 52 src/commands/migrations/v0_12_0.ts:255 __testing+42 1 52 src/commands/migrations/v0_12_2.ts:142 __testing+42 1 52 src/commands/migrations/v0_13_0.ts:164 __testing+42 1 52 src/commands/migrations/v0_16_0.ts:136 __testing+42 1 52 src/commands/migrations/v0_18_0.ts:233 __testing+42 1 52 src/commands/migrations/v0_21_0.ts:146 __testing+42 1 52 src/commands/migrations/v0_22_4.ts:225 __testing+3 1 3 src/commands/migrations/v0_22_4.ts:36 __setTestEngineOverride+42 1 52 src/commands/migrations/v0_28_0.ts:243 __testing+3 1 3 src/commands/migrations/v0_28_0.ts:37 __setTestEngineOverride+42 1 52 src/commands/migrations/v0_29_1.ts:166 __testing+42 1 52 src/commands/migrations/v0_31_0.ts:137 __testing+3 1 3 src/commands/migrations/v0_31_0.ts:28 __setTestEngineOverride+3 1 3 src/commands/migrations/v0_32_2.ts:46 __setTestEngineOverride+42 1 52 src/commands/migrations/v0_32_2.ts:490 __testing+42 1 52 src/commands/mounts.ts:501 __testing+42 1 52 src/commands/skillpack-check.ts:271 __testing+0 1 2 src/commands/storage.ts:117 __resetPGLiteWarn+0 1 2 src/commands/sync.ts:5723 __resetPGLiteTierWarn+0 1 1 src/core/advisor/collect-mcp-client-fit.ts:80 __setUsageNagStatePathForTests+0 1 0 src/core/ai/gateway.ts:1351 _resetRerankWarningsForTest+0 1 1 src/core/ai/gateway.ts:1787 __getShrinkStateForTests+1 2 9 src/core/ai/gateway.ts:4221 __setRerankTransportForTests+0 1 2 src/core/ai/gateway.ts:655 __setGatewayResetBaselineForTests+0 1 1 src/core/ai/gateway.ts:688 _clearGatewayForTests+0 1 10 src/core/ai/gateway.ts:709 __unconfigureGatewayForTests+3 5 88 src/core/ai/gateway.ts:722 __setEmbedTransportForTests+0 2 12 src/core/ai/gateway.ts:734 __setGenerateTextTransportForTests+0 2 3 src/core/ai/gateway.ts:745 __setGenerateObjectTransportForTests+2 6 77 src/core/ai/gateway.ts:760 __setChatTransportForTests+0 1 1 src/core/ai/openai-latest.ts:296 _resetOpenAILatestForTests+0 1 1 src/core/ai/recipes/azure-openai.ts:44 __setEntraTokenForTests+0 1 4 src/core/ai/recipes/index.ts:74 __setTestRecipesForTests+0 1 1 src/core/audit-skill-brain-first.ts:310 _resetWarnedSetForTests+0 1 0 src/core/backfill-registry.ts:42 clearRegistryForTests+0 1 3 src/core/background-work.ts:139 __registerDrainerForTest+0 1 1 src/core/background-work.ts:145 __listDrainerNamesForTest+1 1 2 src/core/backoff.ts:198 _resetForTest+0 1 3 src/core/backup/coverage.ts:416 __resetBackupRefreshForTests+0 1 9 src/core/backup/status-file.ts:145 __setBackupStatusPathForTests+0 1 7 src/core/backup/status-file.ts:152 __setBackupNagStatePathForTests+0 1 8 src/core/backup/status-file.ts:156 __setBackupIntervalForTests+42 1 52 src/core/brain-registry.ts:443 __testing+42 1 52 src/core/brain-resolver.ts:138 __testing+0 1 5 src/core/budget/budget-tracker.ts:189 _resetBudgetTrackerWarningsForTest+42 1 52 src/core/chunkers/qualified-names.ts:107 __testing+0 1 2 src/core/claw-test/agent-runner.ts:220 _resetRegistryForTests+0 1 21 src/core/cli-force-exit.ts:238 _resetCliExitVerdictForTests+0 1 6 src/core/cli-options.ts:342 _resetCliOptionsForTest+0 1 1 src/core/config-db-merge.ts:97 _resetDbPlaneMergeMemoForTests+0 1 4 src/core/console-prefix.ts:114 _resetStdoutRedirectForTests+0 1 3 src/core/context-engine.ts:101 __resetSdkLoadStateForTests+0 1 3 src/core/context/checkpoint-harvest.ts:169 __resetCheckpointHarvestForTests+0 1 3 src/core/context/checkpoint-harvest.ts:179 __drainCheckpointHarvestForTests+0 1 5 src/core/context/volunteer-events.ts:233 _resetPendingVolunteerEventWritesForTests+0 1 2 src/core/context/volunteer-events.ts:238 _peekPendingVolunteerEventWritesForTests+0 2 4 src/core/conversation-parser/llm-base.ts:72 _resetLlmCacheForTests+42 2 52 src/core/cycle.ts:3205 __testing+42 1 52 src/core/cycle/auto-think.ts:224 __testing+0 1 2 src/core/cycle/budget-meter.ts:223 _resetBudgetMeterWarningsForTest+42 1 52 src/core/cycle/calibration-profile.ts:435 __testing+42 1 52 src/core/cycle/drift.ts:383 __testing+0 1 1 src/core/cycle/filing-rules.ts:161 __filingRulesTesting+42 1 52 src/core/cycle/grade-takes.ts:879 __testing+42 3 52 src/core/cycle/patterns.ts:715 __testing+42 1 52 src/core/cycle/propose-takes.ts:1060 __testing+42 4 52 src/core/cycle/synthesize.ts:3202 __testing+0 1 1 src/core/db.ts:121 _resetMaxLifetimeWarningForTests+0 1 1 src/core/doctor-categories.ts:255 _resetUnknownCheckWarningsForTest+1 1 1 src/core/embed-retry.ts:158 _setRateLimitFloorsForTests+0 1 1 src/core/embed-stall.ts:86 _resetEmbedApiLivenessForTests+0 1 0 src/core/embedding-dim-check.ts:651 _resetFactsDimCheckCacheForTest+0 1 1 src/core/env-number.ts:73 _resetEnvNumberWarnedForTests+0 1 1 src/core/eval-capture.ts:222 _resetPendingEvalCapturesForTests+0 1 0 src/core/extract/rollup-writer.ts:186 _resetRollupErrorLogForTests+0 1 2 src/core/facts/absorb-log.ts:65 _resetFactsAbsorbDisconnectedFlagForTests+0 1 1 src/core/facts/backstop.ts:166 __resetBackstopWarningsForTests+0 1 2 src/core/facts/cli-process-mode.ts:33 __resetShortLivedCliForTests+0 1 1 src/core/facts/extract.ts:717 _resetExtractWrapperWarningsForTests+0 1 7 src/core/facts/meta-hook.ts:216 __resetHotMemoryCacheForTests+0 1 1 src/core/facts/meta-hook.ts:221 __hotMemoryCacheForTests+0 1 7 src/core/facts/queue.ts:255 __resetFactsQueueForTests+1 1 2 src/core/git-head.ts:75 _setGitHeadProbeForTests+0 1 2 src/core/git-head.ts:79 _setGitCleanProbeForTests+0 1 3 src/core/google/loop-detect.ts:207 __clearSuppressionCacheForTests+0 1 2 src/core/guardrails.ts:104 __resetGuardrailProvidersForTests+0 1 2 src/core/import-file.ts:1894 _resetOcrRunBudgetForTests+0 1 1 src/core/import-file.ts:1901 _getOcrRunBudgetForTests+0 1 1 src/core/import-file.ts:1943 _maybeOcrGatedForTests+42 1 52 src/core/ingestion/skillpack-load.ts:339 __testing+42 1 52 src/core/ingestion/sources/file-watcher.ts:307 __testing+42 1 52 src/core/ingestion/sources/inbox-folder.ts:365 __testing+0 1 1 src/core/last-retrieved.ts:120 _resetPendingLastRetrievedWritesForTests+0 1 1 src/core/last-retrieved.ts:125 _peekPendingLastRetrievedWritesForTests+0 1 1 src/core/last-retrieved.ts:161 _resetTrackRetrievalCacheForTests+0 1 4 src/core/minions/admission.ts:207 _resetAdmissionCacheForTest+42 1 52 src/core/minions/handlers/subagent-aggregator.ts:164 __testing+42 1 52 src/core/minions/handlers/subagent-audit.ts:140 __testing+42 1 52 src/core/minions/handlers/subagent.ts:1904 __testing+0 1 1 src/core/minions/llm-halt-cooldown.ts:69 _resetLlmHaltCooldownsForTests+0 2 1 src/core/minions/lock-renewal-tick.ts:146 _resetKnobWarningsForTests+42 1 52 src/core/minions/plugin-loader.ts:232 __testing+0 1 1 src/core/minions/queue.ts:85 _resetStallGraceWarningsForTests+42 1 52 src/core/minions/tools/brain-allowlist.ts:372 __testing+42 1 52 src/core/minions/wait-for-completion.ts:121 __testing+0 1 7 src/core/model-config.ts:683 _resetDeprecationWarningsForTest+42 1 52 src/core/mounts-cache.ts:459 __testing+1 1 1 src/core/ops/request-tools.ts:38 __resetRequestToolsPersistLimiterForTests+0 1 1 src/core/pglite-engine.ts:226 __snapshotMemoStatsForTests+0 1 1 src/core/pglite-engine.ts:230 __resetSnapshotMemoForTests+0 1 1 src/core/pid1-reaper.ts:180 _uninstallPid1OrphanReaperForTests+0 2 1 src/core/process-cleanup.ts:208 _resetForTests+0 1 1 src/core/process-cleanup.ts:90 _registeredCleanupCountForTests+0 1 1 src/core/progress.ts:494 __liveReporterCountForTest+0 1 1 src/core/progress.ts:498 __signalHandlerInstalledForTest+0 1 1 src/core/recall-cursor-state.ts:119 _cursorPathForTests+2 3 12 src/core/schema-pack/load-active.ts:80 __setPackLocatorForTests+2 2 13 src/core/schema-pack/load-active.ts:85 _resetPackLocatorForTests+1 1 24 src/core/schema-pack/registry.ts:141 _resetPackCacheForTests+1 1 1 src/core/schema-pack/registry.ts:216 _cacheSizeForTests+1 1 1 src/core/schema-pack/registry.ts:221 _cacheNamesForTests+0 1 1 src/core/search/hybrid.ts:243 _resetPendingSearchCacheWritesForTests+0 1 3 src/core/search/hybrid.ts:715 _resetSupersedeProbeForTests+0 1 4 src/core/search/private-visibility.ts:127 __resetPrivateVisibilityCacheForTests+0 1 1 src/core/search/query-intent.ts:389 clearIntentPatternConfigForTests+0 0 0 src/core/search/sql-ranking.ts:423 __test+0 3 5 src/core/search/telemetry.ts:651 _resetTelemetryWriterForTest+0 0 0 src/core/search/title-match.ts:93 __test+0 1 1 src/core/serve-sweep-runner.ts:142 __resetDelegatedSweepForTests+0 1 2 src/core/serve-sync-runner.ts:401 __resetDelegatedSyncForTests+0 1 2 src/core/serve-sync-runner.ts:413 __deferredEmbedsPendingForTests+0 2 1 src/core/skill-trigger-index.ts:58 _resetWarnedSkillsForTests+0 1 7 src/core/skillopt/audit.ts:69 _resetAuditWriterForTests+0 1 1 src/core/source-health.ts:70 _resetPriorityWarningsForTest+0 1 1 src/core/source-resolver.ts:1019 __resetSourceGuardQueryShape+42 3 52 src/core/source-resolver.ts:1024 __testing+0 1 1 src/core/source-resolver.ts:523 __resetDefaultWriteGuardMemo+0 2 6 src/core/ssrf-validate.ts:37 __setDnsLookupForTests+0 1 5 src/core/storage-config.ts:439 __resetMissingStorageWarning+0 2 1 src/core/sync-concurrency.ts:245 _resetWorkersClampWarningsForTest+0 1 1 src/core/sync-delta.ts:58 _setGitRunnerForTests+0 1 1 src/core/takes-write.ts:202 __takesWriteTesting+0 1 1 src/core/thin-client-upgrade-prompt.ts:271 _setVerifierForTest+0 1 1 src/core/thin-client-upgrade-prompt.ts:305 _setPromptReaderForTest+0 1 1 src/core/thin-client-upgrade-prompt.ts:321 _setUpgradeRunnerForTest+0 1 0 src/core/thin-client-upgrade-prompt.ts:330 _clearPromptStateForTest+0 1 1 src/core/think/index.ts:1214 __thinkAdapter+0 2 4 src/core/utils.ts:396 _resetWarnOnceForTests+0 1 7 src/core/verbs/usage-log.ts:51 __setUsageLogPathForTests+0 1 11 src/core/write-through.ts:186 _resetWriteThroughCacheForTest+0 1 1 src/core/zombie-reap.ts:42 _uninstallSigchldHandlerForTests+0 1 1 src/mcp/dispatch.ts:74 __resetBackupNoticeForTests+0 1 1 src/mcp/surface.ts:206 __resetSurfaceWarnCachesForTestsdiff --git a/docs/test-audit/2026-09-29/lane-seams/seams.md b/docs/test-audit/2026-09-29/lane-seams/seams.mdnew file mode 100644index 0000000000..8deacc27ca--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-seams/seams.md@@ -0,0 +1,184 @@+# Test audit — lane `seams` (gbrain @ 2ede415, v0.59.11.0)++Read-only discovery. Every probe edit was reverted with `git checkout -- .`; `git status --short` is empty at the end. Nothing was committed or pushed.++Method: openclaw `test-audit` skill (evidence fields per candidate), gbrain `AGENTS.md`/`CLAUDE.md`, and `docs/TESTING.md` "Coverage responsibilities before consolidation". Cost comes from `scripts/ubicloud/weights.json` (ms per file per lane). Scratch artifacts sit next to this report: `seam-callers.tsv`, `test-only-exports.tsv`, `unreachable.tsv`, `dead-modules.txt`, `dead-tests.txt`, `bundled-src.txt`, plus the scripts `dead-exports.ts`, `reach.ts` and `modtable.py`.++## TL;DR++1. **The biggest lever is dead production modules kept alive only by tests, not `ForTests` seams.** 42 `src/` modules (9,261 prod LOC) are unreachable from every runtime entry point and every script. I confirmed this three ways: a static import walk, the repo's own `scripts/check-orphan-modules.mjs` (it reports "45/46 test-only-reachable"; 7 of those are script-used, and 4 more are allowlisted hard orphans), and a `bun build` of all runtime entries plus the package `exports`, where none of the 42 appear in the source maps. Then I poisoned all 42 with a top-level `throw`. The CLI (`--version`, `--help`, `doctor`, `upgrade/jobs/takes/recall --help`) and imports of every runtime entry (cli, mcp/server, openclaw engine, core/index, minions/index, ingestion/index, ingestion/test-harness, operations, extract) all still succeed. Only the dedicated test files fail. 37 test files (8,427 LOC; unit 18.1 s + serial 0.33 s + e2e 9.45 s) test nothing but these modules. 11 more are mixed and need a split.+2. **Four of these dead modules claim shipped product behavior, so their tests give false assurance.** This needs a wire-or-delete product decision, not a silent deletion (details in §2.3).+3. **The seam inventory itself is mostly legitimate.** There are 165 test-named exports in `src/` (75 reset/clear, 27 injector, 15 introspection, 48 `__testing`/private bundles). None has a production caller, and there are no `GBRAIN_TEST_*` reads in `src/`. High-confidence cleanups are small: 7 seams with zero callers anywhere, 3 compatibility or test-only wrappers, and 4 tests that only test a test seam. Together that's about 75 prod LOC and 60 test LOC.+4. **`test/scripts` and `test/helpers` protect real CI behavior.** Every script test's target is wired into `package.json`, `verify`, workflows, or a CI script. The helper self-tests guard corpus isolation. No deletions are recommended there.++## 1. Seam inventory (test-only exports / knobs in src)++| Category | Count | Non-test callers | Verdict |+|---|---:|---|---|+| reset/clear module state (`_reset*ForTest(s)`, `clear*`, `_uninstall*`) | 75 | none (by design) | Keep: module-level memos/warn-once need isolation. Delete only the zero-caller ones (§3.1). |+| injectors (`__set*ForTests`, `__setTestEngineOverride`, `_set*Probe`) | 27 | none | Keep: DI for network/LLM/git/engine. The gateway transports alone are imported by 77–88 test files. |+| introspection/drain (`_peek*`, `_cacheSize*`, `__liveReporterCount*`, …) | 15 | none | Implementation-coupled by nature. Each has 1–2 consumer files. Low priority. |+| `__testing` / `__test__` / `_testHelpers` private bundles | 48 | none | They reach private functions from 52 test files. Not dead code. Review per file only if another lane flags the test. |+| exported functions with **no** reference outside their own declaration except tests (non-public files) | 211 (136 excluding the seam names above) | none | Dead-in-prod exports. Largely subsumed by §2. The rest need per-symbol review (examples in §3). |+| exported only so tests can reach an otherwise internally used function | 1,207 | none | Normal "export for test". Not a deletion signal. |+| test-only env knobs | `GBRAIN_TEST_*` in src: **0**. `NODE_ENV==='test'` guards: 2 (`src/cli.ts:359` update-marker, `src/core/backup/status-file.ts:546` backup nag, with `GBRAIN_FORCE_BACKUP_NAG` as its test override) | — | Keep: they stop the corpus from spawning detached network refreshes and nags (see comment at cli.ts:355–358). |++Package-export note: `src/core/operations.ts` (a public `./operations` export) re-exports `__resetRequestToolsPersistLimiterForTests` (line 124), and `src/core/schema-pack/index.ts:95-96` re-exports `_cacheSizeForTests`/`_cacheNamesForTests`. A test seam leaking into a public barrel is a small API-hygiene follow-up.++## 2. Dead production modules kept alive by tests (the main opportunity)++### 2.1 Evidence that they are dead++- **Static walk:** `reach.ts` (entries: `src/cli.ts`, package `exports`, all `scripts/**`, `admin/src/**`, plus string-referenced src paths). The only dynamic-import sites with variable specifiers are `guardrails.ts:220` (user plugins) and `skillpack-load.ts:237` (itself dead), so the walk is sound.+- **Repo guard:** `node scripts/check-orphan-modules.mjs` prints `OK (1467 modules, 32 entrypoints, 4 allowlisted, 45/46 test-only-reachable)`. Its list minus 7 script-used modules (`bootstrap/template-repo`, `eval-contradictions/fixture-redact`, `eval/longmemeval/{diagnostics,evidence-packet}`, `eval/shared/autocut-replay`, `mcp/http-transport`, `mcp/tool-catalog`) plus its 4 allowlisted orphans gives exactly my 42.+- **Bundle:** `bun build` of cli + mcp/server + openclaw-context-engine + admin-embedded + agent-install/entry + every package `exports` target (1,402 src files in the maps). None of the 42 are present.+- **Mutation probe (poison):** a `throw new Error('SEAM_PROBE:<path>')` at the top of all 42 files. Every runtime entry import passed (rc=0, no SEAM_PROBE). `bun src/cli.ts --version` and `--help`, `doctor --fast` on a fresh PGLite home, and `upgrade|jobs|takes|recall --help` all ran without SEAM_PROBE. All 40 non-E2E dependent test files failed at import (`0 pass 1 fail`). So the only detectors of these modules are their own tests. Reverted.++### 2.2 Module → test table (prod LOC; test LOC, ms/lane)++Pure means the test imports nothing live except type-only imports or engine/queue fixture substrate. A pure test goes with its module.++| Dead module (LOC) | Tests (LOC, ms) | Class |+|---|---|---|+| core/data-research.ts (435) | data-research.test.ts (343, u182) | pure |+| core/archive-crawler-config.ts (350) | archive-crawler-config.test.ts (328, u179) | pure |+| core/fail-improve.ts (287) | fail-improve.test.ts (234, u329) | pure |+| core/eval-capture-graph.ts (169) | code-intel/eval-capture-graph.test.ts (150, u201) | pure |+| commands/eval-schema-authoring.ts (176) | eval-schema-authoring.test.ts (94, u184) | pure |+| core/artifact/index.ts (149) | artifact-abstraction.test.ts (50, u187) · e2e/schema-cathedral (176, e4680) | pure + mixed |+| core/distribution/index.ts (124) | distribution-import-boundary.test.ts (93, u175) | pure (architecture test of a dead module) |+| core/diarize/payload-fitter.ts (268) | payload-fitter.test.ts (70, u161) · payload-fitter-summarize.test.ts (217, u203) | pure |+| core/conversation-parser/llm-polish.ts (231) | conversation-parser/llm-polish.test.ts (174, u185) | pure |+| core/enrichment/{budget,completeness}.ts (369+275) | enrichment.test.ts (357, **u4286**) | pure |+| core/calibration/{take-forecast,recall-footer,cross-brain,nudge}.ts (170+81+169+209) | take-forecast (213, u164) · recall-footer (154, u165) · cross-brain-calibration (259, u335) · nudge (299, u153) | pure (type-only imports of commands/calibration) |+| core/eval-contradictions/calibration-join.ts (102) | eval-contradictions-calibration-join (170, u192) · regressions/v0.36.1.0-iron-rule (156, u159) | pure + mixed |+| core/progressive-batch/{orchestrator,retrofit-wrap,stage-report}.ts (778+78+52) | progressive-batch/orchestrator.test.ts (625, u269) · retrofit-wrap.test.ts (84, u185) | pure |+| core/ingestion/{daemon,dedup,skillpack-load}.ts + sources/{file-watcher,inbox-folder,gstack-learnings,markdown-greenfield}.ts (544+169+345+309+369+344+333 = 2,413) | ingestion/daemon (558, u333) · migration-mode (226, u159) · dedup (160, u177) · skillpack-load (318, u167) · sources/file-watcher (294, u703) · sources/inbox-folder (358, u795) · gstack-learnings (224, u174) · markdown-greenfield (336, u210) · e2e/ingestion-roundtrip (334, **e4097**) | pure |+| core/minions/{budget-tracker,self-fix,lease-cap-controller,batch-projection,stagger}.ts (291+275+285+186+35) | budget-tracker (230, u1843) · self-fix (223, u1278) · lease-cap-controller (160, u2234) · batch-projection (282, u222) · e2e/minions-budget-cathedral (126, e1820) · e2e/minions-controller-bounce-only (98, e1873) · e2e/minions-self-fix-flow (144, e1661) · mixed: minions-quiet-hours (215, u5534; the stagger part only), skillopt/silent-abort-3516 (294, u565), e2e/jobs-watch-readsnapshot (86, e2072; uses `setOwnerBudget` as fixture) | pure + mixed |+| core/upgrade-checkpoint.ts (160) | upgrade-checkpoint.serial.test.ts (214, s332) · mixed: e2e/v030_1-integration-pglite (Lane E only, 4 of 14 tests; file e26038, dominated by initSchema, so small ms win) | pure + mixed |+| core/schema-pack/{expand-type-filter,rewrite-links-batch}.ts (186+91) | schema-pack-expand-type-filter (145, u182) · schema-pack-rewrite-links-batch (83, u1919) · mixed: company-brain-schema (111, u318) | pure + mixed |+| core/skillpack/brain-pack-lint.ts (69) | mixed: skillpack-init-brain-pack (83, u302) | mixed |+| core/chronicle/backstop.ts (38) | mixed: chronicle-extract (199, u1588) | mixed |+| core/onboard/impact-capture.ts (188) | mixed: e2e/onboard-full-flow (181, e2035) | mixed |+| core/source-config-redact.ts (47) | source-config-redact.test.ts (54, u160) | **HOLD**, see §2.3 |+| core/chunkers/{llm,semantic}.ts, core/search/{keyword,vector}.ts (163+342+10+10) | none (allowlisted hard orphans in check-orphan-modules) | prod-only deletion; allowlist entries must go too |++Totals:+- **Pure tests:** 37 files, 8,427 LOC; unit 18,131 ms + serial 332 ms + e2e 9,451 ms.+- **Mixed:** 11 files, 1,777 LOC (unit 8,626 ms, e2e 34,825 ms). Only the dead-module cases are removable. The E2E ms mostly stays because setup dominates.+- **Prod:** 9,261 LOC across 42 modules.+- Deleting them lets `MAX_TEST_ONLY_REACHABLE` in `scripts/check-orphan-modules.mjs` ratchet from 46 toward 7, and the 4 allowlist entries go away.++### 2.3 Wire-or-delete decisions (do not delete silently)++- **`core/minions/budget-tracker.ts` / `self-fix.ts` / `lease-cap-controller.ts` / `batch-projection.ts`.** Their headers claim runtime `--budget-usd` enforcement, subagent self-fix and an adaptive lease cap. The live `--budget-usd` path uses a *different* module, `src/core/budget/budget-tracker.ts` (17 live src files). The minions twin is superseded. `self_fix_max_depth` and the lease-cap controller have no live references at all. Recommendation: delete, after the parent confirms these features aren't meant to be wired.+- **`core/upgrade-checkpoint.ts`.** Its header promises `gbrain upgrade --resume`. That flag doesn't exist (`rg -- "--resume" src/commands/upgrade.ts` finds nothing, and no docs mention it). The 18 serial tests and E2E Lane E protect a feature users can't reach.+- **`core/calibration/nudge.ts`.** Migration `take_nudge_log_v0_36` (migrate.ts:3588) creates a table whose only writer is this dead module. Keep the migration (migration contract) even if nudge.ts goes.+- **`core/source-config-redact.ts`: HOLD, route to the security lane.** `scripts/check-source-config-leak.sh` (a CI guard, passes today) names `redactSourceConfig()` as the required remediation and whitelists this file, but no serializer calls it. Deleting the module orphans the guard's advice. Wiring it may be the right fix. Either way the unit test is not what protects secrets today.++Risk for the whole batch: **low technical risk** (bundle-proven dead) but a **product decision**, because some modules are unfinished features someone may intend to wire. Validation: `node scripts/check-orphan-modules.mjs` (lower the ceiling), `bun run typecheck`, the `bun build` source-map check above, then `bun run verify`.++## 3. Seam-level candidates (high confidence, small)++### 3.1 Zero-caller seams (no production caller and no test caller)++| Seam | Location | Evidence | Unlocks |+|---|---|---|---|+| `_clearIdentityCacheForTest` | src/cli.ts:1028-1031 | 0 test refs. Mentioned only in comments in thin-client-upgrade-prompt.ts | 4 LOC |+| `_clearPromptStateForTest` | src/core/thin-client-upgrade-prompt.ts:324-334 | Empty body ("No in-process state to clear today… exists for symmetry"), 0 refs | 11 LOC |+| `_resetFactsDimCheckCacheForTest` | src/core/embedding-dim-check.ts:650-655 | No-op body (WeakMap can't clear), 0 refs | 6 LOC |+| `_resetRerankWarningsForTest` | src/core/ai/gateway.ts:1351-1353 | 0 refs. The memo is actually cleared by `configureGateway` (gateway.ts:458), which is what `test/rerank-no-key.serial.test.ts` "…and the test seam clears it" really uses | 3 LOC |+| `clearRegistryForTests` | src/core/backfill-registry.ts:42-45 | 0 refs | 4 LOC |+| `_resetRollupErrorLogForTests` | src/core/extract/rollup-writer.ts:182-188 | 0 refs | 7 LOC |+| `PostgresEngine.__resetFactsEmbeddingCastCacheForTest()` | src/core/postgres-engine.ts:4357-4360 | 0 callers. Kept alive only by a source-grep test (below) | 4 LOC |++History: every one of these first appears in the squashed baseline `d9909cd` (2026-08-28), except `_resetRerankWarningsForTest`, which appears in `db56c77` (v0.56.2.0). No other history is available.++### 3.2 Tests that only test a seam++**A. `test/embedding-dim-check-facts.test.ts` › "postgres-engine fact insert cast (T6, codex #20) › cached cast suffix has a test-only reset hook for unit cases"** (lines 254-256; file unit 190 ms)+- **What it detects:** only whether the string `__resetFactsEmbeddingCastCacheForTest` exists in postgres-engine.ts.+- **Probe:** a behavior-preserving rename of that zero-caller method made the test FAIL (20 pass, 1 fail). So it's implementation-coupled and pins a dead seam.+- **Non-test callers:** none. **Surviving owner:** not needed, since no behavior is asserted.+- **Action:** delete the test (3 LOC) and the method (4 LOC). Risk: low.++**B. `test/backoff.test.ts` › "backoff › _resetForTest clears module state"** (lines 114-120; unit 195 ms)+- **Probe 1:** broke the production counter (removed `_activeProcesses++` in `preflight`). This test still PASSED, while "concurrent process limit blocks when exceeded", "complete decrements…" and "preflight returns boolean" failed.+- **Probe 2:** made `_resetForTest` a no-op. Only this test failed.+- So it detects breakage of a test helper only. The seam itself stays (used by `beforeEach`), and the owner for the real counter contract is the three tests named above.+- **Action:** delete the test (7 LOC). Risk: low. `src/core/backoff.ts` is live (enrichment-service.ts, minions/worker.ts).++**C. `test/core/git-head.test.ts` › "isSourceUnchangedSinceSync — test-seam round-trip › case 10: …ForTests round-trip"** (lines 123-141; unit 198 ms)+- **Probe:** broke both real probes in `src/core/git-head.ts` (`DEFAULT_HEAD_PROBE` and `DEFAULT_CLEAN_PROBE` always return `null`). **All 21 tests in git-head.test.ts, including case 10, still PASSED.** Its "restore worked" assertion (non-git path → false) is satisfied by a broken probe too.+- **Owner at the real git boundary:** `test/source-health.test.ts` (unit 1,990 ms). It FAILED on the same probe: "isSourceUnchangedSinceSync (ignore-untracked) — local caught-up contract › HEAD == last_commit, clean → caught up", "… WITH untracked dirs → still caught up (the headline bug)", and "computeAllSourceMetrics › commit-relative lag › LOCAL (probeContent)…".+- **Action:** delete case 10 (about 19 LOC). Keep cases 1-9 and 11+: they are predicate logic over injected probes, a legitimate DI use. Risk: low.++**D. `test/resolvers.test.ts` › "_resetDefaultRegistry gives a fresh instance"** (lines 172-179)+- Same pattern as B: the seam is used by `beforeEach` at lines 163-164, and this test asserts only the seam.+- Not separately probed. Confidence is medium-high by analogy with B.+- **Action:** delete (8 LOC). The file weight (unit 4,231 ms) comes from the url_reachable network cases, not this test.++**E. `test/search/title-match.test.ts` › "tokenizeTitle › MIN_CONTENT_TOKENS is 2 (the precision floor)"** (lines 65-67; unit 270 ms)+- **Probe up (2→3):** the behavior tests "isTitlePhraseMatch — positive (the incident) › the exact incident query matches" and "… case + whitespace insensitive" failed, plus the pin.+- **Probe down (2→1):** "isTitlePhraseMatch — negative (precision guard) › single generic content word does NOT match (would over-promote)" failed, plus the pin.+- So the constant pin is redundant in both directions, and the behavior tests are the owner.+- **Action:** delete the pin test (3 LOC). The `__test__` export in `src/core/search/title-match.ts:93` then has no consumer and can go (1 LOC). Risk: low.++### 3.3 Compatibility or test-only wrappers with no production caller (rewrite tests to the real function, delete the wrapper)++**F. `checkDnsRebinding`** (src/core/resolvers/builtin/url-reachable.ts:130-138, doc says "Compatibility helper; the shared validator is the only address policy")+- **Callers:** 0 production; tests are `test/resolvers.test.ts` › "url_reachable resolver › checkDnsRebinding: validates IP literals using the shared policy", "… rejects an unparseable URL" and "… fails closed on DNS failure".+- **Probe A** (dropped the `isInternalUrl` layer in `validateAndResolveUrl`): the owner `test/ssrf-validate.test.ts` failed 5 tests ("validateAndResolveUrl — static rejections (via isInternalUrl) › rejects http://127.0.0.1 (loopback)", "… 169.254.169.254 (AWS metadata)", decimal and hex encodings…). The resolver's real-path tests "blocks localhost via SSRF guard" and "blocks RFC1918 addresses" also failed.+- **Probe B** (DNS failure fails open): the owner failed "validateAndResolveUrl — DNS resolution failures › rejects when DNS lookup fails (ENOTFOUND)".+- So the wrapper tests are fully duplicated by the owner on the same boundary (the shared validator used by `fetchWithSSRFGuard`).+- **Action:** delete the wrapper (9 LOC) and its 3 tests (about 15 LOC). Risk: low. Security contract retained in ssrf-validate.test.ts and the resolver's SSRF tests.++**G. `maybeWarnUnscopedDefaultWrite`** (src/core/source-resolver.ts:605-612)+- A one-line projection of `assessUnscopedDefaultWrite`. Its only production caller is the stdio MCP lane (`src/mcp/server.ts:104-105`), which calls `assessUnscopedDefaultWrite` directly.+- The tests in `test/source-resolver-default-write-guard.test.ts` › "maybeWarnUnscopedDefaultWrite (stdio MCP lane, keyed on the RESOLVED tier)" (about 10 cases) protect a real trust-boundary (remote MCP) contract, so **keep the assertions**.+- **Action:** rewrite them to call `assessUnscopedDefaultWrite(...).warning`, then delete the wrapper (8 LOC). Risk: low.++**H. `_maybeOcrGatedForTests`** (src/core/import-file.ts:1941-1948)+- Bypasses the `GBRAIN_EMBEDDING_IMAGE_OCR` opt-in gate.+- **Probe:** inverted the gate (OCR runs when *not* opted in, a privacy and cost regression). `test/ocr-run-budget.test.ts` (7 tests, unit 1,854 ms) still passed. `test/persistence-image-import.serial.test.ts` still passed. Only `test/e2e/chunk-canonical-text-privacy.test.ts` › "successful OCR normalizes protected markers before image sealing" failed.+- So the budget tests can't see the gate by construction, and the gate's only owner is one E2E case.+- **Action:** rewrite ocr-run-budget at the import boundary (env set, real `maybeOcr` path) and delete the wrapper (8 LOC). Keep the budget contract. Risk: medium (cost contract), so this is a rewrite, not a delete.++### 3.4 Other dead-in-prod exported functions (sample; the 136 need per-symbol review)++`resolveParallelism` (sync.ts:5607), `getMigration` (migrations/index.ts:55, used by 8 tests), `estimateAnthropicCost`, `resolveFile` (file-resolver.ts), `filterOutQuarantined`/`hasContentFlag` (quarantine.ts), `isSupabaseOnly`, `isSupabaseAutoMaintenance`, `writeSnooze`, `removeEntry`, and the `_*AuditFeatureName` exports. Each is referenced nowhere in `src/`, `scripts/` or `admin/src` except its own declaration. The full list is in `test-only-exports.tsv` (column 1 `DEAD-IN-PROD`). I left these as a follow-up rather than ranking them, because many are one-liners inside live modules and the deletion unit is small.++## 4. test/scripts and test/helpers (tests of test infrastructure)++- **`test/scripts/*.test.ts` (39 files):** every target script is wired.+ - Most are direct `package.json`/`verify`/workflow entries: run-unit-parallel, run-serial-tests, run-e2e, test-shard, merge-lcov, coverage gates, check-* guards, e2e-matrix/select-e2e, native workflows.+ - The ones that looked unwired are reached indirectly: `classify-tests.ts` via `check-structural-manifest.sh` in verify, `ubicloud/schedule.ts` via `ci-ubicloud.ts`, `native/compiled-smoke-cleanup.ts` via `compiled-smoke.ts`, `check-skill-refs.mjs`/`check-module-size.sh`/`check-wasm-embedded.sh` via package scripts, and `typecheck-incremental` pins `pkg.scripts.typecheck` semantics against real tsc.+ - These guard real CI behavior (sharding, rescue passes, gate exit codes). **No deletion candidates.**+ - Cost hot spots, which are lane or speed topics rather than value problems: run-unit-parallel 16,187 ms, e2e-runner 10,910 ms, run-serial-pool 9,499 ms, typecheck-incremental 8,637 ms, check-engine-dynamic-import 5,442 ms, run-verify-parallel 4,653 ms.+- **`test/helpers/*.test.ts` (10 files):** agent-harness, cli-spawn, git-fixture, reset-pglite(-narrow), schema-diff(-indexes), wait-for, with-env and with-snapshot. They protect helpers the whole corpus relies on for isolation, where a broken helper means cross-file flakiness. Keep. Note `reset-pglite.test.ts` costs 15,178 ms, a candidate for a speed pass, not deletion.++## 5. Retained false positives (looked low-value, are the independent contract)++- **`src/core/search/sql-ranking.ts` `__test__`** (escapeLikePattern / escapeSqlLiteral / buildLikePrefixLiteral) → `test/sql-ranking.test.ts`. SQL-escaping security contract. The direct unit test is the cheapest independent guard.+- **Gateway transport injectors** (`__setChatTransportForTests` 77 files, `__setEmbedTransportForTests` 88, rerank 9, plus generateText/generateObject). They make the keyless unit corpus possible, and the alternative is live providers.+- **`__setTestEngineOverride`** in migrations v0_22_4/v0_28_0/v0_31_0/v0_32_2. Migration contract tests (`migrations-v0_32_2`, `migration-orchestrator-v0_31_0`, e2e/frontmatter-migration) need an engine without a configured home. Keep.+- **The 75 reset/clear seams** other than the 6 zero-caller ones. Each backs a real module-level memo or warn-once; removing a seam requires removing the memo.+- **The `NODE_ENV==='test'` guards plus `GBRAIN_FORCE_BACKUP_NAG`.** They protect CI from detached network refreshes. The override lets `backup-status-file.serial` and `hook-backup-notice.serial` test the nag at the real boundary.+- **`test/ai/gateway-reset-baseline.test.ts` › "__unconfigureGatewayForTests() gives a genuinely unconfigured gateway".** It tests a seam, but that seam's correctness is a corpus-isolation contract for 80+ files. Keep.+- **The rest of `test/core/git-head.test.ts` (cases 1-9, 11+).** Predicate logic through DI, with the real boundary owned by `test/source-health.test.ts` (proven by probe).+- **`test/ocr-run-budget.test.ts` budget assertions.** The cost-cap contract. Rewrite at the boundary (H), don't delete.+- **Script-used modules the orphan guard counts as "test-only"** (mcp/http-transport, mcp/tool-catalog, bootstrap/template-repo, eval-contradictions/fixture-redact, longmemeval diagnostics/evidence-packet, eval/shared/autocut-replay). Used by `scripts/**` (check-tool-catalog-fresh, shared-skills lifecycle, generate-template-repo, lme-miss-diagnostics, …). Not dead.+- **`core/source-config-redact.ts` + test.** HOLD (§2.3). A CI security guard's remediation depends on it.+- **`src/core/agent-install/{entry,setup}.ts`.** My first walk flagged them, but they are a direct entry (`scripts/setup-in-agent.sh`) and are in the bundle.++## 6. Sizing summary++| Batch | Prod LOC removable | Test LOC removable | Compute (weights.json) | Confidence / risk |+|---|---:|---:|---|---|+| Dead modules, pure tests (§2, excluding source-config-redact HOLD) | ~9,210 (includes 525 untested allowlisted orphans) | 8,427 (37 files) | unit 18.1 s + serial 0.33 s + e2e 9.45 s ≈ 27.9 s file-time/run | High that the code is dead; needs a product wire-or-delete sign-off |+| Dead modules, mixed-file splits | (included above) | part of 1,777 (11 files) | small; E2E setup dominates | Medium; per-file surgery |+| Zero-caller seams (§3.1) | ~39 | 0 | 0 | High / low risk |+| Seam-only tests (§3.2 A–E) | ~5 | ~40 | negligible (tests inside kept files) | High (A, B, C, E probed); D medium-high |+| Wrappers (§3.3 F–H) | ~25 | ~15 deleted + ~10 cases rewritten | negligible | F, G high / low risk; H medium (rewrite) |++Bottom line: the seams themselves are cheap and mostly justified. The real reduction is the 42-module dead-code cluster and its 37 pure tests, which should go as one owner-boundary PR per feature cluster (ingestion, minions-v0.41, calibration-v0.36.1, progressive-batch, misc), each paired with lowering the `check-orphan-modules` ratchet, after the parent confirms none of those features is meant to be wired.diff --git a/docs/test-audit/2026-09-29/lane-seams/test-only-exports.tsv b/docs/test-audit/2026-09-29/lane-seams/test-only-exports.tsvnew file mode 100644index 0000000000..43bee614c9--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-seams/test-only-exports.tsv@@ -0,0 +1,1440 @@+DEAD-IN-PROD - src/cli.ts:1694 resetRetrievalMetaForTests 4 test/cli-empty-retrieval-render.test.ts,test/cli-explain-degraded-render.test.ts,test/cli-incomplete-retrieval-render.test.ts+DEAD-IN-PROD - src/commands/auth.ts:826 parseRescopeSurfaceValue 1 test/auth-create-args.test.ts+DEAD-IN-PROD - src/commands/embed.ts:109 _resetEmbedQuarantineForTest 1 test/embed-quarantine.serial.test.ts+DEAD-IN-PROD - src/commands/extract-conversation-facts.ts:656 _resetLockBusyLogCacheForTest 1 test/extract-conversation-facts-workers.test.ts+DEAD-IN-PROD - src/commands/init-mode-picker.ts:295 MODE_PICKER_MENU 2 test/init-mode-picker.test.ts,test/search/operation-expansion-contract.serial.test.ts+DEAD-IN-PROD - src/commands/migrations/index.ts:55 getMigration 8 test/migration-orchestrator-v0_21_0.test.ts,test/migrations-registry.test.ts,test/migrations-v0_12_0.test.ts+DEAD-IN-PROD - src/commands/schema.ts:422 _testHelpers 1 test/commands/schema-packpath.test.ts+DEAD-IN-PROD - src/commands/storage.ts:117 __resetPGLiteWarn 2 test/e2e/storage-tiering.test.ts,test/storage-pglite.test.ts+DEAD-IN-PROD - src/commands/sync.ts:5607 resolveParallelism 1 test/sync-all-parallel.test.ts+DEAD-IN-PROD - src/commands/sync.ts:5723 __resetPGLiteTierWarn 2 test/e2e/storage-tiering.test.ts,test/storage-pglite.test.ts+DEAD-IN-PROD - src/core/advisor/collect-mcp-client-fit.ts:80 __setUsageNagStatePathForTests 1 test/advisor-mcp-client-fit.test.ts+DEAD-IN-PROD - src/core/ai/anthropic-key.ts:56 setGatewayAnthropicKeySnapshot 2 test/ai/anthropic-key.test.ts,test/chat-key-plane.test.ts+DEAD-IN-PROD - src/core/ai/chat-usage.ts:89 setChatUsageSink 1 test/chat-usage.test.ts+DEAD-IN-PROD - src/core/ai/openai-latest.ts:296 _resetOpenAILatestForTests 1 test/openai-latest.serial.test.ts+DEAD-IN-PROD - src/core/ai/recipes/azure-openai.ts:44 __setEntraTokenForTests 1 test/ai/recipe-azure-openai.test.ts+DEAD-IN-PROD - src/core/ai/recipes/index.ts:74 __setTestRecipesForTests 4 test/ai/adaptive-embed-batch.test.ts,test/ai/no-batch-cap-item-split.test.ts,test/ai/no-batch-cap-suppression.serial.test.ts+DEAD-IN-PROD - src/core/archive-crawler-config.ts:275 loadArchiveCrawlerConfig 1 test/archive-crawler-config.test.ts+DEAD-IN-PROD - src/core/artifact/index.ts:43 detectArtifactKind 2 test/artifact-abstraction.test.ts,test/e2e/schema-cathedral.test.ts+DEAD-IN-PROD - src/core/audit-parser-probe.ts:50 computeParserProbeAuditFilename 1 test/audit-parser-probe.serial.test.ts+DEAD-IN-PROD - src/core/audit-skill-brain-first.ts:264 readRecentBrainFirstEvents 1 test/skill-brain-first.test.ts+DEAD-IN-PROD - src/core/audit-skill-brain-first.ts:310 _resetWarnedSetForTests 1 test/skill-brain-first.test.ts+DEAD-IN-PROD - src/core/audit/content-sanity-audit.ts:76 computeContentSanityAuditFilename 2 test/audit/audit-dir-preload.test.ts,test/audit/content-sanity-audit.test.ts+DEAD-IN-PROD - src/core/audit/db-disconnect-audit.ts:156 _dbDisconnectAuditFeatureName 1 test/db-disconnect-audit.test.ts+DEAD-IN-PROD - src/core/audit/lock-renewal-audit.ts:197 readRecentLockRenewalEvents 2 test/audit/lock-renewal-audit.test.ts,test/worker-lock-renewal-e2e.serial.test.ts+DEAD-IN-PROD - src/core/audit/lock-renewal-audit.ts:250 pruneOldLockRenewalAuditFiles 1 test/audit/lock-renewal-audit.test.ts+DEAD-IN-PROD - src/core/audit/pool-recovery-audit.ts:132 _poolRecoveryAuditFeatureName 1 test/audit/pool-recovery-audit.test.ts+DEAD-IN-PROD - src/core/audit/redact-connection-info.ts:98 getRedactionKinds 1 test/audit/redact-connection-info.test.ts+DEAD-IN-PROD - src/core/background-work.ts:139 __registerDrainerForTest 3 test/cli-finish-teardown.test.ts,test/core/background-work.test.ts,test/fix-wave-structural.test.ts+DEAD-IN-PROD - src/core/background-work.ts:145 __listDrainerNamesForTest 1 test/core/background-work.test.ts+DEAD-IN-PROD - src/core/backup/coverage.ts:416 __resetBackupRefreshForTests 3 test/backup-cli.serial.test.ts,test/backup-coverage.serial.test.ts,test/mcp-backup-nag.serial.test.ts+DEAD-IN-PROD - src/core/backup/status-file.ts:145 __setBackupStatusPathForTests 9 test/advisor-backup-coverage.serial.test.ts,test/backup-cli.serial.test.ts,test/backup-coverage.serial.test.ts+DEAD-IN-PROD - src/core/backup/status-file.ts:152 __setBackupNagStatePathForTests 7 test/advisor-backup-coverage.serial.test.ts,test/backup-cli.serial.test.ts,test/backup-coverage.serial.test.ts+DEAD-IN-PROD - src/core/backup/status-file.ts:156 __setBackupIntervalForTests 8 test/advisor-backup-coverage.serial.test.ts,test/backup-cli.serial.test.ts,test/backup-coverage.serial.test.ts+DEAD-IN-PROD - src/core/bootstrap/codex-toml.ts:136 detectForeignCodexServer 1 test/codex-toml.test.ts+DEAD-IN-PROD - src/core/bootstrap/status.ts:355 readInstallLog 5 test/bootstrap-dispatcher.serial.test.ts,test/bootstrap-status.serial.test.ts,test/bootstrap-subcommand-help.serial.test.ts+DEAD-IN-PROD - src/core/brain-score-recommendations.ts:445 estimateAnthropicCost 2 test/brain-score-recommendations.test.ts,test/model-pricing.test.ts+DEAD-IN-PROD - src/core/budget/budget-tracker.ts:189 _resetBudgetTrackerWarningsForTest 5 test/ai/gateway-ocr-budget.test.ts,test/core/budget/budget-tracker.test.ts,test/core/budget/expand-records-budget.test.ts+DEAD-IN-PROD - src/core/calibration/cross-brain.ts:142 canReadMountsForCtx 1 test/cross-brain-calibration.test.ts+DEAD-IN-PROD - src/core/calibration/cross-brain.ts:164 attributionSuffix 1 test/cross-brain-calibration.test.ts+DEAD-IN-PROD - src/core/calibration/cross-brain.ts:84 queryAcrossBrains 1 test/cross-brain-calibration.test.ts+DEAD-IN-PROD - src/core/calibration/nudge.ts:163 evaluateAndFireNudge 1 test/nudge.test.ts+DEAD-IN-PROD - src/core/calibration/nudge.ts:200 resetNudgeCooldown 1 test/nudge.test.ts+DEAD-IN-PROD - src/core/calibration/recall-footer.ts:43 buildRecallCalibrationFooter 1 test/recall-footer.test.ts+DEAD-IN-PROD - src/core/calibration/take-forecast.ts:109 forecastForTake 1 test/take-forecast.test.ts+DEAD-IN-PROD - src/core/calibration/take-forecast.ts:136 batchForecast 1 test/take-forecast.test.ts+DEAD-IN-PROD - src/core/calibration/templates.ts:106 dashboardCaptionTemplate 1 test/voice-gate.test.ts+DEAD-IN-PROD - src/core/calibration/templates.ts:111 morningPulseTemplate 1 test/voice-gate.test.ts+DEAD-IN-PROD - src/core/calibration/templates.ts:94 forecastBlurbTemplate 1 test/voice-gate.test.ts+DEAD-IN-PROD - src/core/chronicle/backstop.ts:20 runChronicleBackstop 1 test/chronicle-extract.test.ts+DEAD-IN-PROD - src/core/chunkers/code.ts:292 unregisterLanguage 2 test/chunkers/code-dart.test.ts,test/language-manifest.test.ts+DEAD-IN-PROD - src/core/chunkers/code.ts:297 listRegisteredLanguages 1 test/language-manifest.test.ts+DEAD-IN-PROD - src/core/chunkers/symbol-resolver.ts:305 readEdgeResolution 1 test/e2e/symbol-resolver-pglite.test.ts+DEAD-IN-PROD - src/core/claw-test/agent-runner.ts:220 _resetRegistryForTests 2 test/agent-runner.test.ts,test/claw-test-cli.test.ts+DEAD-IN-PROD - src/core/claw-test/progress-tail.ts:42 eventsByPhase 1 test/progress-tail.test.ts+DEAD-IN-PROD - src/core/cli-force-exit.ts:238 _resetCliExitVerdictForTests 21 test/backup-invalidation.serial.test.ts,test/call-federated-scope.test.ts,test/cli-finish-teardown.test.ts+DEAD-IN-PROD - src/core/cli-options.ts:342 _resetCliOptionsForTest 6 test/backup-cli.serial.test.ts,test/cli-concept-nudge.test.ts,test/cli-explain-degraded-render.test.ts+DEAD-IN-PROD - src/core/code-intel/traversal-cache.ts:67 bumpClusterGeneration 1 test/code-intel/traversal-cache.test.ts+DEAD-IN-PROD - src/core/company-brain/receipts.ts:241 discardSourceIngestionReceipt 1 test/helpers/company-brain-receipts.ts+DEAD-IN-PROD - src/core/company-brain/receipts.ts:245 pruneSourceIngestionReceipts 1 test/helpers/company-brain-receipts.ts+DEAD-IN-PROD - src/core/config-db-merge.ts:97 _resetDbPlaneMergeMemoForTests 1 test/config-db-merge.test.ts+DEAD-IN-PROD - src/core/connection-audit.ts:36 setAuditEnabled 1 test/audit/connection-audit.serial.test.ts+DEAD-IN-PROD - src/core/connection-audit.ts:88 tailRecentErrors 1 test/audit/connection-audit.serial.test.ts+DEAD-IN-PROD - src/core/console-prefix.ts:106 isStdoutLoggingRedirected 1 test/stdio-stderr-redirect.serial.test.ts+DEAD-IN-PROD - src/core/console-prefix.ts:114 _resetStdoutRedirectForTests 4 test/serve-stdin-eof-drain.test.ts,test/serve-stdio-lifecycle.test.ts,test/stdio-stderr-redirect.serial.test.ts+DEAD-IN-PROD - src/core/context-engine.ts:101 __resetSdkLoadStateForTests 3 test/context-engine-checkpoint.serial.test.ts,test/context-engine.test.ts,test/e2e/openclaw-context-engine-plugin.test.ts+DEAD-IN-PROD - src/core/context/checkpoint-harvest.ts:169 __resetCheckpointHarvestForTests 3 test/checkpoint-harvest.serial.test.ts,test/context-pack-wb-lane.serial.test.ts,test/writeback-review-fixes.serial.test.ts+DEAD-IN-PROD - src/core/context/checkpoint-harvest.ts:179 __drainCheckpointHarvestForTests 3 test/checkpoint-harvest.serial.test.ts,test/context-pack-wb-lane.serial.test.ts,test/writeback-review-fixes.serial.test.ts+DEAD-IN-PROD - src/core/context/reflex.ts:407 disposeReflex 1 test/retrieval-reflex.test.ts+DEAD-IN-PROD - src/core/context/volunteer-events.ts:233 _resetPendingVolunteerEventWritesForTests 5 test/e2e/volunteer-context-postgres.test.ts,test/retrieval-reflex.test.ts,test/volunteer-context.test.ts+DEAD-IN-PROD - src/core/context/volunteer-events.ts:238 _peekPendingVolunteerEventWritesForTests 2 test/volunteer-context.test.ts,test/volunteer-events-delivery.test.ts+DEAD-IN-PROD - src/core/context/volunteer-events.ts:45 isVolunteerChannel 2 test/reflex-volunteer.test.ts,test/volunteer-events-delivery.test.ts+DEAD-IN-PROD - src/core/contextual-retrieval-resolver.ts:151 ALL_CR_MODES 1 test/contextual-retrieval-resolver.test.ts+DEAD-IN-PROD - src/core/contextual-retrieval-service.ts:204 computeSourceTextHash 1 test/contextual-retrieval-service-pure.test.ts+DEAD-IN-PROD - src/core/contextual-retrieval-service.ts:779 expectedModeForPageSourceOnly 1 test/contextual-retrieval-service-pure.test.ts+DEAD-IN-PROD - src/core/conversation-parser/llm-base.ts:67 getLlmCacheStats 1 test/conversation-parser/llm-base.test.ts+DEAD-IN-PROD - src/core/conversation-parser/llm-polish.ts:88 runLlmPolish 1 test/conversation-parser/llm-polish.test.ts+DEAD-IN-PROD - src/core/cross-modal-eval/receipt-name.ts:140 listReceiptsForSlug 1 test/cross-modal-eval-cli.test.ts+DEAD-IN-PROD - src/core/cross-modal-eval/receipt-name.ts:158 isReceiptFile 1 test/cross-modal-eval-cli.test.ts+DEAD-IN-PROD - src/core/cycle/auto-think.ts:107 runPhaseAutoThink 1 test/auto-think-phase.test.ts+DEAD-IN-PROD - src/core/cycle/budget-meter.ts:223 _resetBudgetMeterWarningsForTest 2 test/auto-think-phase.test.ts,test/budget-meter.test.ts+DEAD-IN-PROD - src/core/cycle/extract-atoms.ts:1579 parseAtomsResponse 2 test/cycle/extract-atoms-synthesize-concepts.test.ts,test/extract-atoms-chunk-embed.test.ts+DEAD-IN-PROD - src/core/cycle/filing-rules.ts:161 __filingRulesTesting 1 test/cycle-dream-output-root.test.ts+DEAD-IN-PROD - src/core/cycle/transcript-discovery.ts:161 compileExcludePatterns 2 test/cycle-synthesize.test.ts,test/frontmatter-inference.test.ts+DEAD-IN-PROD - src/core/cycle/transcript-discovery.ts:98 isBrainstormOutput 1 test/brainstorm/lsd-mode-skip.test.ts+DEAD-IN-PROD - src/core/data-research.ts:158 extractFields 1 test/data-research.test.ts+DEAD-IN-PROD - src/core/data-research.ts:191 verifyExtraction 1 test/data-research.test.ts+DEAD-IN-PROD - src/core/data-research.ts:267 parseTrackerPage 1 test/data-research.test.ts+DEAD-IN-PROD - src/core/data-research.ts:288 appendToTracker 1 test/data-research.test.ts+DEAD-IN-PROD - src/core/data-research.ts:314 computeTotals 1 test/data-research.test.ts+DEAD-IN-PROD - src/core/data-research.ts:335 buildDateWindows 1 test/data-research.test.ts+DEAD-IN-PROD - src/core/data-research.ts:396 stripEmailHtml 1 test/data-research.test.ts+DEAD-IN-PROD - src/core/data-research.ts:73 validateRecipe 1 test/data-research.test.ts+DEAD-IN-PROD - src/core/db-lock.ts:1069 buildTenantLockId 1 test/db-lock-refresh.test.ts+DEAD-IN-PROD - src/core/db-lock.ts:86 DEFAULT_STEAL_GRACE_SECONDS 1 test/db-lock-heartbeat-takeover.test.ts+DEAD-IN-PROD - src/core/db.ts:121 _resetMaxLifetimeWarningForTests 1 test/db-pool-max-lifetime.test.ts+DEAD-IN-PROD - src/core/doctor-categories.ts:255 _resetUnknownCheckWarningsForTest 1 test/doctor-categories.test.ts+DEAD-IN-PROD - src/core/doctor-cause-rank.ts:136 CAUSE_GRAPH_NAMES 1 test/doctor-cause-rank.test.ts+DEAD-IN-PROD - src/core/doctor-cause-rank.ts:142 allKnownCheckNames 1 test/doctor-cause-rank.test.ts+DEAD-IN-PROD - src/core/embed-stall.ts:86 _resetEmbedApiLivenessForTests 1 test/embed-stall.test.ts+DEAD-IN-PROD - src/core/embedding-context.ts:171 modeRequiresHaiku 1 test/embedding-context.test.ts+DEAD-IN-PROD - src/core/enrich/thin.ts:61 isThinBody 1 test/enrich/thin.test.ts+DEAD-IN-PROD - src/core/enrichment-service.ts:94 entityPagePath 1 test/enrichment-service.test.ts+DEAD-IN-PROD - src/core/enrichment/completeness.ts:245 scorePage 1 test/enrichment.test.ts+DEAD-IN-PROD - src/core/enrichment/completeness.ts:263 getRubric 1 test/enrichment.test.ts+DEAD-IN-PROD - src/core/env-number.ts:73 _resetEnvNumberWarnedForTests 1 test/env-number.test.ts+DEAD-IN-PROD - src/core/eval-capture-graph.ts:158 compareCodeWalk 1 test/code-intel/eval-capture-graph.test.ts+DEAD-IN-PROD - src/core/eval-capture.ts:222 _resetPendingEvalCapturesForTests 1 test/eval-capture-drain.test.ts+DEAD-IN-PROD - src/core/eval/metric-glossary.ts:292 ALL_METRICS 1 test/metric-glossary.test.ts+DEAD-IN-PROD - src/core/facts/absorb-log.ts:65 _resetFactsAbsorbDisconnectedFlagForTests 2 test/facts-absorb-log.test.ts,test/facts-backstop-outcome.serial.test.ts+DEAD-IN-PROD - src/core/facts/backstop.ts:166 __resetBackstopWarningsForTests 1 test/facts-backstop-outcome.serial.test.ts+DEAD-IN-PROD - src/core/facts/classify.ts:69 classifyAgainstCandidates 1 test/facts-classify.test.ts+DEAD-IN-PROD - src/core/facts/cli-process-mode.ts:33 __resetShortLivedCliForTests 2 test/facts-backstop-outcome.serial.test.ts,test/facts-visibility.test.ts+DEAD-IN-PROD - src/core/facts/extract.ts:717 _resetExtractWrapperWarningsForTests 1 test/facts-backstop-outcome.serial.test.ts+DEAD-IN-PROD - src/core/facts/meta-hook.ts:216 __resetHotMemoryCacheForTests 7 test/ambient-recall.test.ts,test/e2e/facts-context-injection-postgres.test.ts,test/e2e/serve-http-meta.test.ts+DEAD-IN-PROD - src/core/facts/meta-hook.ts:221 __hotMemoryCacheForTests 1 test/facts-meta-cache.test.ts+DEAD-IN-PROD - src/core/facts/queue.ts:255 __resetFactsQueueForTests 7 test/checkpoint-harvest.serial.test.ts,test/context-pack-wb-lane.serial.test.ts,test/facts-backstop-integration.test.ts+DEAD-IN-PROD - src/core/file-resolver.ts:50 resolveFile 2 test/file-migration.test.ts,test/file-resolver.test.ts+DEAD-IN-PROD - src/core/git-head.ts:79 _setGitCleanProbeForTests 2 test/core/git-head.test.ts,test/doctor.test.ts+DEAD-IN-PROD - src/core/github-source.ts:94 isGitHubSourceConfig 1 test/github-source-page.test.ts+DEAD-IN-PROD - src/core/google/loop-detect.ts:207 __clearSuppressionCacheForTests 3 test/google-source-materialize.test.ts,test/google-source-reconcile.test.ts,test/loop-apply.test.ts+DEAD-IN-PROD - src/core/ingestion/skillpack-load.ts:119 loadSkillpackSources 1 test/ingestion/skillpack-load.test.ts+DEAD-IN-PROD - src/core/ingestion/sources/file-watcher.ts:81 createFileWatcherSource 1 test/ingestion/sources/file-watcher.test.ts+DEAD-IN-PROD - src/core/ingestion/sources/inbox-folder.ts:141 createInboxFolderSource 2 test/e2e/ingestion-roundtrip.test.ts,test/ingestion/sources/inbox-folder.test.ts+DEAD-IN-PROD - src/core/last-retrieved.ts:120 _resetPendingLastRetrievedWritesForTests 1 test/last-retrieved.test.ts+DEAD-IN-PROD - src/core/last-retrieved.ts:125 _peekPendingLastRetrievedWritesForTests 1 test/last-retrieved.test.ts+DEAD-IN-PROD - src/core/last-retrieved.ts:161 _resetTrackRetrievalCacheForTests 1 test/last-retrieved.test.ts+DEAD-IN-PROD - src/core/mcp-client.ts:43 _clearMcpClientTokenCache 2 test/mcp-client.test.ts,test/remote-cli.test.ts+DEAD-IN-PROD - src/core/minions/admission.ts:207 _resetAdmissionCacheForTest 4 test/jobs-lifecycle-ops.test.ts,test/jobs-ops-token-redaction.test.ts,test/minions-admission.test.ts+DEAD-IN-PROD - src/core/minions/agent-audit.ts:91 readRecentAgentEvents 1 test/minions/agent-audit.test.ts+DEAD-IN-PROD - src/core/minions/batch-projection.ts:162 formatProjection 1 test/batch-projection.test.ts+DEAD-IN-PROD - src/core/minions/batch-projection.ts:180 shouldPromptAtThreshold 1 test/batch-projection.test.ts+DEAD-IN-PROD - src/core/minions/batch-projection.ts:94 projectBatch 1 test/batch-projection.test.ts+DEAD-IN-PROD - src/core/minions/budget-meter.ts:228 sweepExpiredReservations 1 test/minions/budget-meter.test.ts+DEAD-IN-PROD - src/core/minions/budget-meter.ts:242 getClientDailyCapCents 1 test/minions/budget-meter.test.ts+DEAD-IN-PROD - src/core/minions/budget-tracker.ts:231 haltBudgetSubtree 2 test/budget-tracker.test.ts,test/e2e/minions-budget-cathedral.test.ts+DEAD-IN-PROD - src/core/minions/job-isolation.ts:231 decodeChildOutcomeFile 3 test/e2e/job-isolation.test.ts,test/job-isolation-protocol.test.ts,test/run-child-entry.test.ts+DEAD-IN-PROD - src/core/minions/lease-cap-controller.ts:271 controllerTick 2 test/e2e/minions-controller-bounce-only.test.ts,test/lease-cap-controller.test.ts+DEAD-IN-PROD - src/core/minions/llm-halt-cooldown.ts:69 _resetLlmHaltCooldownsForTests 1 test/llm-halt-cooldown.test.ts+DEAD-IN-PROD - src/core/minions/llm-halt-cooldown.ts:74 llmHaltCooldownRemainingMs 1 test/llm-halt-cooldown.test.ts+DEAD-IN-PROD - src/core/minions/queue.ts:85 _resetStallGraceWarningsForTests 1 test/minions.test.ts+DEAD-IN-PROD - src/core/minions/stagger.ts:33 staggerSecondOffset 1 test/minions-quiet-hours.test.ts+DEAD-IN-PROD - src/core/model-config.ts:336 isOpenRouterAnthropic 1 test/model-config.serial.test.ts+DEAD-IN-PROD - src/core/model-config.ts:683 _resetDeprecationWarningsForTest 7 test/ai/gateway-model-sources.serial.test.ts,test/e2e/skillopt-models-strict.serial.test.ts,test/gateway-reconfigure-clobber.serial.test.ts+DEAD-IN-PROD - src/core/op-checkpoint.ts:376 reindexFingerprint 1 test/op-checkpoint.test.ts+DEAD-IN-PROD - src/core/ops/pages.ts:314 autoLinkLockKey 1 test/lock-keys.test.ts+DEAD-IN-PROD - src/core/output/scaffold.ts:132 entityLink 1 test/writer.test.ts+DEAD-IN-PROD - src/core/output/scaffold.ts:154 timelineLine 1 test/writer.test.ts+DEAD-IN-PROD - src/core/persistence/verb-errors.ts:93 committedVerbOutcome 1 test/persistence-write-contracts.test.ts+DEAD-IN-PROD - src/core/pid1-reaper.ts:180 _uninstallPid1OrphanReaperForTests 1 test/pid1-reaper.test.ts+DEAD-IN-PROD - src/core/preferences.ts:263 preferencesPaths 1 test/preferences.test.ts+DEAD-IN-PROD - src/core/process-cleanup.ts:90 _registeredCleanupCountForTests 1 test/process-cleanup.test.ts+DEAD-IN-PROD - src/core/progress.ts:494 __liveReporterCountForTest 1 test/progress.test.ts+DEAD-IN-PROD - src/core/progress.ts:498 __signalHandlerInstalledForTest 1 test/progress.test.ts+DEAD-IN-PROD - src/core/progressive-batch/retrofit-wrap.ts:65 retrofitWrap 1 test/progressive-batch/retrofit-wrap.test.ts+DEAD-IN-PROD - src/core/quarantine.ts:151 hasContentFlag 1 test/quarantine.test.ts+DEAD-IN-PROD - src/core/quarantine.ts:92 filterOutQuarantined 1 test/quarantine.test.ts+DEAD-IN-PROD - src/core/recall-cursor-state.ts:119 _cursorPathForTests 1 test/recall-extensions.test.ts+DEAD-IN-PROD - src/core/resolvers/builtin/url-reachable.ts:131 checkDnsRebinding 1 test/resolvers.test.ts+DEAD-IN-PROD - src/core/retry.ts:355 isBatchAuditSite 1 test/core/retry.test.ts+DEAD-IN-PROD - src/core/schema-pack/expand-type-filter.ts:166 buildTypeFilterSql 1 test/schema-pack-expand-type-filter.test.ts+DEAD-IN-PROD - src/core/search/autocut.ts:93 resolveAutocut 1 test/search/autocut.test.ts+DEAD-IN-PROD - src/core/search/embedding-column.ts:515 isBuiltinColumn 1 test/search/embedding-column.serial.test.ts+DEAD-IN-PROD - src/core/search/image-loader.ts:38 DEFAULT_REMOTE_IMAGE_MAX_BYTES 1 test/cross-modal-phase2.test.ts+DEAD-IN-PROD - src/core/search/private-visibility.ts:127 __resetPrivateVisibilityCacheForTests 4 test/chronicle-ontology-private-visibility.test.ts,test/e2e/engine-content-privacy.test.ts,test/e2e/legacy-chunk-privacy.test.ts+DEAD-IN-PROD - src/core/search/query-cache-gate.ts:204 validateCacheRowAgainstPages 1 test/query-cache-gate.test.ts+DEAD-IN-PROD - src/core/search/query-intent.ts:389 clearIntentPatternConfigForTests 1 test/query-intent-config.test.ts+DEAD-IN-PROD - src/core/search/return-policy.ts:114 adaptiveReturnEnabled 1 test/search/return-policy.test.ts+DEAD-IN-PROD - src/core/self-upgrade.ts:387 writeSnooze 1 test/self-upgrade.test.ts+DEAD-IN-PROD - src/core/serve-sweep-runner.ts:142 __resetDelegatedSweepForTests 1 test/serve-sweep-runner-677.test.ts+DEAD-IN-PROD - src/core/serve-sync-runner.ts:401 __resetDelegatedSyncForTests 2 test/serve-sync-embed-drain.serial.test.ts,test/serve-sync-runner.serial.test.ts+DEAD-IN-PROD - src/core/serve-sync-runner.ts:413 __deferredEmbedsPendingForTests 2 test/serve-sync-embed-drain.serial.test.ts,test/serve-sync-runner.serial.test.ts+DEAD-IN-PROD - src/core/skillopt/audit.ts:69 _resetAuditWriterForTests 7 test/e2e/skillopt-loop.serial.test.ts,test/e2e/skillopt-models-strict.serial.test.ts,test/e2e/skillopt-models-used.serial.test.ts+DEAD-IN-PROD - src/core/skillopt/audit.ts:79 readRecentEvents 1 test/skillopt/audit.test.ts+DEAD-IN-PROD - src/core/skillopt/audit.ts:94 currentAuditFilename 6 test/e2e/skillopt-loop.serial.test.ts,test/e2e/skillopt-models-strict.serial.test.ts,test/e2e/skillopt-models-used.serial.test.ts+DEAD-IN-PROD - src/core/skillopt/held-out.ts:82 appendCapture 1 test/skillopt/held-out.test.ts+DEAD-IN-PROD - src/core/skillopt/reflect.ts:432 parseEditsResponse 1 test/skillopt/reflect.test.ts+DEAD-IN-PROD - src/core/skillopt/remediation.ts:44 SKILLOPT_REMEDIATION_CODES 2 test/skillopt/error-code-docs.test.ts,test/skillopt/run-outcome.test.ts+DEAD-IN-PROD - src/core/skillpack/audit.ts:135 currentAuditFilePath 1 test/skillpack-rubric-doctor.test.ts+DEAD-IN-PROD - src/core/skillpack/audit.ts:94 readRecentSkillpackEvents 1 test/skillpack-rubric-doctor.test.ts+DEAD-IN-PROD - src/core/skillpack/brain-pack-lint.ts:46 lintBrainPackTools 1 test/skillpack-init-brain-pack.test.ts+DEAD-IN-PROD - src/core/skillpack/state.ts:170 removeEntry 1 test/skillpack-state.test.ts+DEAD-IN-PROD - src/core/source-config-redact.ts:43 hasWebhookSecret 1 test/source-config-redact.test.ts+DEAD-IN-PROD - src/core/source-health.ts:70 _resetPriorityWarningsForTest 1 test/source-health.test.ts+DEAD-IN-PROD - src/core/source-resolver.ts:1019 __resetSourceGuardQueryShape 1 test/serve-source-guard.serial.test.ts+DEAD-IN-PROD - src/core/source-resolver.ts:523 __resetDefaultWriteGuardMemo 1 test/import-default-write-guard-once.test.ts+DEAD-IN-PROD - src/core/source-resolver.ts:606 maybeWarnUnscopedDefaultWrite 1 test/source-resolver-default-write-guard.test.ts+DEAD-IN-PROD - src/core/storage-config.ts:436 isSupabaseOnly 1 test/storage-config.test.ts+DEAD-IN-PROD - src/core/storage-config.ts:439 __resetMissingStorageWarning 5 test/e2e/storage-tiering.test.ts,test/storage-config.test.ts,test/storage-export.test.ts+DEAD-IN-PROD - src/core/sync-delta.ts:58 _setGitRunnerForTests 1 test/sync-delta.test.ts+DEAD-IN-PROD - src/core/takes-quality-eval/receipt-name.ts:54 parseReceiptFilename 1 test/eval-takes-quality-receipt-name.test.ts+DEAD-IN-PROD - src/core/takes-quality-eval/replay.ts:56 loadReceiptFromDb 2 test/e2e/eval-takes-quality.test.ts,test/eval-takes-quality-replay.test.ts+DEAD-IN-PROD - src/core/takes-write.ts:202 __takesWriteTesting 1 test/takes-write-ops.test.ts+DEAD-IN-PROD - src/core/thin-client-upgrade-prompt.ts:271 _setVerifierForTest 1 test/thin-client-upgrade-prompt.test.ts+DEAD-IN-PROD - src/core/thin-client-upgrade-prompt.ts:305 _setPromptReaderForTest 1 test/thin-client-upgrade-prompt.test.ts+DEAD-IN-PROD - src/core/thin-client-upgrade-prompt.ts:321 _setUpgradeRunnerForTest 1 test/thin-client-upgrade-prompt.test.ts+DEAD-IN-PROD - src/core/upgrade-checkpoint.ts:120 validateCheckpoint 2 test/e2e/v030_1-integration-pglite.test.ts,test/upgrade-checkpoint.serial.test.ts+DEAD-IN-PROD - src/core/upgrade-checkpoint.ts:137 markStepComplete 2 test/e2e/v030_1-integration-pglite.test.ts,test/upgrade-checkpoint.serial.test.ts+DEAD-IN-PROD - src/core/upgrade-checkpoint.ts:147 markStepFailed 1 test/upgrade-checkpoint.serial.test.ts+DEAD-IN-PROD - src/core/upgrade-checkpoint.ts:160 ALL_UPGRADE_STEPS 1 test/upgrade-checkpoint.serial.test.ts+DEAD-IN-PROD - src/core/upgrade-checkpoint.ts:53 computeBrainId 2 test/e2e/v030_1-integration-pglite.test.ts,test/upgrade-checkpoint.serial.test.ts+DEAD-IN-PROD - src/core/vector-index.ts:294 isSupabaseAutoMaintenance 1 test/vector-index-lifecycle.test.ts+DEAD-IN-PROD - src/core/verbs/usage-log.ts:51 __setUsageLogPathForTests 7 test/ambient-writeback-wiring-pins.test.ts,test/doctor-memory-verbs-check.test.ts,test/mcp-surface.test.ts+DEAD-IN-PROD - src/core/write-through.ts:186 _resetWriteThroughCacheForTest 11 test/bootstrap-verify.serial.test.ts,test/e2e/put-page-persistence-postgres.test.ts,test/extract-facts-phase.test.ts+DEAD-IN-PROD - src/core/zombie-reap.ts:42 _uninstallSigchldHandlerForTests 1 test/zombie-reap.test.ts+DEAD-IN-PROD - src/eval/brainbench/harness.ts:90 seamFor 1 test/brainbench-adapters.test.ts+DEAD-IN-PROD - src/eval/longmemeval/diagnostics.ts:123 emptyRanks 1 test/longmemeval-diagnostics.test.ts+DEAD-IN-PROD - src/eval/longmemeval/judge.ts:198 parseJudgeVerdict 1 test/longmemeval-judge.test.ts+DEAD-IN-PROD - src/eval/shared/judge-runner.ts:36 JUDGE_ERROR_CLASSES 1 test/longmemeval-judge.test.ts+DEAD-IN-PROD - src/mcp/dispatch.ts:74 __resetBackupNoticeForTests 1 test/mcp-backup-nag.serial.test.ts+DEAD-IN-PROD - src/mcp/surface.ts:206 __resetSurfaceWarnCachesForTests 1 test/mcp-surface.test.ts+DEAD-IN-PROD - src/mcp/validate-params.ts:169 resetStrictParamsModeCache 3 test/fixtures/shared-skills-transport-cases.ts,test/shared-skills-brain-assertion.test.ts,test/validate-params.test.ts+DEAD-IN-PROD PUBLIC src/core/ai/gateway.ts:1787 __getShrinkStateForTests 1 test/ai/adaptive-embed-batch.test.ts+DEAD-IN-PROD PUBLIC src/core/ai/gateway.ts:655 __setGatewayResetBaselineForTests 2 test/embed-preflight.test.ts,test/helpers/legacy-embedding-preload.ts+DEAD-IN-PROD PUBLIC src/core/ai/gateway.ts:688 _clearGatewayForTests 1 test/doctor-reranker-health.test.ts+DEAD-IN-PROD PUBLIC src/core/ai/gateway.ts:709 __unconfigureGatewayForTests 10 test/ai/gateway-reset-baseline.test.ts,test/ai/gateway.test.ts,test/doctor-embedding-width.test.ts+DEAD-IN-PROD PUBLIC src/core/ai/gateway.ts:810 getMultimodalModel 1 test/cli-multimodal-integration.test.ts+DEAD-IN-PROD PUBLIC src/core/ai/gateway.ts:832 getChatFallbackChain 1 test/ai/gateway-chat.test.ts+DEAD-IN-PROD PUBLIC src/core/backoff.ts:188 getThrottleState 1 test/backoff.test.ts+DEAD-IN-PROD PUBLIC src/core/embedding.ts:121 EMBEDDING_COST_PER_1K_TOKENS 2 test/e2e/dream-cycle-phase-order-pglite.test.ts,test/sync-cost-preview.test.ts+DEAD-IN-PROD PUBLIC src/core/embedding.ts:197 willEmbedSynchronously 3 test/e2e/dream-cycle-phase-order-pglite.test.ts,test/sync-cost-gate.serial.test.ts,test/sync-cost-preview.test.ts+DEAD-IN-PROD PUBLIC src/core/guardrails.ts:104 __resetGuardrailProvidersForTests 2 test/guardrails-env-load.test.ts,test/guardrails.test.ts+DEAD-IN-PROD PUBLIC src/core/guardrails.ts:99 unregisterGuardrailProvider 1 test/guardrails.test.ts+DEAD-IN-PROD PUBLIC src/core/import-file.ts:1894 _resetOcrRunBudgetForTests 2 test/e2e/chunk-canonical-text-privacy.test.ts,test/ocr-run-budget.test.ts+DEAD-IN-PROD PUBLIC src/core/import-file.ts:1901 _getOcrRunBudgetForTests 1 test/ocr-run-budget.test.ts+DEAD-IN-PROD PUBLIC src/core/import-file.ts:1943 _maybeOcrGatedForTests 1 test/ocr-run-budget.test.ts+DEAD-IN-PROD PUBLIC src/core/pglite-engine.ts:226 __snapshotMemoStatsForTests 1 test/snapshot-shape-guard.test.ts+DEAD-IN-PROD PUBLIC src/core/pglite-engine.ts:230 __resetSnapshotMemoForTests 1 test/snapshot-shape-guard.test.ts+DEAD-IN-PROD PUBLIC src/core/pglite-lock.ts:122 isPidReusedByOtherProgram 1 test/pglite-lock-process-probe.test.ts+DEAD-IN-PROD PUBLIC src/core/pglite-lock.ts:181 peekLock 2 test/pglite-lock.test.ts,test/public-exports.test.ts+DEAD-IN-PROD PUBLIC src/core/search/hybrid.ts:243 _resetPendingSearchCacheWritesForTests 1 test/search-telemetry-cache-wiring.serial.test.ts+DEAD-IN-PROD PUBLIC src/core/search/hybrid.ts:444 DEFAULT_TITLE_BOOST 1 test/search/title-boost-stage.test.ts+DEAD-IN-PROD PUBLIC src/core/search/hybrid.ts:715 _resetSupersedeProbeForTests 3 test/e2e/read-enrichment-privacy.test.ts,test/search/exact-lookup.test.ts,test/search/supersede-downrank.test.ts+DEAD-IN-PROD PUBLIC src/core/think/index.ts:1214 __thinkAdapter 1 test/think-gateway-adapter.test.ts+internal-used - src/cli.ts:1112 resolveQueryImage 1 test/cli-query-image.test.ts+internal-used - src/cli.ts:1144 parseOpArgs 8 test/cli-args.test.ts,test/cli-flag-validation.test.ts,test/cli-input-plumbing-2822.test.ts+internal-used - src/cli.ts:1266 applyStdinParam 1 test/cli-stdin-hang.test.ts+internal-used - src/cli.ts:1430 validateCommandFlags 3 test/cli-flag-validation.test.ts,test/cli-recall-flag-ownership.test.ts,test/generate-flag-registry.test.ts+internal-used - src/cli.ts:1451 findUnknownFlag 1 test/cli-flag-validation.test.ts+internal-used - src/cli.ts:1471 findUnknownOpFlag 2 test/cli-args.test.ts,test/cli-flag-validation.test.ts+internal-used - src/cli.ts:1687 captureRetrievalMeta 4 test/cli-empty-retrieval-render.test.ts,test/cli-explain-degraded-render.test.ts,test/cli-incomplete-retrieval-render.test.ts+internal-used - src/cli.ts:1726 maybePrintConceptNudge 1 test/cli-concept-nudge.test.ts+internal-used - src/cli.ts:1985 THIN_CLIENT_REFUSED_COMMANDS 2 test/bootstrap-status.serial.test.ts,test/thin-client-routing-audit.test.ts+internal-used - src/cli.ts:3613 resolveReadOnlyDispatchTimeoutMs 1 test/sync-timeout-cli-dispatch.test.ts+internal-used - src/cli.ts:81 normalizeLocalResult 2 test/cli.test.ts,test/e2e/thin-client.test.ts+internal-used - src/commands/agent-logs.ts:150 parseSince 1 test/agent-cli.test.ts+internal-used - src/commands/agent-register.ts:111 RegisterError 1 test/agent-register.test.ts+internal-used - src/commands/agent-register.ts:149 parseAgentRegisterArgs 1 test/agent-register.test.ts+internal-used - src/commands/agent-register.ts:287 resolvePreset 1 test/agent-register.test.ts+internal-used - src/commands/agent-register.ts:349 snapshotGrantSources 1 test/agent-register.test.ts+internal-used - src/commands/agent-register.ts:608 ensureWorkspaceSource 1 test/agent-register.test.ts+internal-used - src/commands/agent-register.ts:74 REGISTER_DEFAULT_TOKEN_TTL_SECONDS 1 test/agent-register.test.ts+internal-used - src/commands/agent-register.ts:801 rotateClientSecret 1 test/agent-register.test.ts+internal-used - src/commands/agent-register.ts:83 WORKSPACE_NAME_MAX 1 test/agent-register.test.ts+internal-used - src/commands/agent.ts:288 runAgentRun 2 test/agent-cli.test.ts,test/minions/dream-quota-degradation.test.ts+internal-used - src/commands/auth.ts:1050 parseAuthCreateArgs 1 test/auth-create-args.test.ts+internal-used - src/commands/auth.ts:189 renderTokenScopes 1 test/auth-create-args.test.ts+internal-used - src/commands/auth.ts:743 formatRegisterClientOutput 2 test/agent-register.test.ts,test/auth-register-client-output-pin.test.ts+internal-used - src/commands/auth.ts:878 parseAuthClientsArgs 1 test/auth-create-args.test.ts+internal-used - src/commands/auth.ts:918 listClientRows 1 test/auth-create-args.test.ts+internal-used - src/commands/autopilot-fanout.ts:183 readLastFullCycleAt 6 test/autopilot-fanout.test.ts,test/cycle-enabled-phase-completeness.test.ts,test/cycle-last-full-cycle-at.test.ts+internal-used - src/commands/autopilot-fanout.ts:199 isSourceStale 1 test/autopilot-fanout.test.ts+internal-used - src/commands/autopilot-fanout.ts:226 cooldownMinForCount 1 test/autopilot-failure-cooldown.test.ts+internal-used - src/commands/autopilot-fanout.ts:238 isInFailureCooldown 1 test/autopilot-failure-cooldown.test.ts+internal-used - src/commands/autopilot-fanout.ts:256 resolveFailureCooldownOpts 1 test/autopilot-failure-cooldown.test.ts+internal-used - src/commands/autopilot-fanout.ts:280 readRecentSourceFailures 2 test/autopilot-failure-cooldown.test.ts,test/e2e/autopilot-cooldown-parity.test.ts+internal-used - src/commands/autopilot-fanout.ts:347 selectSourcesForDispatch 3 test/autopilot-failure-cooldown.test.ts,test/autopilot-fanout.test.ts,test/e2e/autopilot-fanout-postgres.test.ts+internal-used - src/commands/autopilot-fanout.ts:618 isGlobalMaintenanceStale 2 test/autopilot-global-maintenance.test.ts,test/cycle/global-freshness-postcondition.serial.test.ts+internal-used - src/commands/autopilot.ts:169 resolveWindowsCliPath 1 test/autopilot-resolve-cli.test.ts+internal-used - src/commands/autopilot.ts:1771 AUTOPILOT_SYSTEMD_UNIT 1 test/autopilot-self-disable-and-status.test.ts+internal-used - src/commands/autopilot.ts:1799 generateSelfDisableGuard 2 test/autopilot-launchd-lifecycle.serial.test.ts,test/autopilot-self-disable-and-status.test.ts+internal-used - src/commands/autopilot.ts:1864 writeWrapperScript 3 test/autopilot-install-wrapper.serial.test.ts,test/autopilot-install.test.ts,test/e2e/autopilot-linux-lifecycle.serial.test.ts+internal-used - src/commands/autopilot.ts:2055 pgliteDaemonGuardMessage 1 test/serve-sweep-runner-677.test.ts+internal-used - src/commands/autopilot.ts:2080 generateLaunchdPlist 2 test/autopilot-reconnect-classifier.test.ts,test/sources-abs-path-3696.test.ts+internal-used - src/commands/autopilot.ts:2157 generateSystemdUnit 2 test/autopilot-install.test.ts,test/autopilot-self-upgrade.test.ts+internal-used - src/commands/autopilot.ts:2537 autopilotStatusExitCode 2 test/autopilot-self-disable-and-status.test.ts,test/e2e/autopilot-linux-lifecycle.serial.test.ts+internal-used - src/commands/autopilot.ts:2552 classifyAutopilotStatus 1 test/autopilot-self-disable-and-status.test.ts+internal-used - src/commands/autopilot.ts:2627 crontabIndicatesAutopilotInstall 3 test/autopilot-install.test.ts,test/autopilot-self-disable-and-status.test.ts,test/e2e/autopilot-linux-lifecycle.serial.test.ts+internal-used - src/commands/autopilot.ts:264 AUTOPILOT_FOREIGN_PID_TAKEOVER_GRACE_MS 1 test/autopilot-lock.test.ts+internal-used - src/commands/autopilot.ts:274 decideLockAcquisition 1 test/autopilot-lock.test.ts+internal-used - src/commands/autopilot.ts:371 guardAutopilotEngine 2 test/autopilot-transaction-fence.test.ts,test/supervisor-configuration-blocked.test.ts+internal-used - src/commands/autopilot.ts:581 chatBootWarning 2 test/autopilot-install-wrapper.serial.test.ts,test/autopilot-install.test.ts+internal-used - src/commands/autopilot.ts:93 classifyReconnectError 1 test/autopilot-reconnect-classifier.test.ts+internal-used - src/commands/backlinks.ts:202 insertBacklinkEntry 1 test/backlinks.test.ts+internal-used - src/commands/backlinks.ts:253 fixBacklinkGaps 2 test/backlinks.test.ts,test/core/cycle.serial.test.ts+internal-used - src/commands/backlinks.ts:354 parseBacklinksArgs 1 test/backlinks.test.ts+internal-used - src/commands/backlinks.ts:66 extractPageTitle 2 test/backlinks.test.ts,test/core/cycle.serial.test.ts+internal-used - src/commands/backlinks.ts:75 hasBacklink 2 test/backlinks.test.ts,test/core/cycle.serial.test.ts+internal-used - src/commands/backlinks.ts:80 buildBacklinkEntry 2 test/backlinks.test.ts,test/core/cycle.serial.test.ts+internal-used - src/commands/backlinks.ts:94 findBacklinkGaps 2 test/backlinks.test.ts,test/core/cycle.serial.test.ts+internal-used - src/commands/bench-publish.ts:195 buildBaselineFromInput 2 test/bench-publish.test.ts,test/e2e/eval-loop.test.ts+internal-used - src/commands/book-mirror.ts:358 prepareBookMirrorPublication 1 test/persistence-internal-callers.test.ts+internal-used - src/commands/bootstrap.ts:1700 workspaceBrainStats 1 test/bootstrap-dispatcher.serial.test.ts+internal-used - src/commands/bootstrap.ts:479 runOpencodeProbe 1 test/bootstrap-opencode-door.serial.test.ts+internal-used - src/commands/bootstrap.ts:592 applyDeclaredAudienceFromInterview 1 test/writeback-review-fixes.serial.test.ts+internal-used - src/commands/brainstorm.ts:364 persistSavedIdea 2 test/brainstorm/save.test.ts,test/e2e/brainstorm-resume.test.ts+internal-used - src/commands/brainstorm.ts:397 formatSaveOutcome 1 test/brainstorm/save.test.ts+internal-used - src/commands/brainstorm.ts:452 buildIdeaSlug 1 test/brainstorm/save.test.ts+internal-used - src/commands/brainstorm.ts:58 parseBrainstormArgs 1 test/brainstorm/cost-guardrails.test.ts+internal-used - src/commands/calibration.ts:82 formatProfileText 1 test/calibration-cli.test.ts+internal-used - src/commands/check-update.ts:114 extractChangelogBetween 1 test/check-update.test.ts+internal-used - src/commands/check-update.ts:64 parseVersionFileBody 1 test/check-update-refresh.serial.test.ts+internal-used - src/commands/claw-test.ts:752 mergeChildFriction 1 test/claw-test-cli.test.ts+internal-used - src/commands/code-def.ts:109 probeFilteredSymbolTypes 3 test/code-def-refs-source-scope.test.ts,test/code-def-refs.test.ts,test/code-read-currency.test.ts+internal-used - src/commands/code-scope.ts:200 shouldWidenForNoCode 1 test/code-def-refs-source-scope.test.ts+internal-used - src/commands/company-brain-connect.ts:43 parseCompanyBrainConnectArgs 1 test/company-brain-connect-cli.serial.test.ts+internal-used - src/commands/company-brain-inspect.ts:30 parseCompanyBrainInspectionArgs 1 test/company-brain-inspect-cli.test.ts+internal-used - src/commands/compile-context.ts:44 COMPILED_BLOCK_BEGIN 1 test/e2e/compile-context-pglite.test.ts+internal-used - src/commands/compile-context.ts:45 COMPILED_BLOCK_END 1 test/e2e/compile-context-pglite.test.ts+internal-used - src/commands/config.ts:130 redactConfigValue 3 test/config-db-plane.serial.test.ts,test/config-get-plane.test.ts,test/config.test.ts+internal-used - src/commands/config.ts:161 handleDbPlaneRoutedKeys 1 test/config-db-plane.serial.test.ts+internal-used - src/commands/config.ts:20 isSensitiveConfigKey 1 test/config.test.ts+internal-used - src/commands/connect.ts:110 AGENT_IDS 1 test/connect.test.ts+internal-used - src/commands/connect.ts:123 LEARN_INSTRUCTION 2 test/connect.test.ts,test/e2e/serve-stdio-roundtrip.test.ts+internal-used - src/commands/connect.ts:203 resolveToken 1 test/connect.test.ts+internal-used - src/commands/connect.ts:343 buildConnectBlock 1 test/connect.test.ts+internal-used - src/commands/connect.ts:357 buildJson 1 test/connect.test.ts+internal-used - src/commands/connect.ts:92 ENV_VAR 1 test/connect.test.ts+internal-used - src/commands/connect.ts:93 PLACEHOLDER_TOKEN 1 test/connect.test.ts+internal-used - src/commands/connect.ts:94 PLACEHOLDER_SECRET 1 test/connect.test.ts+internal-used - src/commands/connect.ts:96 DEFAULT_SCOPES 1 test/connect.test.ts+internal-used - src/commands/doctor-asset-paths.ts:47 resolveAssetPath 1 test/doctor-asset-paths.test.ts+internal-used - src/commands/doctor.ts:4134 doctorProgressOptions 1 test/doctor.test.ts+internal-used - src/commands/doctor.ts:422 upgradeErrorResolved 1 test/doctor-upgrade-errors-stale.test.ts+internal-used - src/commands/doctor.ts:4356 renderRemediationPlanLines 1 test/doctor-remediation-plan-render.test.ts+internal-used - src/commands/doctor.ts:525 checkUpgradeErrors 1 test/doctor-upgrade-errors.test.ts+internal-used - src/commands/doctor/checks/engine-fit.ts:22 PGLITE_SCALE_PAGE_THRESHOLD 1 test/doctor-engine-fit.serial.test.ts+internal-used - src/commands/doctor/checks/routing-federation.ts:20 DCR_PRIVILEGED_SCOPES 1 test/doctor-oauth-client-scope-health.test.ts+internal-used - src/commands/embed.ts:830 isKeylessStaleRefusal 2 test/dream-keyless-exit.test.ts,test/embed-keyless-guard.test.ts+internal-used - src/commands/enrich.ts:184 enrichFingerprint 1 test/e2e/enrich-pglite.test.ts+internal-used - src/commands/enrich.ts:247 assembleEvidence 1 test/enrich/evidence-order.test.ts+internal-used - src/commands/enrich.ts:857 backgroundIdempotencyKey 1 test/enrich/idempotency.test.ts+internal-used - src/commands/enrich.ts:89 HYBRID_CHUNK_CLAMP_CHARS 1 test/enrich/evidence-order.test.ts+internal-used - src/commands/enrich.ts:909 budgetExhaustedMessage 1 test/enrich/budget-message.test.ts+internal-used - src/commands/eval-brainstorm.ts:177 readBrainstormEvalFixture 1 test/brainstorm/eval-brainstorm.test.ts+internal-used - src/commands/eval-brainstorm.ts:207 computeGroundingRate 1 test/brainstorm/eval-brainstorm.test.ts+internal-used - src/commands/eval-brainstorm.ts:56 DEFAULT_BRAINSTORM_THRESHOLDS 1 test/brainstorm/eval-brainstorm.test.ts+internal-used - src/commands/eval-cross-modal.ts:303 substituteUnavailableDefaultSlots 1 test/cross-modal-default-slots.test.ts+internal-used - src/commands/eval-run-all.ts:224 estimateRunCost 1 test/eval-run-all.test.ts+internal-used - src/commands/eval-run-all.ts:260 evaluateCostGuard 1 test/eval-run-all.test.ts+internal-used - src/commands/eval-run-all.ts:52 parseRunAllArgs 1 test/eval-run-all.test.ts+internal-used - src/commands/eval-schema-authoring.ts:112 runEvalSchemaAuthoring 1 test/eval-schema-authoring.test.ts+internal-used - src/commands/eval-schema-authoring.ts:163 runEvalSchemaAuthoringCli 1 test/eval-schema-authoring.test.ts+internal-used - src/commands/eval-schema-authoring.ts:66 aggregateVerdict 1 test/eval-schema-authoring.test.ts+internal-used - src/commands/eval-suspected-contradictions.ts:252 buildRunSummaryLines 1 test/eval-contradictions-run-health.test.ts+internal-used - src/commands/eval-synthesize-concepts.ts:26 runEvalSynthesizeConcepts 2 test/eval-synthesize-concepts-routing.test.ts,test/eval-v041_2-scaffolds.test.ts+internal-used - src/commands/eval-takes-quality.ts:64 parseSubcmd 1 test/eval-takes-quality-cli.test.ts+internal-used - src/commands/eval-whoknows.ts:144 readFixture 2 test/e2e/whoknows.test.ts,test/eval-whoknows.test.ts+internal-used - src/commands/eval-whoknows.ts:187 jaccardAtK 1 test/eval-whoknows.test.ts+internal-used - src/commands/eval-whoknows.ts:197 topKHit 1 test/eval-whoknows.test.ts+internal-used - src/commands/eval-whoknows.ts:40 HIT_RATE_THRESHOLD 1 test/eval-whoknows.test.ts+internal-used - src/commands/eval-whoknows.ts:41 REGRESSION_THRESHOLD 1 test/eval-whoknows.test.ts+internal-used - src/commands/eval-whoknows.ts:42 MIN_REPLAY_ROWS 1 test/eval-whoknows.test.ts+internal-used - src/commands/extract-attendance-repair.ts:29 attendanceRepairConnectionIdentity 3 test/attendance-repair-cli.serial.test.ts,test/attendance-repair-identity.test.ts,test/attendance-repair.test.ts+internal-used - src/commands/extract-attendance-repair.ts:65 parseAttendanceRepairArgs 1 test/attendance-repair-cli.serial.test.ts+internal-used - src/commands/extract-benchmark.ts:166 parseBenchmarkFixtures 1 test/extract/benchmark.test.ts+internal-used - src/commands/extract-benchmark.ts:92 validateFixturePath 1 test/extract/benchmark.test.ts+internal-used - src/commands/extract-conversation-facts.ts:126 DEFAULT_SEGMENT_GAP_MINUTES 1 test/extract-conversation-facts.test.ts+internal-used - src/commands/extract-conversation-facts.ts:135 DEFAULT_SEGMENT_MAX_MESSAGES 1 test/extract-conversation-facts.test.ts+internal-used - src/commands/extract-conversation-facts.ts:176 MAX_PAGE_BODY_BYTES 1 test/extract-conversation-facts.test.ts+internal-used - src/commands/extract-conversation-facts.ts:197 ALLOWED_TYPE_ALIASES 2 test/conversation-facts-type-allowlist-drift.test.ts,test/extract-conversation-facts.test.ts+internal-used - src/commands/extract-conversation-facts.ts:211 pageTypesForAllowed 1 test/extract-conversation-facts.test.ts+internal-used - src/commands/extract-conversation-facts.ts:442 splitIntoSegments 1 test/extract-conversation-facts.test.ts+internal-used - src/commands/extract-conversation-facts.ts:499 renderSegmentForExtraction 1 test/extract-conversation-facts.test.ts+internal-used - src/commands/extract-conversation-facts.ts:524 extractConversationFactsFingerprint 2 test/extract-conversation-facts.test.ts,test/extract-conversation-facts-entity-resolution.test.ts+internal-used - src/commands/extract-conversation-facts.ts:543 encodeCheckpointEntry 1 test/extract-conversation-facts.test.ts+internal-used - src/commands/extract-conversation-facts.ts:549 decodeCheckpointEntry 1 test/extract-conversation-facts.test.ts+internal-used - src/commands/extract-conversation-facts.ts:636 extractConversationFactsLockId 1 test/extract-conversation-facts-workers.test.ts+internal-used - src/commands/extract-status.ts:47 buildStatusReport 1 test/extract/status.test.ts+internal-used - src/commands/extract-status.ts:93 formatStatusTable 1 test/extract/status.test.ts+internal-used - src/commands/features.ts:115 scanFeatures 2 test/features-no-sync.test.ts,test/features-recipe-secrets.test.ts+internal-used - src/commands/features.ts:47 RECIPE_META 2 test/features-recipe-secrets.test.ts,test/features.test.ts+internal-used - src/commands/files.ts:39 getMimeType 1 test/files.test.ts+internal-used - src/commands/files.ts:49 formatFileSizeKb 1 test/files.test.ts+internal-used - src/commands/files.ts:61 noStorageBackendMessage 1 test/files.test.ts+internal-used - src/commands/founder-scorecard.ts:81 computeFounderScorecard 2 test/founder-scorecard.test.ts,test/regressions/v0_40_2_0-trajectory-backcompat.test.ts+internal-used - src/commands/friction.ts:226 resolveRunSpec 1 test/friction-diff.serial.test.ts+internal-used - src/commands/friction.ts:295 computeFrictionDiff 1 test/friction-diff.serial.test.ts+internal-used - src/commands/frontmatter-install-hook.ts:315 activeGitHooks 1 test/frontmatter-install-hook.test.ts+internal-used - src/commands/frontmatter-install-hook.ts:383 installHook 1 test/frontmatter-install-hook.test.ts+internal-used - src/commands/frontmatter-install-hook.ts:424 uninstallHook 1 test/frontmatter-install-hook.test.ts+internal-used - src/commands/google-attachments.ts:32 parseGoogleAttachmentsArgs 1 test/google-attachments-command.serial.test.ts+internal-used - src/commands/google.ts:829 runGoogleCalendars 1 test/google-connect-cmd.serial.test.ts+internal-used - src/commands/hook.ts:116 DIGEST_MEMORY_CAP_BYTES 1 test/hook-command.serial.test.ts+internal-used - src/commands/hook.ts:126 WRITEBACK_TRANSCRIPT_TAIL_BYTES 1 test/hook-writeback-stop.serial.test.ts+internal-used - src/commands/hook.ts:164 PUSH_ANNOUNCE_REFIRE_MS 1 test/hook-command.serial.test.ts+internal-used - src/commands/hook.ts:603 memoryDigest 1 test/hook-command.serial.test.ts+internal-used - src/commands/import.ts:38 configuredRootImportError 1 test/import-configured-root-guard.serial.test.ts+internal-used - src/commands/import.ts:56 listConfiguredRoots 1 test/import-configured-root-guard.serial.test.ts+internal-used - src/commands/import.ts:96 recordImportFailure 1 test/import-error-summary.test.ts+internal-used - src/commands/init-mode-picker.ts:183 parseModeInput 1 test/init-mode-picker.test.ts+internal-used - src/commands/init-mode-picker.ts:67 recommendModeFor 1 test/init-mode-picker.test.ts+internal-used - src/commands/init.ts:310 seedAIOptionsFromConfig 1 test/init-env-detection.test.ts+internal-used - src/commands/init.ts:513 groupReadyByProvider 1 test/init-env-detection.test.ts+internal-used - src/commands/init.ts:547 findEnvKeyTypos 1 test/init-env-detection.test.ts+internal-used - src/commands/init.ts:799 resolveChatByEnv 1 test/jobs-gateway-refresh.serial.test.ts+internal-used - src/commands/integrations.ts:143 isUnsafeHealthCheck 1 test/integrations.test.ts+internal-used - src/commands/integrations.ts:1486 installRecipeIntoHostRepo 1 test/integrations-install.test.ts+internal-used - src/commands/integrations.ts:169 parseMaxAge 1 test/integrations-heartbeat-max-age.test.ts+internal-used - src/commands/integrations.ts:186 expandVars 1 test/integrations.test.ts+internal-used - src/commands/integrations.ts:205 executeHealthCheck 2 test/integrations-heartbeat-max-age.test.ts,test/integrations.test.ts+internal-used - src/commands/integrations.ts:376 parseRecipe 4 test/features.test.ts,test/integrations-getstatus-anyof.test.ts,test/integrations-heartbeat-max-age.test.ts+internal-used - src/commands/integrations.ts:417 getRecipeDirs 1 test/integrations.test.ts+internal-used - src/commands/integrations.ts:555 checkSecrets 1 test/integrations.test.ts+internal-used - src/commands/integrations.ts:631 getStatus 1 test/integrations-getstatus-anyof.test.ts+internal-used - src/commands/integrity.ts:133 findExternalLinks 2 test/benchmark-knowledge-runtime.ts,test/integrity.test.ts+internal-used - src/commands/integrity.ts:751 extractXHandleFromFrontmatter 2 test/benchmark-knowledge-runtime.ts,test/integrity.test.ts+internal-used - src/commands/integrity.ts:83 findBareTweetHits 2 test/benchmark-knowledge-runtime.ts,test/integrity.test.ts+internal-used - src/commands/jobs-watch.ts:231 resolveWatchMode 1 test/jobs-watch-mode.test.ts+internal-used - src/commands/jobs-watch.ts:76 renderSnapshot 1 test/jobs-watch-snapshot.test.ts+internal-used - src/commands/jobs.ts:157 parseMaxWaitingFlag 1 test/minions.test.ts+internal-used - src/commands/jobs.ts:198 parseNiceFlag 1 test/jobs-nice-flag.test.ts+internal-used - src/commands/jobs.ts:209 resolveWorkerConcurrency 1 test/minions.test.ts+internal-used - src/commands/jobs.ts:239 parseJobIsolationFlag 1 test/jobs-isolation-flag.test.ts+internal-used - src/commands/jobs.ts:269 rehydrateJobDates 2 test/jobs-format-detail.test.ts,test/jobs-thin-client-date-rehydration.test.ts+internal-used - src/commands/jobs.ts:329 formatJobDetail 2 test/jobs-format-detail.test.ts,test/jobs-thin-client-date-rehydration.test.ts+internal-used - src/commands/jobs.ts:47 resolveJobPull 1 test/job-pull-policy.test.ts+internal-used - src/commands/jobs.ts:603 maybeRunWorkerStartupRecovery 2 test/jobs-worker-startup-recovery.test.ts,test/supervisor.test.ts+internal-used - src/commands/jobs.ts:68 refreshGatewayForJob 2 test/jobs-gateway-refresh-set.test.ts,test/jobs-gateway-refresh.serial.test.ts+internal-used - src/commands/jobs.ts:94 factsAbsorbShouldRetry 1 test/facts-backstop-outcome.serial.test.ts+internal-used - src/commands/lint.ts:320 promoteCreatedFromCapture 1 test/lint-3958.test.ts+internal-used - src/commands/lint.ts:333 fixContent 2 test/lint.test.ts,test/lint-3958.test.ts+internal-used - src/commands/maintain.ts:49 parseMaintainArgs 1 test/maintain.test.ts+internal-used - src/commands/maintain.ts:59 extractCycleFreshnessSourceIds 1 test/maintain.test.ts+internal-used - src/commands/mcp-expose-probe.ts:78 isUnresolvedLookupError 1 test/mcp-expose.test.ts+internal-used - src/commands/mcp-expose.ts:265 parseExposeArgs 1 test/mcp-expose.test.ts+internal-used - src/commands/mcp-expose.ts:49 MCP_EXPOSE_HELP 1 test/mcp-expose.test.ts+internal-used - src/commands/mcp.ts:57 parseMcpGrant 2 test/harness-install-ownership.test.ts,test/harness-onboarding.test.ts+internal-used - src/commands/migrate-embeddings.ts:332 persistEmbeddingFileConfig 3 test/embedding-recovery.serial.test.ts,test/migrate-embeddings-flow.serial.test.ts,test/migrate-embeddings-hardening.serial.test.ts+internal-used - src/commands/migrate-embeddings.ts:48 GLOBAL_MIGRATION_LOCK_ID 3 test/migrate-embeddings-hardening.serial.test.ts,test/migrate-embeddings-op-contract.serial.test.ts,test/migrate-embeddings-recovery-cli.serial.test.ts+internal-used - src/commands/migrate-engine.ts:1197 COPIED_TIMELINE_COUNT_SQL 1 test/migrate-timeline-full-copy.test.ts+internal-used - src/commands/migrate-engine.ts:124 copyMigrationSources 2 test/e2e/migrate-engine-sources-postgres.test.ts,test/e2e/multi-source-bug-class.test.ts+internal-used - src/commands/migrate-engine.ts:298 copyMigrationFacts 1 test/migrate-engine-completeness.serial.test.ts+internal-used - src/commands/migrate-engine.ts:373 MIGRATE_CONFIG_ENGINE_LOCAL_KEYS 1 test/migrate-engine-completeness.serial.test.ts+internal-used - src/commands/migrate-engine.ts:386 copyMigrationConfig 1 test/migrate-engine-completeness.serial.test.ts+internal-used - src/commands/migrate-engine.ts:405 copyPageLinksToTarget 1 test/e2e/multi-source-bug-class.test.ts+internal-used - src/commands/migrate-engine.ts:464 copyPageToTarget 5 test/migrate-engine-page-copy-failure.serial.test.ts,test/migrate-engine-raw-include-deleted.test.ts,test/migrate-timeline-full-copy.test.ts+internal-used - src/commands/migrate-engine.ts:631 quiesceAutopilot 1 test/autopilot-pause-marker.test.ts+internal-used - src/commands/migrate-engine.ts:72 migrationTargetId 2 test/migrate-engine-page-copy-failure.serial.test.ts,test/migrate-engine-resume.test.ts+internal-used - src/commands/migrate-engine.ts:81 manifestMatchesTarget 1 test/migrate-engine-resume.test.ts+internal-used - src/commands/migrations/v0_11_0.ts:342 loadPendingHostWork 1 test/migrations-v0_11_0.test.ts+internal-used - src/commands/migrations/v0_13_1.ts:119 phaseCGrandfather 3 test/e2e/grandfather-projection-postgres.test.ts,test/grandfather-managed.test.ts,test/migrations-v0_13_1-grandfather.test.ts+internal-used - src/commands/models.ts:419 resolveLiveRerankerModel 1 test/models-doctor-reranker.test.ts+internal-used - src/commands/models.ts:442 resolveLiveRerankerTimeoutMs 1 test/models-doctor-chat-probe-timeout.test.ts+internal-used - src/commands/models.ts:529 probeRerankerReachability 2 test/models-doctor-embed.test.ts,test/models-doctor-v1-hint.test.ts+internal-used - src/commands/models.ts:626 resolveChatProbeTimeoutMs 2 test/models-doctor-chat-probe-timeout.slow.test.ts,test/models-doctor-chat-probe-timeout.test.ts+internal-used - src/commands/models.ts:636 probeModel 4 test/models-doctor-chat-probe-timeout.slow.test.ts,test/models-doctor-chat-probe-timeout.test.ts,test/models-doctor-v1-hint.test.ts+internal-used - src/commands/notability-eval.ts:125 mineNotabilityCandidates 1 test/notability-eval.test.ts+internal-used - src/commands/notability-eval.ts:283 loadJsonlCases 1 test/notability-eval.test.ts+internal-used - src/commands/notability-eval.ts:300 writeJsonlCases 1 test/notability-eval.test.ts+internal-used - src/commands/notability-eval.ts:68 defaultMiningOutPath 1 test/notability-eval.test.ts+internal-used - src/commands/notability-eval.ts:73 defaultReviewOutPath 1 test/notability-eval.test.ts+internal-used - src/commands/orphans.ts:198 formatOrphansText 3 test/core/cycle.serial.test.ts,test/dream.test.ts,test/orphans.test.ts+internal-used - src/commands/orphans.ts:55 shouldExclude 4 test/core/cycle.serial.test.ts,test/dream.test.ts,test/orphans-pure-fn.test.ts+internal-used - src/commands/orphans.ts:66 deriveDomain 3 test/core/cycle.serial.test.ts,test/dream.test.ts,test/orphans.test.ts+internal-used - src/commands/orphans.ts:83 queryOrphanPages 2 test/core/cycle.serial.test.ts,test/orphans.test.ts+internal-used - src/commands/persistence-admin.ts:61 parsePersistenceAdminArgs 4 test/persistence-activation.test.ts,test/persistence-admin-intent.test.ts,test/persistence-admin-recovery.test.ts+internal-used - src/commands/providers.ts:52 formatEnvOutput 1 test/providers.test.ts+internal-used - src/commands/publish.ts:260 generateHtml 1 test/publish.test.ts+internal-used - src/commands/publish.ts:27 makeShareable 1 test/publish.test.ts+internal-used - src/commands/publish.ts:58 extractTitle 1 test/publish.test.ts+internal-used - src/commands/publish.ts:71 encryptContent 1 test/publish.test.ts+internal-used - src/commands/publish.ts:88 generatePassword 1 test/publish.test.ts+internal-used - src/commands/recall.ts:619 computeRollup 1 test/recall-rollup.test.ts+internal-used - src/commands/reconcile-links.ts:56 runReconcileLinks 1 test/reconcile-links.serial.test.ts+internal-used - src/commands/reindex-code-delegate.ts:12 parseReindexCodeDelegateArgs 2 test/persistence-sync-stdio-owner.serial.test.ts,test/reindex-code-delegate.test.ts+internal-used - src/commands/reindex-code.ts:392 buildCostRefusal 1 test/reindex-cost-refusal.test.ts+internal-used - src/commands/reindex-code.ts:426 reindexForceHint 1 test/reindex-code-recovery.test.ts+internal-used - src/commands/reindex-code.ts:98 shouldNudgeCodeModel 1 test/reindex-code-nudge.serial.test.ts+internal-used - src/commands/reindex-frontmatter.ts:91 runReindexFrontmatter 2 test/reindex-frontmatter-connect.test.ts,test/reindex-frontmatter-pglite-spawn.serial.test.ts+internal-used - src/commands/reindex-search-vector.ts:119 runReindexSearchVector 1 test/reindex-search-vector.serial.test.ts+internal-used - src/commands/serve-http-metrics.ts:37 recordCompletedRequest 1 test/serve-http-metrics.test.ts+internal-used - src/commands/serve-http.ts:111 githubKindCoversRepo 1 test/serve-http-github-webhook.test.ts+internal-used - src/commands/serve-http.ts:143 selectGitHubItemSources 1 test/serve-http-github-webhook.test.ts+internal-used - src/commands/serve-http.ts:176 HEALTH_TIMEOUT_MS 1 test/serve-http-health.test.ts+internal-used - src/commands/serve-http.ts:228 trackServerSockets 1 test/serve-http-socket-tracking.test.ts+internal-used - src/commands/serve-http.ts:266 waitForHttpServerLifecycle 1 test/serve-http-lifecycle.test.ts+internal-used - src/commands/serve-http.ts:397 shouldSuppressBootstrapPrint 1 test/serve-http-bootstrap-token.test.ts+internal-used - src/commands/serve-http.ts:420 resolveOAuthTokenRateLimit 1 test/serve-http-oauth-token-rate-limit.test.ts+internal-used - src/commands/serve-http.ts:446 openAdminSseStream 1 test/admin-sse-handshake.test.ts+internal-used - src/commands/serve-http.ts:506 probeLiveness 1 test/serve-http-health.test.ts+internal-used - src/commands/serve-http.ts:568 resolveTrustProxy 1 test/serve-http-trust-proxy.test.ts+internal-used - src/commands/serve-http.ts:585 parseCorsAllowlistOAuth 1 test/serve-http-cors.test.ts+internal-used - src/commands/serve-http.ts:610 resolveCorsOrigin 1 test/serve-http-cors.test.ts+internal-used - src/commands/serve-http.ts:641 mountOAuthCorsGate 2 test/serve-http-cors.test.ts,test/serve-http-metrics.test.ts+internal-used - src/commands/serve-http.ts:755 queryAgentClientSpend 1 test/admin-agents-spend.test.ts+internal-used - src/commands/serve-http.ts:817 skillPublishStatus 1 test/serve-skills-publish-nudge.test.ts+internal-used - src/commands/serve-http.ts:841 embeddingWidthStartupWarning 1 test/serve-http-embedding-width.test.ts+internal-used - src/commands/serve-http.ts:86 extractGitHubItemRef 1 test/github-source-page.test.ts+internal-used - src/commands/serve.ts:807 readLiveParentPid 1 test/serve-stdio-lifecycle.test.ts+internal-used - src/commands/serve.ts:843 probeWatchdogAvailable 1 test/serve-stdio-lifecycle.test.ts+internal-used - src/commands/skillopt.ts:373 formatRunSummary 2 test/e2e/skillopt-models-used.serial.test.ts,test/skillopt/run-outcome.test.ts+internal-used - src/commands/source-reconcile.ts:122 readReconcileJson 1 test/reconcile-cli.test.ts+internal-used - src/commands/source-reconcile.ts:140 writeReconcilePreview 1 test/reconcile-cli.test.ts+internal-used - src/commands/source-reconcile.ts:58 parseReconcileArgs 1 test/reconcile-cli.test.ts+internal-used - src/commands/status.ts:179 withSectionDeadline 1 test/status-sections.test.ts+internal-used - src/commands/status.ts:428 buildAutopilotStatus 1 test/status-autopilot-lock.test.ts+internal-used - src/commands/status.ts:609 applyRemoteSnapshot 1 test/status-thin-client-skew.test.ts+internal-used - src/commands/status.ts:792 FAST_DEADLINE_MS 1 test/status-sections.test.ts+internal-used - src/commands/status.ts:799 parseDeadlineFlag 1 test/status-sections.test.ts+internal-used - src/commands/status.ts:821 parseSectionFlag 1 test/status-sections.test.ts+internal-used - src/commands/storage.ts:133 getStorageStatus 2 test/e2e/storage-tiering.test.ts,test/storage-pglite.test.ts+internal-used - src/commands/storage.ts:185 formatStorageStatusJson 1 test/storage-status.test.ts+internal-used - src/commands/storage.ts:196 formatStorageStatusHuman 3 test/e2e/storage-tiering.test.ts,test/storage-pglite.test.ts,test/storage-status.test.ts+internal-used - src/commands/sync-delegate.ts:62 WIRE_BOOL_FLAGS 1 test/sync-delegate-ladder.test.ts+internal-used - src/commands/sync-delegate.ts:76 IGNORED_FLAGS 1 test/sync-delegate-ladder.test.ts+internal-used - src/commands/sync-delegate.ts:86 parseDelegatedSyncArgs 1 test/sync-delegate-ladder.test.ts+internal-used - src/commands/sync-persistence-delegate.ts:20 parsePersistenceSyncArgs 1 test/persistence-sync-stdio-owner.serial.test.ts+internal-used - src/commands/sync.ts:245 shouldNudgeAfterSync 1 test/sync-nudge-status-gate.test.ts+internal-used - src/commands/sync.ts:554 runSyncTrigger 1 test/sync-trigger-cli.test.ts+internal-used - src/commands/sync.ts:5552 parseMissingPathMode 1 test/sync-all-missing-path.test.ts+internal-used - src/commands/sync.ts:5572 partitionMissingPathSources 2 test/sync-all-missing-path.test.ts,test/sync-cost-gate.serial.test.ts+internal-used - src/commands/sync.ts:5647 syncOneSource 2 test/fix-wave-structural.test.ts,test/sync-working-tree-cli.test.ts+internal-used - src/commands/takes-mutation.ts:21 parseTakesMutation 1 test/persistence-cli-delegation.test.ts+internal-used - src/commands/think.ts:33 computeThinkCostUsd 1 test/think-cost.test.ts+internal-used - src/commands/transcripts.ts:113 parseIngestArgs 1 test/transcripts-max-bytes.test.ts+internal-used - src/commands/transcripts.ts:259 expandTilde 1 test/transcripts-expand-paths.test.ts+internal-used - src/commands/transcripts.ts:265 expandPaths 2 test/transcripts-expand-paths.test.ts,test/transcripts-self-exclusion.test.ts+internal-used - src/commands/transcripts.ts:305 fmtSummary 1 test/transcripts-truncated-scan.test.ts+internal-used - src/commands/transcripts.ts:92 ingestCheckpointFingerprintInput 1 test/transcripts-max-bytes.test.ts+internal-used - src/commands/upgrade.ts:17 assessUpgradeOutcome 1 test/upgrade.serial.test.ts+internal-used - src/commands/upgrade.ts:230 resolveBunGlobalRoot 1 test/upgrade.serial.test.ts+internal-used - src/commands/upgrade.ts:719 postUpgradeReferenceSweep 1 test/upgrade-reference-sweep.test.ts+internal-used - src/commands/whoknows.ts:112 rankCandidates 1 test/whoknows.test.ts+internal-used - src/core/advisor/collect-mcp-client-fit.ts:64 MIN_CALLS_FOR_FIT 1 test/advisor-mcp-client-fit.test.ts+internal-used - src/core/advisor/run.ts:25 COLLECTORS 3 test/advisor-backup-coverage.serial.test.ts,test/advisor-mcp-client-fit.test.ts,test/ambient-writeback-wiring-pins.test.ts+internal-used - src/core/advisor/run.ts:46 rankFindings 1 test/advisor-core.test.ts+internal-used - src/core/agent-install/entry.ts:6 runAgentSetupCli 1 test/agent-install-backup.serial.test.ts+internal-used - src/core/ai/anthropic-model-ids.ts:34 parseAnthropicModelId 1 test/ai/anthropic-model-ids.test.ts+internal-used - src/core/ai/anthropic-model-ids.ts:49 compareAnthropicVersions 1 test/ai/anthropic-model-ids.test.ts+internal-used - src/core/ai/base-url-probe.ts:22 versionRoot 1 test/models-doctor-v1-hint.test.ts+internal-used - src/core/ai/chat-usage.ts:59 currentChatPhase 1 test/chat-usage.test.ts+internal-used - src/core/ai/openai-latest.ts:110 parseOpenAIChatId 1 test/openai-latest.serial.test.ts+internal-used - src/core/ai/providers/claude-cli-language-model.ts:93 resolveHermeticConfigDir 1 test/skillopt/deadline-and-hermetic.test.ts+internal-used - src/core/ai/providers/claude-cli-scratch.ts:23 CLAUDE_CLI_CWD_PREFIX 1 test/transcripts-self-exclusion.test.ts+internal-used - src/core/ai/recipes/google.ts:22 googleSupportsPromptCache 1 test/ai/recipe-google-prompt-cache.test.ts+internal-used - src/core/ai/recipes/minimax.ts:24 minimaxCompatFetch 1 test/ai/recipe-minimax.test.ts+internal-used - src/core/ai/recipes/openrouter.ts:121 openrouterCompatFetch 1 test/ai/recipe-openrouter.test.ts+internal-used - src/core/ai/recipes/openrouter.ts:34 openrouterSupportsPromptCache 2 test/ai/gateway-cache-breakpoint.test.ts,test/ai/recipe-openrouter.test.ts+internal-used - src/core/archive-crawler-config.ts:199 normalizeAndValidateArchiveCrawlerConfig 1 test/archive-crawler-config.test.ts+internal-used - src/core/archive-crawler-config.ts:331 isPathAllowed 1 test/archive-crawler-config.test.ts+internal-used - src/core/archive-crawler-config.ts:45 ArchiveCrawlerConfigError 1 test/archive-crawler-config.test.ts+internal-used - src/core/artifact/index.ts:71 targetDirForKind 1 test/artifact-abstraction.test.ts+internal-used - src/core/artifact/index.ts:83 validateManifestByKind 2 test/artifact-abstraction.test.ts,test/e2e/schema-cathedral.test.ts+internal-used - src/core/audit-quality-probe.ts:45 computeQualityProbeAuditFilename 1 test/nightly-quality-probe.test.ts+internal-used - src/core/audit-skill-brain-first.ts:206 logBrainFirstEvent 1 test/skill-brain-first.test.ts+internal-used - src/core/audit-skill-brain-first.ts:70 computeBrainFirstAuditFilename 1 test/skill-brain-first.test.ts+internal-used - src/core/audit-synopsis.ts:76 computeSynopsisAuditFilename 2 test/audit-synopsis.serial.test.ts,test/contextual-retrieval-doctor.serial.test.ts+internal-used - src/core/audit-week-file.ts:27 isoWeek 1 test/core/audit-week-file.serial.test.ts+internal-used - src/core/audit/db-disconnect-audit.ts:72 captureCallerStack 1 test/db-disconnect-audit.test.ts+internal-used - src/core/autopilot-lock.ts:80 looksLikeGbrainAutopilotCommand 1 test/autopilot-lock.test.ts+internal-used - src/core/backfill-base.ts:139 ensureBackfillIndex 1 test/backfill-base.test.ts+internal-used - src/core/backup/coverage.ts:86 computeBackupCoverage 4 test/backup-cli.serial.test.ts,test/backup-coverage.serial.test.ts,test/backup-verification.serial.test.ts+internal-used - src/core/backup/repository.ts:10 BACKUP_REMOTE_BUDGET_MS 1 test/backup-verification.serial.test.ts+internal-used - src/core/backup/repository.ts:11 BACKUP_REMOTE_TIMEOUT_MS 1 test/backup-verification.serial.test.ts+internal-used - src/core/backup/snapshot.ts:87 rebaseManagedConfig 2 test/agent-install-backup.serial.test.ts,test/backup-portability-native.serial.test.ts+internal-used - src/core/backup/status-file.ts:142 backupStatusPath 2 test/backup-status-file.serial.test.ts,test/mcp-backup-nag.serial.test.ts+internal-used - src/core/backup/status-file.ts:149 backupNagStatePath 1 test/backup-status-file.serial.test.ts+internal-used - src/core/backup/status-file.ts:165 BACKUP_BANNER_MAX_CHARS 1 test/backup-status-file.serial.test.ts+internal-used - src/core/backup/status-file.ts:167 BACKUP_DAMPENER_MS 1 test/backup-status-file.serial.test.ts+internal-used - src/core/backup/status-file.ts:169 BACKUP_GLOBAL_CEILING 1 test/backup-status-file.serial.test.ts+internal-used - src/core/backup/status-file.ts:347 loadBackupNagState 3 test/advisor-backup-coverage.serial.test.ts,test/backup-status-file.serial.test.ts,test/mcp-backup-nag.serial.test.ts+internal-used - src/core/backup/status-file.ts:368 saveBackupNagState 1 test/backup-status-file.serial.test.ts+internal-used - src/core/backup/status-file.ts:387 backupVerdictVersion 1 test/backup-status-file.serial.test.ts+internal-used - src/core/backup/status-file.ts:52 BACKUP_NAG_SCHEMA_VERSION 2 test/backup-status-file.serial.test.ts,test/hook-backup-notice.serial.test.ts+internal-used - src/core/backup/status-file.ts:522 BACKUP_CLI_NAG_SKIP 1 test/backup-status-file.serial.test.ts+internal-used - src/core/bench/baseline-file.ts:66 normalizeQueryForHash 1 test/bench/baseline-file.test.ts+internal-used - src/core/bench/baseline-file.ts:81 BaselineParseError 1 test/bench/baseline-file.test.ts+internal-used - src/core/bench/qrels-file.ts:29 QRELS_FILE_SCHEMA_VERSION 1 test/bench/qrels-file.test.ts+internal-used - src/core/bench/qrels-file.ts:64 QrelsParseError 1 test/bench/qrels-file.test.ts+internal-used - src/core/binary-self-update.ts:109 expectedAssetName 3 test/binary-self-update.test.ts,test/e2e/self-upgrade-binary-swap.test.ts,test/release-workflow.test.ts+internal-used - src/core/binary-self-update.ts:116 resolvePlatformAsset 1 test/binary-self-update.test.ts+internal-used - src/core/binary-self-update.ts:215 defaultComputeDigest 2 test/e2e/self-upgrade-binary-swap.test.ts,test/helpers/binary-self-update-smoke-harness.ts+internal-used - src/core/binary-self-update.ts:225 parseAttestationBundle 2 test/binary-self-update.test.ts,test/helpers/binary-self-update-smoke-harness.ts+internal-used - src/core/binary-self-update.ts:249 defaultFetchAttestation 1 test/binary-self-update.test.ts+internal-used - src/core/binary-self-update.ts:281 verifyIntegrity 3 test/binary-self-update.test.ts,test/helpers/binary-self-update-smoke-harness.ts,test/release-workflow.test.ts+internal-used - src/core/binary-self-update.ts:59 EXPECTED_BUILDER_ID_PREFIX 1 test/binary-self-update.test.ts+internal-used - src/core/binary-self-update.ts:61 EXPECTED_BUILDER_IDS 3 test/e2e/self-upgrade-binary-swap.test.ts,test/helpers/binary-self-update-smoke-harness.ts,test/release-workflow.test.ts+internal-used - src/core/bootstrap/codex-hooks.ts:115 buildCodexSessionEndCommand 1 test/codex-hooks-writer.test.ts+internal-used - src/core/bootstrap/codex-hooks.ts:138 codexTrustHash 1 test/codex-hooks-writer.test.ts+internal-used - src/core/bootstrap/codex-toml.ts:69 tomlString 1 test/codex-toml.test.ts+internal-used - src/core/bootstrap/contract.ts:14 WRITEBACK_CONTRACT_BEGIN 1 test/bootstrap-contract.test.ts+internal-used - src/core/bootstrap/harness.ts:2229 parseClaudeMcpGetBearer 1 test/bootstrap-harness.serial.test.ts+internal-used - src/core/bootstrap/harness.ts:2242 parseCodexBlockBearer 1 test/bootstrap-harness.serial.test.ts+internal-used - src/core/bootstrap/harness.ts:508 buildConsentBlock 1 test/bootstrap-harness.serial.test.ts+internal-used - src/core/bootstrap/harness.ts:626 parseClaudeMcpGetUrl 1 test/bootstrap-harness.serial.test.ts+internal-used - src/core/bootstrap/hooks.ts:157 buildClaudeHookCommand 1 test/bootstrap-hooks-writers.test.ts+internal-used - src/core/bootstrap/hooks.ts:170 claudeCommittedSettingsPath 1 test/bootstrap-hooks-writers.test.ts+internal-used - src/core/bootstrap/hooks.ts:180 buildPortableClaudeHookCommand 1 test/bootstrap-hooks-writers.test.ts+internal-used - src/core/bootstrap/host-specs.ts:40 CLAUDE_CODE_SPEC_ID 1 test/bootstrap-hooks-writers.test.ts+internal-used - src/core/bootstrap/host-specs.ts:41 CODEX_SPEC_ID 1 test/bootstrap-hooks-writers.test.ts+internal-used - src/core/bootstrap/host-specs.ts:42 OPENCODE_SPEC_ID 1 test/opencode-json.test.ts+internal-used - src/core/bootstrap/instructions-block.ts:116 removeAmbientWritebackBlock 1 test/bootstrap-instructions-block.test.ts+internal-used - src/core/bootstrap/instructions-block.ts:33 AMBIENT_WRITEBACK_BLOCK_END 1 test/bootstrap-instructions-block.test.ts+internal-used - src/core/bootstrap/instructions-block.ts:86 spliceAmbientWritebackBlock 1 test/bootstrap-instructions-block.test.ts+internal-used - src/core/bootstrap/interview.ts:216 sanitizeAnswerValue 1 test/bootstrap-interview.serial.test.ts+internal-used - src/core/bootstrap/lock.ts:119 BOOTSTRAP_LOCK_STALE_AGE_MS 1 test/bootstrap-lock.test.ts+internal-used - src/core/bootstrap/lock.ts:137 bootstrapLockDir 1 test/bootstrap-lock.test.ts+internal-used - src/core/bootstrap/lock.ts:244 releaseBootstrapLock 1 test/bootstrap-lock.test.ts+internal-used - src/core/bootstrap/opencode-json.ts:293 textCarriesInlineBearer 1 test/opencode-json.test.ts+internal-used - src/core/bootstrap/render.ts:127 isBootstrapRenderDest 1 test/bootstrap-render.test.ts+internal-used - src/core/bootstrap/render.ts:136 escapeStructuralMarkers 1 test/bootstrap-render.test.ts+internal-used - src/core/bootstrap/render.ts:146 collapseBlankLines 1 test/bootstrap-render.test.ts+internal-used - src/core/bootstrap/render.ts:67 UnresolvedTokenError 1 test/bootstrap-render.test.ts+internal-used - src/core/bootstrap/repo.ts:89 slugifyRepoName 1 test/bootstrap-repo.test.ts+internal-used - src/core/bootstrap/repo.ts:99 parseGithubRemote 1 test/bootstrap-repo.test.ts+internal-used - src/core/bootstrap/status.ts:339 installLogPath 2 test/bootstrap-dispatcher.serial.test.ts,test/bootstrap-status.serial.test.ts+internal-used - src/core/bootstrap/status.ts:57 BOOTSTRAP_PHASE_IDS 3 test/bootstrap-status.serial.test.ts,test/e2e/bootstrap-compiled-binary.serial.test.ts,test/e2e/bootstrap-lifecycle.serial.test.ts+internal-used - src/core/bootstrap/template-repo.ts:105 renderTemplateReadme 1 test/template-repo-generator.test.ts+internal-used - src/core/bootstrap/template-repo.ts:138 listTreeFiles 1 test/template-repo-generator.test.ts+internal-used - src/core/bootstrap/verify.ts:103 VERIFY_PROBE_SLUG 2 test/bootstrap-verify.serial.test.ts,test/e2e/bootstrap-keyed-postgres.serial.test.ts+internal-used - src/core/bootstrap/verify.ts:104 VERIFY_PROBE_ENTITY_SLUG 2 test/bootstrap-verify.serial.test.ts,test/e2e/bootstrap-keyed-postgres.serial.test.ts+internal-used - src/core/bootstrap/verify.ts:106 VERIFY_MAGIC_TOKEN 2 test/bootstrap-verify.serial.test.ts,test/e2e/bootstrap-keyed-postgres.serial.test.ts+internal-used - src/core/bootstrap/verify.ts:1066 VERIFY_SNAPSHOTS_KEPT 1 test/bootstrap-verify.serial.test.ts+internal-used - src/core/bootstrap/verify.ts:113 FIRST_RUN_TOUR 1 test/bootstrap-verify.serial.test.ts+internal-used - src/core/bootstrap/verify.ts:282 checkWritebackContract 1 test/bootstrap-contract.test.ts+internal-used - src/core/bootstrap/verify.ts:384 checkHookCarrierOverlap 1 test/bootstrap-verify-hook-carrier-overlap.test.ts+internal-used - src/core/bootstrap/verify.ts:514 checkEmbeddingPlane 1 test/bootstrap-verify-embedding-plane.test.ts+internal-used - src/core/brain-repo-durability.ts:146 maintainPushLog 1 test/brain-repo-durability.serial.test.ts+internal-used - src/core/brain-repo-durability.ts:702 renderCronWrapper 1 test/durability-cron.test.ts+internal-used - src/core/brain-repo-durability.ts:729 generateBrainPullPlist 1 test/durability-cron.test.ts+internal-used - src/core/brain-repo-durability.ts:744 installDurabilityCron 1 test/durability-cron.test.ts+internal-used - src/core/brain-writer.ts:341 BrainWriterError 1 test/brain-writer.test.ts+internal-used - src/core/brain-writer.ts:358 writeBrainPage 3 test/brain-writer.test.ts,test/e2e/bench-vs-openclaw/tweet-ingest.bench.ts,test/e2e/frontmatter-migration.test.ts+internal-used - src/core/brainstorm/domain-bank.ts:270 normalizedCosineDistance 1 test/brainstorm/distance.test.ts+internal-used - src/core/brainstorm/error-classify.ts:40 isQueryCanceledError 1 test/brainstorm-timeout.test.ts+internal-used - src/core/brainstorm/judges.ts:109 computeJudgeMaxTokens 1 test/brainstorm/judges-maxtokens.test.ts+internal-used - src/core/brainstorm/judges.ts:45 TOKEN_BUDGET_PER_IDEA 1 test/brainstorm/judges-maxtokens.test.ts+internal-used - src/core/brainstorm/judges.ts:47 TOKEN_BUDGET_ENVELOPE 1 test/brainstorm/judges-maxtokens.test.ts+internal-used - src/core/brainstorm/judges.ts:49 LEGACY_MIN_MAX_TOKENS 1 test/brainstorm/judges-maxtokens.test.ts+internal-used - src/core/brainstorm/judges.ts:51 MAX_OUTPUT_TOKENS_CEIL 1 test/brainstorm/judges-maxtokens.test.ts+internal-used - src/core/brainstorm/judges.ts:63 ANTHROPIC_OUTPUT_CAPS 1 test/brainstorm/judges-maxtokens.test.ts+internal-used - src/core/brainstorm/orchestrator.ts:517 resolveBrainstormChatModel 1 test/brainstorm/model-config.test.ts+internal-used - src/core/brainstorm/orchestrator.ts:529 resolveBrainstormJudgeModel 1 test/brainstorm/model-config.test.ts+internal-used - src/core/budget/budget-tracker.ts:547 extractUsageFromError 1 test/core/budget/budget-tracker.test.ts+internal-used - src/core/budget/models-used.ts:124 mergeModelUsageRows 1 test/core/budget/model-ledger.test.ts+internal-used - src/core/budget/models-used.ts:58 touchpointForLabel 1 test/core/budget/model-ledger.test.ts+internal-used - src/core/by-mention.ts:261 tokenizeForScan 1 test/by-mention.test.ts+internal-used - src/core/by-mention.ts:39 LINKABLE_ENTITY_TYPES 1 test/by-mention.test.ts+internal-used - src/core/calibration/gstack-coupling.ts:72 buildLearningEntry 1 test/gstack-learnings-coupling.test.ts+internal-used - src/core/calibration/nudge.ts:129 buildNudgeText 1 test/nudge.test.ts+internal-used - src/core/calibration/nudge.ts:34 NUDGE_COOLDOWN_DAYS 1 test/nudge.test.ts+internal-used - src/core/calibration/nudge.ts:35 NUDGE_CONVICTION_THRESHOLD 1 test/nudge.test.ts+internal-used - src/core/calibration/nudge.ts:58 takeDomainHint 1 test/nudge.test.ts+internal-used - src/core/calibration/nudge.ts:71 evaluateNudgeRule 1 test/nudge.test.ts+internal-used - src/core/calibration/take-forecast.ts:55 MIN_BUCKET_N 1 test/take-forecast.test.ts+internal-used - src/core/calibration/take-forecast.ts:67 resolveDomainPrefix 1 test/take-forecast.test.ts+internal-used - src/core/calibration/take-forecast.ts:89 computeForecast 1 test/take-forecast.test.ts+internal-used - src/core/calibration/templates.ts:18 VOICE_GATE_MODES 1 test/voice-gate.test.ts+internal-used - src/core/calibration/voice-gate.ts:95 DEFAULT_RUBRICS 1 test/voice-gate.test.ts+internal-used - src/core/check-resolvable.ts:228 extractTriggers 1 test/check-resolvable.test.ts+internal-used - src/core/chronicle/extract-events.ts:66 isoDay 1 test/operations-source-isolation-matrix.test.ts+internal-used - src/core/chunkers/code.ts:288 registerLanguage 2 test/chunkers/code-dart.test.ts,test/language-manifest.test.ts+internal-used - src/core/chunkers/code.ts:318 resetChunkerWarnings 1 test/chunkers/code-dart.test.ts+internal-used - src/core/chunkers/code.ts:546 setLanguageFallback 1 test/sync-classifier-widening.test.ts+internal-used - src/core/chunkers/code.ts:627 ChunkerTimeoutError 1 test/chunker-timeout.test.ts+internal-used - src/core/chunkers/code.ts:658 parseWithTimeout 1 test/chunker-timeout.test.ts+internal-used - src/core/chunkers/edge-extractor.ts:430 extractCallEdges 1 test/code-intel/scope-walker-resolution.test.ts+internal-used - src/core/chunkers/edge-extractor.ts:474 extractImportEdges 1 test/code-intel/edge-densification.test.ts+internal-used - src/core/chunkers/edge-extractor.ts:597 extractReferenceEdges 1 test/code-intel/edge-densification.test.ts+internal-used - src/core/chunkers/edge-extractor.ts:77 WALK_DEPTH_CAP 1 test/code-intel/scope-walker-resolution.test.ts+internal-used - src/core/cjk.ts:21 CJK_RANGES_REGEX 1 test/cjk.test.ts+internal-used - src/core/claw-test/seed-pglite.ts:33 seedPglite 1 test/seed-pglite.serial.test.ts+internal-used - src/core/cli-force-exit.ts:139 resolveStdoutDrainDeadlineMs 1 test/cli-stdout-delivery.test.ts+internal-used - src/core/cli-force-exit.ts:162 resolveDrainTimeoutMs 1 test/cli-finish-teardown.test.ts+internal-used - src/core/cli-force-exit.ts:176 computeTeardownDeadlineMs 1 test/cli-finish-teardown.test.ts+internal-used - src/core/cli-force-exit.ts:486 writeChunkSync 1 test/cli-stdout-delivery.test.ts+internal-used - src/core/cli-force-exit.ts:89 TEARDOWN_DEADLINE_FLOOR_MS 1 test/cli-finish-teardown.test.ts+internal-used - src/core/cli-options.ts:43 DEFAULT_CLI_OPTIONS 4 test/backup-cli.serial.test.ts,test/cli-concept-nudge.test.ts,test/cli-options.test.ts+internal-used - src/core/cli-preflight.ts:294 cwdIsOperatorConfigDir 1 test/cli-cwd-dotenv-quarantine.test.ts+internal-used - src/core/code-intel/traversal-cache.ts:114 putCachedTraversal 1 test/code-intel/traversal-cache.test.ts+internal-used - src/core/code-intel/traversal-cache.ts:49 getClusterGeneration 1 test/code-intel/traversal-cache.test.ts+internal-used - src/core/code-intel/traversal-cache.ts:79 getCachedTraversal 1 test/code-intel/traversal-cache.test.ts+internal-used - src/core/company-brain/inspection.ts:61 companyBrainDigest 1 test/company-brain-inspect.test.ts+internal-used - src/core/company-brain/inspection.ts:65 resolvedCompanySchemaDigest 1 test/company-brain-inspect.test.ts+internal-used - src/core/config-db-merge.ts:88 DB_MERGE_MEMO_TTL_MS 1 test/config-db-merge.test.ts+internal-used - src/core/connect-probe.ts:56 classifyProbeError 1 test/connect.test.ts+internal-used - src/core/connection-manager.ts:216 normalizeDirectUrl 1 test/connection-manager.serial.test.ts+internal-used - src/core/connection-manager.ts:235 isNetworkUnreachableError 1 test/connection-manager.serial.test.ts+internal-used - src/core/connection-manager.ts:246 readKillSwitchEnv 1 test/connection-manager.serial.test.ts+internal-used - src/core/connectors/credentials.ts:39 credentialPath 1 test/connectors-credentials.serial.test.ts+internal-used - src/core/connectors/providers/chatgpt.ts:29 CHATGPT_BASE_URL 1 test/e2e/connectors-sync-pglite.test.ts+internal-used - src/core/connectors/providers/claude.ts:28 CLAUDE_BASE_URL 1 test/e2e/connectors-sync-pglite.test.ts+internal-used - src/core/connectors/sync.ts:359 maybeKickoffEmbed 1 test/connectors-embed-kickoff.test.ts+internal-used - src/core/content-sanity-literals.ts:117 parseLiteralsContent 1 test/content-sanity-literals.test.ts+internal-used - src/core/content-sanity.ts:165 BUILT_IN_JUNK_PATTERNS 1 test/content-sanity.test.ts+internal-used - src/core/content-sanity.ts:302 assessProse 1 test/content-sanity.test.ts+internal-used - src/core/content-sanity.ts:75 DEFAULT_MAX_MARKUP_RATIO 1 test/content-sanity.test.ts+internal-used - src/core/content-sanity.ts:81 PAGE_JUNK_PATTERN_CODE 1 test/content-sanity.test.ts+internal-used - src/core/context-engine.ts:777 sanitizeEngineSessionId 1 test/context-engine-checkpoint.serial.test.ts+internal-used - src/core/context/checkpoint-harvest.ts:132 WRITEBACK_SESSION_CAP 1 test/checkpoint-harvest.serial.test.ts+internal-used - src/core/context/compile-view.ts:68 RECENCY_CANDIDATE_LIMIT 1 test/compile-view.test.ts+internal-used - src/core/context/compile-view.ts:81 PIN_BONUS 1 test/compile-view.test.ts+internal-used - src/core/context/compile-view.ts:87 COMPILED_CONTEXT_ENVELOPE 1 test/compile-view.test.ts+internal-used - src/core/context/corpus-segments.ts:114 splitByBoundaries 1 test/corpus-segments.test.ts+internal-used - src/core/context/corpus-segments.ts:209 coverageComplete 1 test/corpus-segments.test.ts+internal-used - src/core/context/corpus-segments.ts:75 ledgerFileName 1 test/corpus-segments.test.ts+internal-used - src/core/context/entity-salience.ts:60 MAX_WEAK_CANDIDATES 1 test/context/entity-salience.test.ts+internal-used - src/core/context/hook-heartbeat.ts:229 sessionReceiptsPath 1 test/session-receipts.test.ts+internal-used - src/core/context/hook-heartbeat.ts:249 relayResultsPath 2 test/doctor-memorable.test.ts,test/session-receipts.test.ts+internal-used - src/core/context/hook-heartbeat.ts:270 priorRelayFailure 1 test/session-receipts.test.ts+internal-used - src/core/context/hook-heartbeat.ts:382 maybeTrimRelayResults 1 test/session-receipts.test.ts+internal-used - src/core/context/hook-heartbeat.ts:429 appendSessionReceipt 2 test/doctor-memorable.test.ts,test/session-receipts.test.ts+internal-used - src/core/context/hook-heartbeat.ts:566 memorableConsentPath 1 test/config-file-plane-keys.test.ts+internal-used - src/core/context/hook-heartbeat.ts:590 readMemorableConsent 1 test/config-file-plane-keys.test.ts+internal-used - src/core/context/ipc-path.ts:9 UNIX_SOCKET_PATH_MAX_BYTES 1 test/local-ipc-path.test.ts+internal-used - src/core/context/resolve-ipc.ts:325 ipcRunDir 1 test/resolve-ipc-engine-uniform.test.ts+internal-used - src/core/context/resolve-ipc.ts:373 ipcSecretPathForConfig 2 test/local-ipc-path.test.ts,test/resolve-ipc-engine-uniform.test.ts+internal-used - src/core/context/resolve-ipc.ts:409 ipcSecretPath 4 test/e2e/bootstrap-hook-under-serve.serial.test.ts,test/resolve-ipc-engine-uniform.test.ts,test/resolve-ipc-v2.test.ts+internal-used - src/core/context/sensitivity-scan.ts:68 SensitivityScanConfigError 1 test/sensitivity-scan.test.ts+internal-used - src/core/context/session-state.ts:183 CHECKPOINT_MANIFEST_CAP 1 test/checkpoint-manifest.test.ts+internal-used - src/core/context/session-state.ts:22 LOCAL_CLIENT_SENTINEL 1 test/ambient-recall.test.ts+internal-used - src/core/context/session-state.ts:298 MAX_ROWS_PER_CLIENT 2 test/ambient-recall.test.ts,test/session-state-gc.test.ts+internal-used - src/core/context/session-state.ts:59 resolveClientId 1 test/ambient-recall.test.ts+internal-used - src/core/context/sweep-ipc.ts:38 DELEGATED_SWEEP_BUDGET_MAX_MS 1 test/context/resolve-ipc-sweep-kinds.test.ts+internal-used - src/core/context/sync-ipc.ts:125 WIRE_PAGES_AFFECTED_MAX 1 test/context/sync-ipc-validation.test.ts+internal-used - src/core/context/sync-ipc.ts:53 DELEGATED_SYNC_TIMEOUT_MAX_SECONDS 1 test/context/sync-ipc-validation.test.ts+internal-used - src/core/context/turn-context.ts:507 DELTA_PAGE_FETCH_LIMIT 2 test/ambient-recall.test.ts,test/entity-card-perf.slow.test.ts+internal-used - src/core/context/turn-context.ts:63 TURN_CONTEXT_DEFAULT_MAX_BYTES 1 test/turn-context.test.ts+internal-used - src/core/context/turn-context.ts:648 CHECKPOINT_LINKS_RENDER_CAP 1 test/checkpoint-harvest.serial.test.ts+internal-used - src/core/context/volunteer-events.ts:146 insertVolunteerEvents 2 test/migrate.test.ts,test/volunteer-context.test.ts+internal-used - src/core/context/volunteer-events.ts:201 awaitPendingVolunteerEventWrites 5 test/e2e/volunteer-context-postgres.test.ts,test/retrieval-reflex.test.ts,test/volunteer-context.test.ts+internal-used - src/core/context/volunteer-events.ts:32 VOLUNTEER_CHANNELS 1 test/reflex-volunteer.test.ts+internal-used - src/core/context/volunteer-events.ts:55 isHarnessChannel 2 test/reflex-volunteer.test.ts,test/volunteer-events-delivery.test.ts+internal-used - src/core/context/volunteer.ts:140 candidatesByNorm 2 test/reflex-volunteer.test.ts,test/volunteer-context.test.ts+internal-used - src/core/context/volunteer.ts:155 gateVolunteeredPointers 2 test/reflex-volunteer.test.ts,test/volunteer-context.test.ts+internal-used - src/core/contextual-retrieval-resolver.ts:138 crModeDistinct 1 test/contextual-retrieval-resolver.test.ts+internal-used - src/core/contextual-retrieval-service.ts:189 resolveSynopsisMaxTokens 1 test/page-summary-length.serial.test.ts+internal-used - src/core/contextual-retrieval-service.ts:75 TITLE_WRAPPER_VERSION 1 test/contextual-retrieval-service-pure.test.ts+internal-used - src/core/conversation-parser/body.ts:7 readSummaryBody 1 test/conversation-parser/body-path-containment.test.ts+internal-used - src/core/conversation-parser/llm-base.ts:72 _resetLlmCacheForTests 4 test/conversation-parser/llm-base.test.ts,test/conversation-parser/llm-fallback.test.ts,test/conversation-parser/llm-polish.test.ts+internal-used - src/core/conversation-parser/llm-base.ts:99 probeLlmAvailability 1 test/conversation-parser/llm-base.test.ts+internal-used - src/core/conversation-parser/llm-polish.ts:176 applyPolish 1 test/conversation-parser/llm-polish.test.ts+internal-used - src/core/conversation-parser/normalize-block.ts:40 looksLikeBlockConversation 1 test/conversation-parser-normalize-block.test.ts+internal-used - src/core/conversation-parser/parse.ts:628 scorePattern 1 test/conversation-parser/parse.test.ts+internal-used - src/core/conversation-parser/parse.ts:644 scorePatternFull 1 test/conversation-parser/parse.test.ts+internal-used - src/core/creds/export.ts:23 BUNDLE_VERSION 1 test/creds-export.test.ts+internal-used - src/core/creds/export.ts:24 BUNDLE_KIND 1 test/creds-export.test.ts+internal-used - src/core/creds/providers/google.ts:31 GOOGLE_TOKEN_URL 1 test/google-auth.test.ts+internal-used - src/core/creds/providers/google.ts:52 sanitizePastedValue 1 test/google-auth.test.ts+internal-used - src/core/creds/providers/google.ts:59 looksLikeClientId 1 test/google-auth.test.ts+internal-used - src/core/creds/providers/google.ts:63 looksLikeClientSecret 1 test/google-auth.test.ts+internal-used - src/core/creds/providers/google.ts:69 projectNumberFromClientId 1 test/google-auth.test.ts+internal-used - src/core/creds/vault.ts:138 credentialsPath 1 test/creds-vault.serial.test.ts+internal-used - src/core/creds/vault.ts:151 parseVaultFile 1 test/creds-vault.serial.test.ts+internal-used - src/core/creds/vault.ts:214 FileVaultBackend 1 test/creds-vault.serial.test.ts+internal-used - src/core/cross-modal-eval/receipt-name.ts:107 inferSlugFromSkillPath 1 test/cross-modal-eval-cli.test.ts+internal-used - src/core/cross-modal-eval/runner.ts:272 dimensionScoreKey 2 test/cross-modal-default-slots.test.ts,test/cross-modal-eval-prompt.test.ts+internal-used - src/core/cross-modal-eval/runner.ts:284 buildPrompt 2 test/cross-modal-default-slots.test.ts,test/cross-modal-eval-prompt.test.ts+internal-used - src/core/cross-modal-eval/runner.ts:359 EVALUATOR_SYSTEM_PROMPT 2 test/cross-modal-eval-prompt.test.ts,test/e2e/cross-modal-eval.test.ts+internal-used - src/core/cycle.ts:1048 runPhaseLint 3 test/cycle-abort.test.ts,test/cycle-legacy-phases.test.ts,test/cycle-lint-durability.test.ts+internal-used - src/core/cycle.ts:218 SOURCE_PHASES 1 test/autopilot-global-maintenance.test.ts+internal-used - src/core/cycle.ts:219 MIXED_PHASES 1 test/autopilot-global-maintenance.test.ts+internal-used - src/core/cycle.ts:224 SOURCE_BACKGROUND_PHASES 1 test/autopilot-global-maintenance.test.ts+internal-used - src/core/cycle.ts:252 resolveCyclePhases 1 test/autopilot-global-maintenance.test.ts+internal-used - src/core/cycle.ts:811 anyAbortSignal 2 test/cycle-abort.test.ts,test/cycle-any-abort-signal.test.ts+internal-used - src/core/cycle.ts:983 isLockStolenAbort 1 test/db-lock-fencing.test.ts+internal-used - src/core/cycle/anomaly.ts:38 meanStddev 1 test/anomalies.test.ts+internal-used - src/core/cycle/calibration-profile.ts:166 parsePatternStatementsOutput 1 test/calibration-profile.test.ts+internal-used - src/core/cycle/calibration-profile.ts:178 parseBiasTagsOutput 1 test/calibration-profile.test.ts+internal-used - src/core/cycle/drift.ts:119 parseDriftOutput 1 test/auto-think-phase.test.ts+internal-used - src/core/cycle/emotional-weight.ts:29 HIGH_EMOTION_TAGS 1 test/emotional-weight.test.ts+internal-used - src/core/cycle/emotional-weight.ts:53 DEFAULT_USER_HOLDER 1 test/emotional-weight.test.ts+internal-used - src/core/cycle/extract-atoms-drain.ts:173 runExtractAtomsDrain 2 test/extract-atoms-drain-errors.test.ts,test/extract-atoms-drain.test.ts+internal-used - src/core/cycle/extract-atoms-drain.ts:32 MAX_DRAIN_FAILURE_RECORDS 2 test/dream-drain-failure-summary.serial.test.ts,test/extract-atoms-drain-errors.test.ts+internal-used - src/core/cycle/extract-atoms-drain.ts:34 MAX_DRAIN_FAILURE_SOURCE_CHARS 2 test/dream-drain-failure-summary.serial.test.ts,test/extract-atoms-drain-errors.test.ts+internal-used - src/core/cycle/extract-atoms-drain.ts:35 MAX_DRAIN_FAILURE_REASON_CHARS 2 test/dream-drain-failure-summary.serial.test.ts,test/extract-atoms-drain-errors.test.ts+internal-used - src/core/cycle/extract-atoms-page-state.ts:93 matchingLegacyAtomPageState 1 test/extract-atoms-page-state.test.ts+internal-used - src/core/cycle/extract-atoms.ts:1460 parseAtomsOutcome 4 test/extract-atoms-array-anchor-scan.test.ts,test/extract-atoms-empty-array-rule.test.ts,test/extract-atoms-failure-classes.test.ts+internal-used - src/core/cycle/extract-atoms.ts:152 unionExtractableTypes 1 test/extract-atoms-extractable-types.test.ts+internal-used - src/core/cycle/extract-atoms.ts:269 locateQuote 1 test/cycle/extract-atoms-quote-provenance.test.ts+internal-used - src/core/cycle/extract-atoms.ts:362 discoverExtractablePages 7 test/cycle/extract-atoms-work-interleave.test.ts,test/e2e/extract-atoms-discovery-sql.test.ts,test/e2e/extract-atoms-page-state.test.ts+internal-used - src/core/cycle/extract-atoms.ts:578 tombstonedTranscriptsForHashes 1 test/extract-atoms-transcript-state-errors.test.ts+internal-used - src/core/cycle/extract-atoms.ts:638 resolveExtractAtomsModel 2 test/cycle/extract-atoms-model-config-fail-soft.test.ts,test/models-per-task-extract-atoms.serial.test.ts+internal-used - src/core/cycle/extract-atoms.ts:91 DEFAULT_EXTRACT_MAX_INPUT_CHARS 1 test/cycle/extract-atoms-config-caps.test.ts+internal-used - src/core/cycle/extract-atoms.ts:92 DEFAULT_EXTRACT_MAX_OUTPUT_TOKENS 1 test/cycle/extract-atoms-config-caps.test.ts+internal-used - src/core/cycle/extract-atoms.ts:99 MAX_DETERMINISTIC_FAILURES 3 test/extract-atoms-array-anchor-scan.test.ts,test/extract-atoms-failure-classes.test.ts,test/extract-atoms-transcript-failure-classes.test.ts+internal-used - src/core/cycle/extract-takes.ts:186 extractTakesFromDb 4 test/e2e/multi-source-bug-class.test.ts,test/e2e/takes-postgres.test.ts,test/extract-takes-holder-producer-seam.test.ts+internal-used - src/core/cycle/filing-rules.ts:62 bundledDreamGlobs 1 test/cycle-dream-output-root.test.ts+internal-used - src/core/cycle/grade-takes.ts:131 aggregateEnsemble 1 test/grade-takes-ensemble.test.ts+internal-used - src/core/cycle/grade-takes.ts:281 evidenceSignature 1 test/grade-takes.test.ts+internal-used - src/core/cycle/grade-takes.ts:316 EVIDENCE_ITEM_CLAMP_CHARS 1 test/grade-takes-evidence.test.ts+internal-used - src/core/cycle/grade-takes.ts:317 EVIDENCE_BLOCK_CAP_CHARS 1 test/grade-takes-evidence.test.ts+internal-used - src/core/cycle/grade-takes.ts:332 formatEvidenceBlock 1 test/grade-takes-evidence.test.ts+internal-used - src/core/cycle/grade-takes.ts:382 defaultEvidenceRetriever 1 test/grade-takes-evidence.test.ts+internal-used - src/core/cycle/grade-takes.ts:451 takeIsOldEnough 1 test/grade-takes.test.ts+internal-used - src/core/cycle/grade-takes.ts:54 GRADE_TAKES_PROMPT_VERSION 2 test/grade-takes-evidence.test.ts,test/grade-takes.test.ts+internal-used - src/core/cycle/link-manifest.ts:37 MANIFEST_MAX_PAGES 1 test/cycle-link-manifest.test.ts+internal-used - src/core/cycle/link-manifest.ts:38 MANIFEST_MAX_CHARS 1 test/cycle-link-manifest.test.ts+internal-used - src/core/cycle/phantom-redirect.ts:137 stripFenceAndFrontmatterAndLeadingH1 1 test/phantom-redirect.test.ts+internal-used - src/core/cycle/phantom-redirect.ts:351 tryRedirectPhantom 2 test/phantom-redirect-content-hash.test.ts,test/phantom-redirect.test.ts+internal-used - src/core/cycle/propose-takes.ts:108 EXTRACT_TAKES_PROMPT 1 test/propose-takes.test.ts+internal-used - src/core/cycle/propose-takes.ts:293 hasCompleteFence 1 test/propose-takes.test.ts+internal-used - src/core/cycle/propose-takes.ts:302 extractExistingTakesForDedup 1 test/propose-takes.test.ts+internal-used - src/core/cycle/propose-takes.ts:351 PROPOSE_TAKES_MAX_TOKENS 2 test/propose-takes-config-max-tokens.test.ts,test/propose-takes-truncation.test.ts+internal-used - src/core/cycle/propose-takes.ts:352 PROPOSE_TAKES_RETRY_MAX_TOKENS 2 test/propose-takes-config-max-tokens.test.ts,test/propose-takes-truncation.test.ts+internal-used - src/core/cycle/propose-takes.ts:363 EXTRACTOR_FAILURE_HALT_STREAK 1 test/propose-takes-truncation.test.ts+internal-used - src/core/cycle/propose-takes.ts:375 defaultExtractor 3 test/propose-takes-config-max-tokens.test.ts,test/propose-takes-served-model.test.ts,test/propose-takes-truncation.test.ts+internal-used - src/core/cycle/propose-takes.ts:456 isWellFormedEmptyExtraction 1 test/propose-takes.test.ts+internal-used - src/core/cycle/propose-takes.ts:578 PHASE_DEADLINE_FRACTION_OF_JOB 1 test/cycle-phase-deadline-drift.test.ts+internal-used - src/core/cycle/propose-takes.ts:579 PROPOSE_TAKES_FALLBACK_DEADLINE_MS 2 test/cycle-phase-deadline-drift.test.ts,test/propose-takes.test.ts+internal-used - src/core/cycle/propose-takes.ts:584 MIN_PROPOSE_TAKES_BUDGET_MS 2 test/cycle-phase-deadline-drift.test.ts,test/propose-takes.test.ts+internal-used - src/core/cycle/propose-takes.ts:592 resolveProposeTakesDeadlineMs 2 test/cycle-phase-deadline-drift.test.ts,test/propose-takes.test.ts+internal-used - src/core/cycle/propose-takes.ts:60 PROPOSE_TAKES_PROMPT_VERSION 1 test/propose-takes.test.ts+internal-used - src/core/cycle/propose-takes.ts:71 EMPTY_EXTRACTION_TOMBSTONE_TEXT 2 test/e2e/propose-takes-jsonb-postgres.test.ts,test/propose-takes.test.ts+internal-used - src/core/cycle/synthesize-concepts.ts:77 resolveSynthMaxOutputTokens 1 test/cycle/synthesize-concepts-token-cap.test.ts+internal-used - src/core/cycle/synthesize-verify.ts:231 extractQuoteSpans 1 test/cycle-synthesize-verify.test.ts+internal-used - src/core/cycle/synthesize-verify.ts:296 groundQuote 1 test/cycle-synthesize-verify.test.ts+internal-used - src/core/cycle/synthesize-verify.ts:379 countUngroundedNumericClaims 1 test/cycle-synthesize-verify.test.ts+internal-used - src/core/cycle/synthesize-verify.ts:412 repairBody 1 test/cycle-synthesize-verify.test.ts+internal-used - src/core/cycle/synthesize.ts:124 TRIAGE_VERSION 9 test/cycle-synthesize-daily-cap.test.ts,test/cycle-synthesize-subagent-timeout.test.ts,test/cycle-synthesize-triage.test.ts+internal-used - src/core/cycle/synthesize.ts:131 DEFAULT_TRIAGE_THRESHOLD 4 test/cycle-synthesize-triage-calibration.test.ts,test/cycle-synthesize.test.ts,test/cycle/synthesize-gateway-adapter.test.ts+internal-used - src/core/cycle/synthesize.ts:1461 buildDreamSummarySlug 1 test/cycle-dream-output-root.test.ts+internal-used - src/core/cycle/synthesize.ts:161 computeChunkCharBudget 1 test/synthesize-chunk-budget.test.ts+internal-used - src/core/cycle/synthesize.ts:226 splitTranscriptByBudget 1 test/cycle-synthesize-chunker.test.ts+internal-used - src/core/cycle/synthesize.ts:292 rewriteChunkedSlug 1 test/cycle-synthesize-chunker.test.ts+internal-used - src/core/cycle/transcript-discovery.ts:73 DREAM_OUTPUT_MARKER_RE 1 test/cycle-synthesize.test.ts+internal-used - src/core/cycle/transcript-discovery.ts:93 isLsdOutput 1 test/brainstorm/lsd-mode-skip.test.ts+internal-used - src/core/cycle/triage-rescue.ts:103 applyTriageRescue 1 test/cycle-triage-rescue.test.ts+internal-used - src/core/cycle/triage-rescue.ts:52 MIN_RESCUE_SEGMENT_NORM_CHARS 1 test/cycle-triage-rescue.test.ts+internal-used - src/core/data-frontmatter.ts:75 stringifyDataFrontmatter 1 test/data-frontmatter.test.ts+internal-used - src/core/data-research.ts:210 isDuplicate 1 test/data-research.test.ts+internal-used - src/core/db-lock.ts:156 isHolderDeadLocally 1 test/db-lock-auto-takeover.test.ts+internal-used - src/core/db-lock.ts:73 HOLDER_TAKEOVER_GRACE_MS 3 test/db-lock-auto-takeover.test.ts,test/db-lock-reap.test.ts,test/e2e/sync-sigkill-resume-postgres.test.ts+internal-used - src/core/db-lock.ts:841 SYNC_LOCK_ID 4 test/db-lock-per-source.test.ts,test/e2e/phantom-redirect.test.ts,test/phantom-redirect-per-source-lock.test.ts+internal-used - src/core/db-repair-receipts.ts:19 RECEIPTS_CAP 1 test/db-repair.serial.test.ts+internal-used - src/core/db-repair-receipts.ts:30 receiptsPath 1 test/db-repair.serial.test.ts+internal-used - src/core/db.ts:393 isRetryableDbConnectError 2 test/minions.test.ts,test/worker-conn-resilience-1720.test.ts+internal-used - src/core/docker-postgres.ts:18 GBRAIN_PG_IMAGE 1 test/docker-postgres.test.ts+internal-used - src/core/doctor-cause-rank.ts:74 SYMPTOM_CHECKS 1 test/doctor-cause-rank.test.ts+internal-used - src/core/doctor-remote.ts:269 runOrphanRatioCheck 1 test/doctor-orphan-ratio.test.ts+internal-used - src/core/doctor-remote.ts:456 buildScopeCheck 2 test/doctor-remote.serial.test.ts,test/oauth-scope-probe.test.ts+internal-used - src/core/doctor-remote.ts:76 collectRemoteDoctorReport 1 test/doctor-remote.serial.test.ts+internal-used - src/core/dry-fix.ts:140 detectBlockShape 1 test/dry-fix.test.ts+internal-used - src/core/dry-fix.ts:149 expandBullet 1 test/dry-fix.test.ts+internal-used - src/core/dry-fix.ts:184 expandBlockquote 1 test/dry-fix.test.ts+internal-used - src/core/dry-fix.ts:199 expandParagraph 1 test/dry-fix.test.ts+internal-used - src/core/dry-fix.ts:207 expanders 1 test/dry-fix.test.ts+internal-used - src/core/effective-date.ts:119 parseDateLoose 2 test/effective-date-calendar.test.ts,test/effective-date.test.ts+internal-used - src/core/embed-backfill-submit.ts:47 COOLDOWN_CONFIG_KEY 1 test/embed-backfill-submit.test.ts+internal-used - src/core/embed-oversize-heal.ts:77 healOversizedChunks 1 test/embed-oversize-heal.test.ts+internal-used - src/core/embed-preflight.ts:58 formatEmbeddingCredsError 1 test/embed-preflight.test.ts+internal-used - src/core/embed-stale.ts:206 EMBED_PROBE_TEXT 2 test/embed-stale-signature-pagination.serial.test.ts,test/embed-stale.serial.test.ts+internal-used - src/core/embed-stall.ts:50 DEFAULT_EMBED_STALL_ABORT_SEC 1 test/embed-stall.test.ts+internal-used - src/core/embedding-dim-check.ts:48 PGVECTOR_COLUMN_MAX_DIMS 1 test/embedding-dim-check.test.ts+internal-used - src/core/embedding-dim-check.ts:576 FactsEmbeddingDimMismatchError 1 test/embedding-dim-check-facts.test.ts+internal-used - src/core/embedding-input-limit.ts:52 maxInputTokensForModel 1 test/embedding-input-limit.test.ts+internal-used - src/core/embedding-migration.ts:250 TEXT_EMBEDDING_DIM_PINNED_TABLES 1 test/migrate-embeddings-hardening.serial.test.ts+internal-used - src/core/embedding-migration.ts:324 MIGRATION_COMPLETED_KEY 5 test/e2e/migration-wave-phase-leases.test.ts,test/embedding-migration.test.ts,test/migrate-embeddings-boundary.serial.test.ts+internal-used - src/core/embedding-migration.ts:498 readDimPinnedWidths 1 test/migrate-embeddings-hardening.serial.test.ts+internal-used - src/core/embedding-migration.ts:542 resolveMigrationTarget 2 test/ai/ollama-library-tag-dims.test.ts,test/embedding-migration.test.ts+internal-used - src/core/enrich/thin.ts:38 SKIP_SENTINEL 1 test/enrich/thin.test.ts+internal-used - src/core/enrich/thin.ts:93 sanitizeContext 1 test/enrich/thin.test.ts+internal-used - src/core/enrichment-service.ts:82 slugifyEntity 1 test/enrichment-service.test.ts+internal-used - src/core/enrichment/budget.ts:67 BudgetError 1 test/enrichment.test.ts+internal-used - src/core/enrichment/completeness.ts:158 projectRubric 1 test/enrichment.test.ts+internal-used - src/core/enrichment/completeness.ts:181 conceptRubric 1 test/enrichment.test.ts+internal-used - src/core/enrichment/completeness.ts:191 sourceRubric 1 test/enrichment.test.ts+internal-used - src/core/enrichment/completeness.ts:201 mediaRubric 1 test/enrichment.test.ts+internal-used - src/core/enrichment/completeness.ts:212 defaultRubric 1 test/enrichment.test.ts+internal-used - src/core/entity-identity.ts:246 isIdentityUnionEnabled 1 test/entity-identity.test.ts+internal-used - src/core/entity-identity.ts:35 ENTITY_IDENTITY_UNION_CONFIG_KEY 1 test/entity-identity.test.ts+internal-used - src/core/entity-identity.ts:43 validateEntityId 1 test/entity-identity.test.ts+internal-used - src/core/entity-name-quality.ts:33 GENERIC_ENTITY_TOKENS 1 test/junk-entity-guards.test.ts+internal-used - src/core/env-trust.ts:169 CWD_DOTENV_PROTECTED_KEYS 2 test/env-trust-protected-keys.test.ts,test/env-trust.test.ts+internal-used - src/core/env-trust.ts:210 CWD_DOTENV_PROTECTED_PREFIXES 1 test/env-trust.test.ts+internal-used - src/core/env-trust.ts:224 CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS 1 test/env-trust.test.ts+internal-used - src/core/env-trust.ts:293 isCwdDotenvProtectedKey 1 test/env-trust.test.ts+internal-used - src/core/eval-capture-graph.ts:37 nodeSetJaccard 1 test/code-intel/eval-capture-graph.test.ts+internal-used - src/core/eval-capture-graph.ts:53 depthGroupStability 1 test/code-intel/eval-capture-graph.test.ts+internal-used - src/core/eval-capture-graph.ts:76 truncationMatch 1 test/code-intel/eval-capture-graph.test.ts+internal-used - src/core/eval-capture-graph.ts:98 adjustedRandIndex 1 test/code-intel/eval-capture-graph.test.ts+internal-used - src/core/eval-capture.ts:134 classifyCaptureFailure 1 test/eval-capture.test.ts+internal-used - src/core/eval-capture.ts:203 awaitPendingEvalCaptures 1 test/eval-capture-drain.test.ts+internal-used - src/core/eval-capture.ts:86 buildEvalCandidateInput 1 test/eval-capture.test.ts+internal-used - src/core/eval-contradictions/auto-supersession.ts:128 renderResolutionCommand 1 test/eval-contradictions-auto-supersession.test.ts+internal-used - src/core/eval-contradictions/auto-supersession.ts:210 proposeResolution 1 test/eval-contradictions-auto-supersession.test.ts+internal-used - src/core/eval-contradictions/auto-supersession.ts:58 classifyResolution 1 test/eval-contradictions-auto-supersession.test.ts+internal-used - src/core/eval-contradictions/cache.ts:33 buildCacheKey 3 test/e2e/eval-contradictions-postgres.test.ts,test/eval-contradictions-cache.test.ts,test/eval-contradictions-runner.test.ts+internal-used - src/core/eval-contradictions/calibration-join.ts:45 tagFindingWithCalibration 2 test/eval-contradictions-calibration-join.test.ts,test/regressions/v0.36.1.0-iron-rule.test.ts+internal-used - src/core/eval-contradictions/calibration-join.ts:68 computeDomainHint 1 test/eval-contradictions-calibration-join.test.ts+internal-used - src/core/eval-contradictions/calibration-join.ts:91 buildBiasContextString 1 test/eval-contradictions-calibration-join.test.ts+internal-used - src/core/eval-contradictions/calibration.ts:29 wilsonCI 1 test/eval-contradictions-calibration.test.ts+internal-used - src/core/eval-contradictions/date-filter.ts:129 hasSameParagraphDualDate 1 test/eval-contradictions-date-filter.test.ts+internal-used - src/core/eval-contradictions/date-filter.ts:83 extractDates 1 test/eval-contradictions-date-filter.test.ts+internal-used - src/core/eval-contradictions/fixture-redact.ts:121 redactNames 1 test/eval-contradictions-fixture-redact.test.ts+internal-used - src/core/eval-contradictions/fixture-redact.ts:134 redactMonetary 1 test/eval-contradictions-fixture-redact.test.ts+internal-used - src/core/eval-contradictions/judge.ts:222 normalizeVerdict 2 test/eval-contradictions-judge.test.ts,test/eval-contradictions-severity.test.ts+internal-used - src/core/eval-contradictions/run-health.ts:40 inferVerdictSum 1 test/eval-contradictions-run-health.test.ts+internal-used - src/core/eval-contradictions/run-health.ts:65 assessRunHealth 1 test/eval-contradictions-run-health.test.ts+internal-used - src/core/eval/cycle-default.ts:26 DEFAULT_CYCLES_TTY 1 test/eval/cycle-default.test.ts+internal-used - src/core/eval/drift-watch.ts:26 RETRIEVAL_WATCH_PATTERNS 1 test/drift-watch.test.ts+internal-used - src/core/eval/drift-watch.ts:41 matchesWatchPattern 1 test/drift-watch.test.ts+internal-used - src/core/eval/drift-watch.ts:88 filesDriftedSince 1 test/drift-watch.test.ts+internal-used - src/core/eval/metric-glossary.ts:264 eli10For 1 test/metric-glossary.test.ts+internal-used - src/core/export-stage.ts:6 EXPORT_MARKER 2 test/export-publication-native.serial.test.ts,test/export-publication.test.ts+internal-used - src/core/export-stage.ts:8 EXPORT_STAGE_LIMIT 1 test/export-stage.test.ts+internal-used - src/core/extract-frontmatter.ts:22 INCLUDE_FRONTMATTER_KEY 1 test/extract-include-frontmatter-config.serial.test.ts+internal-used - src/core/extract/receipt-writer.ts:109 dateFromIso 1 test/extract/receipt-writer.test.ts+internal-used - src/core/extract/receipt-writer.ts:121 receiptSlug 1 test/extract/receipt-writer.test.ts+internal-used - src/core/extraction-review.ts:49 PROVENANCE_AUTO_EXTRACTED 1 test/extraction-review.test.ts+internal-used - src/core/extraction-review.ts:50 STATUS_UNVERIFIED 1 test/extraction-review.test.ts+internal-used - src/core/facts/absorb-log.ts:165 classifyFactsAbsorbError 2 test/facts-absorb-log.test.ts,test/facts-backstop-outcome.serial.test.ts+internal-used - src/core/facts/absorb-log.ts:35 FACTS_ABSORB_REASONS 1 test/facts-absorb-log.test.ts+internal-used - src/core/facts/audit-sources.ts:38 LEGACY_TERMINAL_AUDIT_SOURCE 1 test/facts-recall-audit-rows.test.ts+internal-used - src/core/facts/extract-from-fence.ts:128 METRIC_NORMALIZATION_MAP 1 test/facts-fence-typed.test.ts+internal-used - src/core/facts/extract.ts:101 getFactsExtractionPromptAppendix 1 test/facts-extract-junk-filter.test.ts+internal-used - src/core/facts/extract.ts:141 JUNK_FACT_PATTERNS 1 test/facts-extract-junk-filter.test.ts+internal-used - src/core/facts/extract.ts:153 isJunkFact 1 test/facts-extract-junk-filter.test.ts+internal-used - src/core/facts/extract.ts:161 isJunkFilterEnabled 1 test/facts-extract-junk-filter.test.ts+internal-used - src/core/facts/extract.ts:242 isUnknownSpeakerLabel 1 test/facts-unknown-speaker-gate.test.ts+internal-used - src/core/facts/extract.ts:331 buildExtractorSystem 2 test/facts-extract-idea-kind.test.ts,test/facts-extract-junk-filter.test.ts+internal-used - src/core/facts/extract.ts:757 parseExtractorJson 2 test/facts-extract.test.ts,test/llm-json-reasoning-ladder.test.ts+internal-used - src/core/facts/extract.ts:81 DEFAULT_EXTRACTION_MAX_TOKENS 1 test/facts-extract-truncation.test.ts+internal-used - src/core/facts/extract.ts:83 getFactsExtractionMaxTokens 1 test/facts-extract-truncation.test.ts+internal-used - src/core/facts/meta-hook.ts:179 bumpHotMemoryCache 2 test/facts-meta-cache.test.ts,test/turn-context.test.ts+internal-used - src/core/facts/meta-hook.ts:32 HOT_MEMORY_CACHE_MAX_ENTRIES 1 test/facts-meta-cache.test.ts+internal-used - src/core/facts/phantom-audit.ts:49 computePhantomAuditFilename 1 test/phantom-redirect.test.ts+internal-used - src/core/facts/phantom-audit.ts:94 readRecentPhantomEvents 1 test/phantom-redirect.test.ts+internal-used - src/core/facts/stub-guard-audit.ts:63 computeStubGuardAuditFilename 1 test/stub-guard-audit.test.ts+internal-used - src/core/facts/supersede-resolve.ts:39 PG_INT4_MAX 1 test/extract-from-fence.test.ts+internal-used - src/core/facts/ttl-parse.ts:25 parseDurationShorthandMs 1 test/writeback-config.test.ts+internal-used - src/core/facts/ttl-parse.ts:67 TRANSIENT_TTL_MAX_MS 1 test/writeback-config.test.ts+internal-used - src/core/facts/writeback-audience.ts:38 SHARED_CLIENT_THRESHOLD 1 test/writeback-nudge.serial.test.ts+internal-used - src/core/facts/writeback-config.ts:55 AUTO_WRITEBACK_TTL_KEY 1 test/writeback-config.test.ts+internal-used - src/core/facts/writeback-gate.ts:43 MIN_TURN_CHARS 1 test/facts/writeback-gate.test.ts+internal-used - src/core/facts/writeback-gate.ts:44 MIN_TURN_CHARS_CJK 1 test/facts/writeback-gate.test.ts+internal-used - src/core/facts/writeback-gate.ts:47 MAX_TURN_CHARS 1 test/facts/writeback-gate.test.ts+internal-used - src/core/facts/writeback-gate.ts:83 normalizeTurnText 1 test/facts/writeback-gate.test.ts+internal-used - src/core/facts/writeback-gate.ts:87 turnHash24 1 test/facts/writeback-gate.test.ts+internal-used - src/core/feature-flags.ts:32 FEDERATED_V2_CONFIG_KEY 1 test/feature-flags.test.ts+internal-used - src/core/file-resolver.ts:126 parseRedirect 1 test/file-resolver.test.ts+internal-used - src/core/filing-audit.ts:98 allowedDirectories 1 test/filing-audit.test.ts+internal-used - src/core/frontmatter-inference.ts:214 extractDateFromFilename 1 test/frontmatter-inference.test.ts+internal-used - src/core/frontmatter-inference.ts:233 extractTitleFromFilename 1 test/frontmatter-inference.test.ts+internal-used - src/core/frontmatter-inference.ts:258 extractTitleFromHeading 1 test/frontmatter-inference.test.ts+internal-used - src/core/fts-language.ts:77 resetFtsLanguageCache 6 test/fts-language-cache-isolation.serial.test.ts,test/fts-language-migration.serial.test.ts,test/fts-language-schema-replay.serial.test.ts+internal-used - src/core/git-remote.ts:179 buildGitEnv 1 test/git-remote.test.ts+internal-used - src/core/github-source.ts:1042 isPageFresh 1 test/github-source-page.test.ts+internal-used - src/core/github-source.ts:1055 pageHasDetail 1 test/github-source-page.test.ts+internal-used - src/core/github-source.ts:217 mintAppInstallationToken 1 test/github-source-page.test.ts+internal-used - src/core/github-source.ts:448 linkNextUrl 1 test/github-source-page.test.ts+internal-used - src/core/github-source.ts:781 extractLinkedNumbers 1 test/github-source-page.test.ts+internal-used - src/core/github-source.ts:794 linkifyMentions 1 test/github-source-page.test.ts+internal-used - src/core/github-source.ts:976 renderListItemPage 1 test/github-source-page.test.ts+internal-used - src/core/google/access.ts:42 parseTokenOutput 1 test/google-access.test.ts+internal-used - src/core/google/google-clients.ts:277 extractCalendarMethod 1 test/google-clients.test.ts+internal-used - src/core/google/google-clients.ts:68 rateLimitBackoffMs 1 test/google-clients.test.ts+internal-used - src/core/google/google-clients.ts:86 GoogleApiClient 1 test/google-clients.test.ts+internal-used - src/core/google/google-render.ts:109 isSignatureRequest 1 test/google-render.test.ts+internal-used - src/core/google/google-render.ts:184 subjectSlug 1 test/google-render.test.ts+internal-used - src/core/google/google-render.ts:208 threadRelPath 1 test/google-render.test.ts+internal-used - src/core/google/google-source.ts:121 googleStateFile 2 test/google-source-materialize.test.ts,test/google-source-reconcile.test.ts+internal-used - src/core/google/google-source.ts:138 readGoogleState 2 test/google-source-materialize.test.ts,test/google-source-reconcile.test.ts+internal-used - src/core/google/google-source.ts:167 myAddressSet 1 test/google-source-materialize.test.ts+internal-used - src/core/google/loop-detect.ts:40 INBOUND_GRACE_HOURS 1 test/google-loop-detect.test.ts+internal-used - src/core/google/loop-detect.ts:41 OUTBOUND_GRACE_HOURS 1 test/google-loop-detect.test.ts+internal-used - src/core/google/loop-detect.ts:83 detectThreadLoop 1 test/google-loop-detect.test.ts+internal-used - src/core/google/loops-extract.ts:217 parseLoopsJson 1 test/loops-extract-parse.test.ts+internal-used - src/core/guarded-http.ts:49 createPinnedHttpFetch 1 test/guarded-http-tls.serial.test.ts+internal-used - src/core/harness/capabilities.ts:69 describeAuthCapabilities 1 test/harness-capabilities.test.ts+internal-used - src/core/harness/credentials.ts:24 validateCredentials 5 test/harness-credential-auth.test.ts,test/harness-install-ownership.test.ts,test/harness-onboarding.test.ts+internal-used - src/core/ingestion/daemon.ts:164 IngestionDaemon 3 test/e2e/ingestion-roundtrip.test.ts,test/ingestion/daemon.test.ts,test/ingestion/migration-mode.test.ts+internal-used - src/core/ingestion/sources/gstack-learnings.ts:91 GstackLearningsSource 1 test/ingestion/gstack-learnings.test.ts+internal-used - src/core/ingestion/sources/markdown-greenfield.ts:92 MarkdownGreenfieldSource 1 test/ingestion/markdown-greenfield.test.ts+internal-used - src/core/latin-fold.ts:24 NON_DECOMPOSING_LATIN 1 test/latin-fold.test.ts+internal-used - src/core/levenshtein.ts:17 editDistance 1 test/levenshtein.test.ts+internal-used - src/core/link-source-check-repair.ts:34 LINK_SOURCE_KEBAB_RE 2 test/e2e/link-source-check-repair-postgres.test.ts,test/link-source-check-repair.test.ts+internal-used - src/core/mcp-client.ts:128 toRemoteMcpError 1 test/mcp-client-hardening.test.ts+internal-used - src/core/mcp-client.ts:176 extractToolErrorCode 1 test/mcp-client-hardening.test.ts+internal-used - src/core/mcp-client.ts:194 extractToolErrorDetail 1 test/mcp-client-hardening.test.ts+internal-used - src/core/mcp-client.ts:329 buildAbortController 1 test/mcp-client-hardening.test.ts+internal-used - src/core/mcp-usage.ts:65 AUTOMATION_FRACTION_THRESHOLD 1 test/mcp-usage.test.ts+internal-used - src/core/mcp-usage.ts:71 normalizeLoggedOperation 1 test/mcp-usage.test.ts+internal-used - src/core/migrate.ts:109 isMigrationIdempotent 1 test/migrate-extensions.test.ts+internal-used - src/core/migrate.ts:120 MigrationDriftError 1 test/migrate-extensions.test.ts+internal-used - src/core/migrate.ts:6989 isDeadlockError 1 test/migrate-retry.test.ts+internal-used - src/core/migration-ledger.ts:23 MIGRATION_VERSIONS 1 test/migration-ledger.test.ts+internal-used - src/core/minion-spend.ts:34 getJobClientId 2 test/minions/delegated-execution.serial.test.ts,test/minions/generic-handler-spend-attribution.test.ts+internal-used - src/core/minions/budget-meter.ts:28 RESERVATION_TTL_MS 1 test/minions/budget-meter.test.ts+internal-used - src/core/minions/budget-tracker.ts:146 reserveBudget 2 test/budget-tracker.test.ts,test/e2e/minions-budget-cathedral.test.ts+internal-used - src/core/minions/budget-tracker.ts:201 refundBudget 1 test/budget-tracker.test.ts+internal-used - src/core/minions/budget-tracker.ts:56 BudgetOwnerDeleted 1 test/budget-tracker.test.ts+internal-used - src/core/minions/budget-tracker.ts:76 getBudgetOwner 3 test/budget-tracker.test.ts,test/e2e/minions-budget-cathedral.test.ts,test/self-fix.test.ts+internal-used - src/core/minions/budget-tracker.ts:94 setOwnerBudget 4 test/budget-tracker.test.ts,test/e2e/jobs-watch-readsnapshot.test.ts,test/e2e/minions-budget-cathedral.test.ts+internal-used - src/core/minions/child-readiness.ts:15 CHILD_READINESS_TIMEOUT_MS 1 test/child-readiness.test.ts+internal-used - src/core/minions/child-readiness.ts:16 CHILD_READINESS_MAX_BYTES 1 test/child-readiness.test.ts+internal-used - src/core/minions/child-readiness.ts:17 CHILD_READINESS_FEATURES 1 test/child-readiness.test.ts+internal-used - src/core/minions/child-readiness.ts:27 parseChildReadiness 1 test/child-readiness.test.ts+internal-used - src/core/minions/db-probe.ts:136 runDbReadinessProbe 1 test/db-probe-configuration.test.ts+internal-used - src/core/minions/delegated-spend.ts:25 maximumInvocationCents 1 test/minions/delegated-execution.serial.test.ts+internal-used - src/core/minions/delegated-spend.ts:9 DelegationPricingError 1 test/minions/delegated-execution.serial.test.ts+internal-used - src/core/minions/detached-stderr.ts:40 openDetachedStderrSink 1 test/detached-stderr.test.ts+internal-used - src/core/minions/detached-stderr.ts:57 closeDetachedStderrSink 1 test/detached-stderr.test.ts+internal-used - src/core/minions/handlers/connector-sync.ts:25 connectorSyncLockId 1 test/e2e/connector-sync-handler-pglite.test.ts+internal-used - src/core/minions/handlers/contextual-reindex-per-chunk.ts:106 resolveContextualSynopsisModel 1 test/contextual-synopsis-model.serial.test.ts+internal-used - src/core/minions/handlers/contextual-reindex-per-chunk.ts:61 resolveContextualSynopsisLeaseSettings 1 test/contextual-synopsis-model.serial.test.ts+internal-used - src/core/minions/handlers/ingest-capture.ts:53 defaultSlugForEvent 1 test/ingestion/ingest-capture.test.ts+internal-used - src/core/minions/handlers/subagent-audit.ts:60 computeSubagentAuditFilename 1 test/subagent-audit.test.ts+internal-used - src/core/minions/handlers/subagent-oneshot.ts:136 parseOneshotResponse 1 test/minions/subagent-oneshot.test.ts+internal-used - src/core/minions/handlers/subagent-oneshot.ts:174 extractWikilinkTargets 1 test/minions/subagent-oneshot.test.ts+internal-used - src/core/minions/handlers/subagent-oneshot.ts:92 ONESHOT_SYSTEM 1 test/minions/subagent-oneshot.test.ts+internal-used - src/core/minions/handlers/subagent.ts:124 resolveLeaseCap 1 test/rate-leases-uncapped.test.ts+internal-used - src/core/minions/handlers/subagent.ts:1717 stripProviderPrefix 1 test/subagent-handler.test.ts+internal-used - src/core/minions/handlers/supervisor-audit.ts:192 isCrashExit 1 test/supervisor-audit.test.ts+internal-used - src/core/minions/handlers/supervisor-audit.ts:42 computeSupervisorAuditFilename 5 test/autopilot-fanout-clamp.serial.test.ts,test/doctor-autopilot-fanout-concurrency.serial.test.ts,test/doctor-supervisor-singleton-pidfile.test.ts+internal-used - src/core/minions/job-isolation.ts:178 parseChildOutcome 1 test/job-isolation-protocol.test.ts+internal-used - src/core/minions/job-isolation.ts:53 CHILD_OUTCOME_MAX_BYTES 1 test/job-isolation-protocol.test.ts+internal-used - src/core/minions/lease-cap-controller.ts:147 readControllerWindow 1 test/lease-cap-controller.test.ts+internal-used - src/core/minions/lease-cap-controller.ts:241 readCurrentLeaseCap 2 test/e2e/minions-controller-bounce-only.test.ts,test/lease-cap-controller.test.ts+internal-used - src/core/minions/lease-cap-controller.ts:262 writeLeaseCap 2 test/e2e/minions-controller-bounce-only.test.ts,test/lease-cap-controller.test.ts+internal-used - src/core/minions/lease-cap-controller.ts:72 DEFAULT_CONTROLLER_OPTS 1 test/lease-cap-controller.test.ts+internal-used - src/core/minions/lease-cap-controller.ts:98 nextLeaseCap 1 test/lease-cap-controller.test.ts+internal-used - src/core/minions/llm-halt-cooldown.ts:129 withGlobalLlmHaltCooldown 1 test/llm-halt-cooldown.test.ts+internal-used - src/core/minions/llm-halt-cooldown.ts:217 providerIdentityForJob 1 test/llm-halt-cooldown.test.ts+internal-used - src/core/minions/llm-halt-cooldown.ts:47 HALT_COOLDOWN_BASE_MS 1 test/llm-halt-cooldown.test.ts+internal-used - src/core/minions/lock-renewal-tick.ts:146 _resetKnobWarningsForTests 1 test/worker-lock-renewal.test.ts+internal-used - src/core/minions/niceness.ts:23 NICE_MIN 1 test/niceness.test.ts+internal-used - src/core/minions/niceness.ts:24 NICE_MAX 1 test/niceness.test.ts+internal-used - src/core/minions/plugin-loader.ts:155 loadSinglePlugin 1 test/plugin-loader.test.ts+internal-used - src/core/minions/queue.ts:81 DEFAULT_STALL_RECLAIM_GRACE_MS 1 test/minions.test.ts+internal-used - src/core/minions/queue.ts:89 resolveStallReclaimGraceMs 1 test/minions.test.ts+internal-used - src/core/minions/quiet-hours.ts:79 localHour 1 test/minions-quiet-hours.test.ts+internal-used - src/core/minions/rate-leases.ts:118 renewLease 2 test/rate-leases-uncapped.test.ts,test/rate-leases.test.ts+internal-used - src/core/minions/rss-default.ts:38 RSS_DEFAULT_FLOOR_MB 1 test/rss-default.test.ts+internal-used - src/core/minions/rss-default.ts:39 RSS_DEFAULT_CEIL_MB 1 test/rss-default.test.ts+internal-used - src/core/minions/rss-default.ts:62 readCgroupMemLimitBytes 1 test/rss-default.test.ts+internal-used - src/core/minions/self-fix.ts:100 decideSelfFix 2 test/e2e/minions-self-fix-flow.test.ts,test/self-fix.test.ts+internal-used - src/core/minions/self-fix.ts:134 buildSelfFixPrompt 1 test/self-fix.test.ts+internal-used - src/core/minions/self-fix.ts:77 computeChainDepth 1 test/self-fix.test.ts+internal-used - src/core/minions/stagger.ts:22 staggerMinuteOffset 1 test/minions-quiet-hours.test.ts+internal-used - src/core/minions/supervisor.ts:226 resolveHardStopMaxCrashes 1 test/supervisor.test.ts+internal-used - src/core/minions/supervisor.ts:457 ExitCodes 2 test/supervisor-audit.test.ts,test/supervisor-db-lock.test.ts+internal-used - src/core/minions/supervisor.ts:494 resolveSupervisorLockWaitSeconds 1 test/db-lock-cross-host-wait.test.ts+internal-used - src/core/minions/system-prompt.ts:86 renderToolPreamble 1 test/system-prompt.test.ts+internal-used - src/core/minions/tools/brain-allowlist.ts:339 filterAllowedTools 2 test/brain-allowlist.serial.test.ts,test/subagent-handler.test.ts+internal-used - src/core/minions/worker-registry.ts:129 classifyLiveness 1 test/worker-registry.serial.test.ts+internal-used - src/core/minions/worker-registry.ts:146 parseEtimeToMs 1 test/worker-registry.serial.test.ts+internal-used - src/core/minions/worker-registry.ts:55 workerRegistryDir 1 test/worker-registry.serial.test.ts+internal-used - src/core/minions/worker.ts:102 parseRssFromProcStatus 1 test/worker-rss.test.ts+internal-used - src/core/minions/worker.ts:138 getAccurateRss 1 test/worker-rss.test.ts+internal-used - src/core/model-config.ts:108 openaiStaticTierFallback 4 test/gateway-reconfigure-clobber.serial.test.ts,test/jobs-gateway-refresh.serial.test.ts,test/model-config.serial.test.ts+internal-used - src/core/mounts-cache.ts:126 composeResolvers 1 test/mounts-cache.test.ts+internal-used - src/core/mounts-cache.ts:292 composeManifests 1 test/mounts-cache.test.ts+internal-used - src/core/mounts-cache.ts:336 renderResolverMarkdown 1 test/mounts-cache.test.ts+internal-used - src/core/mounts-cache.ts:395 renderManifestJson 1 test/mounts-cache.test.ts+internal-used - src/core/npm-squat-check.ts:131 classifyGbrainBinary 1 test/npm-squat-check.test.ts+internal-used - src/core/oauth-provider.ts:102 InvalidTokenEndpointAuthMethodError 1 test/oauth.test.ts+internal-used - src/core/oauth-provider.ts:215 coerceTimestamp 1 test/oauth.test.ts+internal-used - src/core/onboard/checks.ts:224 checkEntityLinkCoverage 2 test/onboard-coverage-invariants.test.ts,test/onboard-phantom-rec-gates.test.ts+internal-used - src/core/onboard/checks.ts:313 checkTimelineCoverage 2 test/onboard-coverage-invariants.test.ts,test/onboard-phantom-rec-gates.test.ts+internal-used - src/core/onboard/checks.ts:554 checkTypeProliferation 1 test/onboard-pack-upgrade-checks.test.ts+internal-used - src/core/onboard/checks.ts:623 checkDanglingAliases 1 test/onboard-pack-upgrade-checks.test.ts+internal-used - src/core/onboard/impact-capture.ts:42 captureMetric 1 test/e2e/onboard-full-flow.test.ts+internal-used - src/core/op-checkpoint.ts:333 embedFingerprint 1 test/op-checkpoint.test.ts+internal-used - src/core/op-checkpoint.ts:357 extractFingerprint 1 test/op-checkpoint.test.ts+internal-used - src/core/ops/facts.ts:918 clampRecallLimit 1 test/recall-federated.test.ts+internal-used - src/core/output/post-write.ts:166 summarizeWriterLint 1 test/put-page-writer-lint.test.ts+internal-used - src/core/output/post-write.ts:56 isLintOnPutPageEnabled 1 test/post-write-lint.test.ts+internal-used - src/core/output/scaffold.ts:97 sourceCitation 1 test/writer.test.ts+internal-used - src/core/output/slug-registry.ts:60 SlugRegistryError 1 test/writer.test.ts+internal-used - src/core/output/validators/index.ts:28 registerBuiltinValidators 1 test/writer.test.ts+internal-used - src/core/output/validators/link.ts:111 normalizeToSlug 1 test/writer.test.ts+internal-used - src/core/output/validators/link.ts:94 isExternalUrl 1 test/writer.test.ts+internal-used - src/core/output/validators/link.ts:98 isNonBrainRef 1 test/writer.test.ts+internal-used - src/core/output/writer.ts:142 slugRegistryLockKey 1 test/lock-keys.test.ts+internal-used - src/core/output/writer.ts:77 WriteError 1 test/writer.test.ts+internal-used - src/core/pace-mode.ts:24 PACE_MODES 1 test/pace-mode.test.ts+internal-used - src/core/pace-mode.ts:31 DEFAULT_PACE_MODE 1 test/pace-mode.test.ts+internal-used - src/core/pace-mode.ts:64 PACE_BUNDLES 2 test/db-pacer.test.ts,test/pace-mode.test.ts+internal-used - src/core/pace-mode.ts:95 isPaceMode 1 test/pace-mode.test.ts+internal-used - src/core/page-state/projections.ts:39 PageProjectionConflictError 2 test/page-projection-origin.test.ts,test/page-projection-vector-preservation.test.ts+internal-used - src/core/path-confine.ts:56 resolvedPrefixContained 1 test/path-confine.test.ts+internal-used - src/core/persistence/bundle-files.ts:15 BUNDLE_FILE_LIMITS 1 test/persistence-skill-bundles.serial.test.ts+internal-used - src/core/persistence/connector-sync.ts:112 beginConnectorSync 2 test/persistence-connector-recovery.test.ts,test/persistence-connector-retry.test.ts+internal-used - src/core/persistence/diagnostics.ts:9 WRITER_NEXT_ACTIONS 1 test/persistence-diagnostics.test.ts+internal-used - src/core/persistence/ipc.ts:15 PERSISTENCE_IPC_MAX_CONNECTIONS 1 test/persistence-ipc-backpressure.test.ts+internal-used - src/core/persistence/local-client.ts:33 readPersistenceCliRegistration 3 test/e2e/sync-delegation-under-serve.serial.test.ts,test/persistence-local-client.test.ts,test/persistence-sync-stdio-owner.serial.test.ts+internal-used - src/core/persistence/native-lock.ts:23 NativeLockUnavailableError 1 test/native-lock.test.ts+internal-used - src/core/persistence/onboarding.ts:10 containerPathPreflight 1 test/persistence-container-preflight.test.ts+internal-used - src/core/persistence/physical-root-record.ts:23 physicalRootReservationPath 4 test/persistence-admin-intent.test.ts,test/persistence-admin-recovery.test.ts,test/persistence-physical-root.test.ts+internal-used - src/core/persistence/service.ts:21 preparePersistedMutation 2 test/persistence-import-admission.test.ts,test/persistence-skill-bundles.serial.test.ts+internal-used - src/core/persistence/service.ts:68 stopPersistenceConsumer 1 test/managed-extract-atoms.test.ts+internal-used - src/core/persistence/verb-errors.ts:69 frozenVerbWriteError 2 test/persistence-sync-receipt-diagnostics.test.ts,test/persistence-write-contracts.test.ts+internal-used - src/core/pglite-embedded-assets.ts:115 resolvePgliteAssetPaths 2 test/pglite-embedded-assets.test.ts,test/pglite-hoisted-install.serial.test.ts+internal-used - src/core/pglite-leftovers-check.ts:65 SIZE_WALK_MAX_ENTRIES 1 test/pglite-leftovers-check.test.ts+internal-used - src/core/pglite-leftovers-check.ts:69 MIGRATE_MANIFEST_NAME 1 test/pglite-leftovers-check.test.ts+internal-used - src/core/pglite-leftovers-check.ts:75 isMigrationLeftoverName 1 test/pglite-leftovers-check.test.ts+internal-used - src/core/pglite-repair.ts:244 repairCooldownActive 1 test/pglite-repair.test.ts+internal-used - src/core/pglite-repair.ts:303 pruneRepairBackups 1 test/pglite-repair.test.ts+internal-used - src/core/pglite-repair.ts:583 restoreWalBackup 1 test/pglite-repair.test.ts+internal-used - src/core/pglite-resetwal.ts:116 crc32c 2 test/pglite-repair.test.ts,test/pglite-resetwal.test.ts+internal-used - src/core/pglite-resetwal.ts:134 parseWalSegNo 1 test/pglite-resetwal.test.ts+internal-used - src/core/pglite-resetwal.ts:141 xlogFileName 2 test/pglite-repair.test.ts,test/pglite-resetwal.test.ts+internal-used - src/core/pid1-reaper.ts:121 createPid1ReaperTick 1 test/pid1-reaper.test.ts+internal-used - src/core/pid1-reaper.ts:53 scanZombieChildren 1 test/pid1-reaper.test.ts+internal-used - src/core/post-upgrade-reembed.ts:41 computeReembedEstimate 1 test/upgrade-reembed-prompt.test.ts+internal-used - src/core/post-upgrade-reembed.ts:83 formatReembedPrompt 1 test/upgrade-reembed-prompt.test.ts+internal-used - src/core/postgres-engine/init-schema-lock.ts:29 INIT_SCHEMA_LOCK_KEY 1 test/init-schema-lock.test.ts+internal-used - src/core/postgres-engine/init-schema-lock.ts:50 resolveInitSchemaLockTimeoutMs 1 test/init-schema-lock.test.ts+internal-used - src/core/preferences.ts:154 validateMinionMode 1 test/preferences.test.ts+internal-used - src/core/process-cleanup.ts:208 _resetForTests 1 test/process-cleanup.test.ts+internal-used - src/core/process-cleanup.ts:99 triggerCleanupAndExit 1 test/process-cleanup.test.ts+internal-used - src/core/process-watchdog.ts:100 clampWatchdogTimers 1 test/process-watchdog.test.ts+internal-used - src/core/process-watchdog.ts:243 SERVE_STALL_FLOOR_MS 1 test/process-watchdog.test.ts+internal-used - src/core/process-watchdog.ts:259 stallDecision 1 test/process-watchdog.test.ts+internal-used - src/core/process-watchdog.ts:273 nextStallLatch 1 test/process-watchdog.test.ts+internal-used - src/core/process-watchdog.ts:286 stallCheckSawSuspend 1 test/process-watchdog.test.ts+internal-used - src/core/process-watchdog.ts:50 watchdogDecision 1 test/process-watchdog.test.ts+internal-used - src/core/process-watchdog.ts:84 MAX_WATCHDOG_TIMER_MS 1 test/process-watchdog.test.ts+internal-used - src/core/progressive-batch/orchestrator.ts:106 resolveStages 1 test/progressive-batch/orchestrator.test.ts+internal-used - src/core/progressive-batch/orchestrator.ts:126 resolveCostCap 1 test/progressive-batch/orchestrator.test.ts+internal-used - src/core/progressive-batch/orchestrator.ts:187 awaitInteractiveAbort 1 test/progressive-batch/orchestrator.test.ts+internal-used - src/core/progressive-batch/orchestrator.ts:224 sliceIntoStages 1 test/progressive-batch/orchestrator.test.ts+internal-used - src/core/progressive-batch/orchestrator.ts:84 parseEnvStages 1 test/progressive-batch/orchestrator.test.ts+internal-used - src/core/repo-visibility.ts:118 anonProbeUrl 1 test/repo-visibility.test.ts+internal-used - src/core/repo-visibility.ts:152 classifyGh403 1 test/repo-visibility.test.ts+internal-used - src/core/repo-visibility.ts:391 visibilityCachePath 1 test/workspace-push.serial.test.ts+internal-used - src/core/rerank-audit.ts:64 computeRerankAuditFilename 1 test/rerank-audit.test.ts+internal-used - src/core/resolvers/builtin/x-api/handle-to-tweet.ts:383 computeBackoffMs 1 test/resolvers.test.ts+internal-used - src/core/retry-matcher.ts:96 isLockTimeoutError 1 test/retry-matcher.test.ts+internal-used - src/core/routing-eval.ts:106 normalizeText 1 test/routing-eval.test.ts+internal-used - src/core/routing-eval.ts:122 extractTriggerPhrases 1 test/routing-eval.test.ts+internal-used - src/core/routing-eval.ts:174 structuralRouteMatch 1 test/routing-eval.test.ts+internal-used - src/core/schema-pack/expand-type-filter.ts:65 expandTypeFilter 2 test/company-brain-schema.test.ts,test/schema-pack-expand-type-filter.test.ts+internal-used - src/core/schema-pack/lint-rules.ts:103 aliasReferencesUndeclaredType 1 test/schema-pack-lint-rules.test.ts+internal-used - src/core/schema-pack/lint-rules.ts:126 enrichableTypesUndeclared 1 test/schema-pack-lint-rules.test.ts+internal-used - src/core/schema-pack/lint-rules.ts:144 linkTypesUndeclared 1 test/schema-pack-lint-rules.test.ts+internal-used - src/core/schema-pack/lint-rules.ts:172 frontmatterLinksUndeclared 1 test/schema-pack-lint-rules.test.ts+internal-used - src/core/schema-pack/lint-rules.ts:201 expertRoutingWithoutPrefix 1 test/schema-pack-lint-rules.test.ts+internal-used - src/core/schema-pack/lint-rules.ts:218 prefixCollision 1 test/schema-pack-lint-rules.test.ts+internal-used - src/core/schema-pack/lint-rules.ts:242 prefixStrictSubsetOverlap 1 test/schema-pack-lint-rules.test.ts+internal-used - src/core/schema-pack/lint-rules.ts:367 storedTypeIsAlias 1 test/schema-type-usage.test.ts+internal-used - src/core/schema-pack/lint-rules.ts:398 storedTypeUndeclared 1 test/schema-type-usage.test.ts+internal-used - src/core/schema-pack/lint-rules.ts:59 aliasShadowsType 1 test/schema-pack-lint-rules.test.ts+internal-used - src/core/schema-pack/lint-rules.ts:79 aliasDeclaredByTwoTypes 1 test/schema-pack-lint-rules.test.ts+internal-used - src/core/schema-pack/load-active.ts:270 _versionRangeMatches 1 test/schema-pack-find-pack-successors.serial.test.ts+internal-used - src/core/schema-pack/load-active.ts:292 _versionDescCompare 1 test/schema-pack-find-pack-successors.serial.test.ts+internal-used - src/core/schema-pack/redos-guard.ts:62 MAX_REGEX_INPUT_CHARS 1 test/redos-hardening.test.ts+internal-used - src/core/schema-pack/redos-guard.ts:70 RegexInputTooLargeError 1 test/redos-hardening.test.ts+internal-used - src/core/schema-pack/redos-guard.ts:91 RegexCatastrophicPatternError 1 test/redos-hardening.test.ts+internal-used - src/core/schema-pack/rewrite-links-batch.ts:46 rewriteLinksBatch 1 test/schema-pack-rewrite-links-batch.test.ts+internal-used - src/core/schema-pack/scaffold-extractable.ts:147 buildFixtureCorpus 1 test/schema-pack/scaffold-extractable.test.ts+internal-used - src/core/schema-pack/scaffold-extractable.ts:222 buildExtractableSpec 1 test/schema-pack/scaffold-extractable.test.ts+internal-used - src/core/schema-pack/scaffold-extractable.ts:74 buildPromptTemplate 1 test/schema-pack/scaffold-extractable.test.ts+internal-used - src/core/schema-verify.ts:129 simplifyColumnDef 1 test/schema-verify.test.ts+internal-used - src/core/schema-verify.ts:37 parseExpectedColumns 1 test/schema-verify.test.ts+internal-used - src/core/scope.ts:177 isScope 1 test/scope.test.ts+internal-used - src/core/search/arm-confidence.ts:66 KEYWORD_ARM_CONFIDENCE_FLOOR_MAX 1 test/search/arm-confidence.test.ts+internal-used - src/core/search/crag.ts:64 DEFAULT_CRAG_MIN_TOP 1 test/search/crag.test.ts+internal-used - src/core/search/embedding-column.ts:460 isDefaultColumn 1 test/search/embedding-column.serial.test.ts+internal-used - src/core/search/embedding-column.ts:79 ALLOWED_COLUMN_TYPES 1 test/search/embedding-column.serial.test.ts+internal-used - src/core/search/embedding-column.ts:88 MAX_DIMENSIONS 1 test/search/embedding-column.serial.test.ts+internal-used - src/core/search/evidence.ts:102 createSafetyFor 1 test/search/evidence.test.ts+internal-used - src/core/search/evidence.ts:49 HIGH_MATCH_FLOOR 1 test/search/evidence.test.ts+internal-used - src/core/search/evidence.ts:51 SOLID_MATCH_FLOOR 1 test/search/evidence.test.ts+internal-used - src/core/search/exact-lookup.ts:45 EXACT_TITLE_STAMP 1 test/search/exact-lookup.test.ts+internal-used - src/core/search/exact-lookup.ts:48 isSlugShapedQuery 1 test/search/exact-lookup.test.ts+internal-used - src/core/search/exact-lookup.ts:83 structuralExactLookup 2 test/helpers/deep-research-contract.ts,test/search/exact-lookup.test.ts+internal-used - src/core/search/explain-formatter.ts:115 formatAutocutSummary 1 test/search/explain-formatter.test.ts+internal-used - src/core/search/explain-formatter.ts:129 formatDegradedSummary 1 test/search/explain-formatter.test.ts+internal-used - src/core/search/explain-formatter.ts:39 formatResultExplain 1 test/search/explain-formatter.test.ts+internal-used - src/core/search/fusion-lists.ts:111 EXPANSION_VARIANT_BUDGET_MAX 1 test/search/fusion-lists.test.ts+internal-used - src/core/search/graph-signals.ts:200 sessionPrefix 2 test/search/atom-session-diversification.test.ts,test/search/graph-signals.test.ts+internal-used - src/core/search/graph-signals.ts:240 computeScoreDistribution 1 test/search/graph-signals.test.ts+internal-used - src/core/search/graph-signals.ts:54 ADJACENCY_BOOST 1 test/search/graph-signals.test.ts+internal-used - src/core/search/graph-signals.ts:57 CROSS_SOURCE_BOOST 1 test/search/graph-signals.test.ts+internal-used - src/core/search/image-loader.ts:35 DEFAULT_IMAGE_MAX_BYTES 1 test/cross-modal-phase2.test.ts+internal-used - src/core/search/image-loader.ts:49 ImageLoadError 1 test/cross-modal-phase2.test.ts+internal-used - src/core/search/llm-intent.ts:74 parseModality 1 test/llm-intent-escalation.test.ts+internal-used - src/core/search/metadata-boost-gate.ts:64 METADATA_BOOST_GATES 1 test/search/metadata-boost-gate.test.ts+internal-used - src/core/search/mode-switch-ux.ts:185 probeWorkerAvailable 1 test/mode-switch-ux.test.ts+internal-used - src/core/search/mode-switch-ux.ts:229 buildReindexIdempotencyKey 1 test/mode-switch-ux.test.ts+internal-used - src/core/search/mode-switch-ux.ts:78 WORKER_STALE_THRESHOLD_MS 1 test/mode-switch-ux.test.ts+internal-used - src/core/search/modes-report.ts:76 KNOB_NULL_LABELS 1 test/search/arm-confidence.test.ts+internal-used - src/core/search/modes-report.ts:99 MODES_REPORT_PER_CALL_NOTE 2 test/commands-search.test.ts,test/search/modes-report-coverage.test.ts+internal-used - src/core/search/output-redaction.ts:4 OUTPUT_REDACTION_MAX_FIELD_CHARS 1 test/search/output-redaction.test.ts+internal-used - src/core/search/output-redaction.ts:5 OUTPUT_REDACTION_MAX_TOTAL_CHARS 1 test/search/output-redaction.test.ts+internal-used - src/core/search/output-redaction.ts:6 OUTPUT_REDACTION_LIMIT 1 test/search/output-redaction.test.ts+internal-used - src/core/search/query-cache.ts:163 cacheTextGuard 1 test/query-cache.test.ts+internal-used - src/core/search/query-cache.ts:80 cacheRowId 2 test/query-cache-knobs-hash.serial.test.ts,test/query-cache.test.ts+internal-used - src/core/search/query-intent.ts:295 INTENT_PATTERN_BANKS 1 test/query-intent-config.test.ts+internal-used - src/core/search/query-intent.ts:381 applyIntentPatternConfig 1 test/query-intent-config.test.ts+internal-used - src/core/search/query-intent.ts:589 classifyQueryIntent 4 test/query-intent-concept.test.ts,test/query-intent-legacy.test.ts,test/query-intent.test.ts+internal-used - src/core/search/query-intent.ts:607 intentToDetail 1 test/query-intent-concept.test.ts+internal-used - src/core/search/recency-decay.ts:156 parseRecencyDecayYaml 1 test/recency-decay.test.ts+internal-used - src/core/search/recency-decay.ts:82 RecencyDecayParseError 1 test/recency-decay.test.ts+internal-used - src/core/search/recency-decay.ts:99 parseRecencyDecayEnv 1 test/recency-decay.test.ts+internal-used - src/core/search/relational-intent.ts:212 validateVocab 1 test/relational-intent.test.ts+internal-used - src/core/search/relational-intent.ts:234 defaultRelationalPatterns 1 test/search/relational-intent-memo.test.ts+internal-used - src/core/search/relational-intent.ts:69 KNOWN_LINK_TYPES 2 test/loops-extract-wiring.test.ts,test/relational-intent.test.ts+internal-used - src/core/search/relational-rerank-pin.ts:73 RELATIONAL_RERANK_PIN_MAX 1 test/search/relational-rerank-pin.test.ts+internal-used - src/core/search/rerank.ts:79 capRerankDoc 1 test/rerank-doc-cap.test.ts+internal-used - src/core/search/return-policy.ts:52 DEFAULT_ADAPTIVE_RETURN 1 test/search/return-policy.test.ts+internal-used - src/core/search/snippet-cap.ts:23 buildSnippetMarker 1 test/search-snippet-cap.test.ts+internal-used - src/core/search/source-boost.ts:100 parseHardExcludesEnv 1 test/sql-ranking.test.ts+internal-used - src/core/search/sql-ranking.ts:257 MAX_WEBSEARCH_QUERY_CHARS 1 test/search/title-retrieval-arm.test.ts+internal-used - src/core/search/sql-ranking.ts:258 MAX_WEBSEARCH_QUERY_TERMS 1 test/search/title-retrieval-arm.test.ts+internal-used - src/core/search/telemetry.ts:100 FLUSH_THRESHOLD_CALLS 1 test/search-telemetry-disconnect-hang.serial.test.ts+internal-used - src/core/search/telemetry.ts:357 getTelemetryWriter 5 test/commands-search.test.ts,test/search-telemetry-cache-wiring.serial.test.ts,test/search-telemetry-disconnect-hang.serial.test.ts+internal-used - src/core/search/telemetry.ts:376 awaitPendingTelemetryFlush 1 test/search-telemetry.test.ts+internal-used - src/core/search/telemetry.ts:617 TELEMETRY_COVERAGE_NOTE 1 test/commands-search.test.ts+internal-used - src/core/search/telemetry.ts:651 _resetTelemetryWriterForTest 5 test/commands-search.test.ts,test/search-telemetry-cache-wiring.serial.test.ts,test/search-telemetry-disconnect-hang.serial.test.ts+internal-used - src/core/search/telemetry.ts:75 EMPTY_RESULT_MODE 1 test/search-telemetry.test.ts+internal-used - src/core/secret-scan.ts:252 PEM_BODY_MAX_CHARS 2 test/secret-scan-perf.test.ts,test/secret-scan.test.ts+internal-used - src/core/secret-scan.ts:253 PEM_BLOCK_RE 1 test/secret-scan-perf.test.ts+internal-used - src/core/secret-scan.ts:324 shannonEntropy 1 test/secret-scan.test.ts+internal-used - src/core/secret-scan.ts:363 globToRegExp 1 test/secret-scan.test.ts+internal-used - src/core/secret-scan.ts:842 ECHO_MIN_CHARS_BEARER 1 test/secret-scan.test.ts+internal-used - src/core/secret-scan.ts:848 ECHO_MIN_CHARS_ENTROPY 1 test/secret-scan.test.ts+internal-used - src/core/secret-scan.ts:856 ECHO_MAX_VALUE_CHARS 2 test/secret-scan-perf.test.ts,test/secret-scan.test.ts+internal-used - src/core/secret-scan.ts:864 ECHO_MAX_UNIQUE 2 test/secret-scan-perf.test.ts,test/secret-scan.test.ts+internal-used - src/core/self-upgrade.ts:207 formatMarker 2 test/self-upgrade.test.ts,test/upgrade.serial.test.ts+internal-used - src/core/self-upgrade.ts:237 updateCachePath 1 test/self-upgrade-pending.test.ts+internal-used - src/core/self-upgrade.ts:369 snoozeDurationMs 1 test/self-upgrade.test.ts+internal-used - src/core/self-upgrade.ts:41 CACHE_TTL_UPGRADE_AVAILABLE_MS 1 test/self-upgrade-pending.test.ts+internal-used - src/core/serve-service.ts:224 renderServeLaunchdPlist 1 test/serve-service.test.ts+internal-used - src/core/serve-service.ts:260 renderServeSystemdUnit 1 test/serve-service.test.ts+internal-used - src/core/serve-service.ts:90 refuseSymlink 1 test/serve-service.test.ts+internal-used - src/core/shared-skills/migration.ts:39 migrationCheckpointKey 1 test/shared-skills-setup.serial.test.ts+internal-used - src/core/shared-skills/migration.ts:43 legacyPublication 1 test/shared-skills-setup.serial.test.ts+internal-used - src/core/shared-skills/retention.ts:10 SHARED_SKILL_RETENTION_LIMITS 2 test/shared-skills-catalog.test.ts,test/shared-skills-retention-capacity.test.ts+internal-used - src/core/skill-brain-first.ts:112 EXTERNAL_LOOKUP_PATTERNS 1 test/skill-brain-first.test.ts+internal-used - src/core/skill-brain-first.ts:160 PHASE_HEADING_RE 1 test/skill-brain-first.test.ts+internal-used - src/core/skill-brain-first.ts:338 stripFrontmatter 1 test/skill-brain-first.test.ts+internal-used - src/core/skill-brain-first.ts:348 findFirstBrainRefOffset 1 test/skill-brain-first.test.ts+internal-used - src/core/skill-brain-first.ts:363 findFirstExternalRefOffset 1 test/skill-brain-first.test.ts+internal-used - src/core/skill-catalog.ts:237 resolveSkillMdPath 2 test/skill-catalog-security.test.ts,test/skill-catalog.test.ts+internal-used - src/core/skill-catalog.ts:307 crossReferenceTools 1 test/skill-catalog.test.ts+internal-used - src/core/skill-catalog.ts:393 oneLineDescription 2 test/skill-catalog-block-scalar.test.ts,test/skill-catalog.test.ts+internal-used - src/core/skill-trigger-index.ts:58 _resetWarnedSkillsForTests 1 test/skill-trigger-index.test.ts+internal-used - src/core/skillify/templates.ts:14 SKILLIFY_STUB_MARKER 1 test/skillify-scaffold.test.ts+internal-used - src/core/skillopt/benchmark.ts:277 computeBenchmarkSha8 1 test/skillopt/benchmark.test.ts+internal-used - src/core/skillopt/held-out.ts:49 capturesDir 1 test/skillopt/held-out.test.ts+internal-used - src/core/skillopt/held-out.ts:54 capturePath 2 test/backup-portability-native.serial.test.ts,test/skillopt/held-out.test.ts+internal-used - src/core/skillopt/lock.ts:27 lockIdFor 1 test/skillopt/lock.test.ts+internal-used - src/core/skillopt/lock.ts:36 tryAcquireSkilloptLock 2 test/skillopt/adversarial/concurrent-runs.serial.test.ts,test/skillopt/lock.test.ts+internal-used - src/core/skillopt/lr-schedule.ts:31 cosineLr 1 test/skillopt/lr-schedule.test.ts+internal-used - src/core/skillopt/lr-schedule.ts:46 linearLr 1 test/skillopt/lr-schedule.test.ts+internal-used - src/core/skillopt/lr-schedule.ts:57 constantLr 1 test/skillopt/lr-schedule.test.ts+internal-used - src/core/skillopt/models-plan.ts:323 parseModelsStrict 1 test/skillopt/models-plan.serial.test.ts+internal-used - src/core/skillopt/orchestrator.ts:368 classifyAbortError 1 test/skillopt/silent-abort-3516.test.ts+internal-used - src/core/skillopt/preflight.ts:101 singleCallReservations 1 test/skillopt/preflight-reservation.test.ts+internal-used - src/core/skillopt/reflect.ts:59 describeJudge 1 test/skillopt/reflect.test.ts+internal-used - src/core/skillopt/rejected-buffer.ts:27 REJECTED_BUFFER_CAP 1 test/skillopt/rejected-buffer.test.ts+internal-used - src/core/skillopt/rejected-buffer.ts:45 rejectedFilePath 1 test/skillopt/rejected-buffer.test.ts+internal-used - src/core/skillopt/rejected-buffer.ts:53 rejectedKey 1 test/skillopt/rejected-buffer.test.ts+internal-used - src/core/skillopt/rollout.ts:36 READ_ONLY_BRAIN_TOOLS 2 test/skillopt/adversarial/side-effecting-tool.test.ts,test/skillopt/rollout.test.ts+internal-used - src/core/skillopt/score.ts:105 countCitations 1 test/skillopt/score.test.ts+internal-used - src/core/skillopt/score.ts:220 scoreQrels 1 test/skillopt/score.test.ts+internal-used - src/core/skillopt/score.ts:240 extractRetrievedSlugs 1 test/skillopt/score.test.ts+internal-used - src/core/skillopt/score.ts:55 scoreRule 1 test/skillopt/score.test.ts+internal-used - src/core/skillopt/validate-gate.ts:72 SKILLOPT_ALL_ROLLOUTS_FAILED 1 test/skillopt/validate-gate-abort.test.ts+internal-used - src/core/skillopt/validate-gate.ts:73 SKILLOPT_ALL_JUDGE_ERRORS 1 test/skillopt/validate-gate-abort.test.ts+internal-used - src/core/skillopt/version-store.ts:45 versionsDir 4 test/e2e/skillopt-pglite.serial.test.ts,test/skillopt/adversarial/partial-write-crash.test.ts,test/skillopt/adversarial/resume-after-crash.test.ts+internal-used - src/core/skillopt/version-store.ts:53 bestPath 5 test/e2e/skillopt-loop.serial.test.ts,test/e2e/skillopt-pglite.serial.test.ts,test/skillopt/adversarial/partial-write-crash.test.ts+internal-used - src/core/skillopt/version-store.ts:83 loadHistory 5 test/e2e/skillopt-loop.serial.test.ts,test/e2e/skillopt-pglite.serial.test.ts,test/skillopt/adversarial/partial-write-crash.test.ts+internal-used - src/core/skillpack/apply-hunks.ts:41 ApplyHunksError 1 test/skillpack-apply-hunks.test.ts+internal-used - src/core/skillpack/bridge-state.ts:29 SKILLPACK_BRIDGE_SCHEMA_VERSION 3 test/backup-coverage.serial.test.ts,test/shared-skills-writer-boundary.serial.test.ts,test/skillpack-bridge-state.test.ts+internal-used - src/core/skillpack/endorse.ts:112 applyEndorsement 1 test/skillpack-endorse.test.ts+internal-used - src/core/skillpack/harness-bridge.ts:115 bridgeTargetPath 1 test/skillpack-harness-bridge.test.ts+internal-used - src/core/skillpack/harness-bridge.ts:291 renderSkillStub 1 test/skillpack-harness-bridge.test.ts+internal-used - src/core/skillpack/harness-bridge.ts:329 assertTargetsConfined 1 test/skillpack-harness-bridge.test.ts+internal-used - src/core/skillpack/harness-bridge.ts:78 STUB_MARKER 3 test/jobs-subcommand-help.serial.test.ts,test/skillpack-harness-bridge.test.ts,test/skillpack-reference-harness.test.ts+internal-used - src/core/skillpack/harvest-lint.ts:41 DEFAULT_PRIVATE_PATTERNS 1 test/skillpack-harvest-lint.test.ts+internal-used - src/core/skillpack/harvest.ts:255 addToBundleManifest 1 test/skillpack-harvest.test.ts+internal-used - src/core/skillpack/installer.ts:143 planInstall 3 test/e2e/openclaw-reference-compat.test.ts,test/shared-skills-writer-boundary.serial.test.ts,test/skillpack-install.test.ts+internal-used - src/core/skillpack/installer.ts:297 buildManagedBlock 1 test/skillpack-install.test.ts+internal-used - src/core/skillpack/installer.ts:328 updateManagedBlock 1 test/skillpack-install.test.ts+internal-used - src/core/skillpack/installer.ts:369 applyInstall 4 test/e2e/openclaw-reference-compat.test.ts,test/shared-skills-writer-boundary.serial.test.ts,test/skillpack-install.test.ts+internal-used - src/core/skillpack/installer.ts:696 applyUninstall 1 test/shared-skills-writer-boundary.serial.test.ts+internal-used - src/core/skillpack/installer.ts:97 InstallError 1 test/skillpack-install.test.ts+internal-used - src/core/skillpack/manifest-v1.ts:139 validateSkillpackManifest 2 test/skillpack-init-brain-pack.test.ts,test/skillpack-manifest-v1.test.ts+internal-used - src/core/skillpack/migrate-fence.ts:149 resolveFenceSlugs 1 test/skillpack-migrate-fence.test.ts+internal-used - src/core/skillpack/migrate-fence.ts:188 stripFence 1 test/skillpack-migrate-fence.test.ts+internal-used - src/core/skillpack/migrate-fence.ts:88 parseFence 1 test/skillpack-migrate-fence.test.ts+internal-used - src/core/skillpack/nag-state.ts:25 SKILLPACK_NAG_SCHEMA_VERSION 1 test/advisor-collectors-findings.test.ts+internal-used - src/core/skillpack/nag-state.ts:28 DEFAULT_NAG_CEILING 3 test/advisor-collectors-findings.test.ts,test/advisor-mcp-client-fit.test.ts,test/skillpack-nag-state.test.ts+internal-used - src/core/skillpack/personas.ts:102 computeLaneSet 1 test/skillpack-personas.test.ts+internal-used - src/core/skillpack/post-install-advisory.ts:62 buildAdvisory 1 test/post-install-advisory.test.ts+internal-used - src/core/skillpack/shared-brain-bridge.ts:69 sharedBrainBridgePlan 1 test/skillpack-shared-brain-bridge.test.ts+internal-used - src/core/skillpack/state.ts:26 SKILLPACK_STATE_SCHEMA_VERSION 5 test/advisor-collectors-findings.test.ts,test/shared-skills-writer-boundary.serial.test.ts,test/skillpack-scaffold-third-party.test.ts+internal-used - src/core/skillpack/state.ts:64 SkillpackStateError 1 test/skillpack-state.test.ts+internal-used - src/core/skills-integrity.ts:40 computeSkillsManifest 2 test/doctor-skill-checks.test.ts,test/skills-integrity.test.ts+internal-used - src/core/source-health.ts:104 resolvePriority 1 test/source-health.test.ts+internal-used - src/core/source-health.ts:82 resolvePriorityLabel 1 test/source-health.test.ts+internal-used - src/core/source-resolver.ts:419 GBRAIN_ALLOW_DEFAULT_WRITE_ENV 1 test/source-resolver-default-write-guard.test.ts+internal-used - src/core/spend-posture.ts:48 normalizeSpendPosture 1 test/sync-cost-preview.test.ts+internal-used - src/core/ssrf-validate.ts:37 __setDnsLookupForTests 6 test/cross-modal-phase2.test.ts,test/guarded-http.test.ts,test/integrations.test.ts+internal-used - src/core/storage-config.ts:291 normalizeAndValidateStorageConfig 1 test/storage-config.test.ts+internal-used - src/core/sweep.ts:54 STARTUP_SWEEP_DELAY_MS 1 test/sweep.test.ts+internal-used - src/core/sync-anchor.ts:393 writeSlugRootMode 2 test/multi-source-drift.test.ts,test/sync-slug-root-mode-4342.test.ts+internal-used - src/core/sync-concurrency.ts:17 AUTO_CONCURRENCY_FILE_THRESHOLD 1 test/sync-concurrency.test.ts+internal-used - src/core/sync-concurrency.ts:23 PARALLEL_FILE_FLOOR 1 test/sync-concurrency.test.ts+internal-used - src/core/sync-concurrency.ts:245 _resetWorkersClampWarningsForTest 1 test/pglite-workers-clamp.test.ts+internal-used - src/core/sync.ts:156 unquoteGitPath 1 test/sync.test.ts+internal-used - src/core/tailscale.ts:266 TAILSCALE_FUNNEL_CAPABILITY 1 test/tailscale.test.ts+internal-used - src/core/tailscale.ts:284 normalizeDnsName 1 test/tailscale.test.ts+internal-used - src/core/take-proposals.ts:67 coerceProposalKind 1 test/take-proposals.test.ts+internal-used - src/core/takes-fence.ts:135 HOLDER_REGEX 1 test/takes-holder-validation.test.ts+internal-used - src/core/takes-fence.ts:147 isValidHolder 2 test/slug-unicode-scripts.test.ts,test/takes-holder-validation.test.ts+internal-used - src/core/takes-quality-eval/pricing.ts:54 MODEL_PRICING 2 test/eval-takes-quality-pricing.test.ts,test/model-pricing.test.ts+internal-used - src/core/takes-quality-eval/receipt-write.ts:27 writeReceiptToDb 4 test/e2e/eval-takes-quality.test.ts,test/eval-takes-quality-receipt-write.test.ts,test/eval-takes-quality-replay.test.ts+internal-used - src/core/takes-quality-eval/receipt-write.ts:66 writeReceiptArtifact 1 test/eval-takes-quality-receipt-write.test.ts+internal-used - src/core/takes-quality-eval/rubric.ts:36 RUBRIC_DIMENSION_DEFS 1 test/eval-takes-quality-rubric.test.ts+internal-used - src/core/thin-client-upgrade-prompt.ts:158 savePromptState 1 test/thin-client-upgrade-prompt.test.ts+internal-used - src/core/thin-client-upgrade-prompt.ts:190 acquirePromptLock 1 test/thin-client-upgrade-prompt.test.ts+internal-used - src/core/thin-client-upgrade-prompt.ts:239 decideAction 1 test/thin-client-upgrade-prompt.test.ts+internal-used - src/core/think/cite-render.ts:40 parseInlineCitations 1 test/think-pipeline.serial.test.ts+internal-used - src/core/think/cite-render.ts:65 normalizeStructuredCitations 1 test/think-pipeline.serial.test.ts+internal-used - src/core/think/gather.ts:595 EXCERPT_CUT_START_MARKER 1 test/think-pages-block.test.ts+internal-used - src/core/think/gather.ts:596 EXCERPT_CUT_END_MARKER 1 test/think-pages-block.test.ts+internal-used - src/core/think/persist-take.ts:35 TAKE_CLAIM_MAX_CHARS 1 test/think-persist-take.test.ts+internal-used - src/core/think/persist-take.ts:52 claimFromAnswer 1 test/think-persist-take.test.ts+internal-used - src/core/think/prompt.ts:113 buildCalibrationBlock 1 test/think-with-calibration.test.ts+internal-used - src/core/think/temporal-window.ts:59 resolvePageDateMs 1 test/think-temporal-window.serial.test.ts+internal-used - src/core/think/temporal-window.ts:6 TemporalWindowError 1 test/think-temporal-window.serial.test.ts+internal-used - src/core/timeline-write-through.ts:292 writeTimelineEntryThrough 1 test/timeline-write-through.test.ts+internal-used - src/core/trajectory.ts:142 computeDriftScore 1 test/engine-find-trajectory.test.ts+internal-used - src/core/trajectory.ts:26 DEFAULT_REGRESSION_THRESHOLD 2 test/engine-find-trajectory.test.ts,test/trajectory.test.ts+internal-used - src/core/trajectory.ts:93 detectRegressions 2 test/engine-find-trajectory.test.ts,test/trajectory.test.ts+internal-used - src/core/transcripts/capture-spec.ts:43 CAPTURE_SPECS 1 test/codex-hook-lane.test.ts+internal-used - src/core/transcripts/claude-code-jsonl.ts:495 TOOL_CALL_VALUE_MAX_CHARS 2 test/claude-code-jsonl.test.ts,test/codex-hook-lane.test.ts+internal-used - src/core/transcripts/detect.ts:91 readSample 1 test/transcript-adapters.test.ts+internal-used - src/core/transcripts/grok.ts:187 mapGrokLine 1 test/transcript-adapters.test.ts+internal-used - src/core/transcripts/grok.ts:98 isGrokSessionSidecar 2 test/transcript-adapters.test.ts,test/transcripts-expand-paths.test.ts+internal-used - src/core/transcripts/render.ts:234 escapeAnchorLines 1 test/transcript-render.test.ts+internal-used - src/core/transcripts/render.ts:49 MESSAGE_ANCHOR_RE 1 test/transcript-render.test.ts+internal-used - src/core/transcripts/render.ts:55 MESSAGE_CHAR_CAP 2 test/e2e/transcripts-ingest-pglite.test.ts,test/transcript-render.test.ts+internal-used - src/core/transcripts/render.ts:64 PART_TARGET_BYTES 1 test/transcript-render.test.ts+internal-used - src/core/transcripts/render.ts:66 OVERLAP_MESSAGES 1 test/transcript-render.test.ts+internal-used - src/core/transcripts/types.ts:142 transcriptSlugId 1 test/transcript-adapters.test.ts+internal-used - src/core/upgrade-checkpoint.ts:84 writeCheckpoint 2 test/e2e/v030_1-integration-pglite.test.ts,test/upgrade-checkpoint.serial.test.ts+internal-used - src/core/utils.ts:396 _resetWarnOnceForTests 4 test/engine-resolve-slug-with-alias.test.ts,test/extract-atoms-transcript-state-errors.test.ts,test/hybrid-meta.serial.test.ts+internal-used - src/core/vector-index.ts:114 checkActiveBuild 2 test/e2e/v030_1-integration-pglite.test.ts,test/vector-index-lifecycle.test.ts+internal-used - src/core/vector-index.ts:20 PGVECTOR_HNSW_HALFVEC_MAX_DIMS 1 test/vector-index-lifecycle.test.ts+internal-used - src/core/vector-index.ts:205 dropAndRebuild 1 test/vector-index-lifecycle.test.ts+internal-used - src/core/vector-index.ts:25 chunkEmbeddingIndexSql 2 test/ai/recipe-zhipu.test.ts,test/vector-index-lifecycle.test.ts+internal-used - src/core/vector-index.ts:66 HNSW_EF_SEARCH_MAX 1 test/vector-ef-search.test.ts+internal-used - src/core/verbs/conformance.ts:46 validateAgainstSchema 8 test/memory-verbs-conformance.test.ts,test/persistence-sync-receipt-diagnostics.test.ts,test/persistence-write-contracts.test.ts+internal-used - src/core/workspace-push.ts:137 PUSH_LOCK_STALE_MS 1 test/workspace-push.serial.test.ts+internal-used - src/core/workspace-push.ts:155 pushLockDir 1 test/workspace-push.serial.test.ts+internal-used - src/core/workspace-push.ts:200 acquirePushLock 3 test/backup-invalidation.serial.test.ts,test/sources-push-cli.serial.test.ts,test/workspace-push.serial.test.ts+internal-used - src/core/workspace-push.ts:295 resolveWorkspaceRoot 2 test/sources-push-cli.serial.test.ts,test/workspace-push.serial.test.ts+internal-used - src/core/workspace-push.ts:354 configAllowsUnverifiedRemote 1 test/config-file-plane-keys.test.ts+internal-used - src/core/workspace-push.ts:368 pushStatusPath 1 test/workspace-push.serial.test.ts+internal-used - src/eval/brainbench/fixtures.ts:175 validateGold 1 test/brainbench-fixtures.test.ts+internal-used - src/eval/brainbench/fixtures.ts:70 validateFixture 1 test/brainbench-fixtures.test.ts+internal-used - src/eval/brainbench/metrics/continuity.ts:57 factKeywordProbe 1 test/brainbench-continuity.test.ts+internal-used - src/eval/brainbench/metrics/write-back.ts:107 makeGoldExtractor 1 test/brainbench-writeback.test.ts+internal-used - src/eval/brainbench/metrics/write-back.ts:51 conversationSlug 1 test/brainbench-writeback.test.ts+internal-used - src/eval/brainbench/metrics/write-back.ts:70 renderConversationPage 1 test/brainbench-writeback.test.ts+internal-used - src/eval/code-retrieval/harness.ts:136 top1StabilityRate 1 test/code-retrieval-harness.test.ts+internal-used - src/eval/code-retrieval/harness.ts:155 normalizeRetrieved 1 test/code-retrieval-harness.test.ts+internal-used - src/eval/code-retrieval/harness.ts:168 expandExpectedToRelevantSet 1 test/code-retrieval-harness.test.ts+internal-used - src/eval/code-retrieval/harness.ts:181 isFileRelevant 1 test/code-retrieval-harness.test.ts+internal-used - src/eval/deterministic-embed.ts:26 fnv1a 3 test/eval-canary.test.ts,test/eval-longmemeval-mixedcase.slow.test.ts,test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/diagnostics.ts:153 classifyMiss 1 test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/diagnostics.ts:176 h1Signature 1 test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/diagnostics.ts:196 h3Candidates 1 test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/diagnostics.ts:204 computeInnerLimit 1 test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/diagnostics.ts:209 sessionRowRanks 1 test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/diagnostics.ts:219 sessionDistinctRanks 1 test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/diagnostics.ts:350 splitClauses 1 test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/diagnostics.ts:354 splitClausesDetailed 1 test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/diagnostics.ts:522 receiptTopKSessions 1 test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/diagnostics.ts:541 splitMembership 1 test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/diagnostics.ts:651 summarizeDiagnostics 1 test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/diagnostics.ts:741 glossFor 1 test/longmemeval-diagnostics.test.ts+internal-used - src/eval/longmemeval/judge.ts:113 JUDGE_DATA_BOUNDARY_INSTRUCTION 1 test/longmemeval-judge.test.ts+internal-used - src/eval/longmemeval/judge.ts:139 escapeJudgeData 1 test/longmemeval-judge.test.ts+internal-used - src/eval/longmemeval/metrics.ts:120 distinctRetrievedSessions 1 test/longmemeval-metrics.test.ts+internal-used - src/eval/longmemeval/qa-accuracy.ts:130 dedupeQuestionRows 1 test/longmemeval-judge.test.ts+internal-used - src/eval/longmemeval/resume.ts:158 retrievedIdsAtK 1 test/eval-longmemeval-mixedcase.slow.test.ts+internal-used - src/eval/longmemeval/resume.ts:192 rawifyRetrievedIds 1 test/longmemeval-resume.test.ts+internal-used - src/eval/retrieval-quality/harness.ts:89 scoreQuestion 1 test/retrieval-quality-harness.test.ts+internal-used - src/eval/shared/autocut-replay.ts:112 normalizePoolRow 1 test/replay-autocut-floor.test.ts+internal-used - src/eval/shared/autocut-replay.ts:274 pairedDelta 1 test/replay-autocut-floor.test.ts+internal-used - src/eval/shared/autocut-replay.ts:365 splitHalf 1 test/replay-autocut-floor.test.ts+internal-used - src/eval/shared/autocut-replay.ts:380 topScoreHistogram 1 test/replay-autocut-floor.test.ts+internal-used - src/eval/shared/embed-cache.ts:34 EmbedCacheIntegrityError 1 test/longmemeval-embed-cache.test.ts+internal-used - src/eval/shared/embed-cache.ts:347 sideFromParams 1 test/longmemeval-embed-cache.test.ts+internal-used - src/eval/shared/judge-runner.ts:107 judgeCallCostUsd 1 test/longmemeval-judge.test.ts+internal-used - src/eval/shared/judge-runner.ts:95 classifyJudgeTransportError 1 test/longmemeval-judge.test.ts+internal-used - src/mcp/dispatch.ts:335 buildEmptyRetrievalBlock 2 test/dispatch-response-meta.serial.test.ts,test/e2e/legacy-chunk-privacy.test.ts+internal-used - src/mcp/dispatch.ts:375 isListLevelDenialEnvelope 2 test/denied-after-list.test.ts,test/truthful-catalog.e2e-lite.test.ts+internal-used - src/mcp/instructions.ts:36 buildMcpInstructions 2 test/mcp-instructions-writeback.test.ts,test/mcp-server-identity.test.ts+internal-used - src/mcp/publish-gates.ts:27 readPublishGate 1 test/publish-gates.test.ts+internal-used - src/mcp/resolve-ipc-binding.ts:72 isVolunteerProbeShaped 1 test/config-adaptive-return-keys.test.ts+internal-used - src/mcp/server.ts:131 stdioVisibleTools 3 test/e2e/mcp.test.ts,test/mcp-stdio-gate-list.test.ts,test/server-degraded-scope.test.ts+internal-used - src/mcp/server.ts:181 trackStdioRpc 1 test/serve-stdin-eof-drain.test.ts+internal-used - src/mcp/skill-resources.ts:18 sharedSkillResourceUri 3 test/fixtures/shared-skills-oauth-process.ts,test/fixtures/shared-skills-transport-cases.ts,test/shared-skills-brain-assertion.test.ts+internal-used - src/mcp/surface.ts:269 effectiveSurfaceForClient 2 test/mcp-surface.test.ts,test/truthful-catalog.e2e-lite.test.ts+internal-used - src/mcp/tool-catalog.ts:26 firstSentence 2 test/mcp-tool-defs.test.ts,test/tool-catalog.test.ts+internal-used - src/mcp/validate-params.ts:94 UNKNOWN_PARAM_ALLOWLIST 1 test/validate-params.test.ts+internal-used PUBLIC src/commands/extract.ts:300 buildSlugPathIndex 1 test/extract-incremental.test.ts+internal-used PUBLIC src/commands/extract.ts:385 resolveBasenameMatchesFromSlugs 1 test/extract-fs.test.ts+internal-used PUBLIC src/commands/extract.ts:407 resolveSlugAll 2 test/extract-fs.test.ts,test/link-extraction.test.ts+internal-used PUBLIC src/commands/extract.ts:490 extractLinksFromFile 6 test/attendance-extraction-bounds.test.ts,test/attendance-retrieval.test.ts,test/extract-fs.test.ts+internal-used PUBLIC src/core/ai/gateway.ts:1480 NO_BATCH_CAP_SUB_BATCH_ITEMS 1 test/ai/no-batch-cap-item-split.test.ts+internal-used PUBLIC src/core/ai/gateway.ts:1732 isTokenLimitError 1 test/ai/adaptive-embed-batch.test.ts+internal-used PUBLIC src/core/ai/gateway.ts:226 VoyageResponseTooLargeError 2 test/ai/gateway.test.ts,test/voyage-response-cap.test.ts+internal-used PUBLIC src/core/ai/gateway.ts:2415 parseExpansionResponse 1 test/ai/gateway-chat.test.ts+internal-used PUBLIC src/core/ai/gateway.ts:2852 isThinkingByDefaultModel 2 test/ai/gateway-thinking-headroom.test.ts,test/ai/gateway-thinking-model-re.test.ts+internal-used PUBLIC src/core/ai/gateway.ts:2926 toModelMessages 4 test/ai/gateway-toolcall-pairing.test.ts,test/ai/gateway-tools-schema.test.ts,test/e2e/subagent-gateway-resume-reconciliation.test.ts+internal-used PUBLIC src/core/ai/gateway.ts:3460 openAIPromptCacheKey 1 test/ai/gateway-openai-prompt-cache-key.test.ts+internal-used PUBLIC src/core/ai/gateway.ts:3469 toAISDKTools 1 test/ai/gateway-tools-schema.test.ts+internal-used PUBLIC src/core/ai/gateway.ts:424 recipeSupportsStructuredOutputs 2 test/ai/gateway-chat.test.ts,test/core/budget/expand-records-budget.test.ts+internal-used PUBLIC src/core/ai/gateway.ts:692 resetGateway 258 test/ai/adaptive-embed-batch.test.ts,test/ai/claude-cli-expansion.test.ts,test/ai/diagnose-embedding-dims.test.ts+internal-used PUBLIC src/core/ai/gateway.ts:734 __setGenerateTextTransportForTests 12 test/ai/claude-cli-expansion.test.ts,test/ai/gateway-cache-breakpoint.test.ts,test/ai/gateway-chat-temperature.test.ts+internal-used PUBLIC src/core/ai/gateway.ts:745 __setGenerateObjectTransportForTests 3 test/ai/claude-cli-expansion.test.ts,test/core/budget/expand-records-budget.test.ts,test/e2e/skillopt-models-used.serial.test.ts+internal-used PUBLIC src/core/backoff.ts:107 shouldProceed 1 test/backoff.test.ts+internal-used PUBLIC src/core/guardrails.ts:132 GuardrailLoadError 1 test/guardrails-env-load.test.ts+internal-used PUBLIC src/core/guardrails.ts:86 registerGuardrailProvider 3 test/guardrails-env-load.test.ts,test/guardrails.test.ts,test/public-exports.test.ts+internal-used PUBLIC src/core/import-file.ts:1659 SUPPORTED_IMAGE_EXTS 1 test/import-image-file.test.ts+internal-used PUBLIC src/core/import-file.ts:1700 withImportTransaction 2 test/import-image-file.test.ts,test/put-page-empty-overwrite-guard.test.ts+internal-used PUBLIC src/core/import-file.ts:1751 pLimit 1 test/import-image-file.test.ts+internal-used PUBLIC src/core/ingestion/test-harness.ts:226 expectEvent 2 test/ingestion/test-harness.test.ts,test/public-exports.test.ts+internal-used PUBLIC src/core/ingestion/test-harness.ts:61 IngestionTestHarness 4 test/ingestion/sources/file-watcher.test.ts,test/ingestion/sources/inbox-folder.test.ts,test/ingestion/test-harness.test.ts+internal-used PUBLIC src/core/model-pricing.ts:66 ANTHROPIC_CACHE_READ_MULT 1 test/model-pricing.test.ts+internal-used PUBLIC src/core/model-pricing.ts:67 ANTHROPIC_CACHE_WRITE_5M_MULT 1 test/model-pricing.test.ts+internal-used PUBLIC src/core/model-pricing.ts:80 ANTHROPIC_CACHE_READ_MULT_OVERRIDES 1 test/model-pricing.test.ts+internal-used PUBLIC src/core/pglite-engine.ts:237 tryLoadSnapshot 1 test/snapshot-shape-guard.test.ts+internal-used PUBLIC src/core/pglite-engine.ts:493 buildPgliteInitErrorMessage 2 test/fix-wave-structural.test.ts,test/pglite-init-classifier.test.ts+internal-used PUBLIC src/core/pglite-lock.ts:81 getPgliteKernelLockPath 2 test/pglite-lock.test.ts,test/pglite-maintenance-fence.test.ts+internal-used PUBLIC src/core/search/expansion.ts:40 sanitizeExpansionOutput 1 test/query-sanitization.test.ts+internal-used PUBLIC src/core/search/hybrid.ts:1119 makeQueryEmbedDeadline 1 test/search/query-embed-deadline.test.ts+internal-used PUBLIC src/core/search/hybrid.ts:1131 embedQueryBounded 1 test/search/query-embed-deadline.test.ts+internal-used PUBLIC src/core/search/hybrid.ts:124 shouldBoostCompiledTruth 1 test/search-compiled-truth-boost-scope.test.ts+internal-used PUBLIC src/core/search/hybrid.ts:2940 textVectorArmNonEmpty 2 test/keyword-relaxed-fusion.serial.test.ts,test/search/fusion-lists.test.ts+internal-used PUBLIC src/core/search/hybrid.ts:3002 filterResultsByCallerScope 1 test/cache-scope-key.test.ts+internal-used PUBLIC src/core/search/hybrid.ts:3089 resolveWalkDedupCap 1 test/search/walk-dedup-cap.test.ts+internal-used PUBLIC src/core/search/hybrid.ts:3093 rrfFusion 6 test/benchmark-search-quality.ts,test/extraction-review.test.ts,test/public-exports.test.ts+internal-used PUBLIC src/core/search/hybrid.ts:759 SUPERSEDE_PENALTY 1 test/search/supersede-downrank.test.ts+internal-used PUBLIC src/core/think/index.ts:287 looksLikeJsonEnvelope 1 test/think-envelope-salvage.test.ts+internal-used PUBLIC src/core/think/index.ts:300 salvageThinkEnvelope 1 test/think-envelope-salvage.test.ts+internal-used PUBLIC src/core/think/index.ts:402 composeExtractiveFallback 1 test/think-extractive.serial.test.ts+internal-used PUBLIC src/core/think/index.ts:50 classifyLlmCallFailure 1 test/think-extractive.serial.test.ts+internal-used PUBLIC src/core/types.ts:1899 RANKING_ONLY_DEGRADED_STAGES 1 test/degraded-stages-recall.test.ts+internal-used PUBLIC src/eval/longmemeval/reader.ts:123 buildReaderRequest 2 test/longmemeval-reader.test.ts,test/public-exports.test.ts+internal-used PUBLIC src/eval/longmemeval/reader.ts:62 READER_NOTES_SYSTEM_TEXT 1 test/longmemeval-reader.test.tsdiff --git a/docs/test-audit/2026-09-29/lane-seams/unreachable.tsv b/docs/test-audit/2026-09-29/lane-seams/unreachable.tsvnew file mode 100644index 0000000000..1c99f0ddb9--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-seams/unreachable.tsv@@ -0,0 +1,48 @@+src/commands/eval-schema-authoring.ts 177 strRefsInSrc=2 1 test/eval-schema-authoring.test.ts+src/core/agent-install/entry.ts 43 strRefsInSrc=2895 1 test/agent-install-backup.serial.test.ts+src/core/agent-install/setup.ts 317 strRefsInSrc=429 2 test/agent-install-backup.serial.test.ts,test/agent-install-follow-setup.serial.test.ts+src/core/archive-crawler-config.ts 351 strRefsInSrc=1 1 test/archive-crawler-config.test.ts+src/core/artifact/index.ts 150 strRefsInSrc=2702 2 test/artifact-abstraction.test.ts,test/e2e/schema-cathedral.test.ts+src/core/calibration/cross-brain.ts 170 strRefsInSrc=17 1 test/cross-brain-calibration.test.ts+src/core/calibration/nudge.ts 210 strRefsInSrc=214 1 test/nudge.test.ts+src/core/calibration/recall-footer.ts 82 strRefsInSrc=0 1 test/recall-footer.test.ts+src/core/calibration/take-forecast.ts 171 strRefsInSrc=0 1 test/take-forecast.test.ts+src/core/chronicle/backstop.ts 39 strRefsInSrc=211 1 test/chronicle-extract.test.ts+src/core/chunkers/llm.ts 164 strRefsInSrc=449 0+src/core/chunkers/semantic.ts 343 strRefsInSrc=527 0+src/core/conversation-parser/llm-polish.ts 232 strRefsInSrc=2 1 test/conversation-parser/llm-polish.test.ts+src/core/data-research.ts 436 strRefsInSrc=2 1 test/data-research.test.ts+src/core/diarize/payload-fitter.ts 269 strRefsInSrc=5 2 test/core/diarize/payload-fitter-summarize.test.ts,test/core/diarize/payload-fitter.test.ts+src/core/distribution/index.ts 125 strRefsInSrc=2702 1 test/distribution-import-boundary.test.ts+src/core/enrichment/budget.ts 370 strRefsInSrc=2425 1 test/enrichment.test.ts+src/core/enrichment/completeness.ts 276 strRefsInSrc=24 1 test/enrichment.test.ts+src/core/eval-capture-graph.ts 170 strRefsInSrc=0 1 test/code-intel/eval-capture-graph.test.ts+src/core/eval-contradictions/calibration-join.ts 103 strRefsInSrc=2 2 test/eval-contradictions-calibration-join.test.ts,test/regressions/v0.36.1.0-iron-rule.test.ts+src/core/fail-improve.ts 288 strRefsInSrc=7 1 test/fail-improve.test.ts+src/core/ingestion/daemon.ts 545 strRefsInSrc=357 3 test/e2e/ingestion-roundtrip.test.ts,test/ingestion/daemon.test.ts,test/ingestion/migration-mode.test.ts+src/core/ingestion/dedup.ts 170 strRefsInSrc=632 1 test/ingestion/dedup.test.ts+src/core/ingestion/skillpack-load.ts 346 strRefsInSrc=1 1 test/ingestion/skillpack-load.test.ts+src/core/ingestion/sources/file-watcher.ts 310 strRefsInSrc=22 1 test/ingestion/sources/file-watcher.test.ts+src/core/ingestion/sources/gstack-learnings.ts 345 strRefsInSrc=25 1 test/ingestion/gstack-learnings.test.ts+src/core/ingestion/sources/inbox-folder.ts 370 strRefsInSrc=21 2 test/e2e/ingestion-roundtrip.test.ts,test/ingestion/sources/inbox-folder.test.ts+src/core/ingestion/sources/markdown-greenfield.ts 334 strRefsInSrc=17 1 test/ingestion/markdown-greenfield.test.ts+src/core/minions/batch-projection.ts 187 strRefsInSrc=2 1 test/batch-projection.test.ts+src/core/minions/budget-tracker.ts 292 strRefsInSrc=38 5 test/budget-tracker.test.ts,test/e2e/jobs-watch-readsnapshot.test.ts,test/e2e/minions-budget-cathedral.test.ts,test/self-fix.test.ts+src/core/minions/lease-cap-controller.ts 286 strRefsInSrc=1 2 test/e2e/minions-controller-bounce-only.test.ts,test/lease-cap-controller.test.ts+src/core/minions/self-fix.ts 276 strRefsInSrc=22 2 test/e2e/minions-self-fix-flow.test.ts,test/self-fix.test.ts+src/core/minions/stagger.ts 36 strRefsInSrc=22 1 test/minions-quiet-hours.test.ts+src/core/onboard/impact-capture.ts 189 strRefsInSrc=3 1 test/e2e/onboard-full-flow.test.ts+src/core/progressive-batch/orchestrator.ts 779 strRefsInSrc=323 1 test/progressive-batch/orchestrator.test.ts+src/core/progressive-batch/retrofit-wrap.ts 79 strRefsInSrc=0 1 test/progressive-batch/retrofit-wrap.test.ts+src/core/progressive-batch/stage-report.ts 53 strRefsInSrc=7 0+src/core/schema-pack/expand-type-filter.ts 187 strRefsInSrc=0 2 test/company-brain-schema.test.ts,test/schema-pack-expand-type-filter.test.ts+src/core/schema-pack/rewrite-links-batch.ts 92 strRefsInSrc=0 1 test/schema-pack-rewrite-links-batch.test.ts+src/core/search/keyword.ts 11 strRefsInSrc=614 0+src/core/search/vector.ts 11 strRefsInSrc=1343 0+src/core/shared-skills/setup-assets.d.ts 5 strRefsInSrc=0 0+src/core/skillpack/brain-pack-lint.ts 70 strRefsInSrc=1 1 test/skillpack-init-brain-pack.test.ts+src/core/source-config-redact.ts 48 strRefsInSrc=0 1 test/source-config-redact.test.ts+src/core/upgrade-checkpoint.ts 161 strRefsInSrc=2 2 test/e2e/v030_1-integration-pglite.test.ts,test/upgrade-checkpoint.serial.test.ts+src/types/image-decoders.d.ts 35 strRefsInSrc=0 0+src/types/markdown-assets.d.ts 5 strRefsInSrc=0 0+src/types/schema-assets.d.ts 5 strRefsInSrc=0 0diff --git a/docs/test-audit/2026-09-29/lane-source-grep/inventory.tsv b/docs/test-audit/2026-09-29/lane-source-grep/inventory.tsvnew file mode 100644index 0000000000..ac12408b7f--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-source-grep/inventory.tsv@@ -0,0 +1,199 @@+file lane tests srcreads srcimports spawns ms loc+test/admin-sse-eventsource.test.ts unit 1 1 0 0 179 13+test/agent-install-backup.serial.test.ts serial 14 3 12 3 81187 446+test/agent-install-follow-setup.serial.test.ts serial 4 6 3 2 44197 88+test/agent-register-guards.serial.test.ts serial 2 1 0 6 11667 166+test/agent-register.test.ts unit 35 2 6 0 1904 464+test/ai/silent-drop-regression.test.ts unit 3 3 0 0 197 62+test/ambient-writeback-lifecycle.serial.test.ts serial 1 4 3 5 17567 322+test/apply-migrations.test.ts unit 28 3 2 0 282 291+test/archived-source-scoping.test.ts unit 4 1 2 0 194 128+test/asymmetric-encoding-contract.test.ts unit 6 3 1 0 212 134+test/auto-link-targeted-probe-2544.test.ts unit 6 1 4 0 6348 151+test/autopilot-auto-drain-wiring.test.ts unit 8 1 0 0 155 67+test/autopilot-cycle-failure-classification.test.ts unit 5 2 0 0 168 108+test/autopilot-fanout-wiring.test.ts unit 16 2 2 0 196 263+test/autopilot-install.test.ts unit 18 5 4 6 455 504+test/autopilot-nightly-probe-wiring.test.ts unit 9 1 0 0 274 91+test/autopilot-parser-probe-wiring.test.ts unit 10 1 0 0 177 77+test/autopilot-pause-marker.test.ts unit 13 1 2 2 234 245+test/autopilot-self-upgrade.test.ts unit 7 1 1 3 464 44+test/autopilot-shutdown-engine-close.test.ts unit 6 1 0 0 225 81+test/autopilot-supervisor-wiring.test.ts unit 7 1 0 0 168 99+test/backlinks-job-default.test.ts unit 3 1 0 0 196 47+test/backup-cli.serial.test.ts serial 19 2 5 0 420 443+test/backup-invalidation.serial.test.ts serial 12 1 5 4 3340 309+test/book-mirror.test.ts unit 9 1 0 1 1113 142+test/brain-score-breakdown.test.ts unit 11 1 1 0 2153 192+test/brainstorm-timeout.test.ts unit 14 2 2 0 185 147+test/canonical-writer-inventory.test.ts unit 2 1 0 0 297 32+test/chat-key-plane.test.ts unit 7 2 2 0 365 86+test/check-update.test.ts unit 25 1 1 2 1682 203+test/child-worker-supervisor.test.ts unit 21 1 2 0 3161 1017+test/chronicle-extract.test.ts unit 22 1 4 0 1588 199+test/chunkers/code-bash.test.ts unit 5 2 1 0 697 78+test/claude-cli-recipe.test.ts unit 38 1 38 0 368 1162+test/cli-cwd-dotenv-quarantine.test.ts unit 36 2 1 13 13818 1091+test/cli-force-exit-teardown-arming.test.ts unit 1 2 0 0 170 55+test/cli-stdout-delivery.test.ts unit 17 5 1 9 17469 523+test/cli.test.ts unit 24 1 5 10 8017 324+test/code-retrieval-harness.test.ts unit 26 1 1 0 200 245+test/codex-plugin-manifest.test.ts unit 42 1 0 9 3181 595+test/company-brain-connect-cli.serial.test.ts serial 3 4 3 7 21474 128+test/company-brain-demo.test.ts unit 2 1 2 1 10506 52+test/company-brain-inspect-cli.test.ts unit 7 7 3 5 6980 126+test/company-brain-schema.test.ts unit 8 1 9 0 318 111+test/compile-view.test.ts unit 14 1 4 0 240 310+test/config.test.ts unit 20 1 9 0 161 253+test/connection-resilience.test.ts unit 25 3 0 0 190 332+test/context-engine-checkpoint.serial.test.ts serial 12 9 12 0 504 534+test/contextual-retrieval-service-pure.test.ts unit 25 1 4 0 511 566+test/conversation-facts-type-allowlist-drift.test.ts unit 18 1 3 0 3769 354+test/cross-modal-eval-cli.test.ts unit 13 2 3 0 177 195+test/cycle-abort.test.ts unit 13 12 5 0 480 251+test/cycle-drain-renewal.test.ts unit 7 2 1 0 416 126+test/cycle-pack-gating.test.ts unit 21 1 1 0 199 207+test/cycle-patterns-deadline-budget.test.ts unit 15 5 3 0 1410 173+test/cycle-patterns.test.ts unit 16 1 2 0 400 141+test/cycle-phase-deadline-drift.test.ts unit 4 2 4 0 442 73+test/cycle/cycle-lock-ttl.test.ts unit 1 1 0 0 160 29+test/cycle/nightly-probe-adapters.test.ts unit 7 5 1 0 217 150+test/cycle/regression-pr-wave-r1-r2-r4.test.ts unit 7 2 3 0 375 150+test/cycle/yield-during-phase-throttle.test.ts unit 3 1 3 0 2804 114+test/destructive-guard.test.ts unit 41 1 3 0 7718 806+test/detached-stderr.test.ts unit 5 3 1 0 181 90+test/distribution-import-boundary.test.ts unit 2 2 1 0 175 93+test/docs-mcp-deploy.test.ts unit 9 2 0 0 251 88+test/doctor-categories.test.ts unit 10 1 1 0 260 192+test/doctor-orphan-ratio.test.ts unit 11 3 4 0 11289 267+test/doctor-volunteer-channels.test.ts unit 9 3 2 0 343 191+test/doctor.test.ts unit 107 1 112 1 8723 2075+test/dream-cli-flags.test.ts unit 28 1 0 0 163 198+test/e2e/bootstrap-compiled-binary.serial.test.ts serial 4 2 1 6 -1 186+test/e2e/bootstrap-real-codex.serial.test.ts serial 5 1 9 20 -1 673+test/e2e/compile-context-pglite.test.ts e2e 13 4 6 0 2354 329+test/e2e/fresh-install-pglite.test.ts e2e 6 5 19 0 29181 372+test/e2e/install-real-hermes.serial.test.ts serial 4 3 0 3 -1 345+test/e2e/migration-flow.test.ts e2e 4 3 2 0 4277 299+test/e2e/persistence-http-liveness.test.ts e2e 7 4 2 3 53500 408+test/e2e/postgres-driver-install.test.ts e2e 1 3 0 1 306 84+test/e2e/qm-provisioning.test.ts e2e 11 3 0 3 40319 345+test/e2e/remote-privacy-journeys.test.ts e2e 3 1 8 2 24236 272+test/e2e/skill-brain-first.test.ts e2e 12 9 2 4 770 246+test/e2e/upgrade-bun-link-arc.serial.test.ts serial 5 7 3 4 -1 443+test/embed-helper-migration.test.ts unit 8 1 0 0 275 110+test/embedding-dim-check-facts.test.ts unit 21 1 2 0 190 257+test/eval-brainbench-e2e.slow.test.ts slow 21 6 2 8 48539 428+test/eval-capture-db-plane.serial.test.ts serial 9 2 5 0 562 239+test/eval-contradictions/no-valid-until-write.test.ts unit 4 2 0 0 220 184+test/eval-longmemeval-cli-smoke.test.ts unit 2 1 0 2 6505 76+test/eval-synthesize-concepts-routing.test.ts unit 6 2 1 2 864 118+test/exit-classification.test.ts unit 13 2 1 0 177 131+test/export-help.test.ts unit 1 1 0 1 -1 24+test/extract-atoms-drain-errors.test.ts unit 16 1 1 0 175 356+test/extract-atoms-drain.test.ts unit 16 3 2 0 181 281+test/extract-conversation-facts-workers.test.ts unit 17 1 1 0 200 172+test/extract-include-frontmatter-config.serial.test.ts serial 8 2 3 0 1737 167+test/extract-workers.test.ts unit 10 1 0 0 179 95+test/facts-backstop-remedy-verb.test.ts unit 3 2 0 0 151 45+test/features.test.ts unit 12 4 5 0 223 138+test/fence-extraction.test.ts unit 18 1 3 0 6159 276+test/file-upload-fail-closed.test.ts unit 9 1 2 0 1162 215+test/files.test.ts unit 39 2 5 0 2301 562+test/fix-wave-structural.test.ts unit 31 37 0 3 196 408+test/helpers/agent-harness.unit.test.ts unit 46 1 0 0 448 701+test/hook-command.serial.test.ts serial 70 1 6 13 1772 1518+test/hook-push-spawn-env.test.ts unit 3 1 0 0 220 45+test/integrations.test.ts unit 123 1 3 0 211 860+test/jobs-embed-background-parity.serial.test.ts serial 2 2 4 0 4632 116+test/jobs-gateway-refresh-set.test.ts unit 5 1 0 0 173 69+test/jobs-list-get-json.serial.test.ts serial 7 1 2 0 1689 154+test/jobs-thin-client-date-rehydration.test.ts unit 5 1 1 0 372 80+test/jobs-worker-startup-recovery.test.ts unit 5 1 3 0 1668 146+test/lens-pack-manifests.test.ts unit 31 1 2 0 193 276+test/link-inference-pack.test.ts unit 12 1 3 0 270 159+test/link-source-check-repair.test.ts unit 13 1 5 0 3640 255+test/longmemeval-embed-cache.test.ts unit 21 1 2 1 644 472+test/loops-extract-wiring.test.ts unit 8 2 3 0 348 102+test/migrate-embeddings-recovery-cli.serial.test.ts serial 4 3 6 3 -1 235+test/migrate-stdout-clean.test.ts unit 2 1 2 0 1788 68+test/migrate.test.ts unit 171 11 7 1 8243 2414+test/migration-in-process.serial.test.ts serial 8 4 3 3 9878 183+test/migration-resume.test.ts unit 15 6 9 0 257 178+test/migrations-v0_13_0.test.ts unit 7 4 3 5 239 83+test/migrations-v0_14_0.test.ts unit 8 4 4 0 298 108+test/migrations-v0_22_4.test.ts unit 9 1 5 0 254 149+test/model-id.test.ts unit 27 1 1 0 172 221+test/model-pricing.test.ts unit 30 1 5 0 196 273+test/models-doctor-embed.test.ts unit 3 1 0 0 202 50+test/openclaw-plugin-manifest.test.ts unit 12 1 1 0 175 156+test/operations-trust-boundary.test.ts unit 21 2 6 1 5111 612+test/persistence-activation.test.ts unit 6 1 12 1 6355 136+test/persistence-file-import.test.ts unit 6 3 14 1 44494 210+test/persistence-image-import.serial.test.ts serial 3 1 8 0 3869 106+test/pglite-engine.test.ts unit 110 1 4 0 5336 1541+test/pglite-repair-command.serial.test.ts serial 14 1 2 2 3251 500+test/pglite-wal-repair.serial.test.ts serial 6 1 3 0 10900 200+test/phantom-redirect-per-source-lock.test.ts unit 3 1 1 0 189 46+test/postgres-engine-singleton-ownership.test.ts unit 7 2 0 0 190 159+test/postgres-engine.test.ts unit 8 1 0 0 185 167+test/private-visibility.test.ts unit 26 1 7 0 1823 384+test/reconcile-owner-journey.serial.test.ts serial 1 10 9 2 128103 282+test/redos-hardening.test.ts unit 14 2 4 0 178 140+test/register-client-source-normalize.test.ts unit 16 1 1 0 165 106+test/regression-strict-source-id.test.ts unit 9 6 2 4 247 116+test/reindex-code-recovery.test.ts unit 8 1 3 0 1253 114+test/remediation-command-resolution.test.ts unit 3 1 3 0 648 222+test/remote-ping-status-field.test.ts unit 4 1 0 0 160 53+test/reranker-default-seam.test.ts unit 3 1 2 0 156 31+test/resolve-ipc-binding.test.ts unit 9 6 4 0 258 184+test/retrieval-reflex-recipe-routing.test.ts unit 5 1 1 0 188 78+test/schema-bootstrap-coverage.test.ts unit 13 5 5 0 5701 1273+test/schema-cli-contract.test.ts unit 7 1 0 0 178 93+test/schema-pack-best-effort.test.ts unit 7 1 4 0 192 120+test/schema-pack-unify-types-handler.test.ts unit 11 2 5 0 5535 299+test/schema-pack/suggest.test.ts unit 7 1 2 0 194 188+test/scripts/check-engine-dynamic-import.test.ts unit 23 1 0 4 5442 356+test/scripts/classify-tests.test.ts unit 8 4 0 3 175 119+test/scripts/coverage-diff-gate.test.ts unit 18 1 0 3 593 315+test/scripts/merge-lcov.test.ts unit 26 3 0 3 1846 471+test/scripts/run-unit-shard.test.ts unit 11 1 0 6 1221 213+test/scripts/typecheck-incremental.test.ts unit 4 1 0 2 8637 128+test/search/graph-signals-wire-integration.test.ts unit 3 1 3 0 2405 107+test/search/knobs-hash-reranker.test.ts unit 25 2 3 0 221 328+test/serve-http-admin-route-guard.test.ts unit 4 2 0 0 177 265+test/serve-http-github-webhook.test.ts unit 9 1 1 0 623 114+test/serve-http-mcp-transport-cleanup.test.ts unit 2 1 0 0 186 56+test/serve-http-metrics.test.ts unit 9 1 1 0 255 160+test/serve-service.test.ts unit 35 1 2 1 242 657+test/serve-stdin-eof-drain.test.ts unit 8 1 4 0 724 192+test/shared-skills-init.serial.test.ts serial 4 4 5 3 33390 104+test/shared-skills-proposal-cli.test.ts unit 1 2 1 1 11097 43+test/shared-skills-restore.serial.test.ts serial 10 6 21 1 26315 323+test/shared-skills-setup.serial.test.ts serial 16 5 6 2 706 214+test/skillopt/deadline-and-hermetic.test.ts unit 9 1 3 0 315 143+test/skillpack-copy.test.ts unit 19 11 1 0 210 325+test/skillpack-install.test.ts unit 32 6 2 0 301 670+test/skillpack-reference-harness.test.ts unit 15 3 1 0 326 260+test/skillpack-scaffold-harness.test.ts unit 22 3 0 6 29543 435+test/skillpack-scaffold.test.ts unit 14 1 1 0 223 296+test/snapshot-shape-guard.test.ts unit 11 1 2 0 433 163+test/sources-webhook.test.ts unit 12 1 1 0 187 148+test/spend-off-switch.test.ts unit 5 3 1 0 614 53+test/supervisor-configuration-blocked.test.ts unit 21 11 7 1 7874 628+test/supervisor.test.ts unit 23 1 7 0 4562 632+test/sync-failures.test.ts unit 65 6 58 0 281 682+test/sync-include-hidden.test.ts unit 7 1 2 6 490 128+test/sync.test.ts unit 85 1 25 40 8892 1277+test/thin-client-routing-audit.test.ts unit 13 6 0 0 163 176+test/think-embed-question-wiring.serial.test.ts serial 2 1 3 0 640 86+test/timing-safe.test.ts unit 6 1 1 0 229 52+test/transcript-adapters.test.ts unit 54 6 13 0 483 1104+test/transcription-injection.test.ts unit 2 1 1 11 194 65+test/upgrade-skill-publish-prompt-race.test.ts unit 3 1 0 0 158 62+test/upgrade.serial.test.ts serial 28 1 5 12 3210 404+test/v0_37_fix_wave.serial.test.ts serial 19 2 18 0 591 325+test/v0_37_gap_fill.serial.test.ts serial 17 3 10 0 5408 574+test/voyage-response-cap.test.ts unit 6 6 0 0 239 98+test/worker-lock-renewal-shape.test.ts unit 18 1 1 0 522 263+test/worker-supervised-db-probe.test.ts unit 5 1 2 0 1885 185diff --git a/docs/test-audit/2026-09-29/lane-source-grep/pertest.json b/docs/test-audit/2026-09-29/lane-source-grep/pertest.jsonnew file mode 100644index 0000000000..22447e1ada--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-source-grep/pertest.json@@ -0,0 +1,3026 @@+[+[+"test/admin-sse-eventsource.test.ts",+"unit",+1,+1,+"0",+"179",+"13",+[+"test('Live Activity EventSource sends admin session cookies through reverse proxies', () => {"+]+],+[+"test/agent-install-backup.serial.test.ts",+"serial",+14,+3,+"12",+"81187",+"446",+[+"test('a failed upgrade resumes its migration before reporting the existing brain ready', async () => {",+"test('full backup restores DB-only facts/files, rebases sources, quarantines all unfinished jobs', async () =>",+"test('interrupted publication preserves private recovery staging and refuses an incomplete destination', async"+]+],+[+"test/agent-install-follow-setup.serial.test.ts",+"serial",+4,+1,+"3",+"44197",+"88",+[+"test('adopted local brain stays memory-only pending approval and never acquires a new identity instruction', a"+]+],+[+"test/agent-register-guards.serial.test.ts",+"serial",+2,+2,+"0",+"11667",+"166",+[+"test('thin client is refused with a structured JSON failure before any engine work', async () => {",+"test('duplicate name is refused with the existing client id + reissue hint; pglite live serve is refused pre-c"+]+],+[+"test/agent-register.test.ts",+"unit",+35,+3,+"6",+"1904",+"464",+[+"test('agent-register never acquires its own engine (withConfiguredSql / .connect are banned)', () => {",+"test('registerScopedClient core is print-free and exit-free', () => {",+"test('end-to-end: row, ttl, surface via rescope, audit row, verify round-trip', async () => {"+]+],+[+"test/ai/silent-drop-regression.test.ts",+"unit",+3,+3,+"0",+"197",+"62",+[+"test('ops surface put_page does not gate embedding on OPENAI_API_KEY alone', () => {",+"test('hybrid.ts search does not gate vector path on OPENAI_API_KEY alone', () => {",+"test('import-file.ts does NOT silently swallow embedding failures', () => {"+]+],+[+"test/ambient-writeback-lifecycle.serial.test.ts",+"serial",+1,+1,+"3",+"17567",+"322",+[+"test('the whole story', async () => {"+]+],+[+"test/apply-migrations.test.ts",+"unit",+28,+3,+"2",+"282",+"291",+[+"test('source contains process.exit(listExit) on list/dry-run and exit(0) up-to-date', async () => {",+"test('runner loops result.phases and console.errors failed phase details', async () => {",+"test('up-to-date branch exits 1 when schemaBehind (source shape)', async () => {"+]+],+[+"test/archived-source-scoping.test.ts",+"unit",+4,+2,+"2",+"194",+"128",+[+"test(`${file} carries ${patched} archived-filtered all-source selection(s)`, () => {",+"test('src/core/source-resolver.ts tier-4 selects the archived column for active-over-archived tiering', () => "+]+],+[+"test/asymmetric-encoding-contract.test.ts",+"unit",+6,+3,+"1",+"212",+"134",+[+"test('src/core/search/hybrid.ts imports embedQuery from embedding.ts', () => {",+"test('src/core/search/hybrid.ts calls embedQuery at the search-time query path', () => {",+"test('src/core/embedding.ts re-exports both embed and embedQuery', () => {"+]+],+[+"test/auto-link-targeted-probe-2544.test.ts",+"unit",+6,+1,+"4",+"6348",+"151",+[+"test('probe binds the slug array with an explicit ::text[] cast (postgres.js parity)', () => {"+]+],+[+"test/autopilot-auto-drain-wiring.test.ts",+"unit",+8,+8,+"0",+"155",+"67",+[+"test('CODEX #2: idempotency key includes a UTC-day time slot (not static)', () => {",+"test('CODEX #1: submits with allowProtectedSubmit', () => {",+"test('CODEX #3: enumerates sources and counts backlog per source', () => {",+"test('gates on pack NOT declaring extract_atoms (the silent-backlog condition)', () => {",+"test('gates on the enabled flag and a daily spend cap (DECISION 3C)', () => {",+"test('is Postgres-gated (PGLite has no worker surface)', () => {",+"test('issue #3218: submits with max_attempts 3 (not 1) so a retry can backoff before dead-lettering', () => {",+"test('CODEX impl #4: no maxWaiting (it coalesces by name+queue, not source)', () => {"+]+],+[+"test/autopilot-cycle-failure-classification.test.ts",+"unit",+5,+5,+"0",+"168",+"108",+[+"test(\"the inline-cycle path does NOT treat 'partial' as cycleOk=false\", () => {",+"test(\"the 5-consecutive-error give-up is still wired (regression-safety)\", () => {",+"test('the legacy `count > 20 ? \"warn\" : \"ok\"` ternary is gone', () => {",+"test('the new threshold is ratio-based against total_pages', () => {",+"test('the warn branch still exists (we narrowed, did not remove)', () => {"+]+],+[+"test/autopilot-fanout-wiring.test.ts",+"unit",+16,+16,+"2",+"196",+"263",+[+"test('imports dispatchPerSource from the fan-out helper', () => {",+"test('imports resolveEffectiveFanoutMax (clamps to worker concurrency; PGLite base still 1)', () => {",+"test('calls dispatchPerSource within the shouldFullCycle branch', () => {",+"test('applies the 30-minute timeout floor only to full-cycle dispatch', () => {",+"test('lastFullCycleAt advance-gate counts coalesced ticks (parity with pre-split dispatched)', () => {",+"test('unavailable-path skips in the daemon loops are NDJSON events under --json, and sources-load is a static ",+"test('fanout_summary reports coalesced separately from dispatched (honest surfaces)', () => {",+"test('targeted-plan dispatch honors the honest-dispatch contract (red-team finding)', () => {",+"test('freshness sync dispatch uses the parsed source config for pull policy', () => {",+"test('freshness sync dispatch skips unavailable source paths before enqueueing', () => {",+"test('#4399: freshness sync dispatch skips a syncEnabled:false source BEFORE queuing a job', () => {",+"test('#4046: targeted dispatch scopes stable recommendation keys to the interval', () => {",+"test('#2781: dispatchGlobalMaintenance gets the full-cycle floor, not the outer (non-full-cycle) timeoutMs', (",+"test('updates lastFullCycleAt after dispatch or an all-fresh restart check', () => {",+"test('#2781: full-cycle floor is derived from BOTH handler anchors, not a duplicated literal', () => {",+"test('does NOT regress to the single-job dispatch on the full-cycle path', () => {"+]+],+[+"test/autopilot-install.test.ts",+"unit",+18,+9,+"4",+"455",+"504",+[+"test('wrapper sources ~/.zshenv before ~/.zshrc', async () => {",+"test('wrapper exports ~/.bun/bin onto PATH before the exec', async () => {",+"test('status detects the autopilot-run.sh wrapper line', async () => {",+"test('wrapper sources zshrc AND bashrc independently (no || chain)', async () => {",+"test('wrapper additively sources <gbrainDir>/env after the rc-file profiles, before PATH export/exec', () => {",+"test('honors GBRAIN_HOME: sources <GBRAIN_HOME>/.gbrain/env, not a hardcoded ~/.gbrain', () => {",+"test('behavior: real bash actually sets the var when the file is present, and no-ops (exit 0, var unset) when ",+"test('runAutopilot checks isAvailable(\"chat\") and logs chatBootWarning before the daemon loop starts', async (",+"test('launchd unloads before load, systemd try-restarts, cron/container explain the residual process', async ("+]+],+[+"test/autopilot-nightly-probe-wiring.test.ts",+"unit",+9,+9,+"0",+"274",+"91",+[+"test('imports runNightlyQualityProbe from the phase module', () => {",+"test('uses the eng-D2 adapter module (not direct subprocess of eval-longmemeval/cross-modal)', () => {",+"test('feature flag gate present: dual-plane read (DB row wins, file plane fallback)', () => {",+"test('NO scheduler-side rate-limit check (D10 simplification)', () => {",+"test('probe call wrapped in try/catch that does NOT bump consecutiveErrors', () => {",+"test('DI shape: isEnabled / hasEmbeddingProvider / resolveMaxUsd / resolveRepoRoot / runLongMemEval / runCross",+"test('resolveRepoRoot prefers the gbrain package root (committed fixture home), not the brain repoPath', () =>",+"test('hasEmbeddingProvider reads from gateway.isAvailable(\"embedding\") (codex round-2 #12 \u2014 in-process, not su",+"test('max_usd resolves dual-plane (default = 5 pinned by resolveProbeMaxUsd unit tests)', () => {"+]+],+[+"test/autopilot-parser-probe-wiring.test.ts",+"unit",+10,+10,+"0",+"177",+"77",+[+"test('invokes the phase module and the audit trail', () => {",+"test('flag reads dual-plane: DB row (gbrain config set) wins, file plane fallback', () => {",+"test('D10 mode-gate present: tokenmax brains run the probe by default', () => {",+"test('fixtures resolve from the gbrain package root, NOT the brain repoPath', () => {",+"test('missing fixtures skip quietly (no audit row, once-per-process stderr note)', () => {",+"test('rate_limited outcomes are NOT audit-logged (flood guard)', () => {",+"test('rate-limit gate delegates to the audit module, not inline event reads', () => {",+"test('LLM-key gate reads gateway.isAvailable(\"chat\") in-process', () => {",+"test('probe call wrapped in try/catch that does NOT bump consecutiveErrors', () => {",+"test('DI shape: the exact 7 fields of the parser probe NightlyProbeDeps', () => {"+]+],+[+"test/autopilot-pause-marker.test.ts",+"unit",+13,+1,+"2",+"234",+"245",+[+"test('worker claim loop checks the marker BEFORE queue.claim (static wiring guard)', async () => {"+]+],+[+"test/autopilot-self-upgrade.test.ts",+"unit",+7,+4,+"1",+"464",+"44",+[+"test('supervisor-relaunch, NOT in-process re-exec (Bun has no execve) \u2014 no exec*-call', () => {",+"test('the silent channel does swap-only, never a blocking full post-upgrade in the tick', () => {",+"test('boot reconciles the breadcrumb and the tick attempts the channel', () => {",+"test('apply path unlinks the lock before exit so the relaunched binary does not self-exit on a stale lock', ()"+]+],+[+"test/autopilot-shutdown-engine-close.test.ts",+"unit",+6,+6,+"0",+"225",+"81",+[+"it('registers an engine-close callback in the process-cleanup registry (SIGTERM path)', () => {",+"it('closeEngine aborts the in-flight inline cycle then disconnects the engine', () => {",+"it('the inline runCycle call carries the shutdown abort signal and is tracked as in-flight', () => {",+"it('shutdown() awaits closeEngine() before process.exit (SIGINT + internal-stop path)', () => {",+"it('exits non-zero when the daemon gives up after repeated failures (#2234)', () => {",+"it('keeps operator stops and intentional relaunch stops clean', () => {"+]+],+[+"test/autopilot-supervisor-wiring.test.ts",+"unit",+7,+7,+"0",+"168",+"99",+[+"it('imports ChildWorkerSupervisor from the shared core', () => {",+"it('does not retain the legacy inline spawn loop (`startWorker` + child.on)', () => {",+"it(\"spawns the worker with an auto-sized --max-rss (issue #1678)\", () => {",+"it('uses managed processing state and strips GBRAIN_SUPERVISED so the worker keeps stall detection', () => {",+"it(\"constructs ChildWorkerSupervisor with maxCrashes: 5\", () => {",+"it('routes onMaxCrashesExceeded to autopilot.shutdown (not process.exit directly)', () => {",+"it('shutdown drains via supervisor.killChild + awaitChildExit (not workerProc.kill)', () => {"+]+],+[+"test/backlinks-job-default.test.ts",+"unit",+3,+2,+"0",+"196",+"47",+[+"test(\"default action is 'check' (explicit opt-in required for 'fix')\", () => {",+"test('the inverted (fix-by-default) shape stays absent', () => {"+]+],+[+"test/backup-cli.serial.test.ts",+"serial",+19,+1,+"5",+"420",+"443",+[+"test('source-text contract pin: pglite-engine still throws the literal isLockError matches', () => {"+]+],+[+"test/backup-invalidation.serial.test.ts",+"serial",+12,+3,+"5",+"3340",+"309",+[+"test('a run whose rows were ALL skipped (no git repo) leaves the cache alone', async () => {",+"test('recordRepoInReceipt (post-push success) calls invalidateBackupStatus()', () => {",+"test('recordPendingRepo (pre-push proof-of-intent) does NOT invalidate \u2014 nothing was fixed yet', () => {"+]+],+[+"test/book-mirror.test.ts",+"unit",+9,+9,+"0",+"1113",+"142",+[+"it('book-mirror is in CLI_ONLY (does not get \"Unknown command\")', async () => {",+"it('without DB, never reaches queue submission', async () => {",+"it('exports runBookMirrorCmd', () => {",+"it('documents the trust contract (codex HIGH-1 fix is in the file)', () => {",+"it('uses read-only allowed_tools for subagent fan-out (codex HIGH-1)', () => {",+"it('writes via operator-trust put_page (handler takes the operator-context shape)', () => {",+"it('prints a cost-estimate confirmation before launching (P1)', () => {",+"it('uses idempotency keys for child jobs (retry-friendly)', () => {",+"it('handles partial-failure (continues + flags failed chapters)', () => {"+]+],+[+"test/brain-score-breakdown.test.ts",+"unit",+11,+1,+"1",+"2153",+"192",+[+"test('type includes dead_links + breakdown scores', async () => {"+]+],+[+"test/brainstorm-timeout.test.ts",+"unit",+14,+2,+"2",+"185",+"147",+[+"test('orchestrator.ts imports classifyBrainstormError + StructuredAgentError', async () => {",+"test('commands/brainstorm.ts has the CLI formatter for StructuredAgentError', async () => {"+]+],+[+"test/canonical-writer-inventory.test.ts",+"unit",+2,+1,+"0",+"297",+"32",+[+"test('new canonical write callsites require a reviewed inventory and an enforcement boundary', () => {"+]+],+[+"test/chat-key-plane.test.ts",+"unit",+7,+2,+"2",+"365",+"86",+[+"test('autopilot no longer probes the DB plane for the chat key', () => {",+"test('doctor context uses the same shared helper', () => {"+]+],+[+"test/check-update.test.ts",+"unit",+25,+2,+"1",+"1682",+"203",+[+"test('check-update is in CLI_ONLY set', async () => {",+"test('--help prints usage and exits 0', async () => {"+]+],+[+"test/child-worker-supervisor.test.ts",+"unit",+21,+11,+"2",+"3161",+"1017",+[+"it('runs the maintenance hook before every crash respawn', async () => {",+"it('code=0 worker exit does not count as crash; restarts immediately', async () => {",+"it('code=0 after stable 5min+ run does not reset crashCount', async () => {",+"it('budget exceeded triggers health_warn + budget_exceeded backoff', async () => {",+"it('worker_spawned + worker_exited fire on every cycle with consistent shape', async () => {",+"it('code=12 is labeled rss_watchdog and never increments crashCount', async () => {",+"it('crossing the soft budget does NOT give up; it warns and keeps retrying to the hard ceiling', async () => {",+"it('hardStopMaxCrashes=0 disables permanent give-up (retry-forever-with-backoff)', async () => {",+"it('killChild gates on liveness, not .killed (Codex #1 regression)', () => {",+"it('restartCurrentChild SIGKILLs the captured child, respawns, labels wedge_restart, leaves crashCount=0', asy",+"it('settles the run loop instead of hanging, and counts each failure as a crash', async () => withEnv({ PATH: "+]+],+[+"test/chronicle-extract.test.ts",+"unit",+22,+1,+"4",+"1588",+"199",+[+"test('defaultJudge surfaces llm_unavailable (source contract, #2608)', async () => {"+]+],+[+"test/chunkers/code-bash.test.ts",+"unit",+5,+0,+"1",+"697",+"78",+[]+],+[+"test/claude-cli-recipe.test.ts",+"unit",+38,+19,+"38",+"368",+"1162",+[+"test('getRecipe returns chat + expansion Recipe with the documented models', async () => {",+"test('parses <use_tools> block into LanguageModelV2 tool-call content', async () => {",+"test('#4155: mints a fresh id per call \u2014 two identical envelopes yield distinct ids', async () => {",+"test('#4155: prompt protocol no longer asks the model to invent an id (source-shape pin)', () => {",+"test('parses multiple parallel tool calls in a single block', async () => {",+"test('anchors on the real block when the tag is mentioned in prose first', async () => {",+"test('a prose mention of the CLOSE tag before the real block does not drop the call', async () => {",+"test('a literal <use_tools> tag inside a JSON string argument does not re-anchor the block', async () => {",+"test('a literal </use_tools> tag inside a JSON string argument does not terminate the block early', async () =",+"test('a malformed <use_tools> block is discarded as prose AND reported on stderr', async () => {",+"test('synthesizes an id when the model omits it', async () => {",+"test('returns text-only stop when tools are offered but model declines to call any', async () => {",+"test('argv includes --disable-slash-commands + --system-prompt and cwd is the dedicated tmpdir', async () => {",+"test('scrubs ANTHROPIC_* credentials and cloud-auth backend switches from the child env (subscription-only aut",+"test('non-zero exit with a result envelope on stdout surfaces a typed API error', async () => {",+"test('non-zero exit with non-JSON stdout falls back to the raw blob message', async () => {",+"test('non-zero exit with a SUCCESS envelope falls back to the blob message with stderr', async () => {",+"test('non-zero exit keeps the raw blob behind a --- raw --- marker (auth-looking stdout never classifies)', as",+"test('exit 0 + is_error + api_error_status surfaces the same typed API error', async () => {"+]+],+[+"test/cli-cwd-dotenv-quarantine.test.ts",+"unit",+36,+27,+"1",+"13818",+"1091",+[+"test(`${label}: gbrain --version from the hostile dir runs no code and refuses (fail-closed)`, async () => {",+"test('control: the same module exported from the shell (absolute path) IS loaded', async () => {",+"test('fail-closed: a cwd .env assigning GBRAIN_GUARDRAILS_MODULE (operator also exported one) refuses to run \u2014",+"test('control: an exported GBRAIN_GUARDRAILS_MODULE survives when the cwd .env assigns a DIFFERENT protected k",+"test('the operator-owned $GBRAIN_HOME/.gbrain/.env IS honored as the home for GBRAIN_GUARDRAILS_MODULE', async",+"test('a cwd .env cannot relocate GBRAIN_HOME to smuggle in its own .gbrain/.env: quarantined BEFORE the config",+"test.skipIf(!GIT_BIN)('control: without preflight the planted git config runs the script and the TLS knob is l",+"test.skipIf(!GIT_BIN)('with preflight: git never sees the injection, dropped keys are ABSENT (not \"\"), cwd + a",+"test.skipIf(!GIT_BIN)(`forged marker (${label}) planted in the .env does not suppress the hop`, async () => {",+"test.skipIf(!GIT_BIN)('harness self-check: a planted JSON marker really lands in process.env (no preflight)', ",+"test.skipIf(!GIT_BIN)('depth 2: a hopped process that spawns gbrain again from the hostile cwd hops once more ",+"test.skipIf(!GIT_BIN || !SCRIPT_BIN)('Ctrl-C with a controlling terminal but all three stdio non-tty: the wrap",+"test(\"through cli.ts: SIGTERM to the wrapper \u2014 the wrapper outlives the child's graceful exit(0), relays 0, th",+"test('SIGKILL on the wrapper: the re-run notices within seconds, exits (137) and removes the neutral dir the w",+"test.skipIf(!GIT_BIN)('a planted HOME (HOME unset at spawn) is dropped AND the re-run gets the real home back ",+"test.skipIf(!GIT_BIN)(\"an exported HOME shadowed by a .env assignment (key-presence false drop) comes back as ",+"test.skipIf(!GIT_BIN)('the re-run preserves the dev-runtime execArgv (--smol) across the hop', async () => {",+"test.skipIf(!GIT_BIN)(`a relative runtime path survives the hop: ${label} \u2192 loads in the parent AND the re-run",+"test.skipIf(!GIT_BIN)('control: an absolute --preload path is passed through unchanged (still loads twice)', a",+"test.skipIf(!GIT_BIN)('a relative TMPDIR planted by the .env is quarantined before the neutral dir is made; th",+"test.skipIf(!GIT_BIN)('with preflight: XDG_CONFIG_HOME is quarantined and git from the original cwd does NOT r",+"test('$GBRAIN_HOME/.gbrain as cwd: its .env is honored, no quarantine warning, exit 0', async () => {",+"test('hostile variant: a checkout whose .env assigns GBRAIN_HOME to manufacture the collision is still quarant",+"test('forged home: cwd = <hostile>/.gbrain whose .env assigns HOME (HOME + GBRAIN_HOME unset at spawn) \u2014 modul",+"test('bun src/cli.ts from a dir whose bunfig.toml has a top-level preload: the preload RUNS (Bun, before gbrai",+"test('a re-run whose original cwd vanished aborts with a clear error (exit 1)', async () => {",+"test('a re-run with a live original cwd chdirs back and proceeds (exit 3)', async () => {"+]+],+[+"test/cli-force-exit-teardown-arming.test.ts",+"unit",+1,+1,+"0",+"170",+"55",+[+"test('no timer arming exists between op-dispatch setup and the try; the deadline arms inside finishCliTeardown"+]+],+[+"test/cli-stdout-delivery.test.ts",+"unit",+17,+2,+"1",+"17469",+"523",+[+"test('bounded tail drain (D2): a stalled-open reader cannot hang the exit past GBRAIN_STDOUT_DRAIN_DEADLINE_MS",+"test('direct process.exit: a stalled-open reader cannot wedge the sync drain past GBRAIN_STDOUT_DRAIN_DEADLINE"+]+],+[+"test/cli.test.ts",+"unit",+24,+18,+"5",+"8017",+"324",+[+"test('imports operations from operations.ts', () => {",+"test('builds cliOps map from operations', () => {",+"test('CLI_ONLY set contains expected commands', () => {",+"test('reindex is in CLI_ONLY (does not get \"Unknown command\")', () => {",+"test('has formatResult function for CLI output', () => {",+"test('every handleCliOnly top-level case label is reachable via CLI_ONLY', () => {",+"test('cli.ts no longer uses a replacer-less stringify on the normalize path', () => {",+"test('ask alias maps to query in source', () => {",+"test('ask does NOT appear in --tools-json output', async () => {",+"test('--version outputs version', async () => {",+"test('unknown command prints error and exits 1', async () => {",+"test('per-command --help prints usage without DB connection', async () => {",+"test('upgrade --help prints usage without running upgrade', async () => {",+"test('sync --help prints sync-specific usage block without running sync (v0.37 D.4)', async () => {",+"test('doctor --help short-circuits CLI-only dispatch without diagnostics', async () => {",+"test('init --help short-circuits CLI-only dispatch without writing config', async () => {",+"test('--help prints global help', async () => {",+"test('--tools-json outputs valid JSON with operations', async () => {"+]+],+[+"test/code-retrieval-harness.test.ts",+"unit",+26,+1,+"1",+"200",+"245",+[+"test('parses the v0.34 baseline questions.json', () => {"+]+],+[+"test/codex-plugin-manifest.test.ts",+"unit",+42,+0,+"0",+"3181",+"595",+[]+],+[+"test/company-brain-connect-cli.serial.test.ts",+"serial",+3,+2,+"3",+"21474",+"128",+[+"test('requires explicit destinations and does not reinterpret a false consent flag', () => {",+"test('previews without consent, then verifies the full fictional source and keeps config/files unchanged', asy"+]+],+[+"test/company-brain-demo.test.ts",+"unit",+2,+2,+"2",+"10506",+"52",+[+"test('runs actual typed import and graph extraction with providers disabled', async () => {",+"test('CLI produces one JSON result without a configured brain', () => {"+]+],+[+"test/company-brain-inspect-cli.test.ts",+"unit",+7,+4,+"3",+"6980",+"126",+[+"test('inspects without opening a configured unreachable database or changing source content', async () => {",+"test('writes only an explicitly requested private plan and never overwrites it', async () => {",+"test('help is database-free and thin clients refuse before inspection', async () => {",+"test('unknown flags keep the same versioned JSON and usage exit contract', async () => {"+]+],+[+"test/company-brain-schema.test.ts",+"unit",+8,+0,+"9",+"318",+"111",+[]+],+[+"test/compile-view.test.ts",+"unit",+14,+3,+"4",+"240",+"310",+[+"test('module source contains no wall-clock (Date.now) \u2014 anchor is content-derived', () => {",+"test('a truncated recency window keeps the NEWEST pages; boundary-timestamp rows drop deterministically', asyn",+"test('duplicate slug across sources compiles the requested source body', async () => {"+]+],+[+"test/config.test.ts",+"unit",+20,+1,+"9",+"161",+"253",+[+"test('the local redactUrl duplicate stays deleted (redaction is single-homed)', () => {"+]+],+[+"test/connection-resilience.test.ts",+"unit",+25,+3,+"0",+"190",+"332",+[+"it('PostgresEngine.executeRaw is a single-statement passthrough (no try/catch on connection errors)', () => {",+"it('PostgresEngine.reconnect() still exists for supervisor-driven recovery', () => {",+"it('Supervisor still has the 3-strikes-then-reconnect path', () => {"+]+],+[+"test/context-engine-checkpoint.serial.test.ts",+"serial",+12,+1,+"12",+"504",+"534",+[+"it('F5/CK9 drift guard: hook.ts sanitizeSessionId, corpus-segments safeIdComponent, and sanitizeEngineSessionI"+]+],+[+"test/contextual-retrieval-service-pure.test.ts",+"unit",+25,+1,+"4",+"511",+"566",+[+"test('uses the shared default without starting paid synopsis generation', () => {"+]+],+[+"test/conversation-facts-type-allowlist-drift.test.ts",+"unit",+18,+7,+"3",+"3769",+"354",+[+"test('extract-conversation-facts.ts no longer hand-copies any type list; re-exports from the leaf', () => {",+"test('doctor.ts: no longer imports ALLOWED_TYPES (all call sites peeled)', () => {",+"test('doctor/checks/conversation-coverage.ts: the peeled coverage check derives from the leaf', () => {",+"test('doctor/checks/search-eval.ts: the peeled backlog check derives from the leaf too', () => {",+"test('jobs.ts: the extract-conversation-facts handler filters job.data.types against ALLOWED_TYPES', () => {",+"test('jobs.ts: imports ALLOWED_TYPES + AllowedType from the leaf exactly once', () => {",+"test('sources.ts: FACTS_BACKFILL_ALLOWED imports ALLOWED_TYPES from the leaf', () => {"+]+],+[+"test/cross-modal-eval-cli.test.ts",+"unit",+13,+0,+"3",+"177",+"195",+[]+],+[+"test/cycle-abort.test.ts",+"unit",+13,+10,+"5",+"480",+"251",+[+"test('runCycle bails on pre-aborted signal', async () => {",+"test('runCycle bails mid-flight when signal fires between phases', async () => {",+"test('handler registration passes signal to runCycle', async () => {",+"test('worker.ts has force-eviction safety net after timeout', async () => {",+"test('cycle.ts has checkAborted calls between phases', async () => {",+"test('cycle.ts threads opts.signal into every long phase + guards the success stamp', async () => {",+"test('every long phase core checks isAborted in its batch loop', async () => {",+"test('cycle.ts forwards cycleSignal into the synthesize and patterns phase opts', async () => {",+"test('synthesize threads its signal through judge, inline drain, and completion wait', async () => {",+"test('patterns sibling threads the same signal through inline drain, wait, and reverse-write', async () => {"+]+],+[+"test/cycle-drain-renewal.test.ts",+"unit",+7,+3,+"1",+"416",+"126",+[+"test('the renewTimer interval is guarded and routes through runDrainRenewalTick', () => {",+"test('the handler invocation carries its own chat phase (worker.ts #4218 parity)', () => {",+"test('withRefreshingLock aborts a per-tick signal into handle.refresh and guards re-entrancy', () => {"+]+],+[+"test/cycle-pack-gating.test.ts",+"unit",+21,+14,+"1",+"199",+"207",+[+"test('cycle.ts source includes extract_atoms in NEEDS_LOCK_PHASES', () => {",+"test('cycle.ts source includes synthesize_concepts in NEEDS_LOCK_PHASES', () => {",+"test('cycle.ts dispatch for extract_atoms calls packDeclaresPhase', () => {",+"test('cycle.ts dispatch for synthesize_concepts calls packDeclaresPhase', () => {",+"test('packDeclaresPhase helper function exists in cycle.ts', () => {",+"test('packDeclaresPhase reads phases from active pack manifest (NOT extends chain)', () => {",+"test('packDeclaresPhase fail-open: returns false on catch (no thrown exceptions)', () => {",+"test('only extract_atoms + synthesize_concepts dispatch sites reference packDeclaresPhase', () => {",+"test('extract_facts dispatch does NOT consult packDeclaresPhase', () => {",+"test('calibration_profile dispatch does NOT consult packDeclaresPhase', () => {",+"test('extract_atoms not_in_active_pack skip carries the correct reason marker', () => {",+"test('synthesize_concepts not_in_active_pack uses the same marker (semantic consistency)', () => {",+"test('both skip summaries name the phases: key and a lens pack', () => {",+"test('extract_atoms skip summary keeps the drain hint', () => {"+]+],+[+"test/cycle-patterns-deadline-budget.test.ts",+"unit",+15,+7,+"3",+"1410",+"173",+[+"test('job context exposes deadlineAtMs from the claim-time timeout_at stamp', () => {",+"test('worker arms its abort timer from timeout_at when present (one absolute deadline)', () => {",+"test('autopilot-cycle, global-maintenance AND phase-wrapper handlers thread deadlineAtMs into runCycle', () =>",+"test('runCycle forwards deadlineAtMs to the patterns phase', () => {",+"test('patterns submits + waits with the CLAMPED budgets, not raw config', () => {",+"test('patterns cancels the child on wait timeout (child clock starts at ITS claim)', () => {",+"test('patterns skips honestly when the remaining budget is too small', () => {"+]+],+[+"test/cycle-patterns.test.ts",+"unit",+16,+15,+"2",+"400",+"141",+[+"test('imports queue + waitForCompletion + types', () => {",+"test('threads allowed_slug_prefixes from filing-rules JSON', () => {",+"test('reads min_evidence + lookback_days config', () => {",+"test('uses subagent_tool_executions for slug provenance (Codex #2 fix)', () => {",+"test('gates on gateway provider reachability, not ANTHROPIC_API_KEY (PR #2279)', () => {",+"test('skips when reflections below min_evidence', () => {",+"test('reverse-writes pages to disk via serializeMarkdown', () => {",+"test('runs after extract \u2014 queries fresh graph', () => {",+"test('does NOT use raw_data table (Codex #3 fix)', () => {",+"test('filters reflections by slug LIKE <source_slug_prefix>/%', () => {",+"test('orders by updated_at DESC for recency-bias', () => {",+"test('caps gather to 100 reflections (cost control)', () => {",+"test('output slug prefix is config-driven, defaulting to <output_root>/personal/patterns', () => {",+"test('source slug prefix defaults to <output_root>/personal/reflections', () => {",+"test('adds a configured output_slug_prefix to the subagent write allow-list', () => {"+]+],+[+"test/cycle-phase-deadline-drift.test.ts",+"unit",+4,+2,+"4",+"442",+"73",+[+"test('SOURCE SHAPE: no re-hardcoded 30-minute literal; the derivation stays referenced', () => {",+"test('SOURCE SHAPE: cycle.ts forwards deadlineAtMs to all THREE budgeted phases (patterns, propose_takes, synt"+]+],+[+"test/cycle/cycle-lock-ttl.test.ts",+"unit",+1,+1,+"0",+"160",+"29",+[+"test('LOCK_TTL_MINUTES === 5 in src/core/cycle.ts', () => {"+]+],+[+"test/cycle/nightly-probe-adapters.test.ts",+"unit",+7,+5,+"1",+"217",+"150",+[+"test('adapter argv shape includes --output explicitly (regression for codex finding)', () => {",+"test('runLongMemEvalForProbe builds argv with --output for output path', () => {",+"test('runLongMemEvalForProbe passes the live search config snapshot via RunOpts', () => {",+"test('returns the documented shape: {exitCode, summary}', () => {",+"test('CrossModalBatchSummary shape includes the 6 expected fields', () => {"+]+],+[+"test/cycle/regression-pr-wave-r1-r2-r4.test.ts",+"unit",+7,+2,+"3",+"375",+"150",+[+"test('R4 source-grep: src/cli.ts uses readFileSync(0, ...) not readFileSync(\"/dev/stdin\", ...)', () => {",+"test('R4 behavior: parseOpArgs reads stdin when isTTY=false and no positional content provided', () => {"+]+],+[+"test/cycle/yield-during-phase-throttle.test.ts",+"unit",+3,+1,+"3",+"2804",+"114",+[+"test('yieldDuringPhase throw is non-fatal (logged, not propagated)', async () => {"+]+],+[+"test/destructive-guard.test.ts",+"unit",+41,+16,+"3",+"7718",+"806",+[+"test('counts pages correctly for a populated source', async () => {",+"test('counts facts \u2014 a zero-page fact-holding source is data at risk, not \"safe to remove\"', async () => {",+"test('a fact-only source requires --confirm-destructive (facts gate exactly like pages)', () => {",+"test('listArchivedSources filters via the archived column, not JSONB', async () => {",+"test('gbrain#4115 \u2014 an FK-blocked source is reported and skipped; the deletable one still purges', async () =>",+"test('a soft-deleted referent alone BLOCKS the remove/purge pre-check with the retained-row guidance', async (",+"test('assessDestructiveImpact folds the referent count; formatImpact shows it', async () => {",+"test('purgeExpiredSources purges only the unreferenced expired source and reports the FK-held one as blocked',",+"test('purge block is PHYSICAL: a soft-deleted client row still blocks (FK ignores deleted_at)', async () => {",+"test('formatClientReferentsBlock lists clients + per-client revoke commands, split by liveness', () => {",+"test('degrade ladder: missing oauth_clients table \u2192 [], missing deleted_at \u2192 all referents, other errors propa",+"test('missing source_id column \u2192 [] (no column \u21d2 no FK \u21d2 no referents)', async () => {",+"test('formatImpact renders the boxed preview with the source id and counts', () => {",+"test('formatImpact renders the facts count (mirrors the page-count line)', () => {",+"test('sources remove orders the row DELETE (in-tx) BEFORE external teardown (F1 structural pin)', () => {",+"test('formatSoftDelete renders the post-archive guidance with restore command', () => {"+]+],+[+"test/detached-stderr.test.ts",+"unit",+5,+2,+"1",+"181",+"90",+[+"test('the detach spawn routes through spawnDetachedSupervisor', () => {",+"test(\"no spawn in jobs.ts hands the detached child an 'inherit' stderr\", () => {"+]+],+[+"test/distribution-import-boundary.test.ts",+"unit",+2,+1,+"1",+"175",+"93",+[+"test('every src/core/distribution/*.ts file passes the import allowlist', () => {"+]+],+[+"test/docs-mcp-deploy.test.ts",+"unit",+9,+6,+"0",+"251",+"88",+[+"test('ALTERNATIVES.md distinguishes tailnet-only Serve from public Funnel', () => {",+"test('troubleshooting covers \"needsAuth while tool calls succeed\"', () => {",+"test('documents the owner request and the existing mint endpoint', () => {",+"test('auth help points at the owner login flow without inventing a CLI command', () => {",+"test('warns against consuming the single-use nonce during verification', () => {",+"test('distinguishes login from client creation and states lifecycle limits', () => {"+]+],+[+"test/doctor-categories.test.ts",+"unit",+10,+0,+"1",+"260",+"192",+[]+],+[+"test/doctor-orphan-ratio.test.ts",+"unit",+11,+4,+"4",+"11289",+"267",+[+"test('returns informational ok on network failure (unconfigured config)', async () => {",+"test('source greps: orphan_ratio check name appears in BOTH local doctor and remote doctor', () => {",+"test('source greps: both surfaces reference the same fix command', () => {",+"test('source greps: local hint is self-fix; thin-client hint points at operator', () => {"+]+],+[+"test/doctor-volunteer-channels.test.ts",+"unit",+9,+1,+"2",+"343",+"191",+[+"test('wiring pins: the check runs on BOTH doctor paths and serve registers the delivery callback (source greps"+]+],+[+"test/doctor.test.ts",+"unit",+107,+64,+"112",+"8723",+"2075",+[+"test('dimension recovery previews existing brains without recommending reinitialization', () => {",+"test('CLI registers doctor command', async () => {",+"test('frontmatter_integrity subcheck added in v0.22.4', async () => {",+"test('subagent_capability distinguishes fallback wording for inherited tier source', async () => {",+"test('reranker_health warns on repeated unknown rerank failures', async () => {",+"test('#4648: reranker_health warns on >= 3 empty/malformed pass-throughs (named as pass-through)', async () =>",+"test('#4648: two pass-throughs stay below the threshold \u2014 no pass-through warn', async () => {",+"test('doctor --fast emits source-specific message when URL present', async () => {",+"test('doctor source contains jsonb_integrity and markdown_body_completeness checks', async () => {",+"test('jsonb_integrity check covers the four JSONB sites fixed in v0.12.1', async () => {",+"test('skill conformance derives a valid host manifest when manifest.json is absent', async () => {",+"test('doctor source contains facts_extraction_health check that iterates sources', async () => {",+"test('RLS check scans ALL public tables (no hardcoded tablename IN list near the RLS block)', async () => {",+"test('RLS check raises status=fail with quoted-identifier remediation SQL', async () => {",+"test('RLS check skips on PGLite (no PostgREST, not applicable)', async () => {",+"test('RLS check reads pg_description and recognizes the GBRAIN:RLS_EXEMPT escape hatch', async () => {",+"test('rls_event_trigger check exists, scoped after schema_version, healthy on (O,A) only', async () => {",+"test('graph_coverage hint uses canonical `gbrain extract all`, not removed verbs', async () => {",+"test('takes_weight_grid: 0 takes \u2192 ok with \"No takes yet\"', async () => {",+"test('takes_weight_grid: 100% on-grid \u2192 ok', async () => {",+"test('takes_weight_grid: >10% off-grid \u2192 fail with fix hint', async () => {",+"test('takes_weight_grid: 1-10% off-grid \u2192 warn', async () => {",+"test('takes_weight_grid: takes table missing \u2192 warn (graceful)', async () => {",+"test('local doctor source contains wedge detection alongside the existing stuck path', async () => {",+"test('wedge detection is local to doctor \u2014 no statusForVersion import (D19 anti-regression)', async () => {",+"test('multiple wedged versions chain force-retry calls with &&', async () => {",+"test('remote doctor (doctorReportRemote) also emits the force-retry hint (D14)', async () => {",+"test('last_sync_at IS NULL \u2192 fail with \"never been synced\"', async () => {",+"test('last_sync_at > 72h ago \u2192 fail with day-rounded \"Nd ago\"', async () => {",+"test('exact 72h boundary \u2192 warn (>72h strict; 72h source NOT yet fail)', async () => {",+"test('24h < last_sync_at < 72h \u2192 warn with hour-rounded \"Nh ago\"', async () => {",+"test('exact 24h boundary \u2192 ok (>24h strict)', async () => {",+"test('last_sync_at <= 24h \u2192 ok with \"synced recently\"', async () => {",+"test('future last_sync_at \u2192 warn (clock skew / corrupted timestamp)', async () => {",+"test('mixed sources (one fail + one warn) \u2192 fail with both issues listed', async () => {",+"test('executeRaw throws \u2192 outer-catch returns warn (doctor keeps running)', async () => {",+"test('env-var override: GBRAIN_SYNC_FRESHNESS_FAIL_HOURS=6 \u2192 7h-stale fails', async () => {",+"test('source.id embedded in messages even when source.name is set', async () => {",+"test('case 1: stale + HEAD match + clean tree + chunker match + localOnly=true \u2192 ok', async () => {",+"test('case 3: stale + HEAD mismatch + localOnly=true \u2192 warn (no short-circuit)', async () => {",+"test('case 6: mixed 3 sources (1 unchanged + 1 synced 5min + 1 truly stale 5d) \u2192 fail, three-bucket invariant'",+"test('doctor.ts uses summarizeCrashes \u2014 no ad-hoc worker_exited filter', async () => {",+"test('doctor.ts warn threshold dropped from >3 to >=1', async () => {",+"test('doctor.ts ok + warn messages include per-cause breakdown and clean_exits_24h', async () => {",+"test('jobs.ts supervisor status uses summarizeCrashes \u2014 same wiring as doctor', async () => {",+"test('doctor source defines the stub_guard_24h check', async () => {",+"test('WARN threshold is >10 hits/24h', async () => {",+"test('fix hint points operators at the audit log', async () => {",+"test('check reads via the dual-week-aware reader (NOT supervisor-audit pattern)', async () => {",+"test('zero hits emits no check (keeps doctor output clean on healthy brains)', async () => {",+"test('explicit search.graph_signals=false overrides mode default', async () => {",+"test('check is wired into runDoctor (source-grep)', async () => {",+"test('skipped silently when flag is already enabled', async () => {",+"test('\u22655 would-resolve AND \u226520% ratio \u2192 warn with paste-ready hint', async () => {",+"test('check is wired into runDoctor AND doctorReportRemote (source-grep)', async () => {",+"test('both checks are wired into buildChecks (source-grep)', async () => {",+"test('stale source with NO live lock \u2192 fail (blocked/wedged is not masked)', async () => {",+"test('stale source WITH a live (non-expired) lock \u2192 ok (sync in progress)', async () => {",+"test('never-synced source WITH a live lock \u2192 ok (initial sync in progress)', async () => {",+"test('never-synced source with NO lock \u2192 fail (unchanged behavior)', async () => {",+"test('a lock held PAST the staleness ceiling is wedged, not in-progress \u2192 fail', async () => {",+"test('F2: clone gone but content NEWER than last sync \u2192 warn (real work not masked)', async () => {",+"test('F5: readable clone, HEAD moved \u2192 wall-clock even with old content', async () => {",+"test('F6: three-bucket invariant holds across rescued + unchanged + stale', async () => {"+]+],+[+"test/dream-cli-flags.test.ts",+"unit",+28,+28,+"0",+"163",+"198",+[+"test('declares --input flag with file argument', () => {",+"test('declares --date / --from / --to flags', () => {",+"test('validates ISO date format', () => {",+"test('--input + --date conflict detection', () => {",+"test('--input implies --phase synthesize', () => {",+"test('--from > --to range validation', () => {",+"test('forwards synth fields to runCycle', () => {",+"test('totals line includes synth + patterns counters', () => {",+"test('help text documents dry-run synthesis semantics (Codex finding #8)', () => {",+"test('help text documents local-day cycle timezone configuration (#4348)', () => {",+"test('declares --source flag in argv parsing', () => {",+"test('declares --source-id alias in argv parsing', () => {",+"test('forwards resolved sourceId to runCycle', () => {",+"test('imports resolveSourceId from canonical source-resolver helper', () => {",+"test('uses the shared isResolverUserError predicate for the typed-error catch (T3 from eng review)', () => {",+"test('documents --source in --help output', () => {",+"test('preserves --help short-circuit ordering comment (IRON RULE)', () => {",+"test('declares engine-null guard for --source', () => {",+"test('declares archived-source guard', () => {",+"test('declares --drain and --window flags', () => {",+"test('--drain defaults to extract_atoms and rejects other phases', () => {",+"test('drain routes through the shared helper with the resolved source (5A)', () => {",+"test('drain reports remaining + exits non-zero when incomplete', () => {",+"test('declares --once flag', () => {",+"test('rejects bare --once with no --phase (exit 2)', () => {",+"test('validates against phaseWasExplicit, captured before --input/--drain defaulting', () => {",+"test('threads onceForPhase to runCycle, gated on opts.once', () => {",+"test('documents --once in --help output', () => {"+]+],+[+"test/e2e/bootstrap-compiled-binary.serial.test.ts",+"serial",+4,+2,+"1",+"-1",+"186",+[+"test.skipIf(!built)('compiled `bootstrap render --minimal` in an empty cwd renders bundled templates', () => {",+"test.skipIf(!built)('compiled `bootstrap status --json` parses with the full phase list', () => {"+]+],+[+"test/e2e/bootstrap-real-codex.serial.test.ts",+"serial",+5,+5,+"9",+"-1",+"673",+[+"test('rendered AGENTS.md + HEARTBEAT.md name context-pack (session start) and delta (heartbeat)', async () => ",+"test('INSTALL: keyless init \u2192 interview \u2192 render \u2192 real `codex mcp add` \u2192 verify', async () => {",+"test('SMOKE: real `codex exec` \u2192 gbrain MCP \u2192 brain \u2192 seeded fact', async () => {",+"test('BOUNDARY: real `codex exec` session start \u2192 context_pack/delta over MCP', async () => {",+"test('managed block + plain user statement \u2192 unprompted remember lands the fact', async () => {"+]+],+[+"test/e2e/compile-context-pglite.test.ts",+"e2e",+13,+1,+"6",+"2354",+"329",+[+"test('dup slug across sources: the source flag compiles the right page', async () => {"+]+],+[+"test/e2e/fresh-install-pglite.test.ts",+"e2e",+6,+2,+"19",+"29181",+"372",+[+"test('bare `init --pglite`: schema sized to the new-install default (voyage-4/1024)', async () => {",+"test('init \u2192 seed page \u2192 embed: chunks have non-null embeddings, no dim mismatch', async () => {"+]+],+[+"test/e2e/install-real-hermes.serial.test.ts",+"serial",+4,+3,+"0",+"-1",+"345",+[+"test('version pin: hermes --version matches HERMES_VERSION when the CI pin is set', () => {",+"test('INSTALL: keyless init \u2192 real `hermes mcp add` handshake \u2192 config carries server + env \u2192 mcp test passes'",+"test('SMOKE: real hermes -z answers the seeded fact through the gbrain MCP server', async () => {"+]+],+[+"test/e2e/migration-flow.test.ts",+"e2e",+4,+0,+"2",+"4277",+"299",+[]+],+[+"test/e2e/persistence-http-liveness.test.ts",+"e2e",+7,+4,+"2",+"53500",+"408",+[+"test('private targets and changed source identity hide authenticated receipts immediately', async () => {",+"test.skipIf(!oldBinary)('compatible old and new owners drain original UUIDs after quiesced handoffs', async ()",+"test.skipIf(!oldBinary)(`${oldFirst ? 'old-to-new' : 'new-to-old'} owner handoff retains a real ${boundary} ro",+"test('foreign and narrowed OAuth receipts remain opaque without granting helper access', async () => {"+]+],+[+"test/e2e/postgres-driver-install.test.ts",+"e2e",+1,+1,+"0",+"306",+"84",+[+"test.skipIf(!enabled)('packed, global, upgraded and compiled distributions use vendored cancellation bytes and"+]+],+[+"test/e2e/qm-provisioning.test.ts",+"e2e",+11,+6,+"0",+"40319",+"345",+[+"test(\"alice cannot write bob's namespace or an unbound prefix\", async () => {",+"test('bob is fenced to HIS prefixes (not in eng)', async () => {",+"test('reads stay source-granular: bob CAN read chan-eng pages (documented tradeoff)', async () => {",+"test('the documented health check works on a read+write client (no admin scope)', async () => {",+"test('POST /ingest is closed to bound clients \u2014 it bypasses the op layer entirely', async () => {",+"test('/ingest still works for an unbound webhook client (deny is scoped to bound clients)', async () => {"+]+],+[+"test/e2e/remote-privacy-journeys.test.ts",+"e2e",+3,+3,+"8",+"24236",+"272",+[+"test('same-slug content readers and history retain public data and exclude private rows', async () => {",+"test('fresh query metadata and stored-report containment survive the transport', async () => {",+"test('page-visibility opt-out leaves historical Facts/Takes and report boundaries active', async () => {"+]+],+[+"test/e2e/skill-brain-first.test.ts",+"e2e",+12,+0,+"2",+"770",+"246",+[]+],+[+"test/e2e/upgrade-bun-link-arc.serial.test.ts",+"serial",+5,+3,+"3",+"-1",+"443",+[+"test('full arc: pull --ff-only THEN bun install; state + breadcrumb written; post-upgrade chained', async () =",+"test('--swap-only: swap + verify + breadcrumb, but NO post-upgrade and NO features child', async () => {",+"test('advances .gbrain/migrations/completed.jsonl for the pending migration, then no-ops on re-run', async () "+]+],+[+"test/embed-helper-migration.test.ts",+"unit",+8,+8,+"0",+"275",+"110",+[+"test('imports runSlidingPool from worker-pool helper', () => {",+"test('calls runSlidingPool at least twice (embedAll + embedAllStale paths)', () => {",+"test('pre-migration `let nextIdx = 0; async function worker()` shape is gone', () => {",+"test('pre-migration `Promise.all(Array.from({ length: numWorkers }, () => worker()))` is gone', () => {",+"test('preserves GBRAIN_EMBED_CONCURRENCY default of 20 (codex #13)', () => {",+"test('runSlidingPool call sites pass `workers: CONCURRENCY`', () => {",+"test('embedAllStale path still threads the cancellation signal into pool', () => {",+"test('failureLabel projector uses page.slug (memory bound on large brains)', () => {"+]+],+[+"test/embedding-dim-check-facts.test.ts",+"unit",+21,+3,+"2",+"190",+"257",+[+"test('doctor check uses buildFactsAlterRecipe (NOT a hand-rolled ALTER string)', () => {",+"test('insertFacts batch path uses cached castSuffix, NOT a hardcoded ::vector', () => {",+"test('cached cast suffix has a test-only reset hook for unit cases', () => {"+]+],+[+"test/eval-brainbench-e2e.slow.test.ts",+"slow",+21,+17,+"2",+"48539",+"428",+[+"test('bundled defaults resolve outside the package working directory', () => {",+"test('clean run: exit 0, --out is complete valid JSON with the glossary block', () => {",+"test('--compare against own baseline: exit 0 PASS', () => {",+"test('doctored main baseline (pretends fewer failures): exit 1 REGRESSION with named breach', () => {",+"test('--allow-regression flips the same comparison to exit 0 and records the reason', () => {",+"test('fixtures_hash mismatch without a committed baseline: exit 2 INCONCLUSIVE', () => {",+"test('empty fixtures dir: exit 2', () => {",+"test('suite filter matching zero fixtures: exit 2', () => {",+"test('malformed fixture JSON: exit 2 with the validation error named', () => {",+"test('usage error (unknown flag): exit 2 with usage', () => {",+"test('seed failure (duplicate slug across seed pages in one source): exit 2, fixture named', () => {",+"test('gate mode excludes holdout fixtures; --include-holdout scores them', async () => {",+"test('doctored current vs base: exit 1 with breaches listed', () => {",+"test('stdout parses as a full result doc with compare embedded', () => {",+"test('no config + no keys: exit 2 with an actionable message, before any run', () => {",+"test('renders verdict header + per-cell headline from the --out artifact', () => {",+"test('a fixture with a real dollar amount + out-of-range year fails the scan (gold dir scanned too)', () => {"+]+],+[+"test/eval-capture-db-plane.serial.test.ts",+"serial",+9,+3,+"5",+"562",+"239",+[+"test('reuses the merge connectEngine already did \u2014 zero extra config reads', async () => {",+"test('connectEngine still publishes its merge (the half the runtime test cannot reach)', async () => {",+"test('connectMountEngine still marks its engine as a mount engine', async () => {"+]+],+[+"test/eval-contradictions/no-valid-until-write.test.ts",+"unit",+4,+2,+"0",+"220",+"184",+[+"test('no file under src/core/eval-contradictions/ writes facts.valid_until', () => {",+"test('no src/commands/eval-suspected-contradictions* file writes facts.valid_until', () => {"+]+],+[+"test/eval-longmemeval-cli-smoke.test.ts",+"unit",+2,+0,+"0",+"6505",+"76",+[]+],+[+"test/eval-synthesize-concepts-routing.test.ts",+"unit",+6,+3,+"1",+"864",+"118",+[+"test('cli.ts carries the dedicated pre-engine branch', () => {",+"test('eval.ts re-entry branch precedes the generic qrels flow', () => {",+"test('eval synthesize-concepts --json exits 1 with the envelope, never the qrels error', () => {"+]+],+[+"test/exit-classification.test.ts",+"unit",+13,+5,+"1",+"177",+"131",+[+"it(`${site.label} uses a shared classifier helper (${site.helper})`, () => {",+"it(`${site.label} calls ${site.helper} at least once`, () => {",+"it('doctor.ts no longer has the inline `code !== 0 && code !== undefined` filter', () => {",+"it('jobs.ts no longer has the inline filter', () => {",+"it('child-worker-supervisor.ts uses helper to decide clean_exit vs crash branch', () => {"+]+],+[+"test/export-help.test.ts",+"unit",+1,+1,+"0",+"-1",+"24",+[+"test.each(['--help', '-h'])('actual export %s explains safe scope and recovery without a configured brain', he"+]+],+[+"test/extract-atoms-drain-errors.test.ts",+"unit",+16,+1,+"1",+"175",+"356",+[+"it('maps d.failures {source, error} \u2192 {source, reason} and returns them on the batch', () => {"+]+],+[+"test/extract-atoms-drain.test.ts",+"unit",+16,+5,+"2",+"181",+"281",+[+"it('runExtractAtomsDrainForSource uses cycleLockIdFor(opts.sourceId) + withRefreshingLock', () => {",+"it('runBatch derives providerFailure from failures.length + zero processed items, not r.status', () => {",+"it('does not advertise the non-existent --allow-protected flag', () => {",+"it(\"throws when result.status === 'provider_failure' instead of returning it\", () => {",+"it('still returns the deferred/skipped shape on LockUnavailableError (unchanged)', () => {"+]+],+[+"test/extract-conversation-facts-workers.test.ts",+"unit",+17,+14,+"1",+"200",+"172",+[+"test('imports runSlidingPool from worker-pool helper', () => {",+"test('imports parseWorkers + resolveWorkersWithClamp from sync-concurrency', () => {",+"test('imports withRefreshingLock + LockUnavailableError from db-lock', () => {",+"test('imports assertFactsEmbeddingDimMatchesConfig (D15 preflight)', () => {",+"test('runExtractConversationFactsCore calls resolveWorkersWithClamp', () => {",+"test('preflight fires inside runExtractConversationFactsCore body, BEFORE work loop', () => {",+"test('per-page work wrapped in withRefreshingLock (D2 + D12)', () => {",+"test('LockUnavailableError caught + pages_lock_skipped incremented (D6)', () => {",+"test('delete-orphans-first called BEFORE segment extraction (D11)', () => {",+"test('exit 3 fires when lock-busy pages remain (codex #3)', () => {",+"test('parsedArgs.workers threaded into core opts', () => {",+"test('Minion job envelope includes workers (D9 round-trip)', () => {",+"test('ExtractConversationFactsResult has pages_lock_skipped + orphan_facts_cleaned', () => {",+"test('initial result object literal initializes both counters to 0', () => {"+]+],+[+"test/extract-include-frontmatter-config.serial.test.ts",+"serial",+8,+1,+"3",+"1737",+"167",+[+"test('call sites do not literalise false; the shared helpers resolve the default', () => {"+]+],+[+"test/extract-workers.test.ts",+"unit",+10,+10,+"0",+"179",+"95",+[+"test('imports runSlidingPool from worker-pool helper', () => {",+"test('imports parseWorkers + resolveWorkersWithClamp', () => {",+"test('ExtractOpts type carries optional workers field', () => {",+"test('runExtractCore resolves workers via the PGLite-clamp wrapper', () => {",+"test('CLI runExtract parses --workers via parseWorkers (loud-fail on invalid)', () => {",+"test('all three inner loops accept the workers parameter', () => {",+"test('all three inner loops call runSlidingPool', () => {",+"test('legacy `for (let i = 0; i < files.length; i++)` per-file loops are gone', () => {",+"test('extractForSlugs (the CLI/cycle path) is migrated to the pool', () => {",+"test('CLI threads workers into runExtractCore call', () => {"+]+],+[+"test/facts-backstop-remedy-verb.test.ts",+"unit",+3,+3,+"0",+"151",+"45",+[+"test('warning does not name the nonexistent `gbrain sources update` verb', () => {",+"test('warning names the real attach remedy (`gbrain sources add ... --path`)', () => {",+"test('every `gbrain sources <verb>` the backstop recommends exists in the dispatcher', () => {"+]+],+[+"test/features.test.ts",+"unit",+12,+5,+"5",+"223",+"138",+[+"it('features registry pins the resolver-canonical name', () => {",+"it('the x-to-brain recipe declares and uses only the canonical name', async () => {",+"it('the resolver reads the same env var the recipe documents', () => {",+"it('features is in CLI_ONLY set', async () => {",+"it('help text mentions features', async () => {"+]+],+[+"test/fence-extraction.test.ts",+"unit",+18,+1,+"3",+"6159",+"276",+[+"test('import-file no longer routes fence extraction through marked (#2862)', async () => {"+]+],+[+"test/file-upload-fail-closed.test.ts",+"unit",+9,+1,+"2",+"1162",+"215",+[+"test('every files upsert merges metadata through FILES_METADATA_MERGE_SQL', () => {"+]+],+[+"test/files.test.ts",+"unit",+39,+8,+"5",+"2301",+"562",+[+"test('collectFiles skips node_modules', () => {",+"test('no repo configured: exits 1 instead of lying success', async () => {",+"test('missing --page for a git-storage file: exits 1', async () => {",+"test('file argument resolving to \".\" exits 1 with a clear error, not a filesystem crash', async () => {",+"test('file argument resolving to \"..\" exits 1 with a clear error, not a filesystem crash', async () => {",+"test('rows banked under a source-owned working tree verify against that tree, not sync.repo_path', async () =>",+"test('[GUARD] no storage-dependent path uses the permissive `if (config?.storage)` form', () => {",+"test('[GUARD] verify never hardcodes its mismatch/missing counts', () => {"+]+],+[+"test/fix-wave-structural.test.ts",+"unit",+31,+31,+"0",+"196",+"408",+[+"test('hybrid.ts registers a bounded search-cache drainer', () => {",+"test('serve-http.ts uses ADMIN_ASSETS manifest when admin/dist is not next to cwd', () => {",+"test('src/admin-embedded.ts is auto-generated with file: imports', () => {",+"test('build script + CI guard exist', () => {",+"test('admin endpoint reads grantTypes / redirectUris / tokenEndpointAuthMethod from request body', () => {",+"test('phaseASchema calls runMigrateOnlyCore (in-process) + is awaited', () => {",+"test('apply-migrations skips pre-flight schema-version probe on PGLite', () => {",+"test(\"cli.ts parseOpArgs handles --no-<key> as boolean negation\", () => {",+"test('cli-force-exit.ts imports + drains the registry inside finishCliTeardown', () => {",+"test('last-retrieved.ts still exports the bounded drain + registers a drainer', () => {",+"test('all four sinks register a drainer', () => {",+"test('finishCliTeardown positioning: registry drain appears BEFORE engine disconnect', () => {",+"test('background-work.ts: Map registry, ordered drain, awaited abort, test seam', () => {",+"test('#4136 scan surfaces unrecognized_headings on both output paths', () => {",+"test('#4143 engine parity: BOTH engines call the disconnect drain', () => {",+"test('#4284 caller timeout retains ownership while the actual close drains under its watchdog', () => {",+"test('cli-force-exit.ts daemon guard excludes \"serve\"', () => {",+"test('no bare awaited engine disconnects remain in cli.ts', () => {",+"test('the pre-handler hard-deadline timer is gone (handler time is not teardown budget)', () => {",+"test('all nine swept sites route through finishCliTeardown; one exit seam', () => {",+"test('pglite-engine contains the Emscripten process.exitCode hijack', () => {",+"test('pglite-engine.ts exports classifyPgliteInitError + buildPgliteInitErrorMessage', () => {",+"test('pglite-engine.ts connect catch block routes through the classifier', () => {",+"test('connect() catch wires the WAL auto-repair seam', () => {",+"test('the repair-retry lambda stays inside the #2084 exitCode guard', () => {",+"test('no bare PGlite.create outside the wrapped engine sites', () => {",+"test('pglite-resetwal.ts carries the upstream attribution', () => {",+"test('volunteer-events registers a background-work drainer (order 4)', () => {",+"test(\"the dream cycle's purge phase invokes purgeStaleVolunteerEvents and reports the count\", () => {",+"test('integrity.ts keys seen/progress by progressKey(source_id, slug) and persists source_id', () => {",+"test('both `repoPath: src.local_path` sites in sync.ts wrap with msysToNativePath', () => {"+]+],+[+"test/helpers/agent-harness.unit.test.ts",+"unit",+46,+0,+"0",+"448",+"701",+[]+],+[+"test/hook-command.serial.test.ts",+"serial",+70,+1,+"6",+"1772",+"1518",+[+"test('hook \u2208 STARTUP_HOOK_SKIP_COMMANDS (source grep \u2014 maybeEmitUpdateMarker no-ops under NODE_ENV=test, so no"+]+],+[+"test/hook-push-spawn-env.test.ts",+"unit",+3,+3,+"0",+"220",+"45",+[+"test('the detached push child is spawned with the (quarantined) process.env, explicitly', () => {",+"test('every detached spawn in hook.ts carries an explicit env option', () => {",+"test('the git exec wrapper passes the (quarantined) process.env explicitly', () => {"+]+],+[+"test/integrations.test.ts",+"unit",+123,+0,+"3",+"211",+"860",+[]+],+[+"test/jobs-embed-background-parity.serial.test.ts",+"serial",+2,+1,+"4",+"4632",+"116",+[+"it('payload builder serializes catchUp/includeNullSignature/batchSize/priority; handler reads them', () => {"+]+],+[+"test/jobs-gateway-refresh-set.test.ts",+"unit",+5,+4,+"0",+"173",+"69",+[+"test('chronicle_extract is in the refresh set (the #3387 regression)', () => {",+"test('chronicle_extract is registered via registerBuiltinJob, not bare worker.register', () => {",+"test('every set entry has a registerBuiltinJob call site (no dead entries)', () => {",+"test('every registerBuiltinJob name is in the set (no silently-unwrapped registrations)', () => {"+]+],+[+"test/jobs-list-get-json.serial.test.ts",+"serial",+7,+1,+"2",+"1689",+"154",+[+"test('cli.ts JOBS summary lines carry [--json] (source audit)', () => {"+]+],+[+"test/jobs-thin-client-date-rehydration.test.ts",+"unit",+5,+2,+"1",+"372",+"80",+[+"test('list branch rehydrates', () => {",+"test('get branch rehydrates', () => {"+]+],+[+"test/jobs-worker-startup-recovery.test.ts",+"unit",+5,+1,+"3",+"1668",+"146",+[+"test('the work handler awaits recovery right after ensureSchema, before the worker spawns', () => {"+]+],+[+"test/lens-pack-manifests.test.ts",+"unit",+31,+2,+"2",+"193",+"276",+[+"test('declares atom page type (NEW to base)', () => {",+"test('borrows atom from creator and learning from engineer', () => {"+]+],+[+"test/link-inference-pack.test.ts",+"unit",+12,+0,+"3",+"270",+"159",+[]+],+[+"test/link-source-check-repair.test.ts",+"unit",+13,+1,+"5",+"3640",+"255",+[+"test('LINK_SOURCE_KEBAB_RE matches migration v114, pglite-schema.ts and schema.sql verbatim', () => {"+]+],+[+"test/longmemeval-embed-cache.test.ts",+"unit",+21,+1,+"2",+"644",+"472",+[+"test('the module source carries no raw NUL bytes (the separators are the \\\\0 escape)', () => {"+]+],+[+"test/loops-extract-wiring.test.ts",+"unit",+8,+3,+"3",+"348",+"102",+[+"test(\"GATEWAY_REFRESH_JOB_NAMES contains 'loops_extract'\", () => {",+"test(\"'loops_extract' is registered via registerBuiltinJob, never bare worker.register\", () => {",+"test('gbrain-base-v2.yaml declares both verbs as link_types', () => {"+]+],+[+"test/migrate-embeddings-recovery-cli.serial.test.ts",+"serial",+4,+3,+"6",+"-1",+"235",+[+"test('the shared migration contract preserves supported pacing, globals and exact numeric values', () => {",+"test.each(['apply_failed', 'probe_failed', 'incomplete', 'locked', 'refused', 'retarget_refused'] as const)('r",+"test('both actual migration CLI routes reject unsupported or malformed controls before connection, planning, o"+]+],+[+"test/migrate-stdout-clean.test.ts",+"unit",+2,+1,+"2",+"1788",+"68",+[+"test('migrate.ts contains no console.log (all migration noise goes to stderr)', () => {"+]+],+[+"test/migrate.test.ts",+"unit",+171,+19,+"7",+"8243",+"2414",+[+"test(\"v20 seeds 'default' source inheriting sync config\", () => {",+"test('v20 default source is federated=true (backward-compat)', () => {",+"test('PGLite fresh-install schema reflects v36 columns', async () => {",+"test('embedded schema (src/core/schema-embedded.ts) reflects v36 columns', async () => {",+"test('v23 backfills files.page_id scoped to default source (Codex fix)', () => {",+"test('migration v8 SQL contains idx_links_dedup_helper CREATE+DROP around the DELETE', () => {",+"test('v14 handler source delegates invalid-remnant cleanup to the shared helper (#1178)', async () => {",+"test('no DO $$ ... EXECUTE .DROP INDEX CONCURRENTLY. shape remains anywhere in migrate.ts', async () => {",+"test('every known invalid-remnant site calls dropInvalidConcurrentIndex(engine, version, indexName)', async ()",+"test('dropInvalidConcurrentIndex helper itself probes pg_index.indisvalid and issues a standalone DROP (no DO ",+"test('v66 handler source delegates invalid-remnant cleanup to the shared helper (#1178)', async () => {",+"test('dropInvalidConcurrentIndex helper itself probes pg_index.indisvalid and issues a standalone DROP (no DO ",+"test('Math.max is robust to any array order (structural check)', () => {",+"test('source contains the pre-flight check branch before plan execution', () => {",+"test('structural: setSessionDefaults exists for back-compat; resolveSessionTimeouts is the source of truth', (",+"test('runMigrationSQL uses withReservedConnection for transaction:false branch', () => {",+"test('LATEST_VERSION caught up to 48', () => {",+"test('LATEST_VERSION caught up to 51', () => {",+"test('both source-scoped indexes exist after initSchema', async () => {"+]+],+[+"test/migration-in-process.serial.test.ts",+"serial",+8,+3,+"3",+"9878",+"183",+[+"test('no schema phase still execSyncs `gbrain init --migrate-only`', () => {",+"test('every schema phase calls runMigrateOnlyCore + is awaited', () => {",+"test('NO migration orchestrator anywhere spawns `gbrain init --migrate-only`', () => {"+]+],+[+"test/migration-resume.test.ts",+"unit",+15,+6,+"9",+"257",+"178",+[+"test('v0_13_0 does not import appendCompletedMigration', async () => {",+"test('v0_13_1 does not import appendCompletedMigration', async () => {",+"test('v0_12_0 does not import appendCompletedMigration', async () => {",+"test('v0_12_2 does not import appendCompletedMigration', async () => {",+"test('v0_11_0 does not import appendCompletedMigration', async () => {",+"test('apply-migrations.ts runner writes the ledger', async () => {"+]+],+[+"test/migrations-v0_13_0.test.ts",+"unit",+7,+5,+"3",+"239",+"83",+[+"test('registered in the TS migration registry', async () => {",+"test('source does NOT reference process.execPath (Bug 1 regression)', () => {",+"test('source does NOT build commands from a GBRAIN constant (Bug 1 regression)', () => {",+"test('phases use in-process schema + bare `gbrain` subprocess (v0.41.37.0 #1605)', () => {",+"test('phase commands never reference `bun` or `.ts` paths (Bug 1 regression)', () => {"+]+],+[+"test/migrations-v0_14_0.test.ts",+"unit",+8,+4,+"4",+"298",+"108",+[+"test('v0_14_0 does NOT write the ledger directly', async () => {",+"test('schema-embedded.ts has max_stalled DEFAULT 5', async () => {",+"test('pglite-schema.ts has max_stalled DEFAULT 5', async () => {",+"test('schema.sql has max_stalled DEFAULT 5', async () => {"+]+],+[+"test/migrations-v0_22_4.test.ts",+"unit",+9,+4,+"5",+"254",+"149",+[+"test('phaseASchema is a no-op (returns complete with the no-changes hint)', async () => {",+"test('exports paths used for audit + pending-host-work outputs', async () => {",+"test('dotted migration filename references \u2014 emit-todo entries point at v0.22.4.md', async () => {",+"test('phaseCEmitTodo writes per-source entries with the right shape', async () => {"+]+],+[+"test/model-id.test.ts",+"unit",+27,+2,+"1",+"172",+"221",+[+"test('leading separator is not coerced even with a custom default provider', () => {",+"test('hasAnthropicKey is defined exactly once (the shared helper), not re-copied', () => {"+]+],+[+"test/model-pricing.test.ts",+"unit",+30,+0,+"5",+"196",+"273",+[]+],+[+"test/models-doctor-embed.test.ts",+"unit",+3,+3,+"0",+"202",+"50",+[+"test(\"ProbeResult.touchpoint declares 'embedding_reachability' (codex #7)\", () => {",+"test('probeEmbeddingReachability uses embed() with inputType query + abort signal (codex #6)', () => {",+"test('runModels gates embedding reachability on config-probe ok (codex #8)', () => {"+]+],+[+"test/openclaw-plugin-manifest.test.ts",+"unit",+12,+1,+"1",+"175",+"156",+[+"it('declares the id required by OpenClaw plugin installs', () => {"+]+],+[+"test/operations-trust-boundary.test.ts",+"unit",+21,+3,+"6",+"5111",+"612",+[+"test('find_orphans / get_recent_salience / find_anomalies hide private pages from remote callers (read-leak cl",+"test('export walk attributes the full canonical surface (guard against a vacuous pass)', async () => {",+"test('every op contributed by a flagged module is localOnly or explicitly exempt', async () => {"+]+],+[+"test/persistence-activation.test.ts",+"unit",+6,+1,+"12",+"6355",+"136",+[+"test('actual CLI activation delegates through the verified owner while disk PGLite remains open', () => fixtur"+]+],+[+"test/persistence-file-import.test.ts",+"unit",+6,+3,+"14",+"44494",+"210",+[+"test('fresh public init imports a directory and a file, reads them, and refuses skill publication', async () =",+"test('managed directory import writes through, routes the source, resumes idempotently and does not queue embe",+"test('a committed import replays the durable cursor when checkpoint cleanup was interrupted', async () => with"+]+],+[+"test/persistence-image-import.serial.test.ts",+"serial",+3,+0,+"8",+"3869",+"106",+[]+],+[+"test/pglite-engine.test.ts",+"unit",+110,+1,+"4",+"5336",+"1541",+[+"test('pglite-engine.ts source contains the wrap with #223 hint and nested original error', async () => {"+]+],+[+"test/pglite-repair-command.serial.test.ts",+"serial",+14,+1,+"2",+"3251",+"500",+[+"test('uses the shared confirm-prompt helper, not a local reimplementation', () => {"+]+],+[+"test/pglite-wal-repair.serial.test.ts",+"serial",+6,+3,+"3",+"10900",+"200",+[+"test('gate negative: a REAL wasm-abort with the cooldown gate active refuses repair \u2014 no new backup, honest sk",+"test('gate negative: symlinked data dir \u2014 Emscripten refuses the mount with a NAMED error, repair never fires'",+"test('gate shape: the seam only runs for wasm-abort + persistent dataDir (structural pin)', () => {"+]+],+[+"test/phantom-redirect-per-source-lock.test.ts",+"unit",+3,+2,+"1",+"189",+"46",+[+"test('IRON-RULE: import line uses syncLockId, not bare SYNC_LOCK_ID', () => {",+"test('IRON-RULE: acquireLockWithRetry call passes syncLockId(sourceId)', () => {"+]+],+[+"test/postgres-engine-singleton-ownership.test.ts",+"unit",+7,+7,+"0",+"190",+"159",+[+"test('db.connect() returns the ownership token (Promise<boolean>), not void', () => {",+"test('db.connect() borrower path returns false; creator path returns true', () => {",+"test('PostgresEngine tracks module-singleton ownership with a dedicated flag', () => {",+"test('connect() stores the ownership token from db.connect() \u2014 no separate pre-sample (TOCTOU guard)', () => {",+"test('disconnect() calls db.disconnect() ONLY when this engine owns the singleton', () => {",+"test('db.disconnect() snapshots + nulls the singleton BEFORE awaiting end() (codex #6)', () => {",+"test('reconnect() is connection-style aware: module-singleton path never tears down the shared pool (#1745)', "+]+],+[+"test/postgres-engine.test.ts",+"unit",+8,+8,+"0",+"185",+"167",+[+"test('no bare `SET statement_timeout` statement survives', () => {",+"test('searchKeyword wraps its query in a transaction (via withScopedReadTransaction alwaysTransaction)', () =>",+"test('searchVector wraps its query in a transaction (via withScopedReadTransaction alwaysTransaction)', () => ",+"test('withScopedReadTransaction uses the composable transaction when needed', () => {",+"test('both search methods use SET LOCAL for the timeout', () => {",+"test('connect() with poolSize honors resolvePrepare (PgBouncer regression guard)', () => {",+"test('neither search method clears the timeout with `SET statement_timeout = 0`', () => {",+"test('search paths filter since/until on effective_date before import-time fallback', () => {"+]+],+[+"test/private-visibility.test.ts",+"unit",+26,+1,+"7",+"1823",+"384",+[+"test('entity-card composes privatePagesFilterFragment instead of hand-rolling the predicate', () => {"+]+],+[+"test/reconcile-owner-journey.serial.test.ts",+"serial",+1,+1,+"9",+"128103",+"282",+[+"test(`${transport} resident owner: preview, resolve, pending/restart/replay, and independent remember readback"+]+],+[+"test/redos-hardening.test.ts",+"unit",+14,+3,+"4",+"178",+"140",+[+"test('redos-guard does not import node:vm (freeze regression pin)', () => {",+"test('SyncOpts carries noSchemaPack and it gates loadActivePack', () => {",+"test('begin heartbeat fires before importFile (GBRAIN_SYNC_TRACE)', () => {"+]+],+[+"test/register-client-source-normalize.test.ts",+"unit",+16,+1,+"1",+"165",+"106",+[+"test('normalized source + federatedRead reach registerClientManual in the right positions', () => {"+]+],+[+"test/regression-strict-source-id.test.ts",+"unit",+9,+6,+"2",+"247",+"116",+[+"test('patterns.ts imports validateSourceId from utils.ts', () => {",+"test('synthesize.ts imports validateSourceId from utils.ts', () => {",+"test('patterns.ts calls validateSourceId before reverse-write join (defense ordering)', () => {",+"test('synthesize.ts calls validateSourceId before reverse-write join', () => {",+"test('utils.ts source text contains no `^[a-z0-9_-]+$` regex literal', () => {",+"test('utils.ts re-exports assertValidSourceId from source-id.ts as validateSourceId', () => {"+]+],+[+"test/reindex-code-recovery.test.ts",+"unit",+8,+1,+"3",+"1253",+"114",+[+"test('reindex-code help documents --force', () => {"+]+],+[+"test/remediation-command-resolution.test.ts",+"unit",+3,+0,+"3",+"648",+"222",+[]+],+[+"test/remote-ping-status-field.test.ts",+"unit",+4,+4,+"0",+"160",+"53",+[+"test('no `.state` property reads on job objects remain', () => {",+"test('poll loop reads job.status', () => {",+"test('terminal-state check tests job.status', () => {",+"test('unpack generics type the lifecycle field as status', () => {"+]+],+[+"test/reranker-default-seam.test.ts",+"unit",+3,+1,+"2",+"156",+"31",+[+"test('gateway imports DEFAULT_RERANKER_MODEL from defaults.ts \u2014 no local alias, no literal', () => {"+]+],+[+"test/resolve-ipc-binding.test.ts",+"unit",+9,+5,+"4",+"258",+"184",+[+"it('serve --http wires bindResolveIpcForServe with teardown', async () => {",+"it('the stdio MCP path wires bindResolveIpcForServe with teardown', async () => {",+"it('an exiting serve never blind-unlinks the socket pathname (#4896)', async () => {",+"it('the pre-bind owner probe reads a connect timeout as unknown, never as a dead owner (#4896 follow-up)', asy",+"it('bootstrap verify prefers a live serve socket over self-creating one', async () => {"+]+],+[+"test/retrieval-reflex-recipe-routing.test.ts",+"unit",+5,+1,+"1",+"188",+"78",+[+"it('the install pointer is gated on the hint file existing (source guard)', () => {"+]+],+[+"test/schema-bootstrap-coverage.test.ts",+"unit",+13,+6,+"5",+"5701",+"1273",+[+"test('after bootstrap, PGLITE_SCHEMA_SQL replays without crashing on missing forward references', async () => ",+"test('parseIndexColumnReferences catches v0.27 composite second-column case', () => {",+"test('every CREATE INDEX column in PGLITE_SCHEMA_SQL is covered by CREATE TABLE or bootstrap (A2 static check)",+"test('postgres bootstrap carries the private-queue and authority ALTERs and probes (PGLite symmetry)', async (",+"test('every CREATE INDEX column in the Postgres SCHEMA_SQL blob is covered by CREATE TABLE or the Postgres boo",+"test('postgres bootstrap carries the dream_verdicts.expires_at probe + ALTER (#4657 guard symmetry)', async ()"+]+],+[+"test/schema-cli-contract.test.ts",+"unit",+7,+6,+"0",+"178",+"93",+[+"test('every new verb routes through runSchema dispatch', () => {",+"test('every new verb-handler reads parseFlags() for --json + --source', () => {",+"test('parseFlags() returns the documented shape', () => {",+"test('parseFlags accepts both --source and --source-id forms', () => {",+"test('every new verb when --json passed produces a JSON envelope', () => {",+"test('EXPERIMENTAL_VERBS set matches the documented D14 hybrid choice', () => {"+]+],+[+"test/schema-pack-best-effort.test.ts",+"unit",+7,+0,+"4",+"192",+"120",+[]+],+[+"test/schema-pack-unify-types-handler.test.ts",+"unit",+11,+2,+"5",+"5535",+"299",+[+"it('gbrain-base-v2 statically declares meeting + conversation (temporal, extractable)', () => {",+"it('jobs.ts worker registration defaults apply to false, matching the handler contract', () => {"+]+],+[+"test/schema-pack/suggest.test.ts",+"unit",+7,+1,+"2",+"194",+"188",+[+"test('the 0.5 heuristic constant and the documented 0.6 floor stay in suggest.ts together', () => {"+]+],+[+"test/scripts/check-engine-dynamic-import.test.ts",+"unit",+23,+1,+"0",+"5442",+"356",+[+"it('resolves default inputs from the guard repository', () => {"+]+],+[+"test/scripts/classify-tests.test.ts",+"unit",+8,+6,+"0",+"175",+"119",+[+"test('repo-anchored readFileSync binding attributes the referencing suite', () => {",+"test('tmpdir reads are behavioral, not structural', () => {",+"test('Bun.file reader on src/ is structural', () => {",+"test('doctor-source helper marks the suite structural', () => {",+"test('detector outside any describe attributes to file-level pseudo-suite', () => {",+"test('binding names with regex metachars ($) are escaped, not read as anchors', () => {"+]+],+[+"test/scripts/coverage-diff-gate.test.ts",+"unit",+18,+14,+"0",+"593",+"315",+[+"it(\"covered added lines \u2192 WOULD PASS, exit 0\", () => {",+"it(\"uncovered added lines below 80% \u2192 WOULD FAIL with uncovered line numbers, exit 0\", () => {",+"it(\"non-executable added lines are excluded from the denominator\", () => {",+"it(\"pass \u2192 exit 0\", () => {",+"it(\"fail \u2192 exit 1\", () => {",+"it(\"a changed file with no coverage record is ONE violation, not a physical-line count\", () => {",+"it(\"zero gate-scoped changes \u2192 explicit PASS, exit 0\", () => {",+"it(\"classify EMPTY / DOC_ONLY \u2192 gate not applicable, exit 0 even with uncovered diff\", () => {",+"it(\"exempt files are reported with their tag but never gated\", () => {",+"it(\"only-exempt changes \u2192 no gate-scoped changes, tags still reported\", () => {",+"it(\"a working-tree-only exemption entry does NOT exempt (list resolves from origin/master)\", () => {",+"it(\"degraded summary \u2192 DEGRADED banner, report-only even when enforcing\", () => {",+"it(\"[coverage-exempt:] trailer \u2192 loud bypass, exit 0 even when enforcing\", () => {",+"it(\"missing summary JSON \u2192 exit 2\", () => {"+]+],+[+"test/scripts/merge-lcov.test.ts",+"unit",+26,+14,+"0",+"1846",+"471",+[+"it(\"sums per-line hits, unions lines, regenerates counters\", () => {",+"it(\"merges absolute, repo-relative, and foreign-checkout-prefix SF paths into one record\", () => {",+"it(\"skips a malformed lcov file whole and marks degraded, keeping the good lane\", () => {",+"it(\"parseLcovText unit: unknown record types warn and are skipped without malforming\", () => {",+"it(\"missing manifest for an expected lane \u2192 degraded\", () => {",+"it(\"shard manifest with lcovCount != 1 \u2192 degraded (xargs-batching tripwire)\", () => {",+"it('requires all four nightly E2E identities with their independent multi-process LCOV counts', () => {",+"it('duplicate lane identities cannot satisfy the expected lane', () => {",+"it(\"totals/dirs/files count src/ only; out-lcov keeps every record\", () => {",+"it(\"neverLoaded inventories real src files absent from the data \u2014 count + sorted list, no percentage\", () => {",+"it(\"skips lcov.info under a coverage-merged path segment without degrading\", () => {",+"it(\"skips a direct lcov.info FILE input under a coverage-merged segment\", () => {",+"it(\"missing required args \u2192 exit 2\", () => {",+"it(\"nonexistent input path warns and marks degraded, never aborts\", () => {"+]+],+[+"test/scripts/run-unit-shard.test.ts",+"unit",+11,+0,+"0",+"1221",+"213",+[]+],+[+"test/scripts/typecheck-incremental.test.ts",+"unit",+4,+0,+"0",+"8637",+"128",+[]+],+[+"test/search/graph-signals-wire-integration.test.ts",+"unit",+3,+1,+"3",+"2405",+"107",+[+"test('hybrid.ts postFusionOpts literal threads graphSignalsEnabled from resolvedMode', async () => {"+]+],+[+"test/search/knobs-hash-reranker.test.ts",+"unit",+25,+2,+"3",+"221",+"328",+[+"test('parts[] order in source: reranker fields appear AFTER the existing 9', async () => {",+"test('v=3 additions: col= and prov= appear AFTER the reranker block', async () => {"+]+],+[+"test/serve-http-admin-route-guard.test.ts",+"unit",+4,+2,+"0",+"177",+"265",+[+"test('anti-vacuity floor: the extractor still sees the known admin surface', () => {",+"test('allowlist is not stale: every entry matches its declared unguarded occurrences', () => {"+]+],+[+"test/serve-http-github-webhook.test.ts",+"unit",+9,+1,+"1",+"623",+"114",+[+"test('legacy-only match ACKs 202 ignored before any job submission', () => {"+]+],+[+"test/serve-http-mcp-transport-cleanup.test.ts",+"unit",+2,+2,+"0",+"186",+"56",+[+"test('res.on(close) cleanup sits between transport construction and handleRequest', () => {",+"test('cleanup registers before server.connect (early-disconnect safety)', () => {"+]+],+[+"test/serve-http-metrics.test.ts",+"unit",+9,+3,+"1",+"255",+"160",+[+"test('an unauthenticated scrape gets 401, not the exposition', async () => {",+"test('tracking middleware is mounted before the first route registration', () => {",+"test('GET /metrics is gated behind requireAdmin', () => {"+]+],+[+"test/serve-service.test.ts",+"unit",+35,+17,+"2",+"242",+"657",+[+"test('reads the token at run time, sources env with set -a, prefixes PATH, cd $HOME, execs serve', () => {",+"test('bakes GBRAIN_HOME, the bun+cli.ts form, --enable-dcr, and single-quote-escapes hostile paths', () => {",+"test('an empty runtime dir produces no PATH prefix', () => {",+"test('plist: label, RunAtLoad, KeepAlive, ThrottleInterval 30, log paths, XML escaping', () => {",+"test('unit: network-online, Restart=always, RestartSec=10, start-limit, append: logs, quoting', () => {",+"test('unit: systemd specifiers are escaped \u2014 % \u2192 %% in ExecStart and both append: paths, $ \u2192 $$ in ExecStart',",+"test('creates dir 0700 + file 0600 with 64 hex chars; reuses a valid token; regenerates a malformed one', () =",+"test('linux-systemd: writes wrapper 0755 + unit 0644, daemon-reload, enable, restart, enable-linger (non-fatal",+"test('linux-systemd: enable failure surfaces as error; restart failure too; linger not attempted', async () =>",+"test('macos: the uid defaults to the running process; an OLD launchctl that does not know bootstrap/bootout fa",+"test('reads the token at RUN time, exports the env file, bakes GBRAIN_HOME, cd $HOME, execs the baked program ",+"test('missing token file \u2192 exit 1 with the re-run hint and the CLI is never executed; baked CLI gone \u2192 PATH fa",+"test('daemon-reload failure is a note (install continues); uninstall notes a disable failure, tolerates a miss",+"test('resolveServeGbrainCommand honors a compiled argv[1]; runtimeDir \".\" adds no PATH prefix; log paths hang ",+"test('renderServeSystemdUnit quotes a wrapper path carrying a double quote and a backslash exactly', () => {",+"test('a silent supervisor failure reports the exit status (null when killed); stdout is used when stderr is em",+"test('every supervisor subprocess carries a timeout: 60s for bootstrap/bootout/enable/restart/disable, 15s for"+]+],+[+"test/serve-stdin-eof-drain.test.ts",+"unit",+8,+1,+"4",+"724",+"192",+[+"test('serve.ts has no static import of serve-sync-runner', () => {"+]+],+[+"test/shared-skills-init.serial.test.ts",+"serial",+4,+1,+"5",+"33390",+"104",+[+"test('compiled CLI creates the same useful pack without runtime checkout assets', async () => {"+]+],+[+"test/shared-skills-proposal-cli.test.ts",+"unit",+1,+0,+"1",+"11097",+"43",+[]+],+[+"test/shared-skills-restore.serial.test.ts",+"serial",+10,+1,+"21",+"26315",+"323",+[+"test('explicit recovery CLI preserves brain identity but revokes old service authority', async () => {"+]+],+[+"test/shared-skills-setup.serial.test.ts",+"serial",+16,+0,+"6",+"706",+"214",+[]+],+[+"test/skillopt/deadline-and-hermetic.test.ts",+"unit",+9,+1,+"3",+"315",+"143",+[+"test('the provider doc comment does not promise it either', () => {"+]+],+[+"test/skillpack-copy.test.ts",+"unit",+19,+0,+"1",+"210",+"325",+[]+],+[+"test/skillpack-install.test.ts",+"unit",+32,+0,+"2",+"301",+"670",+[]+],+[+"test/skillpack-reference-harness.test.ts",+"unit",+15,+0,+"1",+"326",+"260",+[]+],+[+"test/skillpack-scaffold-harness.test.ts",+"unit",+22,+13,+"0",+"29543",+"435",+[+"test('defaults: coding-agent persona into HOME/.claude/skills; state under GBRAIN_HOME; idempotent re-run', ()",+"test('codex/opencode without a dest exit 2 naming the observation-run gap', () => {",+"test('unknown persona exits 2 listing the valid choices', () => {",+"test('--skill testing is refused with the recorded lane-exclusion reason [OV5]', () => {",+"test('--stub with the publish gate off exits 2 with the exact enable command [D3B preflight]', () => {",+"test('unknown --harness value exits 2 naming the valid set', () => {",+"test('removes only ledger-owned files and updates state', () => {",+"test('all-additions selection refuses with a clear error; --stub and --dest are refused', () => {",+"test('skillpack status renders the installed-bridges section', () => {",+"test('stub preflight gate 2: an unservable slug is refused with the skills_dir hint', () => {",+"test('reference --harness: positional slug lens + apply guard requires a single skill', () => {",+"test('active shared brain installs a live source-bound router only after follow approval and cleanly opts out'",+"test('stub preflight honors the DB config plane (gbrain config set, no config.json key)', () => {"+]+],+[+"test/skillpack-scaffold.test.ts",+"unit",+14,+0,+"1",+"223",+"296",+[]+],+[+"test/snapshot-shape-guard.test.ts",+"unit",+11,+0,+"2",+"433",+"163",+[]+],+[+"test/sources-webhook.test.ts",+"unit",+12,+2,+"1",+"187",+"148",+[+"test('GitHub sig format is sha256=<64 hex chars>', () => {",+"test('opts into extraction before the pushed commit is consumed', () => {"+]+],+[+"test/spend-off-switch.test.ts",+"unit",+5,+3,+"1",+"614",+"53",+[+"test('reindex-code: --max-cost off proceeds past the confirmation gate', async () => {",+"test('onboard: --max-usd off lifts the --auto missing-cap refusal', async () => {",+"test('enrich: uncapped path maps the Infinity sentinel to no BudgetTracker ceiling', async () => {"+]+],+[+"test/supervisor-configuration-blocked.test.ts",+"unit",+21,+4,+"7",+"7874",+"628",+[+"test.skipIf(process.platform === 'win32')('without tini, killing the owner process group also kills its manage",+"test('unwritable managed status fails publication before admission and follows ordinary bounded retry', async ",+"test('an old worker resumed by the timeout signal cannot publish ready or admit during the kill grace', async ",+"test.skipIf(process.platform === 'win32')(`${kind} survives Restart=always, retains singleton and recovers onl"+]+],+[+"test/supervisor.test.ts",+"unit",+23,+2,+"7",+"4562",+"632",+[+"it('auto-sizes --max-rss when no explicit cap is given', async () => {",+"it('the hook bounds recovery in a Promise.race with a 30_000ms timeout', () => {"+]+],+[+"test/sync-failures.test.ts",+"unit",+65,+8,+"58",+"281",+"682",+[+"test('doctor source contains sync_failures check', async () => {",+"test('both doctor surfaces use the shared decideSyncFailureSeverity', async () => {",+"test('runSync parses --skip-failed and --retry-failed flags', async () => {",+"test('runSync acks pre-existing unacked failures up-front when --skip-failed is set', async () => {",+"test('performSync gates the bookmark through the shared failure ledger', async () => {",+"test('performFullSync routes failures through the same shared gate', async () => {",+"test('runImport returns RunImportResult and records via the ledger', async () => {",+"test('both blocked gates name the files and hint at frontmatter validate', async () => {"+]+],+[+"test/sync-include-hidden.test.ts",+"unit",+7,+1,+"2",+"490",+"128",+[+"test('the hoisted syncOpts literal carries includeHidden', () => {"+]+],+[+"test/sync.test.ts",+"unit",+85,+1,+"25",+"8892",+"1277",+[+"test('src/commands/sync.ts does not wrap the add/modify loop in engine.transaction()', async () => {"+]+],+[+"test/thin-client-routing-audit.test.ts",+"unit",+13,+13,+"0",+"163",+"176",+[+"test('THIN_CLIENT_REFUSED_COMMANDS set declaration is intact', () => {",+"test(`'${command}' is in THIN_CLIENT_REFUSED_COMMANDS`, () => {",+"test(`'${command}' has a hint in THIN_CLIENT_REFUSE_HINTS`, () => {",+"test('every v0.31.1-era REFUSED command is still in the set (no accidental removals)', () => {",+"test('src/commands/recall.ts imports callRemoteTool + isThinClient', () => {",+"test('src/commands/recall.ts: recall routing branch calls callRemoteTool with op=\"recall\"', () => {",+"test('src/commands/recall.ts: forget routing branch calls callRemoteTool with op=\"forget\"', () => {",+"test('src/commands/jobs.ts: list/get routing branches call callRemoteTool', () => {",+"test('cli.ts dispatches thin-client jobs list/get engine-free (runJobs(null, ...))', () => {",+"test('cli.ts refuses non-routable jobs subcommands on thin clients via refuseThinClient', () => {",+"test(\"'config' is in THIN_CLIENT_REFUSED_COMMANDS with a hint\", () => {",+"test(\"'jobs' is NOT in THIN_CLIENT_REFUSED_COMMANDS (partial dispatch owns it)\", () => {",+"test('jobs.ts guards the null-engine path to list/get only', () => {"+]+],+[+"test/think-embed-question-wiring.serial.test.ts",+"serial",+2,+1,+"3",+"640",+"86",+[+"test('ops/search.ts CRAG runThink call passes embedQuestion', () => {"+]+],+[+"test/timing-safe.test.ts",+"unit",+6,+1,+"1",+"229",+"52",+[+"test('IRON-RULE: serve-http.ts imports safeHexEqual from timing-safe.ts (not redefined)', () => {"+]+],+[+"test/transcript-adapters.test.ts",+"unit",+54,+18,+"13",+"483",+"1104",+[+"test('harness sessions get per-day format+hash12 slugs', () => {",+"test('identity is HASHED, never a prefix \u2014 same-prefix ids cannot collide', () => {",+"test('unknown format names every detector tried', () => {",+"test('yields one session with diagnostics on the fixture', async () => {",+"test('zero-turn file explains itself (drift signal shape)', async () => {",+"test('oversized rollout degrades to head+tail instead of throwing, keeping session_meta', async () => {",+"test('user turns from event_msg, assistant from output_text; injected preambles never leak', async () => {",+"test('messages only; model_change/custom/compaction skipped; timestamps kept', async () => {",+"test('yields sessions in start order; tool rows and empty content skipped; epoch \u2192 ISO', async () => {",+"test('user/assistant text only; system, reasoning, tools, synthetic user never leak', async () => {",+"test('missing summary.json (in-progress session / partial rsync) imports with file-mtime provenance; no drift,",+"test(\"created_at 'yesterday' is never parsed into a fabricated timestamp\", async () => {",+"test('a summary-less session outside a UUID dir gets a stable path-hash id, not the literal \"chat_history\"', a",+"test('user rows whose text sits under an unknown field are MALFORMED, not typed: expectedEmpty=false, driftFil",+"test('redaction runs on grok text the same as every other format', async () => {",+"test('empty (system-only) session explains itself and is not host-format drift', async () => {",+"test('canonical path via current_node; branches, tool nodes, and system-only convs never leak', async () => {",+"test('no raw NUL bytes in src/core/transcripts (git would flag binary, guards would skip)', () => {"+]+],+[+"test/transcription-injection.test.ts",+"unit",+2,+1,+"1",+"194",+"65",+[+"test('source uses execFileSync arg-arrays, never shell execSync', () => {"+]+],+[+"test/upgrade-skill-publish-prompt-race.test.ts",+"unit",+3,+3,+"0",+"158",+"62",+[+"test('the close listener is guarded by an `answered` flag, not unconditional', () => {",+"test('resolveAns for the answer is called strictly before rl.close() in the question callback', () => {",+"test('the [Y/n] default-yes contract is preserved: an empty (Enter-only) answer resolves true', () => {"+]+],+[+"test/upgrade.serial.test.ts",+"serial",+28,+17,+"5",+"3210",+"404",+[+"test('--help prints usage and exits 0', async () => {",+"test('-h also prints usage', async () => {",+"test('checks node_modules before binary', () => {",+"test('checks binary before clawhub', () => {",+"test('uses clawhub --version, not which clawhub', () => {",+"test('has timeout on upgrade execSync calls', () => {",+"test('return type includes bun-link variant (v0.28.5 cluster D)', () => {",+"test('does not reference npm in case labels or messages', () => {",+"test('bun-link signal walks .git/config for garrytan/gbrain match', () => {",+"test('detectBunLink does not gate on isSymbolicLink (bun resolves argv[1])', () => {",+"test('detectBunLink returns repoRoot, not a string literal', () => {",+"test('bun-link upgrade uses execFileSync for shell-injection safety', () => {",+"test('bun global upgrade passes cwd to bun update', () => {",+"test('classifyBunInstall checks repository.url AND src/cli.ts marker', () => {",+"test('squatter recovery message names both source-clone AND release-binary paths', () => {",+"test('--help prints usage', async () => {",+"test('mismatch exits nonzero, keeps the pending-upgrade cache, and records verify-target', async () => {"+]+],+[+"test/v0_37_fix_wave.serial.test.ts",+"serial",+19,+6,+"18",+"591",+"325",+[+"test('A.1: getPGLiteSchema() default-args produce a vector(1024) column', async () => {",+"test('A.2: getPostgresSchema() default-args produce a vector(1024) column', async () => {",+"test('A.2: getPostgresSchema() with explicit args still routes the override', async () => {",+"test('CDX2-12: sync is in CLI_ONLY_SELF_HELP', async () => {",+"test('reinit-pglite is registered in CLI_ONLY + CLI_ONLY_SELF_HELP', () => {",+"test('embeddingMismatchMessage PGLite branch recommends `gbrain reinit-pglite`', async () => {"+]+],+[+"test/v0_37_gap_fill.serial.test.ts",+"serial",+17,+5,+"10",+"5408",+"574",+[+"test('schema=1536 + gateway=Voyage/1024 \u2192 runEmbedCore throws EmbeddingDimMismatchError before transport fires",+"test('source-text grep: both sync.ts catch sites detect EmbeddingDimMismatchError', () => {",+"test('source-text grep: tip mentions --no-embed at the hint site', () => {",+"test('source-text grep: loadRecommendationContext is provider-aware via the shared helper', () => {",+"test('refuses on non-PGLite engine', async () => {"+]+],+[+"test/voyage-response-cap.test.ts",+"unit",+6,+6,+"0",+"239",+"98",+[+"test('MAX_VOYAGE_RESPONSE_BYTES constant is declared at 256 MB (D2 sizing)', async () => {",+"test('Layer 1: Content-Length pre-check fires BEFORE resp.clone().json() (D10 OOM defense)', async () => {",+"test('Layer 1 throws on Content-Length over the cap (not silent return)', async () => {",+"test('Layer 2: per-embedding base64 cap fires inside the json.data iteration', async () => {",+"test('inbound try/catch rethrows VoyageResponseTooLargeError (Codex P3 follow-up)', async () => {",+"test('comment thread documents both layers + the cap-sizing decision', async () => {"+]+],+[+"test/worker-lock-renewal-shape.test.ts",+"unit",+18,+0,+"1",+"522",+"263",+[]+],+[+"test/worker-supervised-db-probe.test.ts",+"unit",+5,+1,+"2",+"1885",+"185",+[+"it('structural: DB probe is NOT gated on !isSupervisedChild; stall detection IS', () => {"+]+]+]\ No newline at end of filediff --git a/docs/test-audit/2026-09-29/lane-source-grep/probes.log b/docs/test-audit/2026-09-29/lane-source-grep/probes.lognew file mode 100644index 0000000000..9588712dfd--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-source-grep/probes.log@@ -0,0 +1,65 @@+### baseline voyage+ test/voyage-response-cap.test.ts => 6 pass 0 fail+ test/ai/gateway.test.ts => 40 pass 0 fail+### P1a rename const MAX_VOYAGE_RESPONSE_BYTES->VOYAGE_RESPONSE_CAP_BYTES (behavior-preserving)+ test/voyage-response-cap.test.ts => 4 pass 2 fail+ test/ai/gateway.test.ts => 40 pass 0 fail+### P1b break rethrow (instanceof && false) [ 1 file changed, 1 insertion(+), 1 deletion(-)]+ test/voyage-response-cap.test.ts => 5 pass 1 fail+ test/ai/gateway.test.ts => 39 pass 1 fail+### P1c cap doubled to 512MB [ 1 file changed, 1 insertion(+), 1 deletion(-)]+ test/voyage-response-cap.test.ts => 6 pass 0 fail+ test/ai/gateway.test.ts => 38 pass 2 fail+### baseline remote+ test/remote-ping-status-field.test.ts => 4 pass 0 fail+ test/remote-cli.test.ts => 9 pass 0 fail+### P2a poll loop reads job.state (the original bug) [ 1 file changed, 6 insertions(+), 6 deletions(-)]+ test/remote-ping-status-field.test.ts => 3 pass 1 fail+ test/remote-cli.test.ts => 6 pass 3 fail+### P2b behavior-preserving String(job.status) wrap in terminal check [ 1 file changed, 1 insertion(+), 1 deletion(-)]+ test/remote-ping-status-field.test.ts => 3 pass 1 fail+ test/remote-cli.test.ts => 9 pass 0 fail+### baseline dream+ test/dream-cli-flags.test.ts => 28 pass 0 fail+ test/dream.test.ts => 45 pass 0 fail+### P3a rename local phaseWasExplicit->explicitPhaseGiven (behavior-preserving) [ 1 file changed, 3 insertions(+), 3 deletions(-)]+ test/dream-cli-flags.test.ts => 26 pass 2 fail+ test/dream.test.ts => 45 pass 0 fail+### P3b bare --once no longer rejected (guard made unreachable) [ 1 file changed, 1 insertion(+), 1 deletion(-)]+ test/dream-cli-flags.test.ts => 27 pass 1 fail+ test/dream.test.ts => 40 pass 5 fail+### baseline fix-wave/cli-args/classifier+ test/fix-wave-structural.test.ts => 31 pass 0 fail+ test/cli-args.test.ts => 12 pass 0 fail+ test/pglite-init-classifier.test.ts => 33 pass 0 fail+### P4a rename positiveDef->boolDef in parseOpArgs (behavior-preserving) [ 1 file changed, 2 insertions(+), 2 deletions(-)]+ test/fix-wave-structural.test.ts => 30 pass 1 fail+ test/cli-args.test.ts => 12 pass 0 fail+### P4b --no-<bool> sets true (behavior break) [ 1 file changed, 1 insertion(+), 1 deletion(-)]+ test/fix-wave-structural.test.ts => 30 pass 1 fail+ test/cli-args.test.ts => 11 pass 1 fail+### baseline embed+ test/embed-helper-migration.test.ts => 8 pass 0 fail+ test/embed.serial.test.ts => 52 pass 0 fail+### P5a rename lambda param page->p in failureLabel (behavior-preserving) [ 1 file changed, 1 insertion(+), 1 deletion(-)]+ test/embed-helper-migration.test.ts => 7 pass 1 fail+ test/embed.serial.test.ts => 52 pass 0 fail+### P5b embedAll pool forced serial (workers: 1) [ 1 file changed, 1 insertion(+), 1 deletion(-)]+ test/embed-helper-migration.test.ts => 7 pass 1 fail+ test/embed.serial.test.ts => 51 pass 1 fail+### P5c default concurrency 20->4 in embedAll [ 1 file changed, 1 insertion(+), 1 deletion(-)]+ test/embed-helper-migration.test.ts => 8 pass 0 fail+ test/embed.serial.test.ts => 52 pass 0 fail+### baseline connection-resilience+ test/connection-resilience.test.ts => 25 pass 0 fail+ test/exit-classification.test.ts => 17 pass 0 fail+### P6a production classifyWorkerExit always clean_exit [ 1 file changed, 1 insertion(+), 1 deletion(-)]+ test/connection-resilience.test.ts => 25 pass 0 fail+ test/exit-classification.test.ts => 11 pass 6 fail+### P6b supervisor degraded/reconnect branch made unreachable (keeps '>= 3' literal) [ 1 file changed, 1 insertion(+), 1 deletion(-)]+ test/connection-resilience.test.ts => 25 pass 0 fail+ test/supervisor.test.ts => 23 pass 0 fail+ test/supervisor-configuration-blocked.test.ts => 22 pass 0 fail+### P7a EXPERIMENTAL_VERBS emptied (behavior change: no verb tagged experimental) [ 1 file changed, 1 insertion(+), 1 deletion(-)]+ test/schema-cli-contract.test.ts => 7 pass 0 fail+ test/schema-cli.test.ts => 15 pass 0 faildiff --git a/docs/test-audit/2026-09-29/lane-source-grep/source-grep.md b/docs/test-audit/2026-09-29/lane-source-grep/source-grep.mdnew file mode 100644index 0000000000..e43710398d--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-source-grep/source-grep.md@@ -0,0 +1,193 @@+# Test audit — LANE=source-grep (gbrain @ 2ede415, read-only)++Method: openclaw `test-audit` skill (discovery mode), gbrain AGENTS.md / CLAUDE.md / docs/TESTING.md+"Coverage responsibilities before consolidation". Every mutation probe below was a temporary edit to+`src/**`, followed by `bun test <file>` on the grep test and its claimed owner, then `git checkout -- <file>`.+The tree was verified clean afterwards (`git status --short` → empty). Raw probe log:+`~/.capy/work/test-audit/probes.log`. Inventory artefacts: `inventory.tsv`, `pertest.json`,+`struct_src.json` in the same directory.++Caveat on history: the checkout is a **shallow clone (50 commits)**. Every older test file shows its+last change as the boundary commit `d9909cd` (2026-08-28), so `git log -S` and blame can't go past that+point. Provenance below comes from the issue and version references in each file's header.++Caveat on cost: `scripts/ubicloud/weights.json` records **per-file** ms. A pure source-grep file costs+150–275 ms, and most of that is bun's per-file startup. Unit compute totals 3,985 s over 1,953 files, so+**deleting source-grep tests saves almost no compute**. The payoff is less refactor friction, fewer+tests that give false confidence (see the probes), and less LOC. Treat ms as a side benefit only.++---++## 1. Inventory and sizing++| Measure | Count |+|---|---|+| Test files that read `src/**` (or `admin/src`) as text | **198** (unit 159, serial 30, e2e 8, slow 1) |+| Individual tests that read src and then assert on the text (my per-test scan) | **871** |+| Files where most tests are source greps (per-test scan) | **84** files / 608 tests |+| Repo classifier (`scripts/structural-suites.tsv`, suite-level; src readers only) | 128 files / 1,007 cases; 70 majority-structural files / 685 cases |+| Scanner false positives in the 84 (these read src for a path or spawn the CLI; they're behavioral) | ~22 (e.g. export-help, company-brain-*, e2e/qm-provisioning, e2e/remote-privacy-journeys, eval-brainbench-e2e.slow, scripts/merge-lcov, scripts/coverage-diff-gate, skillpack-scaffold-harness, cli-cwd-dotenv-quarantine, child-worker-supervisor, claude-cli-recipe, reconcile-owner-journey) |+| **Lane corpus (real source-grep files)** | **~92 files** (62 majority-grep + ~30 behavior files with 1–5 embedded grep tests) |++### Class counts (lane corpus, ~92 files)++| Class | Files | Tests | Notes |+|---|---|---|---|+| (1) Duplicated at the owning boundary, or detects nothing → delete/trim | **8** (4 verified by probe, 2 by reading the owner, 1 guard overlap, 1 low-value pins) | **~61** | Details in §2 |+| (2) Cheapest independent guard (architecture, security, default, packaging, drift) → keep | **~62** | ~420 | ~20 read in full; the rest classified from test names (§4) |+| (3) Should be a behavior test at the real boundary → rewrite | **~22** | ~150 | Includes 2 real **coverage gaps** found by probes (§3) |++**Estimated savings from class 1 alone:** ~**640 test LOC**, **3 whole files** (voyage-response-cap,+remote-ping-status-field, embed-helper-migration), and ~**674 ms** of unit compute. No production+test-only seams are unlocked, because none of these tests need an export that production lacks.+Class-3 rewrites are about LOC-neutral but convert ~150 implementation-coupled pins into real checks.++### Overlap with `scripts/guards-manifest.tsv` / `bun run verify`++Only one source-grep test duplicates a verify guard outright.+`test/worker-lock-renewal-shape.test.ts` › "launchJob calls runLockRenewalTick" re-asserts invariant 2 of+`scripts/check-worker-lock-renewal-shape.sh` (`grep -q runLockRenewalTick`), and the test's own header+says "pinned here + the CI guard". The other scanner guards (search-path, jsonb, pg-url-redaction,+worker-pool-atomicity, no-legacy-getconnection, operations-filter-bypass, …) target different patterns+from the src-grep tests. The `test/scripts/check-*.test.ts` files are guard self-tests, not duplicates.++One process note: deleting or renaming any structural suite requires regenerating+`scripts/structural-suites.tsv` (`bun scripts/classify-tests.ts`). Otherwise `check:structural-manifest`+fails in verify.++---++## 2. Class 1 candidates (full evidence)++### C1. `test/voyage-response-cap.test.ts`: delete the whole file+- **Tests (6):** "MAX_VOYAGE_RESPONSE_BYTES constant is declared at 256 MB", "Layer 1: Content-Length pre-check fires BEFORE resp.clone().json()", "Layer 1 throws on Content-Length over the cap", "Layer 2: per-embedding base64 cap…", "inbound try/catch rethrows VoyageResponseTooLargeError", "comment thread documents both layers + the cap-sizing decision".+- **What it can detect:** changes in the text of `src/core/ai/gateway.ts`. The last test pins **comments** ("Layer 1", "16K embeddings").+- **Probes:**+ - P1a rename `MAX_VOYAGE_RESPONSE_BYTES`→`VOYAGE_RESPONSE_CAP_BYTES` (behavior-preserving): grep **4 pass / 2 fail**; gateway.test.ts **40/0**. The grep test is coupled to the implementation.+ - P1b make the rethrow unreachable: grep 5/1, gateway.test.ts 39/**1 fail**. Both detect it.+ - P1c **double the cap to 512 MB**: grep **6/0 pass** (the regex `=\s*256\s*\*\s*1024\s*\*\s*1024` still matches a prefix of `256*1024*1024*2`); gateway.test.ts 38/**2 fail**. The grep test misses a real behavior break that the owner catches.+- **Non-test callers of seams:** none needed. `VoyageResponseTooLargeError` is exported and used by gateway.ts callers.+- **Surviving owner (same contract, same boundary):** `test/ai/gateway.test.ts` › describe "Voyage OOM-cap: too-large response throws (Codex P3 follow-up)". It covers "Layer 1 — Content-Length above cap propagates…", "Layer 2 — oversized base64 embedding string propagates (not swallowed)", and "VoyageResponseTooLargeError is exported as a tagged class". It drives real `embed()` through `configureGateway` with a stubbed fetch. It runs in the unit lane, so the cadence is the same.+- **History:** header says v0.31.8, D2+D10 (voyageCompatFetch OOM). File is at the shallow boundary.+- **Unlocks:** 98 test LOC, 1 file. **Cost:** 239 ms (unit). **Risk:** low.+- **Action:** delete. Validate with `bun test test/ai/gateway.test.ts`.++### C2. `test/remote-ping-status-field.test.ts`: delete the whole file+- **Tests (4):** "no `.state` property reads on job objects remain", "poll loop reads job.status", "terminal-state check tests job.status", "unpack generics type the lifecycle field as status".+- **Probes:**+ - P2a reintroduce the original bug (poll loop reads `job.state`): grep 3/1 fail; `test/remote-cli.test.ts` 6/**3 fail**.+ - P2b behavior-preserving `terminal.includes(String(job.status))`: grep **3/1 fail**; remote-cli **9/0**. The grep test is coupled to the implementation.+- **Surviving owner:** `test/remote-cli.test.ts` › describe "remote ping poll loop". It returns `get_job {status:'completed'|'failed'}` through a fake MCP server and asserts the exit and JSON status. The describe "remote ping --timeout parsing (behavioral…)" also covers it. Unit lane. The typed-generic assertion is already enforced by `tsc` in verify.+- **History:** header describes the `status` vs `state` regression in `gbrain remote ping`. Shallow boundary.+- **Unlocks:** 53 LOC, 1 file. **Cost:** 160 ms. **Risk:** low.+- **Action:** delete. Validate with `bun test test/remote-cli.test.ts`.++### C3. `test/connection-resilience.test.ts`: delete 22 of 25 tests (lines ~11–244)+- **Tests:** describes "isConnectionError" (12), "classifyWorkerExit" (6), "PostgresEngine reconnect behavior" (2), "Supervisor health check failure tracking" (2).+- **What it can detect: nothing in production.** Each of these tests exercises a function or loop **defined inside the test file**: a local `isConnectionError`, a local `classifyWorkerExit`, and simulated retry and counter loops. The file has zero `src` imports. The local `classifyWorkerExit` has also **drifted** from production: it maps code 1 to `'runtime_error'`, while `src/core/minions/exit-classification.ts` returns `'crash'`.+- **Probes:**+ - P6a production `classifyWorkerExit` always returns `'clean_exit'`: connection-resilience **25/0 pass**; `test/exit-classification.test.ts` 11/**6 fail**.+ - P6b supervisor degraded/reconnect branch made unreachable (keeping the `>= 3` literal): connection-resilience **25/0**, `supervisor.test.ts` **23/0**, `supervisor-configuration-blocked.test.ts` **22/0**. **Nothing catches it** (gap G1, §3).+- **Surviving owners:** `test/exit-classification.test.ts` (imports the real `classifyWorkerExit`). For the connection-error predicates, the real classifiers live in `src/core/pg-access-classify.ts` / `connect-probe.ts` and have their own tests. No owner is needed for the simulated loops, because they test only themselves.+- **Keep:** the 3 "Eng-review D3" guards (lines 261–331). They are architecture invariants: no per-call retry in `executeRaw`, `reconnect()` build-then-swap, and supervisor 3-strikes. Rewrite the 3-strikes one as a behavior test (G1).+- **Unlocks:** ~234 LOC. **Cost:** file stays (190 ms). **Risk:** low.+- **Action:** delete the self-copy describes; move the 3-strikes check to the supervisor harness.++### C4. `test/dream-cli-flags.test.ts`: trim 14 of 28 tests, rewrite the rest+- **Delete:** describe "--source / --source-id wiring (v0.41.13)" (9 tests, lines 70–119) and "--once wiring (issue #2860)" (5 tests, lines 154–~196).+- **Probes:**+ - P3a rename local `phaseWasExplicit` (behavior-preserving): grep 26/**2 fail**; `test/dream.test.ts` **45/0**.+ - P3b make the bare-`--once` guard unreachable: grep 27/1; dream.test.ts 40/**5 fail**.+- **Surviving owner:** `test/dream.test.ts`. It covers "runDream — --once (issue #2860)" (bare --once exits 2; `--input … --once` and `--drain --once` exit 2 because an implied phase doesn't count; `--help --once`) and the `--source` behaviors: missing value exits 2, conflict exits 2, engine=null gives "requires a connected brain", archived source exits 1, `--source-id` equivalence, and "non-resolver-user errors propagate uncaught (T3)". Same unit lane.+- **Rewrite in dream.test.ts:** `--input`+`--date` conflict, `--from > --to` "empty range", `--drain` rejecting non-extract_atoms phases, and the ISO date check. No behavior owner exists for these today. Drop the pins on help text, comments, and variable names ("IRON RULE comment", `synthInputFile` identifiers, `patterns=` literal).+- **Unlocks:** ~93 LOC deleted now, ~198 LOC once rewritten. **Cost:** 163 ms. **Risk:** low.++### C5. `test/fix-wave-structural.test.ts`: trim 2 of 31 tests+- **Delete:** "cli.ts parseOpArgs handles --no-<key> as boolean negation" (#1124) and "pglite-engine.ts exports classifyPgliteInitError + buildPgliteInitErrorMessage" (#1340).+- **Probes:**+ - P4a rename `positiveDef` in parseOpArgs (behavior-preserving): fix-wave 30/**1 fail**; `test/cli-args.test.ts` **12/0**.+ - P4b make `--no-<bool>` set `true`: fix-wave 30/1; cli-args 11/**1 fail**.+- **Surviving owners:** `test/cli-args.test.ts` › "parseOpArgs › --no-<boolean> maps to false without consuming the next flag" (calls the real parseOpArgs with `--no-expand`). `test/pglite-init-classifier.test.ts` imports both functions and covers the `$$bunfs`, ENOENT+pglite.data, wasm-abort, and corrupt arms (33 tests).+- **Keep** the rest of the file for now. It's a grab-bag; each block needs its own owner check (follow-up).+- **Unlocks:** ~20 LOC. **Risk:** low.++### C6. `test/embed-helper-migration.test.ts`: delete, after moving one default into a behavior test+- **Tests (8):** refactor-history pins ("imports runSlidingPool", "pre-migration `let nextIdx…` shape is gone", "pre-migration Promise.all fan-out is gone", "failureLabel projector uses page.slug", "call sites pass `workers: CONCURRENCY`", "threads the cancellation signal", "calls runSlidingPool at least twice") plus "preserves GBRAIN_EMBED_CONCURRENCY default of 20".+- **Probes:**+ - P5a rename lambda param `page`→`p` (behavior-preserving): grep 7/**1 fail**; `test/embed.serial.test.ts` **52/0**.+ - P5b force embedAll serial (`workers: 1`): grep 7/1; embed.serial 51/**1 fail**.+ - P5c change embedAll's default concurrency from 20 to 4: grep **8/0** (its regex also matches the second `'20'` site at line 1796) and embed.serial **52/0**. **Neither catches it** (gap G2).+- **Surviving owner:** `test/embed.serial.test.ts` › "runEmbed --all (parallel)" ("runs embedBatch calls concurrently across pages" measures max concurrent calls ≤ env; "respects GBRAIN_EMBED_CONCURRENCY=1 (serial)") plus the `--stale` abort tests (signal threading).+- **Action:** add one behavior test to embed.serial (env unset → max concurrency > 4, or ≤ 20), then delete the file. **Unlocks:** 110 LOC, 1 file. **Cost:** 275 ms. **Risk:** low once the default test lands.++### C7. `test/worker-lock-renewal-shape.test.ts` › "launchJob calls runLockRenewalTick": merge into the guard+- It is the same assertion as `scripts/check-worker-lock-renewal-shape.sh` invariant 2, which runs in verify and has a self-test (`test/scripts/check-worker-lock-renewal-shape.test.ts`). The header of the test file names the duplicate itself. ~4 LOC. Risk: low.++### C8. `test/book-mirror.test.ts` › describe "source file invariants": delete 5 of 7 pins+- **Delete:** "exports runBookMirrorCmd" (tsc and the spawn tests cover it), "documents the trust contract (codex HIGH-1 fix is in the file)" (asserts a **comment** string), "prints a cost-estimate confirmation" (identifier presence), "uses idempotency keys", and "handles partial-failure" (string literals). None of these detects a behavior break at a boundary.+- **Keep:** "uses read-only allowed_tools for subagent fan-out" and "writes via operator-trust put_page … remote: false". These are trust-boundary pins with no cheaper owner.+- ~35 LOC. Risk: low. (No probe run; this is by reading only.)++---++## 3. Class 3: rewrite at the real boundary (includes two real gaps)++| File › tests | Why | Evidence | Rewrite target |+|---|---|---|---|+| **G1** `connection-resilience` › "Supervisor still has the 3-strikes-then-reconnect path" | The only guard on `supervisor.ts` `consecutiveHealthFailures >= 3 → emit health_warn db_connection_degraded + engine.reconnect()`, and it's a literal grep | **P6b: branch unreachable → all supervisor tests pass** | Supervisor harness in `test/supervisor-configuration-blocked.test.ts` (it already sets `consecutiveHealthFailures`): 3 failing health checks → assert the event and the reconnect call |+| **G2** `embed-helper-migration` › "preserves GBRAIN_EMBED_CONCURRENCY default of 20" | Default contract; the regex matches the wrong site | **P5c: default 20→4 undetected by grep and owner** | `embed.serial.test.ts`, env unset |+| `schema-cli-contract.test.ts` (7) | "legacy v0.38 verbs are explicitly NOT in NEW_VERBS" compares two **test-local constants** (a tautology). "EXPERIMENTAL_VERBS set matches…" only checks that the words `init`/`fork`/… appear anywhere in schema.ts | **P7a: EXPERIMENTAL_VERBS emptied → 7/0 pass** (schema-cli.test.ts 15/0, also blind). Behavior coverage of verbs: suggest/diff/review-orphans/downgrade/usage have 0 behavior tests | Table-driven `runSchema([verb,'--json',…])` envelope test (`schema_version:1`, experimental tag) |+| `extract-workers.test.ts` (10) | Import and "legacy loop gone" pins; no behavior test of `extract --workers` exists | Read: no test calls runExtractCore with workers | `runExtract(['links','--workers','0'])` fails loudly; N>1 runs the pool |+| `thin-client-routing-audit.test.ts` (13) | Set-membership greps on cli.ts | `test/cli-dispatch-thin-client.test.ts` already spawns refusals for sync/embed/extract/migrate/apply-migrations/repair-jsonb/orphans/integrity/serve/config/jobs-work, but **not** pages/files/eval/code-*/dream/transcripts/storage/takes/sources | Extend that `refusedCommands` batch (one batched spawn) |+| `models-doctor-embed.test.ts` (3) | Slice-of-function greps; no test drives runModels' embedding probe | Read: no behavior caller | runModels with a fake gateway |+| `extract-conversation-facts-workers.test.ts` (~12 structural of 17) | Import and ordering pins; `extract-conversation-facts-diagnostics.serial.test.ts` already drives pool workers through the real core | Read | Fold the ordering and lock-skip assertions into the diagnostics test |+| `cli.test.ts` (structural ~15), `upgrade.serial.test.ts` (~17 "checks X before Y" order greps), `cycle-pack-gating` (14), `cycle-patterns` (15), `regression-strict-source-id` (6), `phantom-redirect-per-source-lock` (2), `asymmetric-encoding-contract` source-text half (3, self-described "belt + suspenders"), `cycle/cycle-lock-ttl` (1), `backlinks-job-default` (3) | Name-level classification; each has a callable production entry point | Not probed | Per file |+| autopilot wiring family (8 files, ~75 tests: auto-drain, cycle-failure-classification, fanout-wiring, nightly-probe-wiring, parser-probe-wiring, shutdown-engine-close, supervisor-wiring, self-upgrade) | All pin the inline tick body of `runAutopilot()`, which has no test harness | Every header gives that reason | **Keep for now.** Long term, extract a tick function (it has a real production caller: the loop) and test it directly. That's a production refactor, so it's a separate decision |++---++## 4. Retained false positives (look low-value, but are the independent contract)++- **`postgres-engine-singleton-ownership.test.ts`** (7 tests, 190 ms). The behavior owners exist (`test/e2e/postgres-engine-disconnect-idempotency.test.ts`, `db-singleton-shared-recovery.test.ts`, `postgres-reconnect-singleton.test.ts`), but I simulated a PR that touches only `src/core/postgres-engine.ts`: `scripts/select-e2e.ts` selected 25 E2E files and **none of those three**, because `scripts/e2e-test-map.ts` doesn't map them. So on PRs the static guard is the only one that runs. **Action:** add the three files to the `src/core/postgres-engine.ts` map entry, then this file becomes a class-1 delete. `postgres-engine.test.ts` (SET LOCAL statement_timeout, effective_date predicates) follows the same logic, and the absence of session-level `SET` is hard to prove through E2E. Keep.+- **`serve-http-admin-route-guard.test.ts`**: every `/admin` route needs `requireAdmin`. Security, with an anti-vacuity self-test. Keep.+- **`canonical-writer-inventory.test.ts`**: census of canonical write callsites against a reviewed ceiling TSV. Architecture. Keep.+- **`eval-contradictions/no-valid-until-write.test.ts`**: IRON RULE allow-list for writers of `facts.valid_until`. Architecture. Keep.+- **`ai/silent-drop-regression.test.ts`**: no `!process.env.OPENAI_API_KEY` gating. A no-legacy-API guard across the whole ops surface. Keep.+- **`transcription-injection.test.ts`** (execFileSync only, never shell) and **`hook-push-spawn-env.test.ts`** (detached children get the quarantined env): security, and cheaper than any behavior harness. Keep.+- **`migrate-stdout-clean.test.ts`** › "no console.log in migrate.ts": **stronger** than its behavior sibling, which only replays v122→latest. Keep both.+- **`jobs-gateway-refresh-set.test.ts`**: two-way drift check between a set and its registrations. Keep. Could become a behavior test if the set were exported, but no production need exists.+- **`think-embed-question-wiring.serial.test.ts`** CRAG pin: the synthesize behavior test is a different call site. The CRAG site can't be reached hermetically. Keep.+- **`book-mirror`** allowed_tools and `remote:false` pins: trust boundary. Keep.+- **`migrations-v0_13_0`** (no `process.execPath`/bun/.ts in phase commands: compiled-binary packaging), **`migrations-v0_14_0`** (schema defaults in all three schema sources), **`reranker-default-seam`**, **`v0_37_fix_wave` / `v0_37_gap_fill`** defaults: default, migration, and packaging contracts. Keep.+- **`cli-force-exit-teardown-arming`**, **`upgrade-skill-publish-prompt-race`**, **`serve-http-mcp-transport-cleanup`**: ordering and resource invariants with no cheap harness. Keep. The transport cleanup could get an HTTP close test later.+- **`openclaw-plugin-manifest` / `codex-plugin-manifest` / `docs-mcp-deploy` / `retrieval-reflex-recipe-routing`**: package and doc contracts, mostly reading non-src files. Out of scope; keep.++---++## 5. Recommended batches (in order)++1. **Batch A (low risk, ~400 LOC, 2 files):** delete C1 and C2, remove the 22 self-copy tests in C3, trim C5 and C7. Regenerate `scripts/structural-suites.tsv`. Validate with `bun test test/ai/gateway.test.ts test/remote-cli.test.ts test/exit-classification.test.ts test/cli-args.test.ts test/pglite-init-classifier.test.ts test/connection-resilience.test.ts test/fix-wave-structural.test.ts`, then `bun run verify`.+2. **Batch B (gaps first, then delete):** add the G1 supervisor behavior test and the G2 embed default test, then delete C6 and trim C4 and C8.+3. **Batch C (routing):** add the E2E map entries, then delete `postgres-engine-singleton-ownership.test.ts`.+4. **Batch D (rewrites):** schema-cli-contract, extract-workers, thin-client-routing-audit, models-doctor-embed.++## 6. Probe log (verbatim summary)++| Probe | Mutation | Grep test | Owner test |+|---|---|---|---|+| P1a | rename MAX_VOYAGE_RESPONSE_BYTES (preserving) | voyage-response-cap 4/2 **fail** | gateway 40/0 |+| P1b | rethrow unreachable | 5/1 | gateway 39/1 |+| P1c | cap doubled | **6/0 pass** | gateway 38/2 |+| P2a | poll reads job.state | remote-ping 3/1 | remote-cli 6/3 |+| P2b | String(job.status) (preserving) | 3/1 **fail** | remote-cli 9/0 |+| P3a | rename phaseWasExplicit (preserving) | dream-cli-flags 26/2 **fail** | dream 45/0 |+| P3b | bare --once guard unreachable | 27/1 | dream 40/5 |+| P4a | rename positiveDef (preserving) | fix-wave 30/1 **fail** | cli-args 12/0 |+| P4b | --no-bool sets true | 30/1 | cli-args 11/1 |+| P5a | failureLabel param rename (preserving) | embed-helper-migration 7/1 **fail** | embed.serial 52/0 |+| P5b | embedAll workers: 1 | 7/1 | embed.serial 51/1 |+| P5c | default 20→4 | **8/0 pass** | **52/0 pass** (gap) |+| P6a | prod classifyWorkerExit → clean_exit | connection-resilience **25/0 pass** | exit-classification 11/6 |+| P6b | supervisor 3-strikes unreachable | **25/0 pass** | supervisor 23/0, supervisor-configuration-blocked 22/0 (gap) |+| P7a | EXPERIMENTAL_VERBS emptied | schema-cli-contract **7/0 pass** | schema-cli 15/0 (gap) |+| — | select-e2e with postgres-engine.ts-only diff | — | 25 files selected, none of the 3 singleton E2E owners |diff --git a/docs/test-audit/2026-09-29/lane-source-grep/struct_src.json b/docs/test-audit/2026-09-29/lane-source-grep/struct_src.jsonnew file mode 100644index 0000000000..caa35cc8ee--- /dev/null+++ b/docs/test-audit/2026-09-29/lane-source-grep/struct_src.json@@ -0,0 +1 @@+[["test/agent-register.test.ts", "unit", 12, 35, 1904, 464], ["test/apply-migrations.test.ts", "unit", 7, 28, 282, 291], ["test/archived-source-scoping.test.ts", "unit", 2, 4, 194, 128], ["test/asymmetric-encoding-contract.test.ts", "unit", 3, 6, 212, 134], ["test/auto-link-targeted-probe-2544.test.ts", "unit", 6, 6, 6348, 151], ["test/autopilot-auto-drain-wiring.test.ts", "unit", 8, 8, 155, 67], ["test/autopilot-cycle-failure-classification.test.ts", "unit", 5, 5, 168, 108], ["test/autopilot-fanout-wiring.test.ts", "unit", 16, 16, 196, 263], ["test/autopilot-install.test.ts", "unit", 11, 18, 455, 504], ["test/autopilot-pause-marker.test.ts", "unit", 1, 13, 234, 245], ["test/autopilot-self-upgrade.test.ts", "unit", 4, 7, 464, 44], ["test/autopilot-shutdown-engine-close.test.ts", "unit", 6, 6, 225, 81], ["test/autopilot-supervisor-wiring.test.ts", "unit", 7, 7, 168, 99], ["test/backlinks-job-default.test.ts", "unit", 3, 3, 196, 47], ["test/backup-cli.serial.test.ts", "serial", 3, 19, 420, 443], ["test/backup-invalidation.serial.test.ts", "serial", 2, 12, 3340, 309], ["test/book-mirror.test.ts", "unit", 7, 9, 1113, 142], ["test/brain-score-breakdown.test.ts", "unit", 8, 11, 2153, 192], ["test/brainstorm-timeout.test.ts", "unit", 2, 14, 185, 147], ["test/canonical-writer-inventory.test.ts", "unit", 2, 2, 297, 32], ["test/chat-key-plane.test.ts", "unit", 2, 7, 365, 86], ["test/check-update.test.ts", "unit", 3, 25, 1682, 203], ["test/child-worker-supervisor.test.ts", "unit", 3, 21, 3161, 1017], ["test/chronicle-extract.test.ts", "unit", 9, 22, 1588, 199], ["test/claude-cli-recipe.test.ts", "unit", 38, 38, 368, 1162], ["test/cli-force-exit-teardown-arming.test.ts", "unit", 1, 1, 170, 55], ["test/cli.test.ts", "unit", 15, 24, 8017, 324], ["test/codex-plugin-manifest.test.ts", "unit", 22, 42, 3181, 595], ["test/compile-view.test.ts", "unit", 6, 14, 240, 310], ["test/config.test.ts", "unit", 1, 20, 161, 253], ["test/connection-resilience.test.ts", "unit", 3, 25, 190, 332], ["test/contextual-retrieval-service-pure.test.ts", "unit", 1, 25, 511, 566], ["test/conversation-facts-type-allowlist-drift.test.ts", "unit", 18, 18, 3769, 354], ["test/cycle-abort.test.ts", "unit", 13, 13, 480, 251], ["test/cycle-drain-renewal.test.ts", "unit", 3, 7, 416, 126], ["test/cycle-pack-gating.test.ts", "unit", 14, 21, 199, 207], ["test/cycle-patterns-deadline-budget.test.ts", "unit", 7, 15, 1410, 173], ["test/cycle-patterns.test.ts", "unit", 16, 16, 400, 141], ["test/cycle-phase-deadline-drift.test.ts", "unit", 4, 4, 442, 73], ["test/cycle/cycle-lock-ttl.test.ts", "unit", 1, 1, 160, 29], ["test/destructive-guard.test.ts", "unit", 19, 41, 7718, 806], ["test/detached-stderr.test.ts", "unit", 2, 5, 181, 90], ["test/docs-mcp-deploy.test.ts", "unit", 9, 9, 251, 88], ["test/doctor-orphan-ratio.test.ts", "unit", 4, 11, 11289, 267], ["test/doctor-volunteer-channels.test.ts", "unit", 9, 9, 343, 191], ["test/doctor.test.ts", "unit", 107, 107, 8723, 2075], ["test/dream-cli-flags.test.ts", "unit", 28, 28, 163, 198], ["test/e2e/bootstrap-real-codex.serial.test.ts", "serial", 5, 5, -1, 673], ["test/e2e/migration-flow.test.ts", "e2e", 4, 4, 4277, 299], ["test/embedding-dim-check-facts.test.ts", "unit", 4, 21, 190, 257], ["test/eval-brainbench-e2e.slow.test.ts", "slow", 5, 21, 48539, 428], ["test/eval-capture-db-plane.serial.test.ts", "serial", 9, 9, 562, 239], ["test/eval-synthesize-concepts-routing.test.ts", "unit", 3, 6, 864, 118], ["test/exit-classification.test.ts", "unit", 5, 13, 177, 131], ["test/extract-atoms-drain-errors.test.ts", "unit", 1, 16, 175, 356], ["test/extract-atoms-drain.test.ts", "unit", 5, 16, 181, 281], ["test/extract-include-frontmatter-config.serial.test.ts", "serial", 1, 8, 1737, 167], ["test/extract-workers.test.ts", "unit", 10, 10, 179, 95], ["test/facts-backstop-remedy-verb.test.ts", "unit", 3, 3, 151, 45], ["test/features.test.ts", "unit", 2, 12, 223, 138], ["test/fence-extraction.test.ts", "unit", 18, 18, 6159, 276], ["test/files.test.ts", "unit", 19, 39, 2301, 562], ["test/fix-wave-structural.test.ts", "unit", 31, 31, 196, 408], ["test/hook-command.serial.test.ts", "serial", 14, 70, 1772, 1518], ["test/hook-push-spawn-env.test.ts", "unit", 3, 3, 220, 45], ["test/integrations.test.ts", "unit", 3, 123, 211, 860], ["test/jobs-embed-background-parity.serial.test.ts", "serial", 2, 2, 4632, 116], ["test/jobs-gateway-refresh-set.test.ts", "unit", 5, 5, 173, 69], ["test/jobs-list-get-json.serial.test.ts", "serial", 2, 7, 1689, 154], ["test/jobs-thin-client-date-rehydration.test.ts", "unit", 2, 5, 372, 80], ["test/jobs-worker-startup-recovery.test.ts", "unit", 1, 5, 1668, 146], ["test/link-source-check-repair.test.ts", "unit", 1, 13, 3640, 255], ["test/longmemeval-embed-cache.test.ts", "unit", 4, 21, 644, 472], ["test/loops-extract-wiring.test.ts", "unit", 4, 8, 348, 102], ["test/migrate-stdout-clean.test.ts", "unit", 2, 2, 1788, 68], ["test/migrate.test.ts", "unit", 63, 171, 8243, 2414], ["test/migration-resume.test.ts", "unit", 6, 15, 257, 178], ["test/migrations-v0_14_0.test.ts", "unit", 8, 8, 298, 108], ["test/migrations-v0_22_4.test.ts", "unit", 9, 9, 254, 149], ["test/model-pricing.test.ts", "unit", 5, 30, 196, 273], ["test/models-doctor-embed.test.ts", "unit", 3, 3, 202, 50], ["test/openclaw-plugin-manifest.test.ts", "unit", 12, 12, 175, 156], ["test/pglite-engine.test.ts", "unit", 1, 110, 5336, 1541], ["test/pglite-repair-command.serial.test.ts", "serial", 1, 14, 3251, 500], ["test/pglite-wal-repair.serial.test.ts", "serial", 6, 6, 10900, 200], ["test/phantom-redirect-per-source-lock.test.ts", "unit", 3, 3, 189, 46], ["test/postgres-engine-singleton-ownership.test.ts", "unit", 7, 7, 190, 159], ["test/postgres-engine.test.ts", "unit", 8, 8, 185, 167], ["test/private-visibility.test.ts", "unit", 1, 26, 1823, 384], ["test/redos-hardening.test.ts", "unit", 7, 14, 178, 140], ["test/register-client-source-normalize.test.ts", "unit", 1, 16, 165, 106], ["test/regression-strict-source-id.test.ts", "unit", 6, 9, 247, 116], ["test/reindex-code-recovery.test.ts", "unit", 1, 8, 1253, 114], ["test/remediation-command-resolution.test.ts", "unit", 3, 3, 648, 222], ["test/reranker-default-seam.test.ts", "unit", 3, 3, 156, 31], ["test/retrieval-reflex-recipe-routing.test.ts", "unit", 5, 5, 188, 78], ["test/schema-cli-contract.test.ts", "unit", 7, 7, 178, 93], ["test/schema-pack-unify-types-handler.test.ts", "unit", 1, 11, 5535, 299], ["test/schema-pack/suggest.test.ts", "unit", 1, 7, 194, 188], ["test/scripts/classify-tests.test.ts", "unit", 18, 8, 175, 119], ["test/scripts/coverage-diff-gate.test.ts", "unit", 3, 18, 593, 315], ["test/serve-http-admin-route-guard.test.ts", "unit", 4, 4, 177, 265], ["test/serve-http-github-webhook.test.ts", "unit", 1, 9, 623, 114], ["test/serve-http-mcp-transport-cleanup.test.ts", "unit", 2, 2, 186, 56], ["test/serve-http-metrics.test.ts", "unit", 2, 9, 255, 160], ["test/serve-stdin-eof-drain.test.ts", "unit", 1, 8, 724, 192], ["test/shared-skills-init.serial.test.ts", "serial", 4, 4, 33390, 104], ["test/shared-skills-setup.serial.test.ts", "serial", 9, 16, 706, 214], ["test/skillopt/deadline-and-hermetic.test.ts", "unit", 2, 9, 315, 143], ["test/skillpack-install.test.ts", "unit", 15, 32, 301, 670], ["test/skillpack-scaffold.test.ts", "unit", 6, 14, 223, 296], ["test/snapshot-shape-guard.test.ts", "unit", 10, 11, 433, 163], ["test/sources-webhook.test.ts", "unit", 1, 12, 187, 148], ["test/spend-off-switch.test.ts", "unit", 3, 5, 614, 53], ["test/supervisor.test.ts", "unit", 1, 23, 4562, 632], ["test/sync-failures.test.ts", "unit", 12, 65, 281, 682], ["test/sync-include-hidden.test.ts", "unit", 1, 7, 490, 128], ["test/sync.test.ts", "unit", 23, 85, 8892, 1277], ["test/thin-client-routing-audit.test.ts", "unit", 13, 13, 163, 176], ["test/think-embed-question-wiring.serial.test.ts", "serial", 2, 2, 640, 86], ["test/timing-safe.test.ts", "unit", 1, 6, 229, 52], ["test/transcription-injection.test.ts", "unit", 2, 2, 194, 65], ["test/upgrade-skill-publish-prompt-race.test.ts", "unit", 3, 3, 158, 62], ["test/upgrade.serial.test.ts", "serial", 13, 28, 3210, 404], ["test/v0_37_fix_wave.serial.test.ts", "serial", 19, 19, 591, 325], ["test/v0_37_gap_fill.serial.test.ts", "serial", 16, 17, 5408, 574], ["test/voyage-response-cap.test.ts", "unit", 6, 6, 239, 98], ["test/worker-supervised-db-probe.test.ts", "unit", 5, 5, 1885, 185]]\ No newline at end of filediff --git a/llms-full.txt b/llms-full.txtindex 77aa5f7c7a..c3fcbc1300 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1981,7 +1981,7 @@ detail on demand.)| publishing the brain's MCP server to other devices and agents (`gbrain mcp expose`, Tailscale default, Grok Bot / Muse hosted path) | `docs/guides/remote-mcp.md` + `docs/mcp/DEPLOY.md` + the `remote-mcp` skill || memory verbs / MCP tool surface (`--surface`) / conformance | `docs/protocol/MEMORY_VERBS_v1.md` + the `verbs*`/`surface.ts`/`protocol.ts` entries in `KEY_FILES.md` || the CLI surface (commands + flags) | `gbrain --help` / `gbrain --tools-json`, plus the relevant `KEY_FILES.md` entry |-| running or writing tests | `docs/TESTING.md` |+| running, writing or retiring tests | `docs/TESTING.md` ([authoring gate](docs/TESTING.md#authoring-gate), [retiring](docs/TESTING.md#retiring-a-test)) || bulk-command progress wiring | `docs/progress-events.md` || eval methodology / metrics | `docs/eval/` || brains vs sources / topology | `docs/architecture/brains-and-sources.md`, `topologies.md` |@@ -1993,9 +1993,7 @@ detail on demand.)The per-file index (`## Key files`), the thin-client routing seam, and the testingdiscipline used to live inline here. They moved to the docs above so this file-stays small enough to load every session. Nothing was lost — the pre-move content-is in git, and the docs carry every load-bearing invariant (compressed to-current-state).+stays small enough to load every session.## Maintaining CLAUDE.md and the reference docs@@ -4938,7 +4936,7 @@ infer your current location and timezone. All times shown in YOUR local timezone// Hold the notification, fold into morning briefingget_user_timezone():- calendar = gbrain search "flight" --type calendar --recent 7d+ calendar = gbrain query "flight" --types calendar --since 7dif recent_flight:return infer_timezone(flight.destination)return config.default_timezone // fallback: US/Pacificdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex bb1c01b809..d396e6ba01 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.59.18.0",+ "version": "0.59.20.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex 895f6d1622..3677e90153 100644--- a/package.json+++ b/package.json@@ -131,6 +131,7 @@"check:compile-autoload": "bash scripts/check-compile-autoload.sh","check:structural-manifest": "bash scripts/check-structural-manifest.sh","check:orphan-modules": "node scripts/check-orphan-modules.mjs",+ "check:test-placeholders": "node scripts/check-test-placeholders.mjs","build:harness-docs": "bun run scripts/build-harness-docs.ts"},"openclaw": {@@ -190,7 +191,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.59.18.0",+ "version": "0.59.20.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 94711fc4b5..1a67fbc0a6 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.59.18.0",+ "version": "0.59.20.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 5b42be7161..2c98a277b9 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.59.18.0",+ "version": "0.59.20.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 82432d66c6..0aaeab8fc3 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.18.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.20.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-coding/skills/conventions/calibration.md b/plugin-variants/gbrain-coding/skills/conventions/calibration.mdindex 606bd74a50..1f907f026b 100644--- a/plugin-variants/gbrain-coding/skills/conventions/calibration.md+++ b/plugin-variants/gbrain-coding/skills/conventions/calibration.md@@ -50,20 +50,11 @@ to LOWER an active threshold without an explicit `--allow-loosen-confidence`flag — because relaxing after data accumulates silently shifts whichhistorical resolutions count as auto-applied.-## Cross-brain semantics (D18)+## Cross-brain reads-For any read of a calibration profile across mounted brains:--1. **Local first.** Query local. If local has it, return; do not query mounts.-2. **Mount fallback.** Only if local is empty AND `canReadMountsForCtx(ctx)`- returns true. Mount-side rows must have `published=true`.-3. **Cross-brain attribution.** Returned profile carries- `source_brain_id` + `from_mount`. UI consumers MUST surface- "from mounted brain: X" so the user knows.-4. **Subagent prohibition.** `ctx.viaSubagent && !allowedSlugPrefixes`- cannot read mounts — subagent loops see only the local brain. Trusted-- workspace cycle phases (synthesize/patterns) pass- `allowedSlugPrefixes` set and ARE allowed.+Calibration profiles are read from the local brain only. Reading a+profile from a mounted brain is not implemented: the v0.36.1.0 D18+cross-brain helper never had a runtime caller and was removed.## Test seams@@ -84,8 +75,6 @@ the calibration wave has structural defense against:- BaseCyclePhase enforces `sourceScopeOpts(ctx)` threading at the type level.- Every new schema table has `source_id NOT NULL REFERENCES sources(id)`.-- Cross-brain reads route through `canReadMountsForCtx()` classifier.-- Tests pin all 4 D18 rules in `test/cross-brain-calibration.test.ts`.If you find yourself writing a `ctx.engine.executeRaw(...)` inside acalibration module that doesn't pass `sourceScopeOpts`, you've founddiff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex e3199f761d..31b9d8944b 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.59.18.0",+ "version": "0.59.20.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex f06c3d4dff..819bf13189 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.59.18.0",+ "version": "0.59.20.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex b34efb8aec..3e074e7269 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.18.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.20.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin-variants/gbrain-daily/skills/conventions/calibration.md b/plugin-variants/gbrain-daily/skills/conventions/calibration.mdindex 606bd74a50..1f907f026b 100644--- a/plugin-variants/gbrain-daily/skills/conventions/calibration.md+++ b/plugin-variants/gbrain-daily/skills/conventions/calibration.md@@ -50,20 +50,11 @@ to LOWER an active threshold without an explicit `--allow-loosen-confidence`flag — because relaxing after data accumulates silently shifts whichhistorical resolutions count as auto-applied.-## Cross-brain semantics (D18)+## Cross-brain reads-For any read of a calibration profile across mounted brains:--1. **Local first.** Query local. If local has it, return; do not query mounts.-2. **Mount fallback.** Only if local is empty AND `canReadMountsForCtx(ctx)`- returns true. Mount-side rows must have `published=true`.-3. **Cross-brain attribution.** Returned profile carries- `source_brain_id` + `from_mount`. UI consumers MUST surface- "from mounted brain: X" so the user knows.-4. **Subagent prohibition.** `ctx.viaSubagent && !allowedSlugPrefixes`- cannot read mounts — subagent loops see only the local brain. Trusted-- workspace cycle phases (synthesize/patterns) pass- `allowedSlugPrefixes` set and ARE allowed.+Calibration profiles are read from the local brain only. Reading a+profile from a mounted brain is not implemented: the v0.36.1.0 D18+cross-brain helper never had a runtime caller and was removed.## Test seams@@ -84,8 +75,6 @@ the calibration wave has structural defense against:- BaseCyclePhase enforces `sourceScopeOpts(ctx)` threading at the type level.- Every new schema table has `source_id NOT NULL REFERENCES sources(id)`.-- Cross-brain reads route through `canReadMountsForCtx()` classifier.-- Tests pin all 4 D18 rules in `test/cross-brain-calibration.test.ts`.If you find yourself writing a `ctx.engine.executeRaw(...)` inside acalibration module that doesn't pass `sourceScopeOpts`, you've founddiff --git a/plugin/README.md b/plugin/README.mdindex ef9b095821..f543e49448 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.18.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.20.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/plugin/skills/brain-pdf/SKILL.md b/plugin/skills/brain-pdf/SKILL.mdindex 3ff6f2a232..f18f9eb8c5 100644--- a/plugin/skills/brain-pdf/SKILL.md+++ b/plugin/skills/brain-pdf/SKILL.md@@ -80,7 +80,7 @@ if [ -n "$BRAIN_DIR" ] && [ -f "$BRAIN_DIR/$SLUG.md" ]; thenRAW="$BRAIN_DIR/$SLUG.md"elseRAW=$(mktemp /tmp/brain-page-XXXXXX.md)- gbrain get "$SLUG" --raw > "$RAW" # whatever flag exposes raw body+ gbrain get "$SLUG" > "$RAW" # prints the page as markdown with frontmatterfi# 3. Strip YAML frontmatter — sed: skip the opening '---' through thediff --git a/plugin/skills/conventions/calibration.md b/plugin/skills/conventions/calibration.mdindex 606bd74a50..1f907f026b 100644--- a/plugin/skills/conventions/calibration.md+++ b/plugin/skills/conventions/calibration.md@@ -50,20 +50,11 @@ to LOWER an active threshold without an explicit `--allow-loosen-confidence`flag — because relaxing after data accumulates silently shifts whichhistorical resolutions count as auto-applied.-## Cross-brain semantics (D18)+## Cross-brain reads-For any read of a calibration profile across mounted brains:--1. **Local first.** Query local. If local has it, return; do not query mounts.-2. **Mount fallback.** Only if local is empty AND `canReadMountsForCtx(ctx)`- returns true. Mount-side rows must have `published=true`.-3. **Cross-brain attribution.** Returned profile carries- `source_brain_id` + `from_mount`. UI consumers MUST surface- "from mounted brain: X" so the user knows.-4. **Subagent prohibition.** `ctx.viaSubagent && !allowedSlugPrefixes`- cannot read mounts — subagent loops see only the local brain. Trusted-- workspace cycle phases (synthesize/patterns) pass- `allowedSlugPrefixes` set and ARE allowed.+Calibration profiles are read from the local brain only. Reading a+profile from a mounted brain is not implemented: the v0.36.1.0 D18+cross-brain helper never had a runtime caller and was removed.## Test seams@@ -84,8 +75,6 @@ the calibration wave has structural defense against:- BaseCyclePhase enforces `sourceScopeOpts(ctx)` threading at the type level.- Every new schema table has `source_id NOT NULL REFERENCES sources(id)`.-- Cross-brain reads route through `canReadMountsForCtx()` classifier.-- Tests pin all 4 D18 rules in `test/cross-brain-calibration.test.ts`.If you find yourself writing a `ctx.engine.executeRaw(...)` inside acalibration module that doesn't pass `sourceScopeOpts`, you've founddiff --git a/plugin/skills/schema-unify/SKILL.md b/plugin/skills/schema-unify/SKILL.mdindex 9e2dd9927f..b61bd4019b 100644--- a/plugin/skills/schema-unify/SKILL.md+++ b/plugin/skills/schema-unify/SKILL.md@@ -143,7 +143,7 @@ Expected:### Phase 5: Post-migration-Anything that used `--type article` keeps working post-unify if your CLI calls go through the `expandTypeFilter` helper (it expands `article` to `media+subtype=article` automatically). Direct SQL against `pages.type` needs updating to the canonical types.+Search and query `--type article` keep returning those pages post-unify: `media` declares `article` as an alias, so the type filter expands through the active pack's alias closure (the results also include other `media` pages). Direct SQL against `pages.type` needs updating to the canonical types.Search queries get a small ranking signal: pages reached via `slug_aliases` (canonicals of one or more aliases) get a 1.05x boost. Visible via `gbrain search --explain`.@@ -219,7 +219,7 @@ Outputs:Side effects:- Source pages soft-deleted with 72h restore TTL (`gbrain restore <slug>`).- One-time cache invalidation on KNOBS_HASH_VERSION bump (5→6); self-healing in `cache.ttl_seconds`.-- Query-time `--type X` alias-expands via `expandTypeFilter` (back-compat).+- Search/query `--type X` expands through the active pack's alias closure (back-compat).Failure modes:- Concurrent submission rejected by the `gbrain-unify` db-lock; second call exits gracefully.diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjsindex 405f21b068..f7a26f55c9 100644--- a/scripts/check-orphan-modules.mjs+++ b/scripts/check-orphan-modules.mjs@@ -19,11 +19,14 @@// lazy seams are reachable by construction.//// Self-test seam: argv[2] (or GBRAIN_GUARD_ROOT) points at a fixture tree;-// in fixture mode the entries are `src/entry*.ts` and the allowlist is-// empty, so scripts/guard-self-test.sh can prove the guard fails on bad-// and passes on good fixtures.+// in fixture mode the entries are `src/entry*.ts`, the hard-orphan+// allowlist is empty, and the permitted test-only set is read from+// `<root>/permitted-test-only.json` (absent = empty), so+// scripts/guard-self-test.sh and test/scripts/check-orphan-modules.test.ts+// can prove every rule fails on bad and passes on good trees.//-// Exit: 0 clean · 1 orphans or stale allowlist entries · 2 infra error.+// Exit: 0 clean · 1 orphans, unpermitted test-only modules, or stale+// entries · 2 infra error.import { readdirSync, readFileSync, statSync, existsSync } from 'node:fs';import { join, relative, dirname } from 'node:path';@@ -31,8 +34,13 @@ import { join, relative, dirname } from 'node:path';const root = process.argv[2] || process.env.GBRAIN_GUARD_ROOT || '.';const fixtureMode = !!(process.argv[2] || process.env.GBRAIN_GUARD_ROOT);-// Reasoned allowlist (repo mode only). SHRINK-ONLY: a stale entry (module-// became reachable or was deleted) fails the guard so the list can't rot.+const RERUN = 'bun run check:orphan-modules';+const DOCS = 'docs/TESTING.md#orphan-module-guard';+const SELF = 'scripts/check-orphan-modules.mjs';++// Hard-orphan allowlist (repo mode only): modules imported by nothing, not+// even tests. SHRINK-ONLY: a stale entry (module became reachable or was+// deleted) fails the guard so the list can't rot.const ALLOWLIST = new Map([// Alternate chunker strategies kept as documented options for the chunker// registry; selectable via config in a future wave, currently unreferenced.@@ -44,33 +52,86 @@ const ALLOWLIST = new Map([['src/core/search/vector.ts', 'single-arm search kept for eval comparisons'],]);-// Modules unreachable from RUNTIME entrypoints but imported (transitively)-// by the test tree are a separate, softer tier: not dead code, but not-// product code either — candidates for wiring or deletion. Their COUNT is a-// shrink-only ratchet so the tier can't quietly grow.-const MAX_TEST_ONLY_REACHABLE = 46;+// Permitted test-only modules (repo mode): unreachable from every runtime+// entrypoint but imported by the test tree. Every such module must be named+// here with a reason; a test-only module missing from the set fails, and an+// entry that is deleted, wired into a runtime entrypoint, or no longer+// imported by any test fails as stale. The set may grow only with a reason+// string in a reviewer-visible edit. Modules reached from `scripts/**` carry+// reason 'script-reachable', which the guard verifies.+const PERMITTED_TEST_ONLY = [+ { path: 'src/core/bootstrap/template-repo.ts', reason: 'script-reachable' },+ { path: 'src/core/eval-contradictions/fixture-redact.ts', reason: 'script-reachable' },+ { path: 'src/eval/longmemeval/diagnostics.ts', reason: 'script-reachable' },+ { path: 'src/eval/longmemeval/evidence-packet.ts', reason: 'script-reachable' },+ { path: 'src/eval/shared/autocut-replay.ts', reason: 'script-reachable' },+ { path: 'src/mcp/http-transport.ts', reason: 'script-reachable' },+ { path: 'src/mcp/tool-catalog.ts', reason: 'script-reachable' },+ { path: 'src/core/archive-crawler-config.ts', reason: "held: skills/archive-crawler/SKILL.md describes the scan_paths safety fence as code-enforced; wire-or-retract is a product decision" },+ { path: 'src/core/chronicle/backstop.ts', reason: 'held: the put_page chronicle backstop was dropped in v0.51.0.0, so the documented auto_chronicle setting does nothing; restore-or-retract is a product decision' },+ { path: 'src/core/onboard/impact-capture.ts', reason: 'held: sole writer of migration_impact_log, which the shipped `gbrain onboard --history` reads; wire-or-retract is a product decision' },+ { path: 'src/core/progressive-batch/orchestrator.ts', reason: 'held: TODOS.md keeps an open item to re-compose progressive-batch with --workers on the 3 reindex sites (callers dropped in the v0.41.17.0 merge)' },+ { path: 'src/core/progressive-batch/retrofit-wrap.ts', reason: 'held: progressive-batch re-compose item still open in TODOS.md' },+ { path: 'src/core/progressive-batch/stage-report.ts', reason: 'held: progressive-batch re-compose item still open in TODOS.md' },+ { path: 'src/core/ingestion/daemon.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (public gbrain/ingestion export, docs/guides/data-ingestion.md)' },+ { path: 'src/core/ingestion/dedup.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },+ { path: 'src/core/ingestion/skillpack-load.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },+ { path: 'src/core/ingestion/sources/file-watcher.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },+ { path: 'src/core/ingestion/sources/gstack-learnings.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },+ { path: 'src/core/ingestion/sources/inbox-folder.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/guides/data-ingestion.md promises the inbox folder)' },+ { path: 'src/core/ingestion/sources/markdown-greenfield.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/migrations/v0.41.2-markdown-greenfield.md)' },+];++const RULES = {+ hardOrphan: 'orphan-modules/hard-orphan',+ unpermitted: 'orphan-modules/unpermitted-test-only',+ invalidEntry: 'orphan-modules/invalid-permitted-entry',+ stalePermitted: 'orphan-modules/stale-permitted-entry',+ staleAllowlist: 'orphan-modules/stale-allowlist-entry',+};-function walkDir(dir, out = []) {+function walkDir(dir, match, out = []) {+ if (!existsSync(dir)) return out;for (const e of readdirSync(dir)) {const p = join(dir, e);const st = statSync(p);if (st.isDirectory()) {if (e === 'node_modules' || e === '.git') continue;- walkDir(p, out);- } else if (p.endsWith('.ts') && !p.endsWith('.d.ts')) {+ walkDir(p, match, out);+ } else if (match(p)) {out.push(p);}}return out;}+function loadPermitted() {+ if (!fixtureMode) return PERMITTED_TEST_ONLY;+ const file = join(root, 'permitted-test-only.json');+ if (!existsSync(file)) return [];+ try {+ return JSON.parse(readFileSync(file, 'utf8'));+ } catch (err) {+ console.error(`check-orphan-modules: cannot parse ${file}: ${err.message}`);+ process.exit(2);+ }+}++function report(rule, path, lines) {+ console.error(`FAIL [${rule}] ${path}`);+ for (const line of lines) console.error(` ${line}`);+ console.error(` rerun: ${RERUN}`);+ console.error(` docs: ${DOCS}`);+}+function main() {const srcDir = join(root, 'src');if (!existsSync(srcDir)) {console.error(`check-orphan-modules: no src/ under ${root}`);process.exit(2);}- const srcFiles = walkDir(srcDir).map(p => relative(root, p));+ const isTs = (p) => p.endsWith('.ts') && !p.endsWith('.d.ts');+ const srcFiles = walkDir(srcDir, isTs).map(p => relative(root, p));const srcSet = new Set(srcFiles);let entries = [];@@ -98,17 +159,21 @@ function main() {// Relative-specifier extraction: static, dynamic, and require forms.const IMPORT_RE = /(?:from\s+|import\(\s*|require\(\s*)['"](\.[^'"]+)['"]/g;- const resolveSpec = (fromFile, spec) => {+ const resolveSpec = (fromFile, spec, allowOutsideSrc) => {const base = join(root, dirname(fromFile), spec);for (const cand of [base, `${base}.ts`, join(base, 'index.ts')]) {const rel = relative(root, cand);if (srcSet.has(rel)) return rel;+ if (allowOutsideSrc && allowOutsideSrc(rel) && existsSync(cand) && statSync(cand).isFile()) return rel;}return null;};- const crawl = (seedFiles) => {+ // Crawls from seed files; files outside src/ are followed only when+ // `allowOutsideSrc` accepts them. Records each file's direct importers.+ const crawl = (seedFiles, allowOutsideSrc) => {const seen = new Set();+ const importers = new Map();const stack = [...seedFiles];while (stack.length > 0) {const f = stack.pop();@@ -119,81 +184,105 @@ function main() {let m;const re = new RegExp(IMPORT_RE.source, 'g');while ((m = re.exec(text)) !== null) {- const dep = resolveSpec(f, m[1]);- if (dep && !seen.has(dep)) stack.push(dep);+ const dep = resolveSpec(f, m[1], allowOutsideSrc);+ if (!dep) continue;+ if (!importers.has(dep)) importers.set(dep, new Set());+ importers.get(dep).add(f);+ if (!seen.has(dep)) stack.push(dep);}}- return seen;+ return { seen, importers };};- const runtimeReachable = crawl(entries);-- // Test-tree reachability (repo mode): seed with test files but only track- // src/ members in the result set. Test files resolve into src via relative- // specifiers; the crawl handles the rest transitively.- let testReachable = new Set();- if (!fixtureMode && existsSync(join(root, 'test'))) {- const testFiles = [];- (function walkTests(dir) {- for (const e of readdirSync(dir)) {- const p = join(dir, e);- const st = statSync(p);- if (st.isDirectory()) walkTests(p);- else if (p.endsWith('.ts')) testFiles.push(relative(root, p));- }- })(join(root, 'test'));- const allSeen = new Set();- const stack = [...testFiles];- while (stack.length > 0) {- const f = stack.pop();- if (allSeen.has(f)) continue;- allSeen.add(f);- let text;- try { text = readFileSync(join(root, f), 'utf8'); } catch { continue; }- let m;- const re = new RegExp(IMPORT_RE.source, 'g');- while ((m = re.exec(text)) !== null) {- const base = join(root, dirname(f), m[1]);- for (const cand of [base, `${base}.ts`, join(base, 'index.ts')]) {- const rel = relative(root, cand);- if (srcSet.has(rel) || rel.startsWith('test/')) {- if (!allSeen.has(rel)) stack.push(rel);- break;- }- }- }+ const runtimeReachable = crawl(entries).seen;++ const testSeeds = walkDir(join(root, 'test'), (p) => p.endsWith('.ts')).map(p => relative(root, p));+ const testCrawl = crawl(testSeeds, (rel) => rel.startsWith('test/'));+ const testReachable = new Set([...testCrawl.seen].filter(f => srcSet.has(f)));++ const scriptSeeds = walkDir(join(root, 'scripts'), (p) => /\.(ts|mjs|js)$/.test(p)).map(p => relative(root, p));+ const scriptCrawl = crawl(scriptSeeds, (rel) => rel.startsWith('scripts/'));+ const scriptReachable = new Set([...scriptCrawl.seen].filter(f => srcSet.has(f)));++ const allow = fixtureMode ? new Map() : ALLOWLIST;+ const permittedList = loadPermitted();+ const permitted = new Map();+ const invalid = [];+ for (const entry of permittedList) {+ const path = entry?.path;+ if (typeof path !== 'string' || path.length === 0) {+ invalid.push({ path: JSON.stringify(entry), why: 'entry has no path' });+ } else if (typeof entry.reason !== 'string' || entry.reason.trim().length === 0) {+ invalid.push({ path, why: 'entry has no reason; every permitted test-only module needs one' });+ } else if (permitted.has(path)) {+ invalid.push({ path, why: 'duplicate entry' });+ } else {+ permitted.set(path, entry.reason);}- testReachable = new Set([...allSeen].filter(f => srcSet.has(f)));}- const allow = fixtureMode ? new Map() : ALLOWLIST;+ const testImporters = (f) => {+ const direct = [...(testCrawl.importers.get(f) ?? [])].sort();+ const fromTests = direct.filter(p => p.startsWith('test/'));+ return fromTests.length > 0 ? fromTests : direct;+ };+const notRuntime = srcFiles.filter(f => !runtimeReachable.has(f));- const hardOrphans = notRuntime.filter(f => !testReachable.has(f) && !allow.has(f)).sort();+ const hardOrphans = notRuntime.filter(f => !testReachable.has(f) && !allow.has(f) && !permitted.has(f)).sort();const testOnly = notRuntime.filter(f => testReachable.has(f) && !allow.has(f)).sort();- const stale = [...allow.keys()].filter(f => !srcSet.has(f) || runtimeReachable.has(f)).sort();-- let failed = false;- if (hardOrphans.length > 0) {- failed = true;- console.error(`FAIL: ${hardOrphans.length} src module(s) unreachable from every RUNTIME entrypoint AND every test, not allowlisted:`);- for (const f of hardOrphans) console.error(` ${f}`);- console.error(' Wire the module, delete it, or add a reasoned allowlist entry in scripts/check-orphan-modules.mjs.');+ const unpermitted = testOnly.filter(f => !permitted.has(f));++ const stalePermitted = [];+ for (const [path, reason] of permitted) {+ if (!srcSet.has(path)) stalePermitted.push({ path, why: 'the module no longer exists' });+ else if (runtimeReachable.has(path)) stalePermitted.push({ path, why: 'the module is now reachable from a runtime entrypoint' });+ else if (!testReachable.has(path)) stalePermitted.push({ path, why: 'no test imports the module any more' });+ else if (reason === 'script-reachable' && !scriptReachable.has(path)) stalePermitted.push({ path, why: "tagged 'script-reachable' but no scripts/** file imports it" });+ }+ stalePermitted.sort((a, b) => a.path.localeCompare(b.path));+ const staleAllow = [...allow.keys()].filter(f => !srcSet.has(f) || runtimeReachable.has(f)).sort();++ for (const f of hardOrphans) {+ report(RULES.hardOrphan, f, [+ 'reason: unreachable from every runtime entrypoint and every test',+ `remedy: wire the module into a runtime caller or delete it; a deliberate keep needs a reasoned ALLOWLIST entry in ${SELF}`,+ ]);+ }+ for (const f of unpermitted) {+ const via = testImporters(f);+ report(RULES.unpermitted, f, [+ `imported by: ${via.length > 0 ? via.join(', ') : '(transitively, via the test tree)'}`,+ 'reason: reachable from tests but from no runtime entrypoint (cli, mcp server, plugin engines, admin, package exports)',+ `remedy: wire the module into a runtime caller, delete it with its tests, or add { path, reason } to PERMITTED_TEST_ONLY in ${SELF} (reason 'script-reachable' when scripts/** imports it)`,+ ]);}- if (!fixtureMode && testOnly.length > MAX_TEST_ONLY_REACHABLE) {- failed = true;- console.error(`FAIL: test-only-reachable tier grew to ${testOnly.length} (ratchet ceiling ${MAX_TEST_ONLY_REACHABLE}):`);- for (const f of testOnly) console.error(` ${f}`);- console.error(' New src modules must be reachable from a runtime entrypoint; wire it or (for a deliberate test-only helper) raise the ceiling in a reviewer-visible edit.');+ for (const { path, why } of invalid) {+ report(RULES.invalidEntry, path, [+ `reason: ${why}`,+ `remedy: fix the record in PERMITTED_TEST_ONLY in ${SELF}`,+ ]);}- if (stale.length > 0) {- failed = true;- console.error(`FAIL: ${stale.length} stale allowlist entr${stale.length === 1 ? 'y' : 'ies'} (now runtime-reachable or deleted) — shrink the list:`);- for (const f of stale) console.error(` ${f}`);+ for (const { path, why } of stalePermitted) {+ report(RULES.stalePermitted, path, [+ `reason: ${why}`,+ `remedy: remove this record from PERMITTED_TEST_ONLY in ${SELF} (or correct its reason); do not restore code to satisfy the list`,+ ]);+ }+ for (const f of staleAllow) {+ report(RULES.staleAllowlist, f, [+ 'reason: allowlisted as a hard orphan but now runtime-reachable or deleted',+ `remedy: remove this record from ALLOWLIST in ${SELF}; do not restore code to satisfy the list`,+ ]);+ }++ const failures = hardOrphans.length + unpermitted.length + invalid.length + stalePermitted.length + staleAllow.length;+ if (failures > 0) {+ console.error(`check-orphan-modules: ${failures} failure(s)`);+ process.exit(1);}- if (failed) process.exit(1);console.log(`check-orphan-modules: OK (${srcFiles.length} modules, ${entries.length} entrypoints, ` +- `${allow.size} allowlisted, ${testOnly.length}/${MAX_TEST_ONLY_REACHABLE} test-only-reachable)`,+ `${allow.size} allowlisted, ${testOnly.length} permitted test-only)`,);}diff --git a/scripts/check-privacy.sh b/scripts/check-privacy.shindex 17b85687e4..3de69da70e 100755--- a/scripts/check-privacy.sh+++ b/scripts/check-privacy.sh@@ -169,7 +169,7 @@ ALLOW_LIST=('src/core/skillpack/harvest-lint.ts''test/skillpack-harvest-lint.test.ts''test/skillpack-harvest.test.ts'- 'test/e2e/skillpack-flow.test.ts'+ 'test/skillpack-flow.test.ts''skills/skillpack-harvest/SKILL.md'# v0.40.1.0 Track D / T5: the qrels gate test contains a privacy-grep# regression guard whose block list names the banned literal to assertdiff --git a/scripts/check-source-config-leak.sh b/scripts/check-source-config-leak.shindex 71dfa87f3e..925cc33ff1 100755--- a/scripts/check-source-config-leak.sh+++ b/scripts/check-source-config-leak.sh@@ -12,6 +12,44 @@## Failure mode is loose-positive on purpose — false positives cost one# 30-second comment-or-fix; false negatives leak production secrets.+#+# This grep is a tripwire, not the contract. The behavioral contract is+# test/source-config-secret-surfaces.test.ts (plus the backup and admin API+# assertions named below): each surface is fed a stored webhook_secret and+# must never print it.+#+# Secret-bearing keys (SECRET_KEYS in src/core/source-config-redact.ts):+# webhook_secret only. Every other key the codebase reads is a pointer, not a+# credential: gh_token_env / g_token_env name an env var, gh_app_pem_path+# names a key file, g_token_command names a mint command, g_account is an+# account pointer (tokens live in the credential vault), and remote_url is+# rejected at registration when it embeds credentials (parseRemoteUrl).+#+# Audited surfaces (source-config security audit):+# LEAKED, fixed with redactSourceConfig():+# - sources_add op result, printed by `gbrain call sources_add` when a+# path is attached to an existing path-less source (src/core/ops/sources.ts)+# - managed `gbrain sources add` receipt, its replay, and the retained+# persistence_topology_changes outcome (src/core/persistence/source-lifecycle.ts)+# Clean (explicit field projections; covered by behavioral tests):+# - sources list / list --json / status / status --json / webhook show /+# current --json / archived / archived --json / remove --dry-run+# - parse warnings for re-wrapped configs (src/core/sources-load.ts)+# - remote MCP sources_list, sources_status, get_status_snapshot, run_doctor+# - local doctor --json+# - admin API GET /admin/api/sources (test/e2e/serve-http-oauth.test.ts)+# - backup metadata, restore reconnect lines and restore-receipt.json+# (test/agent-install-backup.serial.test.ts)+# - audit JSONL / log files under GBRAIN_HOME (none carry source config)+# Intentional one-time reveals, each printing the new secret exactly once:+# - `sources webhook set` and `sources webhook rotate` (src/commands/sources.ts)+# Documented sensitive state (kept): the full-database backup archive+# (classification 'sensitive-full-database-state') and the private 0600+# restore inventory .gbrain/restore-detached.json, which retains detached+# source configs so the operator can reconnect them.+# Internal readers that never serialize config (predicates only): sync,+# autopilot, source resolver, destructive guard, webhook HMAC check,+# connectors, minion authority (hashed into a digest), company brain.set -euo pipefaildiff --git a/scripts/check-test-placeholders.d.mts b/scripts/check-test-placeholders.d.mtsnew file mode 100644index 0000000000..0b7645cc2d--- /dev/null+++ b/scripts/check-test-placeholders.d.mts@@ -0,0 +1,21 @@+export interface PlaceholderSite {+ path: string;+ line: number;+ form: string;+ test: string;+}++export interface AllowlistEntry {+ path: string;+ test?: string;+ reason: string;+ count?: number;+}++export function scanTree(treeRoot: string, fixtures: boolean): { files: string[]; sites: PlaceholderSite[] } | null;++export function evaluate(+ sites: PlaceholderSite[],+ allowlist: AllowlistEntry[],+ treeRoot: string,+): { problems: string[]; allowedSites: number };diff --git a/scripts/check-test-placeholders.mjs b/scripts/check-test-placeholders.mjsnew file mode 100644index 0000000000..3b0c88cafa--- /dev/null+++ b/scripts/check-test-placeholders.mjs@@ -0,0 +1,229 @@+#!/usr/bin/env node+// check-test-placeholders.mjs — flags no-op placeholder assertions in tests.+//+// A test whose only assertion is `expect(true).toBe(true)` passes whatever the+// product does. This guard parses every test/**/*.test.ts file (excluding+// test/fixtures/**) with the TypeScript compiler API and visits CallExpression+// nodes, so text inside string and template literals is never matched. It+// flags exactly these no-op forms:+//+// expect(true) (no matcher)+// expect(true).toBe(true)+// expect(true).toBeTruthy()+// expect(1).toBe(1)+//+// `expect(true).toBe(false)` is a deliberate fail sentinel and is not flagged.+// This is a limited hygiene check: it does not detect low-value coverage in+// general (see docs/TESTING.md "Authoring gate").+//+// Allowlist entries are { path, test?, reason, count? } keyed by repo-relative+// path plus the enclosing test name ("describe > test"); `count` defaults to 1.+// A file or test with more sites than its entry fails as a new placeholder; an+// entry whose file or test is gone, or whose count is above the actual count,+// fails as stale.+//+// Self-test seam: argv[2] (or GBRAIN_GUARD_ROOT) points at a fixture tree with+// its own test/ directory; in fixture mode the allowlist is disabled and files+// named *.test.fixture.ts are scanned too (fixtures under the repo's test/ tree+// must not end in .test.ts, or the unit runner would execute them).+//+// Exit: 0 clean · 1 violations or stale allowlist entries · 2 infra error.++import { readdirSync, readFileSync, statSync, existsSync } from 'node:fs';+import { join, relative, sep } from 'node:path';+import { pathToFileURL } from 'node:url';+import ts from 'typescript';++const root = process.argv[2] || process.env.GBRAIN_GUARD_ROOT || '.';+const fixtureMode = !!(process.argv[2] || process.env.GBRAIN_GUARD_ROOT);++const RULE = 'test-placeholder-assertion';+const RERUN = 'bun run check:test-placeholders';+const DOC = 'docs/TESTING.md#placeholder-assertions';++const ALLOWLIST = [+ {+ path: 'test/operation-context-sourceid-required.test.ts',+ test: 'OperationContext.sourceId — REQUIRED contract > omitting sourceId from an OperationContext literal is a type error',+ reason: 'the assertion is the @ts-expect-error line, enforced by bun run typecheck in verify',+ },+ {+ path: 'test/operation-context-sourceid-required.test.ts',+ test: 'OperationContext.sourceId — REQUIRED contract > passing undefined for sourceId is a type error',+ reason: 'the assertion is the @ts-expect-error line, enforced by bun run typecheck in verify',+ },+ {+ path: 'test/e2e/embedding-column-postgres.test.ts',+ test: 'postgres E2E — embedding column (skipped: DATABASE_URL unset) > skipped',+ reason: 'body of a describe.skip visibility marker for the unset-DATABASE_URL arm; never executes',+ },+ {+ path: 'test/e2e/upsert-chunks-registry-column.test.ts',+ test: '#1262 upsertChunks registry-aware writes (postgres — skipped: DATABASE_URL unset) > skipped',+ reason: 'body of a describe.skip visibility marker for the unset-DATABASE_URL arm; never executes',+ },+ {+ path: 'test/e2e/graph-signals-eval.test.ts',+ test: 'Gate 1 (QUALITY): no statistically significant regression in wrong direction',+ reason: 'the gate fails by throwing a diagnostic above this line; the marker records that it passed',+ },+ {+ path: 'test/e2e/sync-credential-preflight.test.ts',+ test: 'v0.41.6.0 D1 E2E — gbrain sync preflight rejects missing OPENAI_API_KEY > does NOT write 565 identical entries to sync-failures.jsonl',+ reason: 'an absent sync-failures.jsonl is the correct outcome; the other branch asserts the file contents',+ },+];++function walk(dir, pattern, out = []) {+ for (const entry of readdirSync(dir)) {+ const p = join(dir, entry);+ if (statSync(p).isDirectory()) {+ if (entry === 'node_modules' || entry === '.git') continue;+ walk(p, pattern, out);+ } else if (pattern.test(p)) {+ out.push(p);+ }+ }+ return out;+}++function isLiteral(node, value) {+ if (value === true) return node.kind === ts.SyntaxKind.TrueKeyword;+ return ts.isNumericLiteral(node) && node.text === String(value);+}++function expectArg(node) {+ if (!ts.isCallExpression(node)) return null;+ if (!ts.isIdentifier(node.expression) || node.expression.text !== 'expect') return null;+ if (node.arguments.length !== 1) return null;+ const arg = node.arguments[0];+ if (isLiteral(arg, true)) return true;+ if (isLiteral(arg, 1)) return 1;+ return null;+}++function placeholderForm(call) {+ const subject = expectArg(call);+ if (subject === true) {+ const parent = call.parent;+ if (!ts.isPropertyAccessExpression(parent) || parent.expression !== call) return 'expect(true)';+ }+ if (!ts.isPropertyAccessExpression(call.expression)) return null;+ const inner = call.expression.expression;+ const matcher = call.expression.name.text;+ const innerSubject = expectArg(inner);+ if (innerSubject === true && matcher === 'toBe' && call.arguments.length === 1 && isLiteral(call.arguments[0], true)) {+ return 'expect(true).toBe(true)';+ }+ if (innerSubject === true && matcher === 'toBeTruthy' && call.arguments.length === 0) {+ return 'expect(true).toBeTruthy()';+ }+ if (innerSubject === 1 && matcher === 'toBe' && call.arguments.length === 1 && isLiteral(call.arguments[0], 1)) {+ return 'expect(1).toBe(1)';+ }+ return null;+}++const BLOCK_CALLEES = new Set(['describe', 'test', 'it', 'describeE2E', 'describeIf', 'testIf']);++function blockTitle(node) {+ if (!ts.isCallExpression(node) || node.arguments.length === 0) return null;+ let callee = node.expression;+ if (ts.isCallExpression(callee)) callee = callee.expression;+ while (ts.isPropertyAccessExpression(callee)) callee = callee.expression;+ if (!ts.isIdentifier(callee) || !BLOCK_CALLEES.has(callee.text)) return null;+ const first = node.arguments[0];+ if (ts.isStringLiteral(first) || ts.isNoSubstitutionTemplateLiteral(first)) return first.text;+ if (ts.isTemplateExpression(first)) return first.getText().slice(1, -1);+ return null;+}++function scanFile(abs, rel) {+ const text = readFileSync(abs, 'utf8');+ const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);+ const sites = [];+ const visit = (node, titles) => {+ let next = titles;+ if (ts.isCallExpression(node)) {+ const form = placeholderForm(node);+ if (form) {+ const { line } = sf.getLineAndCharacterOfPosition(node.getStart(sf));+ sites.push({ path: rel, line: line + 1, form, test: titles.length ? titles.join(' > ') : '' });+ }+ const title = blockTitle(node);+ if (title !== null) next = [...titles, title];+ }+ ts.forEachChild(node, child => visit(child, next));+ };+ visit(sf, []);+ return sites;+}++export function scanTree(treeRoot, fixtures) {+ const testDir = join(treeRoot, 'test');+ if (!existsSync(testDir)) return null;+ const fixturesPrefix = join(testDir, 'fixtures') + sep;+ const pattern = fixtures ? /\.test(\.fixture)?\.ts$/ : /\.test\.ts$/;+ const files = walk(testDir, pattern).filter(p => !p.startsWith(fixturesPrefix));+ const sites = files.flatMap(abs => scanFile(abs, relative(treeRoot, abs).split(sep).join('/')));+ return { files, sites };+}++export function evaluate(sites, allowlist, treeRoot) {+ const keyOf = (path, test) => `${path}\u0000${test ?? ''}`;+ const byKey = new Map();+ for (const site of sites) {+ const key = keyOf(site.path, site.test);+ if (!byKey.has(key)) byKey.set(key, []);+ byKey.get(key).push(site);+ }+ const footer = ` rerun: ${RERUN}\n docs: ${DOC}`;+ const problems = [];+ const allowed = new Map(allowlist.map(e => [keyOf(e.path, e.test), e]));+ for (const [key, group] of byKey) {+ const entry = allowed.get(key);+ const expected = entry ? (entry.count ?? 1) : 0;+ if (group.length <= expected) continue;+ for (const site of group) {+ problems.push([+ `${RULE}: ${site.path}:${site.line} uses \`${site.form}\`${site.test ? ` in "${site.test}"` : ''}.`,+ ` reason: this assertion passes whatever the product does, so the test protects no behavior.`,+ ` count: ${entry ? 'allowlist expects' : 'expected'} ${expected} placeholder(s) for this test, found ${group.length}.`,+ ` remedy: assert the observable outcome, delete the test if it has no contract, or add a reasoned allowlist entry in scripts/check-test-placeholders.mjs.`,+ footer,+ ].join('\n'));+ }+ }+ for (const entry of allowlist) {+ const actual = (byKey.get(keyOf(entry.path, entry.test)) ?? []).length;+ const expected = entry.count ?? 1;+ if (actual >= expected) continue;+ const why = !existsSync(join(treeRoot, entry.path)) ? 'its file no longer exists'+ : actual === 0 ? 'no placeholder remains for this test'+ : 'the placeholder count dropped';+ problems.push([+ `${RULE} (stale allowlist entry): ${entry.path}${entry.test ? ` "${entry.test}"` : ''}: ${why}.`,+ ` count: allowlist expects ${expected}, found ${actual}.`,+ ` remedy: remove the entry or reduce its count in scripts/check-test-placeholders.mjs; do not restore the placeholder.`,+ footer,+ ].join('\n'));+ }+ return { problems, allowedSites: sites.length };+}++function main() {+ const scan = scanTree(root, fixtureMode);+ if (!scan) {+ console.error(`check-test-placeholders: no test/ under ${root}`);+ process.exit(2);+ }+ const { problems, allowedSites } = evaluate(scan.sites, fixtureMode ? [] : ALLOWLIST, root);+ if (problems.length > 0) {+ console.error(problems.join('\n\n'));+ console.error(`\ncheck-test-placeholders: ${problems.length} problem(s). Rerun: ${RERUN}. See ${DOC}`);+ process.exit(1);+ }+ console.log(`check-test-placeholders: OK (${scan.files.length} test files, ${allowedSites} allowlisted placeholder site(s))`);+}++if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) main();diff --git a/scripts/check-test-real-names.sh b/scripts/check-test-real-names.shindex 759d970e18..ab179d0c33 100755--- a/scripts/check-test-real-names.sh+++ b/scripts/check-test-real-names.sh@@ -35,8 +35,7 @@ BANNED_NAMES=(# 'Hermes' removed (hermes-harness wave): here it names NousResearch/hermes-agent,# a PUBLIC platform gbrain documents (README hero, INSTALL_FOR_AGENTS.md) and now# tests against (claw-test hermes runner, install door e2e).- # test/readme-hero-anchors.test.ts REQUIRES the README to mention it. The original- # scrub targeted conflating the public agent with PRIVATE deployment names — those+ # The original scrub targeted conflating the public agent with PRIVATE deployment names — those# (Wintermute, and any future private fork names) remain banned above/below.'Technium' # real GP handle'McGrew' # ex-OpenAI exec@@ -62,14 +61,13 @@ ALLOWLIST=("test/recency-decay.test.ts:Wintermute" # regression-prevention test asserting wintermute is absent (structural)"test/scripts/check-proposal-pii.test.ts:Wintermute" # privacy-guard test asserting docs/proposals/ rejects wintermute (structural; same meta-rule exception as check-privacy.sh)"test/scripts/check-proposal-pii.test.ts:WINTERMUTE" # case-insensitive sentinel literal for the same privacy-guard test- "test/readme-hero-anchors.test.ts:OpenClaw" # v0.36.0.0 D9 anchor test — asserts README mentions OpenClaw as a credit# v0.36.0.0: skillpack-harvest privacy linter tests structurally# require the literal "Wintermute" to verify the linter catches it.# Same meta-rule exception as integrations.test.ts and the proposal-pii# privacy guard test above."test/skillpack-harvest.test.ts:Wintermute""test/skillpack-harvest-lint.test.ts:Wintermute"- "test/e2e/skillpack-flow.test.ts:Wintermute"+ "test/skillpack-flow.test.ts:Wintermute"# v0.40.1.0 Track D: eval-replay-gate.test.ts has a privacy-grep regression# guard whose block list necessarily SPELLS the real names so the test can# assert they're NOT in the qrels fixture. Same meta-rule exception as thediff --git a/scripts/classify-tests.ts b/scripts/classify-tests.tsindex d7f793b3ef..854566030e 100644--- a/scripts/classify-tests.ts+++ b/scripts/classify-tests.ts@@ -77,7 +77,8 @@ function windowAt(lines: string[], i: number, span = 4): string {function isRepoAnchored(win: string): boolean {if (TMP_ANCHORS.test(win)) return false;- return REPO_ANCHORS.some((r) => r.test(win));+ const code = win.replace(/\bimport\s*\(\s*(['"`])[^'"`]*\1\s*\)/g, '');+ return REPO_ANCHORS.some((r) => r.test(code));}export function classifyFile(relPath: string, content: string): FileResult {diff --git a/scripts/e2e-matrix.ts b/scripts/e2e-matrix.tsindex ae2e70ff94..36573b58f6 100644--- a/scripts/e2e-matrix.ts+++ b/scripts/e2e-matrix.ts@@ -5,11 +5,22 @@ import { realpathSync, statSync } from "node:fs";import { resolve, relative, isAbsolute } from "node:path";import { loadWeights, partition, type WeightMap } from "./sharding.ts";+// PR owner of the reconciliation crash suites is persistence-validation.yml+// (called from test.yml on every PR; postgres x Bun 1.3.11/1.3.13; crash+// manifests uploaded). Nightly full-corpus E2E still runs them.+export const PERSISTENCE_VALIDATION_OWNED = new Set([+ 'test/e2e/reconcile-crash.test.ts',+ 'test/e2e/reconcile-crash-unactivated.test.ts',+]);+export function exclusionNotice(file: string): string {+ return PERSISTENCE_VALIDATION_OWNED.has(file)+ ? `excluded: ${file} (owned by persistence-validation.yml)`+ : `excluded (named-job / live-key lane): ${file}`;+}export const E2E_EXCLUSIONS = new Set(['test/e2e/op-checkpoint-jsonb-parity.test.ts','test/e2e/jsonb-roundtrip.test.ts','test/e2e/mechanical.test.ts',- 'test/e2e/mcp.test.ts','test/e2e/job-isolation.test.ts','test/e2e/sync-reconcile-postgres.test.ts','test/e2e/engine-parity.test.ts',@@ -20,6 +31,7 @@ export const E2E_EXCLUSIONS = new Set(['test/e2e/skills.test.ts','test/e2e/voyage-rerank-live.test.ts','test/e2e/voyage-multimodal.test.ts',+ ...PERSISTENCE_VALIDATION_OWNED,]);export interface E2ERow { shard: number; files: string[]; empty: boolean }function validatePath(file: unknown): asserts file is string {@@ -32,7 +44,7 @@ export function prepareMatrix(files: string[], weights: WeightMap): { include: Eif (new Set(files).size !== files.length) throw new Error("duplicate selected E2E file");const selected = files.filter(file => {if (!E2E_EXCLUSIONS.has(file)) return true;- console.error(`excluded (named-job / live-key lane): ${file}`);+ console.error(exclusionNotice(file));return false;});if (!selected.length) return { include: [{ shard: 1, files: [], empty: true }] };diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 094469fe07..0201907a54 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -62,7 +62,6 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/serve-sync-runner.ts": ["test/e2e/sync-delegation-under-serve.serial.test.ts"],"src/commands/sync-delegate.ts": ["test/e2e/sync-delegation-under-serve.serial.test.ts"],"src/core/context/resolve-ipc.ts": [- "test/e2e/bootstrap-hook-under-serve.serial.test.ts","test/e2e/sync-delegation-under-serve.serial.test.ts",],// Codex session-end capture lane: the hooks writer + hook-lane parser +@@ -70,25 +69,23 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/bootstrap/codex-hooks.ts": ["test/e2e/bootstrap-real-codex.serial.test.ts"],"src/core/transcripts/codex-hook-lane.ts": ["test/e2e/bootstrap-real-codex.serial.test.ts"],"src/core/transcripts/capture-spec.ts": [- "test/e2e/bootstrap-hook-under-serve.serial.test.ts","test/e2e/bootstrap-real-codex.serial.test.ts",],// Concrete content and derived-information read policy parity.- "src/core/remote-body.ts": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts", "test/e2e/legacy-chunk-privacy.test.ts", "test/e2e/chunk-canonical-text-privacy.test.ts"],- "src/core/entity-identity.ts": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts"],- "src/core/ops/**": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts", "test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts", "test/e2e/chunk-canonical-text-privacy.test.ts", "test/e2e/put-page-persistence-postgres.test.ts", "test/e2e/deep-research-source-id.test.ts", "test/e2e/deep-research-http.test.ts"],+ "src/core/remote-body.ts": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts", "test/e2e/chunk-canonical-text-privacy.test.ts"],+ "src/core/entity-identity.ts": ["test/e2e/engine-content-privacy.test.ts"],+ "src/core/ops/**": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts", "test/e2e/chunk-canonical-text-privacy.test.ts", "test/e2e/put-page-persistence-postgres.test.ts", "test/e2e/deep-research-source-id.test.ts", "test/e2e/deep-research-http.test.ts"],"src/commands/whoknows.ts": ["test/e2e/read-enrichment-privacy.test.ts"],- "src/commands/orphans.ts": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts"],+ "src/commands/orphans.ts": ["test/e2e/engine-content-privacy.test.ts"],// Source-aware ranking, hybrid search, intent classification."src/core/search/**": ["test/e2e/unsupported-embedding-identity-postgres.test.ts","test/e2e/projection-statistics-postgres.test.ts","test/e2e/search-query-contract-postgres.test.ts","test/e2e/vector-candidate-safety-postgres.test.ts",- "test/e2e/search-readiness-http.test.ts","test/e2e/projection-readiness-currency.test.ts","test/e2e/chunk-canonical-text-privacy.test.ts",- "test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts",+ "test/e2e/engine-content-privacy.test.ts","test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts","test/e2e/search-quality.test.ts","test/e2e/search-exclude.test.ts",@@ -110,12 +107,6 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/openclaw-context-engine-plugin.test.ts","test/e2e/openclaw-plugin-load-real.test.ts",],- // claw-test harness (command + core: runners, scenarios, seeding, friction- // merge) feeds the scripted + shim-live E2E. The hermes door- // (install-real-hermes.serial.test.ts) is deliberately NOT mapped — it is- // opt-in-gated (GBRAIN_REAL_HERMES_E2E) and self-skips in run-all anyway.- "src/commands/claw-test.ts": ["test/e2e/claw-test.test.ts"],- "src/core/claw-test/**": ["test/e2e/claw-test.test.ts"],// dream.ts is a thin alias over runCycle in cycle.ts."src/core/cycle.ts": ["test/e2e/cycle.test.ts", "test/e2e/dream.test.ts"],// Multi-source sync writes share the per-source bookmark anchor.@@ -226,7 +217,6 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/withdrawal-bounded-safety-postgres.test.ts","test/e2e/withdrawal-crash-postgres.test.ts","test/e2e/memory-safety-wave-postgres.test.ts",- "test/e2e/fact-backfill-resident.test.ts","test/e2e/reconcile-crash.test.ts","test/e2e/reconcile-crash-unactivated.test.ts","test/e2e/reconcile-pgbouncer.test.ts",@@ -249,7 +239,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/persistence-chaos.test.ts","test/e2e/db-lock-acquisition-token.test.ts","test/e2e/chunk-canonical-text-privacy.test.ts",- "test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts",+ "test/e2e/engine-content-privacy.test.ts","test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts","test/e2e/postgres-bootstrap.test.ts","test/e2e/postgres-jsonb.test.ts",@@ -262,6 +252,11 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/health-parity-postgres.test.ts",// #4109: FOR KEY SHARE deletion-race behavior of addLink/addTimelineEntry."test/e2e/source-boundary-mutation-postgres.test.ts",+ // Shared-singleton ownership: disconnect idempotency, shared-pool+ // recovery and reconnect under a live singleton.+ "test/e2e/postgres-engine-disconnect-idempotency.test.ts",+ "test/e2e/db-singleton-shared-recovery.test.ts",+ "test/e2e/postgres-reconnect-singleton.test.ts",],// PGLite bootstrap path + parity guard."src/core/pglite-engine.ts": [@@ -270,7 +265,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/unsupported-embedding-identity-postgres.test.ts","test/e2e/persistence-chaos.test.ts","test/e2e/chunk-canonical-text-privacy.test.ts",- "test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts",+ "test/e2e/engine-content-privacy.test.ts","test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts","test/e2e/postgres-bootstrap.test.ts","test/e2e/engine-parity.test.ts",@@ -282,7 +277,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/postgres-engine/**": ["test/e2e/unsupported-embedding-identity-postgres.test.ts","test/e2e/chunk-canonical-text-privacy.test.ts",- "test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts",+ "test/e2e/engine-content-privacy.test.ts","test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts","test/e2e/postgres-bootstrap.test.ts","test/e2e/postgres-jsonb.test.ts",@@ -296,7 +291,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/pglite-engine/**": ["test/e2e/unsupported-embedding-identity-postgres.test.ts","test/e2e/chunk-canonical-text-privacy.test.ts",- "test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts",+ "test/e2e/engine-content-privacy.test.ts","test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts","test/e2e/postgres-bootstrap.test.ts","test/e2e/engine-parity.test.ts",@@ -344,35 +339,15 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/link-source-check-repair.ts": ["test/e2e/link-source-check-repair-postgres.test.ts"],"src/core/vector-index.ts": ["test/e2e/migration-vector-replay-postgres.test.ts"],// MCP stdio + HTTP transports share dispatch.- "src/mcp/**": ["test/e2e/mcp.test.ts", "test/e2e/http-transport.test.ts", "test/e2e/mcp-search-transport-matrix.test.ts"],- // G6: the --surface verbs CEILING journey over a real `serve --http` boot- // (hermetic PGLite): 7-verb tools/list for full-preset + bare clients,- // fail-closed dispatch on hidden ops, the narrow-only- // GBRAIN_MCP_FORCE_SURFACE kill switch, and a verb round-trip. Keyed on the- // surface implementation; the selector UNIONS this with the src/mcp/**- // entry above. src/commands/serve.ts stays deliberately unmapped- // (fail-closed run-all), so serve-side changes hit this suite too.- "src/mcp/surface.ts": ["test/e2e/serve-http-surface-ceiling.test.ts"],+ "src/mcp/**": ["test/e2e/http-transport.test.ts", "test/e2e/mcp-search-transport-matrix.test.ts"],// Integrity batch-load fast path."src/commands/integrity.ts": ["test/e2e/integrity-batch.test.ts"],- // gbrain connect — raw-bearer MCP smoke probe exercised end-to-end against- // a real serve --http (PGLite), so changes to either feed it.- "src/commands/connect.ts": ["test/e2e/connect-bearer.test.ts"],- "src/core/connect-probe.ts": ["test/e2e/connect-bearer.test.ts"],- // G4: brain-axis mount ROUTING journey — resolver tiers (flag > env >- // dotfile > path-prefix > host) exercised over real CLI spawns against two- // real PGLite DBs. mounts.ts subcommand dispatch itself is unit-covered in- // test/mounts-cli.test.ts; this e2e pins the resolver→engine wiring.- "src/core/brain-resolver.ts": ["test/e2e/mounts-routing-pglite.test.ts"],- "src/commands/mounts.ts": ["test/e2e/mounts-routing-pglite.test.ts"],// Upgrade chains migration ledger; touches both runners. The bun-link arc- // (detection marker, pull→install ordering, post-upgrade ledger checkpoint,- // --swap-only) is behaviorally pinned by the shimmed serial e2e (G6).+ // is pinned by test/upgrade-bun-link-arc.serial.test.ts (serial lane)."src/commands/upgrade.ts": ["test/e2e/upgrade.test.ts","test/e2e/migrate-chain.test.ts","test/e2e/migration-flow.test.ts",- "test/e2e/upgrade-bun-link-arc.serial.test.ts",],"src/commands/apply-migrations.ts": ["test/e2e/migration-preview-safety.test.ts",@@ -429,8 +404,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/ingestion-roundtrip.test.ts","test/e2e/serve-http-ingest-webhook.test.ts",],- "src/core/embed-facts*.ts": ["test/e2e/fact-embedding-backfill-parity.test.ts", "test/e2e/fact-backfill-resident.test.ts"],- "src/commands/embed-facts-delegate.ts": ["test/e2e/fact-backfill-resident.test.ts"],+ "src/core/embed-facts*.ts": ["test/e2e/fact-embedding-backfill-parity.test.ts"],"src/core/cycle/extract-facts.ts": ["test/e2e/fact-vector-repair-parity.test.ts", "test/e2e/facts-fence-reconcile-postgres.test.ts"],"src/core/cycle/phases/consolidate.ts": ["test/e2e/managed-maintenance.test.ts", "test/e2e/cycle.test.ts"],"src/core/ops/facts.ts": ["test/e2e/managed-facts-backstop.test.ts"],diff --git a/scripts/e2e-weights.json b/scripts/e2e-weights.jsonindex 69374e5562..976cb78799 100644--- a/scripts/e2e-weights.json+++ b/scripts/e2e-weights.json@@ -5,13 +5,10 @@"test/e2e/autopilot-cooldown-parity.test.ts": 1950,"test/e2e/autopilot-fanout-postgres.test.ts": 1308,"test/e2e/autopilot-linux-lifecycle.serial.test.ts": 12420,- "test/e2e/backfill-perf-pglite.test.ts": 10760,"test/e2e/backup-coverage-parity.test.ts": 2230,"test/e2e/bootstrap-attach.serial.test.ts": 5010,"test/e2e/bootstrap-compiled-binary.serial.test.ts": 4059.9999999999995,"test/e2e/bootstrap-degraded-modes.serial.test.ts": 5730,- "test/e2e/bootstrap-harness-lifecycle.serial.test.ts": 8280,- "test/e2e/bootstrap-hook-under-serve.serial.test.ts": 9780,"test/e2e/bootstrap-keyed-postgres.serial.test.ts": 2580,"test/e2e/bootstrap-lifecycle.serial.test.ts": 6390,"test/e2e/bootstrap-magic-moment.serial.test.ts": 4980,@@ -28,7 +25,6 @@"test/e2e/chunker-takes-strip.test.ts": 1260,"test/e2e/cjk-roundtrip.test.ts": 1670,"test/e2e/claude-plugin-install-real.serial.test.ts": 544,- "test/e2e/claw-test.test.ts": 185940,"test/e2e/cli-source-scoping-pglite.test.ts": 1560,"test/e2e/client-grants.test.ts": 1850,"test/e2e/code-edges-jsonb-postgres.test.ts": 1149,@@ -39,7 +35,6 @@"test/e2e/company-brain-receipts.test.ts": 846,"test/e2e/compile-context-pglite.test.ts": 1640,"test/e2e/concurrent-embed-race.test.ts": 1251,- "test/e2e/connect-bearer.test.ts": 10690,"test/e2e/connector-sync-handler-pglite.test.ts": 1690,"test/e2e/connectors-sync-pglite.test.ts": 5680,"test/e2e/contextual-retrieval-pglite.test.ts": 2640,@@ -61,7 +56,6 @@"test/e2e/dream-allow-list-pglite.test.ts": 2490,"test/e2e/dream-cycle-phase-order-pglite.test.ts": 3230,"test/e2e/dream-patterns-pglite.test.ts": 4010,- "test/e2e/dream-synthesize-chunking.test.ts": 9090,"test/e2e/dream-synthesize-concurrency-postgres.test.ts": 12860,"test/e2e/dream-synthesize-pglite.test.ts": 14040,"test/e2e/dream-triage-postgres.test.ts": 1329,@@ -82,7 +76,6 @@"test/e2e/extract-atoms-discovery-sql.test.ts": 1354,"test/e2e/extract-atoms-page-state.test.ts": 2650,"test/e2e/extraction-review-postgres.test.ts": 1580,- "test/e2e/fact-backfill-resident.test.ts": 7820,"test/e2e/fact-embedding-backfill-parity.test.ts": 5570,"test/e2e/fact-vector-repair-parity.test.ts": 5000,"test/e2e/facts-context-injection-postgres.test.ts": 1273,@@ -94,7 +87,6 @@"test/e2e/facts-recall-render.test.ts": 1270,"test/e2e/facts-separation-postgres.test.ts": 1269,"test/e2e/facts-worker-config.test.ts": 2420,- "test/e2e/fresh-install-pglite.test.ts": 23380,"test/e2e/frontmatter-migration.test.ts": 3490,"test/e2e/global-basename-pglite.test.ts": 2890,"test/e2e/grandfather-projection-postgres.test.ts": 5350,@@ -106,7 +98,6 @@"test/e2e/http-transport.test.ts": 1660,"test/e2e/import-credential-preflight.test.ts": 1790,"test/e2e/ingestion-roundtrip.test.ts": 2860,- "test/e2e/init-fresh-pglite.test.ts": 44500,"test/e2e/install-real-grok.serial.test.ts": 557,"test/e2e/install-real-hermes.serial.test.ts": 521,"test/e2e/install-real-opencode.serial.test.ts": 509,@@ -134,7 +125,6 @@"test/e2e/managed-sync-failures.test.ts": 56060,"test/e2e/managed-synthesis-postprocess.test.ts": 20490,"test/e2e/mcp-budget-reservation-postgres.test.ts": 582,- "test/e2e/mcp.test.ts": 473,"test/e2e/mechanical.test.ts": 68280,"test/e2e/migrate-chain.test.ts": 3460,"test/e2e/migrate-embeddings-postgres.test.ts": 1760,@@ -148,16 +138,11 @@"test/e2e/migration-v47-notability.test.ts": 1258,"test/e2e/migration-v50-ingest-log-source-id.test.ts": 1257,"test/e2e/minions-authority-parity.test.ts": 1426,- "test/e2e/minions-budget-cathedral.test.ts": 1394,"test/e2e/minions-concurrency.test.ts": 1730,- "test/e2e/minions-controller-bounce-only.test.ts": 1305,- "test/e2e/minions-field-report-repro.test.ts": 26470,"test/e2e/minions-prefix-strip-smoke.test.ts": 1417,"test/e2e/minions-resilience.test.ts": 12690,- "test/e2e/minions-self-fix-flow.test.ts": 1243,"test/e2e/minions-shell-pglite.test.ts": 2050,"test/e2e/minions-shell.test.ts": 1680,- "test/e2e/mounts-routing-pglite.test.ts": 31030,"test/e2e/multi-source-bug-class.test.ts": 3520,"test/e2e/multi-source-emotional-weight-pglite.test.ts": 1168,"test/e2e/multi-source.test.ts": 5470,@@ -170,8 +155,6 @@"test/e2e/openclaw-context-engine-plugin.test.ts": 322,"test/e2e/openclaw-plugin-load-real.test.ts": 179,"test/e2e/openclaw-reference-compat.test.ts": 1372,- "test/e2e/openrouter-anthropic-subagent-replay.live.test.ts": 1560,- "test/e2e/openrouter-deepseek-subagent-replay.live.test.ts": 1500,"test/e2e/orphan-reduction.test.ts": 4090,"test/e2e/persistence-admin-intent.test.ts": 10430,"test/e2e/persistence-chaos.test.ts": 28520,@@ -192,13 +175,11 @@"test/e2e/propose-takes-jsonb-postgres.test.ts": 1276,"test/e2e/purge-deleted-dryrun-postgres.test.ts": 1256,"test/e2e/put-page-persistence-postgres.test.ts": 12410,- "test/e2e/qm-provisioning.test.ts": 28260,"test/e2e/quarantine-search-exclusion.test.ts": 2760,"test/e2e/read-enrichment-privacy.test.ts": 5630,"test/e2e/reconcile-crash-unactivated.test.ts": 97900,"test/e2e/reconcile-crash.test.ts": 97840,"test/e2e/reconcile-pgbouncer.test.ts": 482,- "test/e2e/remote-privacy-journeys.test.ts": 19870,"test/e2e/restore-source-config-jsonb-postgres.test.ts": 1246,"test/e2e/salience-anomalies-source-isolation-pglite.test.ts": 1610,"test/e2e/salience-llm-routing.test.ts": 177,@@ -208,7 +189,6 @@"test/e2e/search-exclude.test.ts": 1650,"test/e2e/search-quality.test.ts": 1499,"test/e2e/search-query-contract-postgres.test.ts": 2300,- "test/e2e/search-readiness-http.test.ts": 8650,"test/e2e/search-swamp.test.ts": 1408,"test/e2e/self-upgrade-binary-swap.test.ts": 194,"test/e2e/self-upgrade-marker.test.ts": 4420,@@ -218,15 +198,12 @@"test/e2e/serve-http-multi-agent.test.ts": 19360,"test/e2e/serve-http-oauth.test.ts": 21020,"test/e2e/serve-http-source-grant.test.ts": 3530,- "test/e2e/serve-http-surface-ceiling.test.ts": 16810,"test/e2e/serve-http-takes-holders.test.ts": 3340,- "test/e2e/serve-stdio-roundtrip.test.ts": 19790,"test/e2e/shared-skills-rls.test.ts": 2070,"test/e2e/shared-skills-transports.test.ts": 15630,"test/e2e/skill-brain-first.test.ts": 828,"test/e2e/skillopt-loop.serial.test.ts": 6290,"test/e2e/skillopt-pglite.serial.test.ts": 1980,- "test/e2e/skillpack-flow.test.ts": 13680,"test/e2e/skillpack-third-party.test.ts": 6400,"test/e2e/skills.test.ts": 318,"test/e2e/source-boundary-mutation-postgres.test.ts": 1152,@@ -258,21 +235,14 @@"test/e2e/thin-client.test.ts": 14770,"test/e2e/think-source-isolation-pglite.test.ts": 1860,"test/e2e/think-trajectory-pglite.test.ts": 2000,- "test/e2e/transcripts-ingest-pglite.test.ts": 8590,"test/e2e/transcripts-writeback-fidelity.test.ts": 2590,"test/e2e/type-unification-full-flow.test.ts": 2670,- "test/e2e/upgrade-bun-link-arc.serial.test.ts": 9250,"test/e2e/upgrade.test.ts": 3180,"test/e2e/upsert-chunks-registry-column.test.ts": 2520,- "test/e2e/v030_1-integration-pglite.test.ts": 31010,- "test/e2e/v0_28_5-fix-wave.test.ts": 12890,"test/e2e/v0_29-mcp-dispatch-pglite.test.ts": 1710,- "test/e2e/v0_30_3-fix-wave.test.ts": 11110,"test/e2e/vector-candidate-safety-postgres.test.ts": 26430,"test/e2e/vector-ef-search-postgres.test.ts": 5330,"test/e2e/volunteer-context-postgres.test.ts": 1241,- "test/e2e/voyage-multimodal.test.ts": 175,- "test/e2e/voyage-rerank-live.test.ts": 162,"test/e2e/whoknows.test.ts": 2450,"test/e2e/worker-abort-recovery.test.ts": 5050,"test/e2e/worker-lock-renewal-starvation.test.ts": 4040,diff --git a/scripts/e2e-weights.metadata.json b/scripts/e2e-weights.metadata.jsonindex 5a212b9561..8f08cfdf6f 100644--- a/scripts/e2e-weights.metadata.json+++ b/scripts/e2e-weights.metadata.json@@ -4,8 +4,8 @@"run": "35964154815","commit": "31f257a0a7b218b40e03d302bc6913c99f26f0ec","source": "github",- "measuredFiles": 281,- "totalFiles": 281,+ "measuredFiles": 274,+ "totalFiles": 274,"mergeExisting": false,"e2eProfile": "full","attempt": 1,diff --git a/scripts/e5-lease-cap-ab.ts b/scripts/e5-lease-cap-ab.tsdeleted file mode 100644index f12eeb8564..0000000000--- a/scripts/e5-lease-cap-ab.ts+++ /dev/null@@ -1,247 +0,0 @@-#!/usr/bin/env bun-/**- * v0.41 E5 A/B harness (D11 + codex pass-2 #7 spec).- *- * Manually-runnable script that proves the auto-adaptive lease-cap- * controller beats fixed-cap on a real upstream. Writes a structured- * receipt to test/fixtures/e5-lease-cap-ab/{timestamp}.json — that file- * is committed as the baseline. Future controller changes ship with- * their own receipt + diff against prior.- *- * **Spec (D11):**- * Workload: 500 subagent jobs, log-normal prompt distribution- * (mean 2k tokens, p99 16k tokens). Synthesized via fixture file.- * Provider: Anthropic (real API) via gateway.- * Cost cap: --budget-usd 8 per arm (D5 enforced).- * Failure injection: synthetic 429 burst at minute 15 (10s window).- * Statistical threshold: controller arm must beat fixed-cap on- * (completed_jobs / wall_clock_time) by ≥5% AND match- * (completed_jobs / dollars_spent) within ±2%.- *- * **Usage:**- * ANTHROPIC_API_KEY=sk-... bun scripts/e5-lease-cap-ab.ts- * ANTHROPIC_API_KEY=sk-... bun scripts/e5-lease-cap-ab.ts --dry-run- *- * **Cost:** ~$16 per full run ($8/arm × 2 arms). Approximate; depends on- * actual prompt lengths sampled from the fixture.- *- * **Not in CI:** This script requires a real API key + ~30min wall-clock- * + real Anthropic budget. Intended to be run BEFORE landing a controller- * change; receipt is the durable artifact. CI gating happens via the- * unit-test suite (`lease-cap-controller.test.ts` covers the pure- * decision function exhaustively).- */--import { writeFileSync, mkdirSync, existsSync } from 'fs';-import { join } from 'path';-import { PostgresEngine } from '../src/core/postgres-engine.ts';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { loadConfig } from '../src/core/config.ts';-import type { BrainEngine } from '../src/core/engine.ts';--interface ArmStats {- arm: 'fixed' | 'adaptive';- jobs_submitted: number;- jobs_completed: number;- jobs_dead: number;- wall_clock_ms: number;- total_cost_usd: number;- lease_cap_history: number[];- bounces: number;- upstream_429s: number;-}--interface ABReceipt {- schema_version: 1;- timestamp: string;- spec: {- job_count: number;- budget_per_arm_usd: number;- injection_at_min: number;- };- arms: ArmStats[];- verdict: {- throughput_advantage_pct: number;- cost_efficiency_delta_pct: number;- pr_gate_pass: boolean;- note: string;- };-}--function parseArgs(argv: string[]) {- const args = {- dryRun: argv.includes('--dry-run'),- jobs: 500,- budgetUsd: 8,- };- for (const arg of argv) {- if (arg.startsWith('--jobs=')) args.jobs = parseInt(arg.split('=')[1] ?? '500', 10);- if (arg.startsWith('--budget-usd=')) args.budgetUsd = parseFloat(arg.split('=')[1] ?? '8');- }- return args;-}--async function openEngine(): Promise<BrainEngine> {- const cfg = loadConfig();- if (cfg?.database_url) {- const engine = new PostgresEngine();- await engine.connect({ database_url: cfg.database_url });- return engine;- }- // Fallback: PGLite ephemeral. Real A/B runs should use Postgres so the- // lease-cap controller's elected-mutator pattern is exercised cross-process.- process.stderr.write('[e5-ab] WARN: using PGLite ephemeral (no DATABASE_URL); cross-worker tests will not run\n');- const engine = new PGLiteEngine();- await engine.connect({ database_url: '' });- await engine.initSchema();- return engine;-}--/**- * Generate a synthetic prompt with the spec'd token distribution.- * Approximate — uses character counts as a stand-in for tokens (1 token- * ≈ 4 chars on English).- */-function syntheticPrompt(index: number): string {- // Log-normal mean=2k tokens, σ such that p99 = 16k tokens.- // log(p99/p50) = z_99 * σ → σ ≈ ln(8) / 2.33 ≈ 0.89- const mu = Math.log(2000);- const sigma = 0.89;- // Box-Muller for deterministic-per-index pseudo-Normal sample.- const u1 = ((index * 9301 + 49297) % 233280) / 233280;- const u2 = ((index * 13849 + 65521) % 233280) / 233280;- const z = Math.sqrt(-2 * Math.log(Math.max(u1, 1e-9))) * Math.cos(2 * Math.PI * u2);- const tokens = Math.exp(mu + sigma * z);- const chars = Math.max(40, Math.min(64000, Math.floor(tokens * 4)));- return `Synthetic A/B test prompt #${index}. Body: ` + 'X'.repeat(chars - 40);-}--async function runArm(- engine: BrainEngine,- arm: 'fixed' | 'adaptive',- opts: { jobs: number; budgetUsd: number; dryRun: boolean },-): Promise<ArmStats> {- const start = Date.now();- const lease_cap_history: number[] = [];- let jobs_submitted = 0;- let jobs_completed = 0;- let jobs_dead = 0;- let total_cost_usd = 0;- let bounces = 0;- let upstream_429s = 0;-- process.stderr.write(`[e5-ab] === arm=${arm} starting ===\n`);-- // Configure the cap policy for this arm.- if (arm === 'fixed') {- await engine.setConfig('minions.auto_lease_cap', 'false');- await engine.setConfig('minions.lease_cap_current', '8');- } else {- await engine.setConfig('minions.auto_lease_cap', 'true');- await engine.setConfig('minions.lease_cap_current', '8');- }-- if (opts.dryRun) {- process.stderr.write(`[e5-ab] --dry-run: skipping real submission. Would submit ${opts.jobs} jobs.\n`);- return {- arm,- jobs_submitted: opts.jobs,- jobs_completed: 0,- jobs_dead: 0,- wall_clock_ms: Date.now() - start,- total_cost_usd: 0,- lease_cap_history: [8],- bounces: 0,- upstream_429s: 0,- };- }-- // Real-run scaffolding lives here. v0.41 ships the spec; the full- // dispatcher (queue submit + worker spin-up + 15-min 429 injector +- // tick loop) lands in the follow-up wave when the controller has been- // exercised manually first. Receipt fixture is committed as a baseline- // shape for future runs to diff against.- process.stderr.write(`[e5-ab] arm=${arm}: real-run implementation deferred to v0.41.1 follow-up.\n`);- process.stderr.write(`[e5-ab] See CHANGELOG.md "v0.41.0.0 → v0.41.1.0 follow-up" for details.\n`);-- return {- arm,- jobs_submitted,- jobs_completed,- jobs_dead,- wall_clock_ms: Date.now() - start,- total_cost_usd,- lease_cap_history,- bounces,- upstream_429s,- };-}--function computeVerdict(fixed: ArmStats, adaptive: ArmStats): ABReceipt['verdict'] {- // Throughput ratio: completed_jobs / wall_clock_ms. Higher is better.- const tputFixed = fixed.wall_clock_ms > 0 ? fixed.jobs_completed / fixed.wall_clock_ms : 0;- const tputAdaptive = adaptive.wall_clock_ms > 0 ? adaptive.jobs_completed / adaptive.wall_clock_ms : 0;- const throughputAdvantage = tputFixed > 0 ? ((tputAdaptive - tputFixed) / tputFixed) * 100 : 0;-- // Cost efficiency ratio: completed_jobs / dollars. Higher is better.- const effFixed = fixed.total_cost_usd > 0 ? fixed.jobs_completed / fixed.total_cost_usd : 0;- const effAdaptive = adaptive.total_cost_usd > 0 ? adaptive.jobs_completed / adaptive.total_cost_usd : 0;- const costEfficiencyDelta = effFixed > 0 ? ((effAdaptive - effFixed) / effFixed) * 100 : 0;-- // PR gate: adaptive must beat fixed by ≥5% on throughput AND match- // within ±2% on cost efficiency.- const pr_gate_pass = throughputAdvantage >= 5 && Math.abs(costEfficiencyDelta) <= 2;-- return {- throughput_advantage_pct: Math.round(throughputAdvantage * 100) / 100,- cost_efficiency_delta_pct: Math.round(costEfficiencyDelta * 100) / 100,- pr_gate_pass,- note: pr_gate_pass- ? 'controller beats fixed-cap; safe to default ON'- : 'controller does NOT meet PR gate; defaults stay OFF',- };-}--async function main() {- const argv = process.argv.slice(2);- const opts = parseArgs(argv);-- const engine = await openEngine();- try {- const fixed = await runArm(engine, 'fixed', opts);- const adaptive = await runArm(engine, 'adaptive', opts);- const verdict = computeVerdict(fixed, adaptive);-- const receipt: ABReceipt = {- schema_version: 1,- timestamp: new Date().toISOString(),- spec: {- job_count: opts.jobs,- budget_per_arm_usd: opts.budgetUsd,- injection_at_min: 15,- },- arms: [fixed, adaptive],- verdict,- };-- const fixtureDir = join(process.cwd(), 'test/fixtures/e5-lease-cap-ab');- if (!existsSync(fixtureDir)) mkdirSync(fixtureDir, { recursive: true });- const receiptPath = join(- fixtureDir,- `${new Date().toISOString().replace(/[:.]/g, '-')}${opts.dryRun ? '-dry-run' : ''}.json`,- );- writeFileSync(receiptPath, JSON.stringify(receipt, null, 2));- process.stderr.write(`[e5-ab] receipt written: ${receiptPath}\n`);- process.stderr.write(`[e5-ab] verdict: ${verdict.note}\n`);- process.exit(verdict.pr_gate_pass || opts.dryRun ? 0 : 1);- } finally {- await engine.disconnect().catch(() => {});- }-}--if (import.meta.main) {- main().catch(err => {- process.stderr.write(`[e5-ab] FATAL: ${err instanceof Error ? err.message : String(err)}\n`);- process.exit(2);- });-}diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsvindex 21b42a297d..867a12b407 100644--- a/scripts/guards-manifest.tsv+++ b/scripts/guards-manifest.tsv@@ -68,5 +68,6 @@ check-structural-manifest.sh buildfresh exempt regenerate+diff of structural-suicheck-opencode-pin.sh repostate exempt pin-stamp drift check (OPENCODE-CLI-PIN.md stamps vs heavy-tests opencode-door env); own bun guard tests in test/check-bootstrap-guards.test.tscheck-pin-doc-privacy.sh repostate exempt PIN-doc placeholder discipline (no operator paths/key material/emails in docs/mcp/*-CLI-PIN.md); own bun guard tests in test/check-bootstrap-guards.test.tscheck-getpage-scoped-write.mjs scanner yes unscoped-getPage + write co-occurrence scanner (source-isolation bug class); argv root override; fixtures under test/fixtures/guards/; also in verify CHECKS-check-orphan-modules.mjs scanner yes runtime-reachability walk (static+dynamic relative imports) from cli/mcp/plugin/admin entrypoints + package.json exports; hard-fails untested orphans, ratchets the test-only tier; fixture root via argv/GBRAIN_GUARD_ROOT; knip v5 evaluated + rejected (crashes on repo layout — see script header)+check-orphan-modules.mjs scanner yes runtime-reachability walk (static+dynamic relative imports) from cli/mcp/plugin/admin entrypoints + package.json exports; hard-fails untested orphans, requires a reasoned PERMITTED_TEST_ONLY entry per test-only module (stale entries fail); fixture root via argv/GBRAIN_GUARD_ROOT; knip v5 evaluated + rejected (crashes on repo layout — see script header)+check-test-placeholders.mjs scanner yes TypeScript AST (CallExpression) scan of test/**/*.test.ts for no-op expect(true)/expect(1) placeholders; path+test+count allowlist (disabled in fixture mode); fixture root via argv/GBRAIN_GUARD_ROOT; in verify CHECKScheck-test-discriminates.sh buildfresh exempt manual per-PR discrimination helper (#3665): reverts named source files to their pre-fix state and runs the named test file to prove it fails without the fix — the test run IS the check; not in verify CHECKS or CIdiff --git a/scripts/run-e2e.sh b/scripts/run-e2e.shindex 8df8509a85..2405767610 100755--- a/scripts/run-e2e.sh+++ b/scripts/run-e2e.sh@@ -173,7 +173,14 @@ else# phantom-redirect lives in test/ (its PGLite arm runs in the unit suite) but# its Postgres arm is only reachable through a DATABASE_URL-bearing lane —# the unit wrappers strip the URL (#3485), so this lane must carry it.- files=(test/e2e/*.test.ts test/phantom-redirect-engine-parity.test.ts)+ # Key-gated live files no CI job provides keys for; run them by name (docs/TESTING.md).+ live_key_only=" test/e2e/openrouter-anthropic-subagent-replay.live.test.ts test/e2e/openrouter-deepseek-subagent-replay.live.test.ts test/e2e/voyage-multimodal.test.ts test/e2e/voyage-rerank-live.test.ts "+ files=()+ for f in test/e2e/*.test.ts; do+ case "$live_key_only" in *" $f "*) continue ;; esac+ files+=("$f")+ done+ files+=(test/phantom-redirect-engine-parity.test.ts)fi# Weighted across isolated databases, sequential within each shard.diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex e0259542b9..0abff02401 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -58,9 +58,12 @@ CHECKS=(# scripts/guards-manifest.tsv (package.json's stale `check:all` copy deleted)."check:guard-self-test"# B4 (test-gap wave 2): runtime-reachability walk over src/** — hard-fails- # true orphans (unreachable from every entrypoint AND every test), ratchets- # the test-only-reachable tier. Whole-tree readFileSync walk, ~1s.+ # true orphans (unreachable from every entrypoint AND every test) and any+ # test-only module without a reasoned PERMITTED_TEST_ONLY entry. ~1s."check:orphan-modules"+ # No-op placeholder assertions (expect(true).toBe(true) and friends) in+ # test/**/*.test.ts; TypeScript AST scan, ~3s over the full corpus.+ "check:test-placeholders"# Chronicle eval: $0, deterministic, exit-0-only-on-perfect (6 gold tasks).# Boots its own PGLite — budget ≤60s under a saturated pool; if it breaches# ~100s under contention, move it into the serial-tests CI job instead.diff --git a/scripts/select-e2e.ts b/scripts/select-e2e.tsindex c8ed99b9ef..5a211c1c36 100644--- a/scripts/select-e2e.ts+++ b/scripts/select-e2e.ts@@ -35,6 +35,7 @@ import { readdirSync, existsSync } from "node:fs";import { join } from "node:path";import { E2E_TEST_MAP } from "./e2e-test-map.ts";+import { PERSISTENCE_VALIDATION_OWNED, exclusionNotice } from "./e2e-matrix.ts";// Doc allowlist (inclusive). A path counts as doc-only ONLY if it matches one// of these patterns. Unrecognized paths fall through to SRC, never silently@@ -193,6 +194,18 @@ export function selectTests(inputs: SelectInputs): string[] {return Array.from(result).sort();}+export function persistenceOwnedNotices(changedFiles: string[], map: Record<string, string[]>): string[] {+ const owned = new Set<string>();+ for (const f of changedFiles) {+ if (PERSISTENCE_VALIDATION_OWNED.has(f)) owned.add(f);+ for (const [glob, tests] of Object.entries(map)) {+ if (!matchGlob(glob, f)) continue;+ for (const t of tests) if (PERSISTENCE_VALIDATION_OWNED.has(t)) owned.add(t);+ }+ }+ return Array.from(owned).sort().map(exclusionNotice);+}+function runGit(args: string[], cwd: string): string {const result = spawnSync("git", args, { cwd, encoding: "utf8" });if (result.status !== 0) {@@ -247,6 +260,7 @@ if (import.meta.main) {map: E2E_TEST_MAP,});+ for (const notice of persistenceOwnedNotices(changedFiles, E2E_TEST_MAP)) process.stderr.write(notice + "\n");process.stdout.write(tests.join("\n"));if (tests.length > 0) process.stdout.write("\n");}diff --git a/scripts/serial-weights.json b/scripts/serial-weights.jsonindex eb36732a8a..85c89e694e 100644--- a/scripts/serial-weights.json+++ b/scripts/serial-weights.json@@ -25,7 +25,9 @@"test/backup-status-file.serial.test.ts": 1,"test/binary-self-update-compiled.serial.test.ts": 1,"test/bootstrap-dispatcher.serial.test.ts": 1,+ "test/bootstrap-harness-lifecycle.serial.test.ts": 8,"test/bootstrap-harness.serial.test.ts": 1,+ "test/bootstrap-hook-under-serve.serial.test.ts": 10,"test/bootstrap-interview.serial.test.ts": 0,"test/bootstrap-opencode-door.serial.test.ts": 3,"test/bootstrap-plugin-lane.serial.test.ts": 1,@@ -81,6 +83,7 @@"test/dream-drain-failure-summary.serial.test.ts": 3,"test/dream-owner-id-threading.serial.test.ts": 3,"test/dream-postgres.serial.test.ts": 9,+ "test/dream-synthesize-chunking.serial.test.ts": 9,"test/embed-backfill-cli-admission.serial.test.ts": 77,"test/embed-exit-code-3037.serial.test.ts": 21,"test/embed-input-type-wire.serial.test.ts": 1,@@ -104,6 +107,7 @@"test/facts-valid-from-context.serial.test.ts": 3,"test/filing-rules-resolution.serial.test.ts": 1,"test/foreground-chat-gateway-init.serial.test.ts": 1,+ "test/fresh-install-pglite.serial.test.ts": 23,"test/friction-diff.serial.test.ts": 1,"test/fts-language-cache-isolation.serial.test.ts": 3,"test/fts-language-migration.serial.test.ts": 0,@@ -198,6 +202,7 @@"test/reindex-search-vector.serial.test.ts": 0,"test/remediation-run-extras.serial.test.ts": 3,"test/remediation-run-loop.serial.test.ts": 0,+ "test/remote-privacy-journeys.serial.test.ts": 20,"test/rerank-no-key.serial.test.ts": 0,"test/rerank-sunset-short-circuit.serial.test.ts": 0,"test/schema-cli-database-path.serial.test.ts": 11,@@ -248,8 +253,9 @@"test/think-pipeline.serial.test.ts": 5,"test/think-temporal-window.serial.test.ts": 4,"test/unified-multimodal.serial.test.ts": 6,- "test/upgrade-checkpoint.serial.test.ts": 0,+ "test/upgrade-bun-link-arc.serial.test.ts": 9,"test/upgrade.serial.test.ts": 5,+ "test/v0_28_5-fix-wave.serial.test.ts": 13,"test/v0_37_fix_wave.serial.test.ts": 1,"test/v0_37_gap_fill.serial.test.ts": 13,"test/watch-sigint.serial.test.ts": 13,diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 41be1917a6..a33651d045 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -10,7 +10,6 @@ test/apply-migrations.test.ts failed migration prints phase detail (#921) 1 readtest/apply-migrations.test.ts resolveSchemaBehind (#1530) 5 readFileSynctest/apply-migrations.test.ts runApplyMigrations exit codes (v0.36.1.x #1062) 1 readFileSynctest/archived-source-scoping.test.ts #3880 structural pins — all-source local_path selections filter archived 2 readFileSync-test/asymmetric-encoding-contract.test.ts Source-text contract (cheap belt + suspenders) 3 readFileSynctest/auto-link-targeted-probe-2544.test.ts #2544 — auto-link behavior through put_page (targeted probe) 6 readFileSynctest/autopilot-auto-drain-wiring.test.ts autopilot auto-drain wiring 8 readFileSynctest/autopilot-cycle-failure-classification.test.ts autopilot cycle-failure classification — only 'failed' trips the circuit breaker 2 readFileSync@@ -27,10 +26,9 @@ test/autopilot-pause-marker.test.ts pause marker fences minion job pickup 1 readtest/autopilot-self-upgrade.test.ts autopilot self-upgrade static-shape regressions 4 readFileSynctest/autopilot-shutdown-engine-close.test.ts autopilot.ts graceful engine shutdown (#1872) 6 readFileSynctest/autopilot-supervisor-wiring.test.ts autopilot.ts ↔ ChildWorkerSupervisor wiring 7 readFileSync-test/backlinks-job-default.test.ts backlinks Minion handler — empty payload defaults to check, not fix 3 readFileSynctest/backup-cli.serial.test.ts runBackupCli — PGLite lock fallback 3 readFileSynctest/backup-invalidation.serial.test.ts bootstrap repo — recordRepoInReceipt contract (source-text pin) 2 readFileSync-test/book-mirror.test.ts gbrain book-mirror — source file invariants 7 readFileSync+test/book-mirror.test.ts gbrain book-mirror — source file invariants 2 readFileSynctest/bootstrap-codex-door.test.ts Codex door — rendered AGENTS.md pull protocol (Gate 3) 2 readFileSynctest/bootstrap-contract.test.ts bootstrap same-turn write-back contract 6 readFileSynctest/bootstrap-opencode-door.serial.test.ts opencode door — rendered AGENTS.md pull protocol 1 readFileSync@@ -49,9 +47,9 @@ test/build-llms.test.ts CLAUDE.md restructure content contracts 5 readFileSynctest/build-llms.test.ts build-llms generator 7 readFileSynctest/canonical-writer-inventory.test.ts (file-level) 2 readFileSynctest/chat-key-plane.test.ts #3944 both planner surfaces share the helper (source guard) 2 readFileSync-test/check-bootstrap-guards.test.ts check-grok-pin.sh 10 readFileSync+test/check-bootstrap-guards.test.ts check-grok-pin.sh 9 readFileSynctest/check-bootstrap-guards.test.ts check-opencode-pin.sh 6 readFileSync-test/check-bootstrap-guards.test.ts verify + workflow wiring 6 readFileSync+test/check-bootstrap-guards.test.ts verify + workflow wiring 4 readFileSynctest/check-update.test.ts check-update CLI 3 bun-filetest/child-worker-supervisor.test.ts issue #1801 — restartCurrentChild + killChild liveness fix 3 readFileSynctest/chronicle-extract.test.ts runChronicleExtract 9 readFileSync@@ -63,9 +61,8 @@ test/claude-cli-recipe.test.ts claude-cli LanguageModel — tool use 17 readFiletest/claude-cli-recipe.test.ts claude-cli recipe registration 2 readFileSynctest/cli-force-exit-teardown-arming.test.ts cli.ts — disconnect hard-deadline armed at teardown entry, not before the op body 1 readFileSynctest/cli.test.ts BigInt-safe output normalization (#2450) 5 readFileSync-test/cli.test.ts CLI structure 6 readFileSync+test/cli.test.ts CLI structure 2 readFileSynctest/cli.test.ts CLI version 2 readFileSync-test/cli.test.ts ask alias 2 readFileSynctest/codex-plugin-manifest.test.ts codex mcp.json 3 readFileSynctest/codex-plugin-manifest.test.ts curated tree membership + scanner guard 5 readFileSynctest/codex-plugin-manifest.test.ts generator negative fixtures (a guard that cannot fail is not coverage) 9 readFileSync@@ -74,36 +71,25 @@ test/compile-view.test.ts compileView — determinism 3 readFileSynctest/compile-view.test.ts compileView — source isolation + read errors 3 readFileSynctest/config.test.ts config source correctness 1 readFileSynctest/connection-resilience.test.ts Eng-review D3 — executeRaw has no per-call retry wrapper 3 readFileSync-test/context-audit-skill.test.ts #4988 context-audit skill states its token-estimate basis 3 readFileSync+test/context-audit-skill.test.ts #4988 context-audit skill token estimate 2 readFileSynctest/contextual-retrieval-service-pure.test.ts inline import contextual synopsis containment 1 readFileSynctest/conversation-facts-type-allowlist-drift.test.ts (file-level) 18 readFileSynctest/cycle-abort.test.ts #1972 — complete cooperative-abort coverage 3 readFileSynctest/cycle-abort.test.ts #4077 — synthesize/patterns cooperative-abort threading 3 readFileSync-test/cycle-abort.test.ts CycleOpts.signal contract (v0.20.5) 4 readFileSync+test/cycle-abort.test.ts CycleOpts.signal contract (v0.20.5) 3 readFileSynctest/cycle-abort.test.ts autopilot-cycle handler contract (v0.20.5) 3 readFileSynctest/cycle-drain-renewal.test.ts db-lock heartbeat wiring (structural — issue #6 cancellation) 1 readFileSynctest/cycle-drain-renewal.test.ts drain-loop wiring (structural — the shape guard only covers worker.ts) 2 readFileSync-test/cycle-pack-gating.test.ts #2117: pack-gated skip summaries are actionable 2 readFileSync-test/cycle-pack-gating.test.ts v0.41 T9 R-GATE: NEEDS_LOCK_PHASES contract (source-shape) 2 readFileSync-test/cycle-pack-gating.test.ts v0.41 T9 R-GATE: dispatch result envelope 2 readFileSync-test/cycle-pack-gating.test.ts v0.41 T9 R-GATE: orchestrator dispatch wires the pack-gate 5 readFileSync-test/cycle-pack-gating.test.ts v0.41 T9 R-GATE: pre-existing 17 core phases always run 3 readFileSynctest/cycle-patterns-deadline-budget.test.ts deadline plumbing wiring (structural) 7 readFileSync-test/cycle-patterns.test.ts patterns phase wiring 9 readFileSync-test/cycle-patterns.test.ts patterns scope filter 7 readFileSync+test/cycle-patterns.test.ts patterns private-queue keepalive wiring 1 readFileSynctest/cycle-phase-deadline-drift.test.ts propose_takes deadline < job timeout (#4168) 4 readFileSync-test/cycle/cycle-lock-ttl.test.ts cycle lock TTL (T2 regression pin) 1 readFileSynctest/destructive-guard.test.ts FK-RESTRICT lifecycle (clientsReferencingSource + purge skip) 9 readFileSynctest/destructive-guard.test.ts assessDestructiveImpact 5 readFileSynctest/destructive-guard.test.ts formatters (display helpers) 4 readFileSynctest/destructive-guard.test.ts purgeExpiredSources — clone cleanup containment 1 readFileSynctest/detached-stderr.test.ts jobs.ts detach branch (source pin, #4418) 2 readFileSync-test/docs-bootstrap-persistence-table.test.ts #4986 bootstrap.md scopes the Stop-push knobs and lists every push path 2 readFileSync-test/docs-mcp-deploy.test.ts DEPLOY.md documents dual-mode /mcp auth (#4893) 1 readFileSync-test/docs-mcp-deploy.test.ts DEPLOY.md documents the owner magic-link flow (#5007) 5 readFileSync-test/docs-mcp-deploy.test.ts DEPLOY.md documents the tailnet/LAN-only serve --http shape (#4500) 3 readFileSync-test/docs-navigation.test.ts primary documentation navigation 3 readFileSync-test/docs-timeline-extraction-guide.test.ts #4987 timeline extraction docs describe the real trigger 2 readFileSync+test/docs-mcp-deploy.test.ts DEPLOY.md documents the owner magic-link flow (#5007) 1 readFileSync+test/docs-navigation.test.ts primary documentation navigation 1 readFileSynctest/doctor-atom-provenance-drift.test.ts computeAtomProvenanceDriftCheck 18 doctor-source-helpertest/doctor-embedding-env-override.test.ts cross-surface parity (source-grep regression guard) 1 doctor-source-helpertest/doctor-fix.test.ts gbrain doctor --fix CLI integration 3 readFileSync@@ -118,7 +104,7 @@ test/doctor-supervisor-singleton-pidfile.test.ts doctor supervisor_singleton —test/doctor-volunteer-channels.test.ts checkVolunteerChannels 9 doctor-source-helper,readFileSynctest/doctor-wedged-queue.test.ts issue #1801 fix #3 — remote queue_health state→status regression 1 doctor-source-helpertest/doctor.test.ts BUG 4 — in-progress sync via live lock, not stale freshness 8 doctor-source-helper-test/doctor.test.ts doctor command 38 doctor-source-helper+test/doctor.test.ts doctor command 35 doctor-source-helpertest/doctor.test.ts issue #972 — link_resolution_opportunity check 8 doctor-source-helpertest/doctor.test.ts stub_guard_24h check (v0.34.5) 5 doctor-source-helpertest/doctor.test.ts supervisor crash classifier wiring (v0.35.x) 4 bun-file,doctor-source-helper@@ -129,16 +115,11 @@ test/doctor.test.ts v0.40.4 — graph_signals_coverage check 7 doctor-source-heltest/doctor.test.ts v0.41.27.0 — sync_freshness git short-circuit 9 doctor-source-helpertest/doctor.test.ts v0.41.32.0 — commit-relative staleness 5 doctor-source-helpertest/doctor.test.ts v0.42 (#1699) — quarantined_pages + flagged_pages checks 1 doctor-source-helper-test/dream-cli-flags.test.ts --drain wiring 4 readFileSync-test/dream-cli-flags.test.ts --once wiring (issue #2860) 5 readFileSync-test/dream-cli-flags.test.ts --source / --source-id wiring (v0.41.13) 9 readFileSync-test/dream-cli-flags.test.ts dream CLI flag wiring 10 readFileSynctest/dry-fix.test.ts autoFixDryViolations 12 readFileSynctest/e2e/bootstrap-real-codex.serial.test.ts bootstrap rendered protocol — ambient boundaries (always runs) 5 readFileSynctest/e2e/codex-plugin-install-real.serial.test.ts (file-level) 2 readFileSynctest/e2e/migration-flow.test.ts (file-level) 4 readFileSynctest/e2e/openclaw-reference-compat.test.ts OpenClaw reference workspace compat (W1 + W2 + W3) 8 readFileSync-test/e2e/skillpack-flow.test.ts skillpack flow (E2E) 17 readFileSynctest/e2e/workspace-generic-compat.test.ts generic agent-workspace compat (INSTALL_FOR_AGENTS.md flow) 6 readFileSynctest/embedding-dim-check-facts.test.ts doctor checkFactsEmbeddingWidthConsistency wiring (T6) 4 doctor-source-helpertest/env-trust-protected-keys.test.ts CWD_DOTENV_PROTECTED_KEYS covers every suspicious GBRAIN_* env read in src/ 3 readFileSync@@ -157,7 +138,6 @@ test/extract-atoms-drain.test.ts extract-atoms-drain Minion handler retries on ptest/extract-atoms-drain.test.ts protected-names register comment names the real trust mechanism 1 readFileSynctest/extract-atoms-drain.test.ts shared wiring helper holds the cycle lock (5A) 2 readFileSynctest/extract-include-frontmatter-config.serial.test.ts no extraction path hardcodes includeFrontmatter 1 readFileSync-test/extract-workers.test.ts extract.ts → workers wiring (T7) 10 readFileSynctest/facts-backstop-remedy-verb.test.ts facts backstop thin-client-fallback remedy verb (#4489) 3 readFileSynctest/features.test.ts CLI routing 2 bun-filetest/fence-extraction.test.ts Layer 8 D2 — markdown fence extraction 18 readFileSync@@ -172,9 +152,8 @@ test/fix-wave-structural.test.ts WAL-repair wave structural pins (#223/#2575) 4test/fix-wave-structural.test.ts five-issue fix wave — integrity progress is (source_id, slug)-keyed 1 readFileSynctest/fix-wave-structural.test.ts v0.36.1.x #1077 — admin register-client supports PKCE public clients 1 readFileSynctest/fix-wave-structural.test.ts v0.36.1.x #1090 — admin embed two-tier resolution 3 readFileSync-test/fix-wave-structural.test.ts v0.36.1.x #1124 — query --no-expand actually negates expand 1 readFileSynctest/fix-wave-structural.test.ts v0.41.37.0 #1605 — v0.11.0 phaseASchema routes in-process for ALL engines 2 readFileSync-test/fix-wave-structural.test.ts v0.41.8.0 #1340 — PGLite WASM init classifier 2 readFileSync+test/fix-wave-structural.test.ts v0.41.8.0 #1340 — PGLite WASM init classifier 1 readFileSynctest/fix-wave-structural.test.ts v0.42.20.0 — background-work registry drains every sink before disconnect 9 readFileSynctest/fix-wave-structural.test.ts v0.42.20.0 — search-cache drained via the background-work registry 1 readFileSynctest/fix-wave-structural.test.ts v0.42.43.0 #2095 — volunteer-events sink + cycle purge wiring (structural pins) 2 readFileSync@@ -194,7 +173,6 @@ test/link-source-check-repair.test.ts regex literal drift guard (#4613) 1 readFitest/longmemeval-embed-cache.test.ts EmbeddingCache — canonical hash 4 readFileSynctest/loops-extract-wiring.test.ts jobs.ts wiring 2 readFileSynctest/loops-extract-wiring.test.ts relational edge vocabulary 2 readFileSync-test/mcp-registration-blocks.test.ts OpenClaw stdio registration docs (#4842) 2 readFileSynctest/migrate-stdout-clean.test.ts migration output stays off stdout 2 readFileSynctest/migrate.test.ts PR #356 + #363 — session timeouts applied via startup parameters 1 readFileSynctest/migrate.test.ts PR #356 — LATEST_VERSION is max(versions), not array[-1] 2 readFileSync@@ -223,7 +201,6 @@ test/migrations-v0_14_0.test.ts Bug 8 — max_stalled default bumped in schema ftest/migrations-v0_22_4.test.ts v0.22.4 migration (B11) 9 readFileSynctest/model-pricing.test.ts DRIFT GUARD — derived views stay equal to canonical (re-hardcode trip-wire) 4 readFileSynctest/model-pricing.test.ts no heavy import (cycle guard) 1 readFileSync-test/models-doctor-embed.test.ts models doctor — embedding reachability probe (v0.40.x) 3 readFileSynctest/ocr-run-budget.test.ts doctor ocr_health surfaces the budget-skip counter (#3973) 1 doctor-source-helpertest/openclaw-plugin-manifest.test.ts bundled-skill reference closure (nothing bundled points at a non-bundled skill) 1 readFileSynctest/openclaw-plugin-manifest.test.ts plugin membership curation (skills = plugin ∪ exclusions, disjoint) 9 readFileSync@@ -233,18 +210,13 @@ test/pg-access-classify.test.ts marker contract (skill↔binary lockstep, the UPtest/pglite-engine.test.ts PGLiteEngine: v0.13.1 error-wrap on connect() (#223) 1 readFileSynctest/pglite-repair-command.serial.test.ts gbrain pglite-repair — interactive confirm wiring (#4318 residual) 1 readFileSynctest/pglite-wal-repair.serial.test.ts WAL auto-repair — real-brain regression (#223/#1670/#2575) 6 readFileSync-test/phantom-redirect-per-source-lock.test.ts phantom-redirect lock contract 3 readFileSynctest/postgres-driver-vendor.test.ts vendored Postgres driver packaging 3 readFileSync-test/postgres-engine-singleton-ownership.test.ts postgres-engine / module-singleton ownership (#1471) 7 readFileSynctest/postgres-engine.test.ts postgres-engine / search date filtering 1 readFileSynctest/postgres-engine.test.ts postgres-engine / search path timeout isolation 7 readFileSynctest/private-visibility.test.ts shared private predicate lives once (#4352 remediation) 1 readFileSync-test/readme-hero-anchors.test.ts README hero anchors (D9 regression guard) 5 readFileSynctest/redos-hardening.test.ts #1569 --no-schema-pack + heartbeat wiring (structural) 2 readFileSynctest/redos-hardening.test.ts megawave vm-watchdog removal (bootstrap-verify freeze) 5 readFileSynctest/register-client-source-normalize.test.ts register-client route wiring (structural) 1 readFileSync-test/regression-strict-source-id.test.ts cycle reverse-write call sites use the consolidated path 4 readFileSync-test/regression-strict-source-id.test.ts utils.ts no longer carries an inline permissive regex 2 readFileSynctest/reindex-code-recovery.test.ts CLI help line (#3970 surface 1) 1 readFileSynctest/release-workflow.test.ts release.yml ↔ binary-self-update asset contract 11 readFileSynctest/remediation-command-resolution.test.ts #3697 — remediation text resolves against the live CLI surface 3 readFileSync@@ -252,17 +224,16 @@ test/reranker-default-seam.test.ts DEFAULT_RERANKER_MODEL seam (#3657, flipped vtest/resolver.test.ts RESOLVER.md trigger round-trip (D5/C) 2 readFileSynctest/resolver.test.ts Skill example-name validator (D13) 4 readFileSynctest/retrieval-reflex-recipe-routing.test.ts retrieval-reflex recipe routing is MECE with the query skill (#4292) 5 readFileSync-test/schema-cli-contract.test.ts v0.39 T6 — schema CLI contract 7 readFileSynctest/schema-pack-unify-types-handler.test.ts #1575 unify-types worker dry-run default 1 readFileSynctest/schema-pack/suggest.test.ts runSuggest — source-text contract (structural) 1 readFileSync-test/scripts/ci-gates.test.ts CI execution evidence 5 readFileSync+test/scripts/ci-gates.test.ts CI execution evidence 6 readFileSynctest/scripts/ci-gates.test.ts test:full exit status 0 readFileSynctest/scripts/ci-local-rendering.test.ts ci-local command rendering 1 readFileSynctest/scripts/ci-local-rendering.test.ts ci-local execution coverage 3 readFileSynctest/scripts/ci-local-rendering.test.ts local test configuration through run-e2e 2 readFileSynctest/scripts/ci-local-rendering.test.ts required PgBouncer execution through run-e2e 1 readFileSynctest/scripts/ci-runner-routing.test.ts CI runner routing 5 readFileSync-test/scripts/classify-tests.test.ts classify-tests detectors 18 bun-file,doctor-source-helper,exec-scan,readFileSync+test/scripts/classify-tests.test.ts classify-tests detectors 20 bun-file,doctor-source-helper,exec-scan,readFileSynctest/scripts/coverage-diff-gate.test.ts exemptions 3 readFileSynctest/scripts/data-safety-native-workflow.test.ts data-safety native CI coverage 12 readFileSynctest/scripts/e2e-runner.test.ts second 5 readFileSync@@ -292,9 +263,9 @@ test/shared-skills-writer-boundary.serial.test.ts (file-level) 5 readFileSynctest/skillify-scaffold.test.ts 11-item scaffold contract (T9 + Phase 3 cross-modal eval) 1 readFileSynctest/skillify-scaffold.test.ts applyScaffold 3 readFileSynctest/skillify-scaffold.test.ts planScaffold 13 readFileSync-test/skillopt/deadline-and-hermetic.test.ts #4741 — hermetic-config docs make no platform-survives-logout claim 2 readFileSynctest/skillopt/error-code-docs.test.ts skillopt error-code table 3 readFileSynctest/skillpack-check-report-only.test.ts (file-level) 2 readFileSync+test/skillpack-flow.test.ts skillpack flow (E2E) 17 readFileSynctest/skillpack-harness-bridge.test.ts review-driven hardening (ship pre-landing findings) 5 readFileSynctest/skillpack-harvest.test.ts addToBundleManifest 1 readFileSynctest/skillpack-harvest.test.ts runHarvest — happy path 2 readFileSync@@ -323,22 +294,19 @@ test/sync.test.ts sync auto-embed arguments 2 bun-filetest/sync.test.ts sync regression — #132 nested transaction deadlock 1 bun-filetest/template-repo-generator.test.ts generateTemplateTree 0 readFileSynctest/template-repo-generator.test.ts renderTemplateReadme 5 readFileSync-test/thin-client-routing-audit.test.ts thin-client routing audit — scratch-DB additions (jobs partial dispatch + config refusal) 5 readFileSync-test/thin-client-routing-audit.test.ts thin-client routing audit — v0.32 REFUSE additions stay in the table 4 readFileSync-test/thin-client-routing-audit.test.ts thin-client routing audit — v0.32 ROUTE additions wire callRemoteTool 4 readFileSynctest/think-embed-question-wiring.serial.test.ts #3734 — CRAG think escalation wires embedQuestion (source pin) 1 readFileSynctest/think-embed-question-wiring.serial.test.ts #3734 — synthesize verb wires embedQuestion into runThink 1 readFileSynctest/timing-safe.test.ts extraction contract 1 readFileSync-test/tool-catalog.test.ts freshness guard 2 readFileSynctest/transcription-injection.test.ts transcription — command injection (#245) 2 readFileSynctest/upgrade-skill-publish-prompt-race.test.ts gbrain upgrade — skill-publish prompt wiring (#4318 residual) 3 readFileSync-test/upgrade.serial.test.ts detectInstallMethod heuristic (source analysis) 13 readFileSync+test/upgrade.serial.test.ts detectInstallMethod — package-install classification (in-process) 4 readFileSync+test/upgrade.serial.test.ts runUpgrade target verification (#4366) 8 readFileSynctest/v0_37_fix_wave.serial.test.ts v0.37 Lane A — defaults sweep 8 readFileSynctest/v0_37_fix_wave.serial.test.ts v0.37 Lane B — init paths 3 readFileSync-test/v0_37_fix_wave.serial.test.ts v0.37 Lane C.3 — Voyage key reaches buildGatewayConfig 3 readFileSync+test/v0_37_fix_wave.serial.test.ts v0.37 Lane C.3 — Voyage key reaches buildGatewayConfig 2 readFileSynctest/v0_37_fix_wave.serial.test.ts v0.37 Lane D.2 — embed pre-flight dim mismatch 1 readFileSynctest/v0_37_fix_wave.serial.test.ts v0.37 Lane D.4 — sync --help dispatch 1 readFileSync-test/v0_37_fix_wave.serial.test.ts v0.37 deferred TODO shipped — gbrain reinit-pglite 3 readFileSync+test/v0_37_fix_wave.serial.test.ts v0.37 deferred TODO shipped — gbrain reinit-pglite 2 readFileSynctest/v0_37_gap_fill.serial.test.ts Lane A.7 — chunk-row INSERT default tracks the gateway-resolved model 1 readFileSynctest/v0_37_gap_fill.serial.test.ts Lane B — init precedence chain (CLI > env > existing file > default) 1 readFileSynctest/v0_37_gap_fill.serial.test.ts Lane C.3 — env OPENAI_API_KEY merges into loadConfig 2 readFileSync@@ -346,7 +314,6 @@ test/v0_37_gap_fill.serial.test.ts Lane D.2 — embed pre-flight catches dim mistest/v0_37_gap_fill.serial.test.ts Lane D.3 — sync surfaces dim-mismatch recipe at incremental AND first-sync catches 2 readFileSynctest/v0_37_gap_fill.serial.test.ts Lane E.4 — loadRecommendationContext is provider-aware 1 readFileSynctest/v0_37_gap_fill.serial.test.ts reinit-pglite — backup + reinit 7 readFileSync-test/voyage-response-cap.test.ts v0.31.8 — voyage Content-Length pre-check + per-item cap 6 bun-filetest/worker-supervised-db-probe.test.ts issue #1801 fix #2 — supervised DB self-defense 5 readFileSync# unknown (detectors present, no attributable suite):# unknown test/e2e/postgres-driver-install.test.tsdiff --git a/scripts/test-weights.json b/scripts/test-weights.jsonindex c483834f4f..2fad5146ed 100644--- a/scripts/test-weights.json+++ b/scripts/test-weights.json@@ -89,7 +89,6 @@"test/apply-migrations.test.ts": 15,"test/archive-crawler-config.test.ts": 12,"test/archived-source-scoping.test.ts": 6,- "test/artifact-abstraction.test.ts": 4,"test/asymmetric-encoding-contract.test.ts": 4,"test/atomic-write.test.ts": 10,"test/atoms-scan-hash-rearm.test.ts": 2723,@@ -130,13 +129,12 @@"test/autopilot-shutdown-engine-close.test.ts": 3,"test/autopilot-supervisor-wiring.test.ts": 6,"test/backfill-base.test.ts": 18,+ "test/backfill-perf-pglite.test.ts": 10760,"test/backlink-count-mention-filter.test.ts": 636,- "test/backlinks-job-default.test.ts": 3,"test/backlinks.test.ts": 10087,"test/backoff.test.ts": 5,"test/backpressure-audit-read.test.ts": 6,"test/balanced-reranker-default.test.ts": 4,- "test/batch-projection.test.ts": 3,"test/bench-publish.test.ts": 32,"test/bench/baseline-file.test.ts": 9,"test/bench/correctness-gate.test.ts": 5,@@ -179,7 +177,6 @@"test/brainstorm/model-config.test.ts": 4,"test/brainstorm/save.test.ts": 2025,"test/budget-meter.test.ts": 5,- "test/budget-tracker.test.ts": 505,"test/budget/free-local-chat-pricing.test.ts": 5,"test/budget/pricing-overrides.test.ts": 9,"test/build-llms.test.ts": 16,@@ -242,6 +239,7 @@"test/claude-cli-recipe.test.ts": 195,"test/claude-code-jsonl.test.ts": 49,"test/claw-test-cli.test.ts": 79,+ "test/claw-test.slow.test.ts": 185940,"test/cli-ambient-source-fail-closed.test.ts": 695,"test/cli-args.test.ts": 14,"test/cli-bigint-normalize.test.ts": 11,@@ -274,14 +272,12 @@"test/cli.test.ts": 6313,"test/client-grants.test.ts": 772,"test/client-slug-fence.test.ts": 15,- "test/code-callers-cli.test.ts": 0,"test/code-def-refs-source-scope.test.ts": 488,"test/code-def-refs.test.ts": 616,"test/code-edges.test.ts": 1154,"test/code-graph-readiness.test.ts": 595,"test/code-intel-source-scope.test.ts": 1311,"test/code-intel/edge-densification.test.ts": 24,- "test/code-intel/eval-capture-graph.test.ts": 1,"test/code-intel/recursive-walk.test.ts": 2354,"test/code-intel/scope-walker-resolution.test.ts": 60,"test/code-intel/traversal-cache.test.ts": 2335,@@ -312,6 +308,7 @@"test/config-unset.test.ts": 441,"test/config.test.ts": 8,"test/confirm-prompt.test.ts": 12,+ "test/connect-bearer.test.ts": 10690,"test/connect.test.ts": 66,"test/connection-resilience.test.ts": 19,"test/connectors-classify.test.ts": 5,@@ -343,7 +340,6 @@"test/conversation-parser/body-path-containment.test.ts": 3,"test/conversation-parser/llm-base.test.ts": 9,"test/conversation-parser/llm-fallback.test.ts": 13,- "test/conversation-parser/llm-polish.test.ts": 18,"test/conversation-parser/nightly-probe.test.ts": 12,"test/conversation-parser/parse.test.ts": 32,"test/core/background-work.test.ts": 11,@@ -351,8 +347,6 @@"test/core/budget/budget-tracker.test.ts": 671,"test/core/budget/expand-records-budget.test.ts": 790,"test/core/budget/gateway-budget-composition.test.ts": 12,- "test/core/diarize/payload-fitter-summarize.test.ts": 13,- "test/core/diarize/payload-fitter.test.ts": 3,"test/core/git-head.test.ts": 8,"test/core/retry-reconnect.test.ts": 93,"test/core/retry-stress.slow.test.ts": 162,@@ -363,7 +357,6 @@"test/cosine-rescore-column.test.ts": 413,"test/creds-export.test.ts": 617,"test/creds-relay-client.test.ts": 32,- "test/cross-brain-calibration.test.ts": 8,"test/cross-modal-default-slots.test.ts": 9,"test/cross-modal-eval-aggregate.test.ts": 4,"test/cross-modal-eval-cli.test.ts": 16,@@ -412,7 +405,6 @@"test/cycle-synthesize.test.ts": 32,"test/cycle-triage-rescue.test.ts": 21,"test/cycle-write-path-mini-eval.test.ts": 627,- "test/cycle/cycle-lock-ttl.test.ts": 7,"test/cycle/extract-atoms-batch.test.ts": 1081,"test/cycle/extract-atoms-config-caps.test.ts": 2665,"test/cycle/extract-atoms-model-config-fail-soft.test.ts": 393,@@ -431,7 +423,6 @@"test/cycle/yield-during-phase-throttle.test.ts": 3450,"test/dart-call-edges.test.ts": 27,"test/data-frontmatter.test.ts": 12,- "test/data-research.test.ts": 11,"test/database-url-guard-preload.test.ts": 493,"test/db-disconnect-audit.test.ts": 19,"test/db-guard-coverage.test.ts": 448,@@ -460,12 +451,9 @@"test/detached-stderr.test.ts": 4,"test/disk-walk.test.ts": 27,"test/dispatch-localonly.test.ts": 273,- "test/distribution-import-boundary.test.ts": 0,"test/docker-postgres.test.ts": 4,- "test/docs-bootstrap-persistence-table.test.ts": 2,"test/docs-cli-commands.test.ts": 63,"test/docs-mcp-deploy.test.ts": 15,- "test/docs-timeline-extraction-guide.test.ts": 17,"test/doctor-abandoned-threads-month-precision.test.ts": 288,"test/doctor-asset-paths.test.ts": 6,"test/doctor-atom-provenance-drift.test.ts": 3397,@@ -542,7 +530,6 @@"test/doctor.test.ts": 3531,"test/domain-aggregators.test.ts": 2725,"test/dream-clean-status-skip-visibility.test.ts": 14,- "test/dream-cli-flags.test.ts": 8,"test/dream-dir-source-stamp.test.ts": 1199,"test/dream-env-source-scope.test.ts": 1294,"test/dream-keyless-exit.test.ts": 10376,@@ -555,7 +542,6 @@"test/edge-extractor.test.ts": 114,"test/effective-date.test.ts": 2,"test/embed-backfill-submit.test.ts": 368,- "test/embed-helper-migration.test.ts": 3,"test/embed-keyless-guard.test.ts": 9,"test/embed-modality-preserved.test.ts": 496,"test/embed-multimodal-batching.test.ts": 23,@@ -589,7 +575,6 @@"test/enrich/thin.test.ts": 5,"test/enrichable-pack.test.ts": 11,"test/enrichment-service.test.ts": 5,- "test/enrichment.test.ts": 2688,"test/entity-card-loops.test.ts": 2172,"test/entity-card-perf.slow.test.ts": 44668,"test/entity-hints-cap.test.ts": 383,@@ -610,7 +595,6 @@"test/eval-compare.test.ts": 14,"test/eval-contradictions-auto-supersession.test.ts": 2,"test/eval-contradictions-cache.test.ts": 2244,- "test/eval-contradictions-calibration-join.test.ts": 2,"test/eval-contradictions-calibration.test.ts": 6,"test/eval-contradictions-cost-prompt.test.ts": 4298,"test/eval-contradictions-cost.test.ts": 21,@@ -644,7 +628,6 @@"test/eval-replay.test.ts": 23,"test/eval-retrieval-quality.test.ts": 658,"test/eval-run-all.test.ts": 14,- "test/eval-schema-authoring.test.ts": 7,"test/eval-shared-json-repair-shim.test.ts": 3,"test/eval-spend-guard.test.ts": 4338,"test/eval-suspected-contradictions-budget-default.test.ts": 22,@@ -689,7 +672,6 @@"test/extract-by-mention-resume.test.ts": 611,"test/extract-by-mention.test.ts": 493,"test/extract-conversation-facts-entity-resolution.test.ts": 1802,- "test/extract-conversation-facts-workers.test.ts": 24,"test/extract-conversation-facts.test.ts": 2896,"test/extract-cross-source-links.test.ts": 5,"test/extract-cross-source-resolution-observability.test.ts": 25,@@ -719,6 +701,7 @@"test/extractable-pack.test.ts": 11,"test/extractable-spec-widening.test.ts": 10,"test/extraction-review.test.ts": 6744,+ "test/fact-backfill-resident.test.ts": 7820,"test/facts-absorb-log.test.ts": 301,"test/facts-anti-loop.test.ts": 490,"test/facts-backstop-gating.test.ts": 459,@@ -760,7 +743,6 @@"test/facts-visibility.test.ts": 522,"test/facts/ttl-validity.test.ts": 362,"test/facts/writeback-gate.test.ts": 8,- "test/fail-improve.test.ts": 76,"test/feature-flags.test.ts": 1156,"test/features-no-sync.test.ts": 3,"test/features-recipe-secrets.test.ts": 12,@@ -890,6 +872,7 @@"test/init-embed-check.test.ts": 10,"test/init-env-detection.test.ts": 16,"test/init-force-engine-preservation.test.ts": 4731,+ "test/init-fresh-pglite.slow.test.ts": 44500,"test/init-mcp-only.test.ts": 6453,"test/init-migrate-only.test.ts": 6362,"test/init-mode-picker.test.ts": 477,@@ -926,7 +909,6 @@"test/language-manifest.test.ts": 179,"test/last-retrieved.test.ts": 304,"test/latin-fold.test.ts": 4,- "test/lease-cap-controller.test.ts": 414,"test/legacy-token-federated-scope.test.ts": 17,"test/lens-pack-manifests.test.ts": 13,"test/levenshtein.test.ts": 3,@@ -1039,6 +1021,7 @@"test/minion-queue-renewlock-signal.test.ts": 4,"test/minions-admission.test.ts": 602,"test/minions-cold-import.test.ts": 887,+ "test/minions-field-report-repro.test.ts": 26470,"test/minions-lease-full-retry.test.ts": 314,"test/minions-quiet-hours.test.ts": 2584,"test/minions-shell-inherit.test.ts": 6,@@ -1063,6 +1046,7 @@"test/modes-report-reranker.test.ts": 15,"test/mounts-cache.test.ts": 23,"test/mounts-cli.test.ts": 461,+ "test/mounts-routing-pglite.slow.test.ts": 31030,"test/multi-source-drift.test.ts": 1164,"test/multi-source-integration.test.ts": 574,"test/niceness.test.ts": 6,@@ -1072,7 +1056,6 @@"test/no-tracked-symlinks-guard.test.ts": 35,"test/notability-eval.test.ts": 25,"test/npm-squat-check.test.ts": 2,- "test/nudge.test.ts": 6,"test/oauth-authorize-scope-default.test.ts": 417,"test/oauth-confidential-client.test.ts": 455,"test/oauth-consent-security.test.ts": 3516,@@ -1138,7 +1121,6 @@"test/pglite-workers-clamp.test.ts": 5,"test/phantom-redirect-content-hash.test.ts": 784,"test/phantom-redirect-engine-parity.test.ts": 1816,- "test/phantom-redirect-per-source-lock.test.ts": 2,"test/phantom-redirect.test.ts": 6977,"test/phase-scope-coverage.test.ts": 14,"test/pid1-reaper.test.ts": 127,@@ -1151,7 +1133,6 @@"test/postgres-engine-getter-selfheal.test.ts": 9,"test/postgres-engine-reserved-routing.test.ts": 38,"test/postgres-engine-rls-scope.test.ts": 19,- "test/postgres-engine-singleton-ownership.test.ts": 8,"test/postgres-engine.test.ts": 14,"test/postgres-execute-raw-direct.test.ts": 5,"test/preferences.test.ts": 17,@@ -1188,6 +1169,7 @@"test/put-page-remote-autolink-hint.test.ts": 924,"test/put-page-write-through-failure.test.ts": 999,"test/put-page-writer-lint.test.ts": 2799,+ "test/qm-provisioning.test.ts": 28260,"test/qualified-names.test.ts": 143,"test/quarantine-cache-ops.test.ts": 342,"test/quarantine-cli.test.ts": 1425,@@ -1209,11 +1191,9 @@"test/ranking-inversion-895.test.ts": 1964,"test/rate-leases-uncapped.test.ts": 680,"test/rate-leases.test.ts": 338,- "test/readme-hero-anchors.test.ts": 7,"test/recall-extensions.test.ts": 2945,"test/recall-federated-search-scope.test.ts": 397,"test/recall-federated.test.ts": 408,- "test/recall-footer.test.ts": 7,"test/recall-keyword-fallback.test.ts": 3894,"test/recall-rollup.test.ts": 17,"test/receipt-cr-state.test.ts": 928,@@ -1226,7 +1206,6 @@"test/regression-strict-source-id.test.ts": 8,"test/regression-v0_16_4.test.ts": 23,"test/regressions/gbrain-base-equivalence.test.ts": 50,- "test/regressions/v0.36.1.0-iron-rule.test.ts": 4,"test/regressions/v0_36_frontier_cap.test.ts": 2517,"test/regressions/v0_40_2_0-trajectory-backcompat.test.ts": 280,"test/reindex-code-empty-file.test.ts": 888,@@ -1245,7 +1224,6 @@"test/remediation-step.test.ts": 20,"test/remote-body.test.ts": 7,"test/remote-cli.test.ts": 7111,- "test/remote-ping-status-field.test.ts": 19,"test/remote-privacy-sweep.test.ts": 4457,"test/repair-jsonb.test.ts": 2,"test/replay-autocut-floor.test.ts": 445,@@ -1287,7 +1265,6 @@"test/schema-lint-pack-confine.test.ts": 15,"test/schema-migrate-link-source-mentions.test.ts": 419,"test/schema-pack-best-effort.test.ts": 30,- "test/schema-pack-expand-type-filter.test.ts": 7,"test/schema-pack-infer-type-and-subtype.test.ts": 4,"test/schema-pack-lint-rules.test.ts": 8,"test/schema-pack-loader.test.ts": 16,@@ -1303,7 +1280,6 @@"test/schema-pack-registry-reload.test.ts": 51,"test/schema-pack-registry.test.ts": 26,"test/schema-pack-retype.test.ts": 5572,- "test/schema-pack-rewrite-links-batch.test.ts": 549,"test/schema-pack-stats.test.ts": 6561,"test/schema-pack-sync.test.ts": 6540,"test/schema-pack-trust-boundary.test.ts": 86,@@ -1352,6 +1328,7 @@"test/search-mode-config-snapshot.test.ts": 5,"test/search-mode.test.ts": 18,"test/search-op-source-id.test.ts": 403,+ "test/search-readiness-http.test.ts": 8650,"test/search-safe-index-probe.test.ts": 411,"test/search-snippet-cap.test.ts": 2628,"test/search-telemetry.test.ts": 2058,@@ -1403,7 +1380,6 @@"test/search/walk-dedup-cap.test.ts": 3,"test/secret-scan.test.ts": 17,"test/select-e2e.test.ts": 12,- "test/self-fix.test.ts": 385,"test/self-upgrade-pending.test.ts": 8,"test/self-upgrade.test.ts": 12,"test/sensitivity-scan.test.ts": 25,@@ -1419,10 +1395,12 @@"test/serve-http-oauth-token-rate-limit.test.ts": 103,"test/serve-http-socket-tracking.test.ts": 746,"test/serve-http-stall-watchdog.test.ts": 49,+ "test/serve-http-surface-ceiling.test.ts": 16810,"test/serve-http-trust-proxy.test.ts": 89,"test/serve-skills-publish-nudge.test.ts": 7,"test/serve-stdin-eof-drain.test.ts": 414,"test/serve-stdio-lifecycle.test.ts": 1406,+ "test/serve-stdio-roundtrip.test.ts": 19790,"test/serve-sweep-runner-677.test.ts": 543,"test/server-degraded-scope.test.ts": 19,"test/session-receipts.test.ts": 822,@@ -1470,6 +1448,7 @@"test/skillpack-check.test.ts": 3968,"test/skillpack-copy.test.ts": 1,"test/skillpack-endorse.test.ts": 122,+ "test/skillpack-flow.test.ts": 13680,"test/skillpack-frontmatter-sources.test.ts": 31,"test/skillpack-harness-bridge.test.ts": 49,"test/skillpack-harvest-lint.test.ts": 4,@@ -1626,7 +1605,6 @@"test/synth-enabled-default.test.ts": 0,"test/synthesize-chunk-budget.test.ts": 32,"test/system-prompt.test.ts": 5,- "test/take-forecast.test.ts": 8,"test/take-proposals.test.ts": 475,"test/takes-command-source-scope.test.ts": 61,"test/takes-engine.test.ts": 408,@@ -1681,6 +1659,7 @@"test/transcription.test.ts": 28,"test/transcripts-claude-code-workflow-drift.test.ts": 9,"test/transcripts-expand-paths.test.ts": 11,+ "test/transcripts-ingest-pglite.test.ts": 8590,"test/transcripts-max-bytes.test.ts": 5,"test/transcripts-nul.test.ts": 716,"test/transcripts-self-exclusion.test.ts": 1,@@ -1711,7 +1690,6 @@"test/volunteer-context.test.ts": 563,"test/volunteer-events-delivery.test.ts": 15,"test/voyage-multimodal.test.ts": 23,- "test/voyage-response-cap.test.ts": 8,"test/wait-for-completion.test.ts": 8213,"test/watch-command.test.ts": 573,"test/wave-security-scan.test.ts": 356,diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.jsonindex 26e5d71a52..48b9ecad00 100644--- a/scripts/ubicloud/weights.json+++ b/scripts/ubicloud/weights.json@@ -1,19 +1,16 @@{"e2e:test/e2e/anomalies-pglite.test.ts": 2886,- "e2e:test/e2e/attendance-repair-postgres.test.ts": 47886,- "e2e:test/e2e/attendance-retrieval-postgres.test.ts": 49195,+ "e2e:test/e2e/attendance-repair-postgres.test.ts": 21285,+ "e2e:test/e2e/attendance-retrieval-postgres.test.ts": 27079,"e2e:test/e2e/auth-permissions.test.ts": 1084,"e2e:test/e2e/auth-takes-holders-pglite.test.ts": 1478,"e2e:test/e2e/autopilot-cooldown-parity.test.ts": 1649,"e2e:test/e2e/autopilot-fanout-postgres.test.ts": 1091,"e2e:test/e2e/autopilot-linux-lifecycle.serial.test.ts": 10888,- "e2e:test/e2e/backfill-perf-pglite.test.ts": 10437,"e2e:test/e2e/backup-coverage-parity.test.ts": 2317,"e2e:test/e2e/bootstrap-attach.serial.test.ts": 5768,"e2e:test/e2e/bootstrap-compiled-binary.serial.test.ts": 5164,"e2e:test/e2e/bootstrap-degraded-modes.serial.test.ts": 5146,- "e2e:test/e2e/bootstrap-harness-lifecycle.serial.test.ts": 10390,- "e2e:test/e2e/bootstrap-hook-under-serve.serial.test.ts": 14450,"e2e:test/e2e/bootstrap-keyed-postgres.serial.test.ts": 2967,"e2e:test/e2e/bootstrap-lifecycle.serial.test.ts": 8510,"e2e:test/e2e/bootstrap-magic-moment.serial.test.ts": 4771,@@ -30,7 +27,6 @@"e2e:test/e2e/chunker-takes-strip.test.ts": 1073,"e2e:test/e2e/cjk-roundtrip.test.ts": 1740,"e2e:test/e2e/claude-plugin-install-real.serial.test.ts": 523,- "e2e:test/e2e/claw-test.test.ts": 82480,"e2e:test/e2e/cli-source-scoping-pglite.test.ts": 1931,"e2e:test/e2e/client-grants.test.ts": 2180,"e2e:test/e2e/code-edges-jsonb-postgres.test.ts": 807,@@ -41,7 +37,6 @@"e2e:test/e2e/company-brain-receipts.test.ts": 1058,"e2e:test/e2e/compile-context-pglite.test.ts": 2354,"e2e:test/e2e/concurrent-embed-race.test.ts": 1926,- "e2e:test/e2e/connect-bearer.test.ts": 11278,"e2e:test/e2e/connector-sync-handler-pglite.test.ts": 1560,"e2e:test/e2e/connectors-sync-pglite.test.ts": 7247,"e2e:test/e2e/contextual-retrieval-pglite.test.ts": 3912,@@ -63,7 +58,6 @@"e2e:test/e2e/dream-allow-list-pglite.test.ts": 3262,"e2e:test/e2e/dream-cycle-phase-order-pglite.test.ts": 3772,"e2e:test/e2e/dream-patterns-pglite.test.ts": 3699,- "e2e:test/e2e/dream-synthesize-chunking.test.ts": 10544,"e2e:test/e2e/dream-synthesize-concurrency-postgres.test.ts": 12664,"e2e:test/e2e/dream-synthesize-pglite.test.ts": 12146,"e2e:test/e2e/dream-triage-postgres.test.ts": 955,@@ -83,9 +77,8 @@"e2e:test/e2e/eval-takes-quality.test.ts": 663,"e2e:test/e2e/extract-atoms-discovery-sql.test.ts": 1002,"e2e:test/e2e/extract-atoms-page-state.test.ts": 2150,- "e2e:test/e2e/extract-timeline-attendance-postgres.test.ts": 4675,+ "e2e:test/e2e/extract-timeline-attendance-postgres.test.ts": 1980,"e2e:test/e2e/extraction-review-postgres.test.ts": 1362,- "e2e:test/e2e/fact-backfill-resident.test.ts": 7921,"e2e:test/e2e/fact-embedding-backfill-parity.test.ts": 7052,"e2e:test/e2e/fact-vector-repair-parity.test.ts": 5977,"e2e:test/e2e/facts-context-injection-postgres.test.ts": 929,@@ -98,7 +91,6 @@"e2e:test/e2e/facts-separation-postgres.test.ts": 868,"e2e:test/e2e/facts-worker-config.test.ts": 2423,"e2e:test/e2e/fixture-reset-postgres.test.ts": 4246,- "e2e:test/e2e/fresh-install-pglite.test.ts": 29181,"e2e:test/e2e/frontmatter-migration.test.ts": 3738,"e2e:test/e2e/global-basename-pglite.test.ts": 3967,"e2e:test/e2e/grandfather-projection-postgres.test.ts": 4645,@@ -110,7 +102,6 @@"e2e:test/e2e/http-transport.test.ts": 1378,"e2e:test/e2e/import-credential-preflight.test.ts": 2277,"e2e:test/e2e/ingestion-roundtrip.test.ts": 4097,- "e2e:test/e2e/init-fresh-pglite.test.ts": 35927,"e2e:test/e2e/install-real-grok.serial.test.ts": 542,"e2e:test/e2e/install-real-hermes.serial.test.ts": 508,"e2e:test/e2e/install-real-opencode.serial.test.ts": 544,@@ -138,8 +129,7 @@"e2e:test/e2e/managed-sync-failures.test.ts": 31428,"e2e:test/e2e/managed-synthesis-postprocess.test.ts": 12231,"e2e:test/e2e/mcp-budget-reservation-postgres.test.ts": 804,- "e2e:test/e2e/mcp.test.ts": 1201,- "e2e:test/e2e/mechanical.test.ts": 60319,+ "e2e:test/e2e/mechanical.test.ts": 65064,"e2e:test/e2e/migrate-chain.test.ts": 2978,"e2e:test/e2e/migrate-embeddings-postgres.test.ts": 1883,"e2e:test/e2e/migrate-engine-pglite-to-postgres.test.ts": 9641,@@ -152,16 +142,11 @@"e2e:test/e2e/migration-v47-notability.test.ts": 920,"e2e:test/e2e/migration-v50-ingest-log-source-id.test.ts": 1063,"e2e:test/e2e/minions-authority-parity.test.ts": 954,- "e2e:test/e2e/minions-budget-cathedral.test.ts": 1820,"e2e:test/e2e/minions-concurrency.test.ts": 1456,- "e2e:test/e2e/minions-controller-bounce-only.test.ts": 1873,- "e2e:test/e2e/minions-field-report-repro.test.ts": 27667,"e2e:test/e2e/minions-prefix-strip-smoke.test.ts": 1753,"e2e:test/e2e/minions-resilience.test.ts": 12390,- "e2e:test/e2e/minions-self-fix-flow.test.ts": 1661,"e2e:test/e2e/minions-shell-pglite.test.ts": 2274,"e2e:test/e2e/minions-shell.test.ts": 1161,- "e2e:test/e2e/mounts-routing-pglite.test.ts": 44757,"e2e:test/e2e/multi-source-bug-class.test.ts": 3606,"e2e:test/e2e/multi-source-emotional-weight-pglite.test.ts": 1437,"e2e:test/e2e/multi-source.test.ts": 2870,@@ -174,8 +159,6 @@"e2e:test/e2e/openclaw-context-engine-plugin.test.ts": 825,"e2e:test/e2e/openclaw-plugin-load-real.test.ts": 331,"e2e:test/e2e/openclaw-reference-compat.test.ts": 1168,- "e2e:test/e2e/openrouter-anthropic-subagent-replay.live.test.ts": 1464,- "e2e:test/e2e/openrouter-deepseek-subagent-replay.live.test.ts": 1913,"e2e:test/e2e/orphan-reduction.test.ts": 6818,"e2e:test/e2e/persistence-admin-intent.test.ts": 9254,"e2e:test/e2e/persistence-chaos.test.ts": 35877,@@ -203,13 +186,11 @@"e2e:test/e2e/propose-takes-jsonb-postgres.test.ts": 930,"e2e:test/e2e/purge-deleted-dryrun-postgres.test.ts": 726,"e2e:test/e2e/put-page-persistence-postgres.test.ts": 13045,- "e2e:test/e2e/qm-provisioning.test.ts": 40319,"e2e:test/e2e/quarantine-search-exclusion.test.ts": 3283,"e2e:test/e2e/read-enrichment-privacy.test.ts": 6533,"e2e:test/e2e/reconcile-crash-unactivated.test.ts": 101348,"e2e:test/e2e/reconcile-crash.test.ts": 102209,"e2e:test/e2e/reconcile-pgbouncer.test.ts": 4541,- "e2e:test/e2e/remote-privacy-journeys.test.ts": 24236,"e2e:test/e2e/restore-source-config-jsonb-postgres.test.ts": 1076,"e2e:test/e2e/salience-anomalies-source-isolation-pglite.test.ts": 2123,"e2e:test/e2e/salience-llm-routing.test.ts": 320,@@ -219,7 +200,6 @@"e2e:test/e2e/search-exclude.test.ts": 2067,"e2e:test/e2e/search-quality.test.ts": 1862,"e2e:test/e2e/search-query-contract-postgres.test.ts": 2042,- "e2e:test/e2e/search-readiness-http.test.ts": 12483,"e2e:test/e2e/search-swamp.test.ts": 1861,"e2e:test/e2e/self-upgrade-binary-swap.test.ts": 521,"e2e:test/e2e/self-upgrade-marker.test.ts": 4124,@@ -229,9 +209,7 @@"e2e:test/e2e/serve-http-multi-agent.test.ts": 22098,"e2e:test/e2e/serve-http-oauth.test.ts": 23362,"e2e:test/e2e/serve-http-source-grant.test.ts": 4308,- "e2e:test/e2e/serve-http-surface-ceiling.test.ts": 18357,"e2e:test/e2e/serve-http-takes-holders.test.ts": 3038,- "e2e:test/e2e/serve-stdio-roundtrip.test.ts": 23374,"e2e:test/e2e/shared-skills-rls.test.ts": 2079,"e2e:test/e2e/shared-skills-transports.test.ts": 17308,"e2e:test/e2e/skill-brain-first.test.ts": 770,@@ -240,7 +218,6 @@"e2e:test/e2e/skillopt-models-used.serial.test.ts": 2212,"e2e:test/e2e/skillopt-outcome.serial.test.ts": 3927,"e2e:test/e2e/skillopt-pglite.serial.test.ts": 2111,- "e2e:test/e2e/skillpack-flow.test.ts": 12999,"e2e:test/e2e/skillpack-third-party.test.ts": 7636,"e2e:test/e2e/skills.test.ts": 397,"e2e:test/e2e/source-boundary-mutation-postgres.test.ts": 863,@@ -272,22 +249,15 @@"e2e:test/e2e/thin-client.test.ts": 14918,"e2e:test/e2e/think-source-isolation-pglite.test.ts": 2118,"e2e:test/e2e/think-trajectory-pglite.test.ts": 2485,- "e2e:test/e2e/transcripts-ingest-pglite.test.ts": 7956,"e2e:test/e2e/transcripts-writeback-fidelity.test.ts": 4103,"e2e:test/e2e/type-unification-full-flow.test.ts": 3159,"e2e:test/e2e/unsupported-embedding-identity-postgres.test.ts": 49264,- "e2e:test/e2e/upgrade-bun-link-arc.serial.test.ts": 10048,"e2e:test/e2e/upgrade.test.ts": 3798,"e2e:test/e2e/upsert-chunks-registry-column.test.ts": 3093,- "e2e:test/e2e/v030_1-integration-pglite.test.ts": 26038,- "e2e:test/e2e/v0_28_5-fix-wave.test.ts": 15254,"e2e:test/e2e/v0_29-mcp-dispatch-pglite.test.ts": 1709,- "e2e:test/e2e/v0_30_3-fix-wave.test.ts": 13153,"e2e:test/e2e/vector-candidate-safety-postgres.test.ts": 26307,"e2e:test/e2e/vector-ef-search-postgres.test.ts": 4882,"e2e:test/e2e/volunteer-context-postgres.test.ts": 1025,- "e2e:test/e2e/voyage-multimodal.test.ts": 270,- "e2e:test/e2e/voyage-rerank-live.test.ts": 297,"e2e:test/e2e/whoknows.test.ts": 2951,"e2e:test/e2e/worker-abort-recovery.test.ts": 5266,"e2e:test/e2e/worker-configuration-release.test.ts": 33879,@@ -332,7 +302,9 @@"serial:test/backup-verification.serial.test.ts": 17191,"serial:test/binary-self-update-compiled.serial.test.ts": 345,"serial:test/bootstrap-dispatcher.serial.test.ts": 765,+ "serial:test/bootstrap-harness-lifecycle.serial.test.ts": 7085,"serial:test/bootstrap-harness.serial.test.ts": 1138,+ "serial:test/bootstrap-hook-under-serve.serial.test.ts": 8825,"serial:test/bootstrap-interview.serial.test.ts": 399,"serial:test/bootstrap-opencode-door.serial.test.ts": 2905,"serial:test/bootstrap-plugin-lane.serial.test.ts": 670,@@ -391,6 +363,7 @@"serial:test/dream-drain-failure-summary.serial.test.ts": 1707,"serial:test/dream-owner-id-threading.serial.test.ts": 1304,"serial:test/dream-postgres.serial.test.ts": 2578,+ "serial:test/dream-synthesize-chunking.serial.test.ts": 8940,"serial:test/embed-backfill-cli-admission.serial.test.ts": 31587,"serial:test/embed-exit-code-3037.serial.test.ts": 10725,"serial:test/embed-input-type-wire.serial.test.ts": 349,@@ -419,6 +392,7 @@"serial:test/facts-valid-from-context.serial.test.ts": 3296,"serial:test/filing-rules-resolution.serial.test.ts": 1013,"serial:test/foreground-chat-gateway-init.serial.test.ts": 520,+ "serial:test/fresh-install-pglite.serial.test.ts": 20603,"serial:test/friction-diff.serial.test.ts": 398,"serial:test/fts-language-cache-isolation.serial.test.ts": 1755,"serial:test/fts-language-migration.serial.test.ts": 334,@@ -535,6 +509,7 @@"serial:test/reindex-trace-transparency.serial.test.ts": 1412,"serial:test/remediation-run-extras.serial.test.ts": 3162,"serial:test/remediation-run-loop.serial.test.ts": 376,+ "serial:test/remote-privacy-journeys.serial.test.ts": 22747,"serial:test/rerank-no-key.serial.test.ts": 480,"serial:test/schema-cli-database-path.serial.test.ts": 4670,"serial:test/schema-cli-db-config.serial.test.ts": 11753,@@ -607,9 +582,10 @@"serial:test/think-temporal-window.serial.test.ts": 2212,"serial:test/unified-multimodal.serial.test.ts": 2403,"serial:test/unsupported-embedding-identity.serial.test.ts": 17450,- "serial:test/upgrade-checkpoint.serial.test.ts": 332,+ "serial:test/upgrade-bun-link-arc.serial.test.ts": 8198,"serial:test/upgrade-no-autopilot.serial.test.ts": 532,"serial:test/upgrade.serial.test.ts": 3210,+ "serial:test/v0_28_5-fix-wave.serial.test.ts": 10335,"serial:test/v0_37_fix_wave.serial.test.ts": 591,"serial:test/v0_37_gap_fill.serial.test.ts": 5408,"serial:test/watch-sigint.serial.test.ts": 6918,@@ -619,6 +595,7 @@"serial:test/write-through-commit.serial.test.ts": 1666,"serial:test/writeback-nudge.serial.test.ts": 1726,"serial:test/writeback-review-fixes.serial.test.ts": 2310,+ "slow:test/claw-test.slow.test.ts": 67740,"slow:test/core/retry-stress.slow.test.ts": 564,"slow:test/entity-card-perf.slow.test.ts": 94612,"slow:test/entity-resolve-perf.slow.test.ts": 6873,@@ -628,8 +605,10 @@"slow:test/eval-longmemeval-mixedcase.slow.test.ts": 14624,"slow:test/eval-longmemeval-reader-mode.slow.test.ts": 4143,"slow:test/eval-longmemeval.slow.test.ts": 6513,+ "slow:test/init-fresh-pglite.slow.test.ts": 35633,"slow:test/managed-atoms-cli.slow.test.ts": 49360,"slow:test/models-doctor-chat-probe-timeout.slow.test.ts": 10918,+ "slow:test/mounts-routing-pglite.slow.test.ts": 27554,"slow:test/persistence-chaos.slow.test.ts": 60817,"slow:test/persistence-skill-crash.slow.test.ts": 45962,"slow:test/persistence-skill-old-binary.slow.test.ts": 421,@@ -731,14 +710,13 @@"unit:test/apply-migrations.test.ts": 282,"unit:test/archive-crawler-config.test.ts": 179,"unit:test/archived-source-scoping.test.ts": 194,- "unit:test/artifact-abstraction.test.ts": 187,"unit:test/asymmetric-encoding-contract.test.ts": 212,"unit:test/atomic-write.test.ts": 298,"unit:test/atoms-scan-hash-rearm.test.ts": 2062,"unit:test/attendance-extraction-bounds.test.ts": 1543,"unit:test/attendance-repair-identity.test.ts": 199,- "unit:test/attendance-repair.test.ts": 24159,- "unit:test/attendance-retrieval.test.ts": 26643,+ "unit:test/attendance-repair.test.ts": 24731,+ "unit:test/attendance-retrieval.test.ts": 26963,"unit:test/audit/audit-dir-preload.test.ts": 172,"unit:test/audit/audit-writer.test.ts": 190,"unit:test/audit/batch-retry-audit.test.ts": 195,@@ -776,14 +754,13 @@"unit:test/autopilot-shutdown-engine-close.test.ts": 225,"unit:test/autopilot-supervisor-wiring.test.ts": 168,"unit:test/autopilot-transaction-fence.test.ts": 2059,- "unit:test/backfill-base.test.ts": 170,+ "unit:test/backfill-base.test.ts": 1172,+ "unit:test/backfill-perf-pglite.test.ts": 9709,"unit:test/backlink-count-mention-filter.test.ts": 2736,- "unit:test/backlinks-job-default.test.ts": 196,"unit:test/backlinks.test.ts": 10347,"unit:test/backoff.test.ts": 195,"unit:test/backpressure-audit-read.test.ts": 203,"unit:test/balanced-reranker-default.test.ts": 205,- "unit:test/batch-projection.test.ts": 222,"unit:test/bench-publish.test.ts": 228,"unit:test/bench/baseline-file.test.ts": 240,"unit:test/bench/correctness-gate.test.ts": 248,@@ -803,7 +780,7 @@"unit:test/bootstrap-shared-skills.test.ts": 2550,"unit:test/bootstrap-verify-embedding-plane.test.ts": 1410,"unit:test/bootstrap-verify-hook-carrier-overlap.test.ts": 391,- "unit:test/bootstrap.test.ts": 30893,+ "unit:test/bootstrap.test.ts": 30738,"unit:test/brain-resolver.test.ts": 303,"unit:test/brain-score-breakdown.test.ts": 2153,"unit:test/brain-score-recommendations.test.ts": 267,@@ -827,7 +804,6 @@"unit:test/brainstorm/model-config.test.ts": 416,"unit:test/brainstorm/save.test.ts": 3165,"unit:test/budget-meter.test.ts": 338,- "unit:test/budget-tracker.test.ts": 1843,"unit:test/budget/free-local-chat-pricing.test.ts": 262,"unit:test/budget/pricing-overrides.test.ts": 169,"unit:test/build-llms.test.ts": 185,@@ -930,14 +906,12 @@"unit:test/cli.test.ts": 8017,"unit:test/client-grants.test.ts": 2259,"unit:test/client-slug-fence.test.ts": 331,- "unit:test/code-callers-cli.test.ts": 191,"unit:test/code-def-refs-source-scope.test.ts": 2222,"unit:test/code-def-refs.test.ts": 2316,"unit:test/code-edges.test.ts": 2775,"unit:test/code-graph-readiness.test.ts": 4229,"unit:test/code-intel-source-scope.test.ts": 3157,"unit:test/code-intel/edge-densification.test.ts": 269,- "unit:test/code-intel/eval-capture-graph.test.ts": 201,"unit:test/code-intel/recursive-walk.test.ts": 2294,"unit:test/code-intel/scope-walker-resolution.test.ts": 266,"unit:test/code-intel/traversal-cache.test.ts": 2173,@@ -978,6 +952,7 @@"unit:test/config-unset.test.ts": 1350,"unit:test/config.test.ts": 161,"unit:test/confirm-prompt.test.ts": 174,+ "unit:test/connect-bearer.test.ts": 9620,"unit:test/connect.test.ts": 547,"unit:test/connection-resilience.test.ts": 190,"unit:test/connectors-classify.test.ts": 267,@@ -1009,7 +984,6 @@"unit:test/conversation-parser/body-path-containment.test.ts": 229,"unit:test/conversation-parser/llm-base.test.ts": 159,"unit:test/conversation-parser/llm-fallback.test.ts": 178,- "unit:test/conversation-parser/llm-polish.test.ts": 185,"unit:test/conversation-parser/nightly-probe.test.ts": 200,"unit:test/conversation-parser/parse.test.ts": 216,"unit:test/conversation-parser/speaker-object.test.ts": 208,@@ -1019,8 +993,6 @@"unit:test/core/budget/expand-records-budget.test.ts": 185,"unit:test/core/budget/gateway-budget-composition.test.ts": 159,"unit:test/core/budget/model-ledger.test.ts": 186,- "unit:test/core/diarize/payload-fitter-summarize.test.ts": 203,- "unit:test/core/diarize/payload-fitter.test.ts": 161,"unit:test/core/git-head.test.ts": 198,"unit:test/core/retry-reconnect.test.ts": 275,"unit:test/core/retry.test.ts": 858,@@ -1030,7 +1002,6 @@"unit:test/cosine-rescore-column.test.ts": 1818,"unit:test/creds-export.test.ts": 774,"unit:test/creds-relay-client.test.ts": 188,- "unit:test/cross-brain-calibration.test.ts": 335,"unit:test/cross-modal-default-slots.test.ts": 172,"unit:test/cross-modal-eval-aggregate.test.ts": 185,"unit:test/cross-modal-eval-cli.test.ts": 177,@@ -1079,7 +1050,6 @@"unit:test/cycle-synthesize.test.ts": 352,"unit:test/cycle-triage-rescue.test.ts": 441,"unit:test/cycle-write-path-mini-eval.test.ts": 3033,- "unit:test/cycle/cycle-lock-ttl.test.ts": 160,"unit:test/cycle/extract-atoms-batch.test.ts": 1972,"unit:test/cycle/extract-atoms-config-caps.test.ts": 1547,"unit:test/cycle/extract-atoms-model-config-fail-soft.test.ts": 1880,@@ -1098,7 +1068,6 @@"unit:test/cycle/yield-during-phase-throttle.test.ts": 2804,"unit:test/dart-call-edges.test.ts": 461,"unit:test/data-frontmatter.test.ts": 238,- "unit:test/data-research.test.ts": 182,"unit:test/database-url-guard-preload.test.ts": 825,"unit:test/db-disconnect-audit.test.ts": 225,"unit:test/db-guard-coverage.test.ts": 523,@@ -1132,13 +1101,10 @@"unit:test/detached-stderr.test.ts": 181,"unit:test/disk-walk.test.ts": 197,"unit:test/dispatch-localonly.test.ts": 412,- "unit:test/distribution-import-boundary.test.ts": 175,"unit:test/docker-postgres.test.ts": 184,- "unit:test/docs-bootstrap-persistence-table.test.ts": 189,"unit:test/docs-cli-commands.test.ts": 558,"unit:test/docs-mcp-deploy.test.ts": 251,"unit:test/docs-navigation.test.ts": 3525,- "unit:test/docs-timeline-extraction-guide.test.ts": 227,"unit:test/doctor-abandoned-threads-month-precision.test.ts": 1509,"unit:test/doctor-asset-paths.test.ts": 261,"unit:test/doctor-atom-provenance-drift.test.ts": 5953,@@ -1217,7 +1183,6 @@"unit:test/doctor.test.ts": 8723,"unit:test/domain-aggregators.test.ts": 2974,"unit:test/dream-clean-status-skip-visibility.test.ts": 239,- "unit:test/dream-cli-flags.test.ts": 163,"unit:test/dream-dir-source-stamp.test.ts": 2211,"unit:test/dream-env-source-scope.test.ts": 2973,"unit:test/dream-keyless-exit.test.ts": 9995,@@ -1230,7 +1195,6 @@"unit:test/edge-extractor.test.ts": 669,"unit:test/effective-date.test.ts": 188,"unit:test/embed-backfill-submit.test.ts": 1429,- "unit:test/embed-helper-migration.test.ts": 275,"unit:test/embed-keyless-guard.test.ts": 247,"unit:test/embed-modality-preserved.test.ts": 1478,"unit:test/embed-multimodal-batching.test.ts": 179,@@ -1265,7 +1229,6 @@"unit:test/enrich/thin.test.ts": 201,"unit:test/enrichable-pack.test.ts": 208,"unit:test/enrichment-service.test.ts": 202,- "unit:test/enrichment.test.ts": 4286,"unit:test/entity-card-loops.test.ts": 2774,"unit:test/entity-hints-cap.test.ts": 1173,"unit:test/entity-identity.test.ts": 2798,@@ -1288,7 +1251,6 @@"unit:test/eval-compare.test.ts": 174,"unit:test/eval-contradictions-auto-supersession.test.ts": 181,"unit:test/eval-contradictions-cache.test.ts": 3269,- "unit:test/eval-contradictions-calibration-join.test.ts": 192,"unit:test/eval-contradictions-calibration.test.ts": 199,"unit:test/eval-contradictions-cost-prompt.test.ts": 2493,"unit:test/eval-contradictions-cost.test.ts": 158,@@ -1319,7 +1281,6 @@"unit:test/eval-replay.test.ts": 234,"unit:test/eval-retrieval-quality.test.ts": 1942,"unit:test/eval-run-all.test.ts": 194,- "unit:test/eval-schema-authoring.test.ts": 184,"unit:test/eval-shared-json-repair-shim.test.ts": 171,"unit:test/eval-spend-guard.test.ts": 5700,"unit:test/eval-suspected-contradictions-budget-default.test.ts": 234,@@ -1366,7 +1327,6 @@"unit:test/extract-by-mention-resume.test.ts": 1897,"unit:test/extract-by-mention.test.ts": 1721,"unit:test/extract-conversation-facts-entity-resolution.test.ts": 2323,- "unit:test/extract-conversation-facts-workers.test.ts": 200,"unit:test/extract-conversation-facts.test.ts": 10046,"unit:test/extract-cross-source-links.test.ts": 333,"unit:test/extract-cross-source-resolution-observability.test.ts": 208,@@ -1387,7 +1347,7 @@"unit:test/extract-takes-md-first.test.ts": 1830,"unit:test/extract-takes-model-resolution.test.ts": 1173,"unit:test/extract-takes.test.ts": 1214,- "unit:test/extract-timeline-attendance.test.ts": 2958,+ "unit:test/extract-timeline-attendance.test.ts": 2082,"unit:test/extract-timeline-from-meetings.test.ts": 2084,"unit:test/extract-workers.test.ts": 179,"unit:test/extract.test.ts": 222,@@ -1397,6 +1357,7 @@"unit:test/extractable-pack.test.ts": 190,"unit:test/extractable-spec-widening.test.ts": 281,"unit:test/extraction-review.test.ts": 10082,+ "unit:test/fact-backfill-resident.test.ts": 6567,"unit:test/facts-absorb-log.test.ts": 1131,"unit:test/facts-anti-loop.test.ts": 4043,"unit:test/facts-backstop-gating.test.ts": 3812,@@ -1439,7 +1400,6 @@"unit:test/facts-worker-config.test.ts": 2388,"unit:test/facts/ttl-validity.test.ts": 1541,"unit:test/facts/writeback-gate.test.ts": 162,- "unit:test/fail-improve.test.ts": 329,"unit:test/feature-flags.test.ts": 1747,"unit:test/features-no-sync.test.ts": 191,"unit:test/features-recipe-secrets.test.ts": 227,@@ -1616,7 +1576,6 @@"unit:test/language-manifest.test.ts": 394,"unit:test/last-retrieved.test.ts": 545,"unit:test/latin-fold.test.ts": 181,- "unit:test/lease-cap-controller.test.ts": 2234,"unit:test/legacy-token-federated-scope.test.ts": 655,"unit:test/lens-pack-manifests.test.ts": 193,"unit:test/levenshtein.test.ts": 197,@@ -1745,6 +1704,7 @@"unit:test/minion-queue-renewlock-signal.test.ts": 192,"unit:test/minions-admission.test.ts": 2279,"unit:test/minions-cold-import.test.ts": 1107,+ "unit:test/minions-field-report-repro.test.ts": 7283,"unit:test/minions-lease-full-retry.test.ts": 2283,"unit:test/minions-quiet-hours.test.ts": 5534,"unit:test/minions-shell-inherit.test.ts": 633,@@ -1779,7 +1739,6 @@"unit:test/no-tracked-symlinks-guard.test.ts": 192,"unit:test/notability-eval.test.ts": 223,"unit:test/npm-squat-check.test.ts": 273,- "unit:test/nudge.test.ts": 153,"unit:test/oauth-authorize-scope-default.test.ts": 1794,"unit:test/oauth-confidential-client.test.ts": 1771,"unit:test/oauth-consent-security.test.ts": 5784,@@ -1917,7 +1876,6 @@"unit:test/pglite-workers-clamp.test.ts": 198,"unit:test/phantom-redirect-content-hash.test.ts": 1749,"unit:test/phantom-redirect-engine-parity.test.ts": 2600,- "unit:test/phantom-redirect-per-source-lock.test.ts": 189,"unit:test/phantom-redirect.test.ts": 4820,"unit:test/phase-scope-coverage.test.ts": 207,"unit:test/pid1-reaper.test.ts": 299,@@ -1932,7 +1890,6 @@"unit:test/postgres-engine-getter-selfheal.test.ts": 202,"unit:test/postgres-engine-reserved-routing.test.ts": 214,"unit:test/postgres-engine-rls-scope.test.ts": 226,- "unit:test/postgres-engine-singleton-ownership.test.ts": 190,"unit:test/postgres-engine.test.ts": 185,"unit:test/postgres-execute-raw-direct.test.ts": 193,"unit:test/preferences.test.ts": 178,@@ -1973,6 +1930,7 @@"unit:test/put-page-remote-autolink-hint.test.ts": 2839,"unit:test/put-page-write-through-failure.test.ts": 2427,"unit:test/put-page-writer-lint.test.ts": 4310,+ "unit:test/qm-provisioning.test.ts": 25142,"unit:test/qualified-names.test.ts": 150,"unit:test/quarantine-cache-ops.test.ts": 1875,"unit:test/quarantine-cli.test.ts": 6256,@@ -1994,7 +1952,6 @@"unit:test/ranking-inversion-895.test.ts": 2757,"unit:test/rate-leases-uncapped.test.ts": 2092,"unit:test/rate-leases.test.ts": 2509,- "unit:test/readme-hero-anchors.test.ts": 154,"unit:test/real-home-guard-preload.test.ts": 1185,"unit:test/recall-budget-policy-thin-cli.test.ts": 14400,"unit:test/recall-budget-policy-transports.test.ts": 56437,@@ -2002,7 +1959,6 @@"unit:test/recall-extensions.test.ts": 3436,"unit:test/recall-federated-search-scope.test.ts": 1935,"unit:test/recall-federated.test.ts": 2676,- "unit:test/recall-footer.test.ts": 165,"unit:test/recall-keyword-fallback.test.ts": 2241,"unit:test/recall-rollup.test.ts": 196,"unit:test/receipt-cr-state.test.ts": 2665,@@ -2017,7 +1973,6 @@"unit:test/regression-strict-source-id.test.ts": 247,"unit:test/regression-v0_16_4.test.ts": 201,"unit:test/regressions/gbrain-base-equivalence.test.ts": 191,- "unit:test/regressions/v0.36.1.0-iron-rule.test.ts": 159,"unit:test/regressions/v0_36_frontier_cap.test.ts": 2587,"unit:test/regressions/v0_40_2_0-trajectory-backcompat.test.ts": 1271,"unit:test/reindex-code-delegate.test.ts": 298,@@ -2037,7 +1992,6 @@"unit:test/remediation-step.test.ts": 231,"unit:test/remote-body.test.ts": 213,"unit:test/remote-cli.test.ts": 7371,- "unit:test/remote-ping-status-field.test.ts": 160,"unit:test/remote-privacy-sweep.test.ts": 9112,"unit:test/repair-jsonb.test.ts": 164,"unit:test/replay-autocut-floor.test.ts": 574,@@ -2080,7 +2034,6 @@"unit:test/schema-migrate-link-source-mentions.test.ts": 1094,"unit:test/schema-pack-best-effort.test.ts": 192,"unit:test/schema-pack-config-key.test.ts": 6784,- "unit:test/schema-pack-expand-type-filter.test.ts": 182,"unit:test/schema-pack-hash-liveness.test.ts": 684,"unit:test/schema-pack-infer-type-and-subtype.test.ts": 206,"unit:test/schema-pack-lint-rules.test.ts": 255,@@ -2097,7 +2050,6 @@"unit:test/schema-pack-registry-reload.test.ts": 233,"unit:test/schema-pack-registry.test.ts": 227,"unit:test/schema-pack-retype.test.ts": 2357,- "unit:test/schema-pack-rewrite-links-batch.test.ts": 1919,"unit:test/schema-pack-stats.test.ts": 3263,"unit:test/schema-pack-sync.test.ts": 7504,"unit:test/schema-pack-trust-boundary.test.ts": 219,@@ -2129,9 +2081,9 @@"unit:test/scripts/coverage-baseline-gate.test.ts": 843,"unit:test/scripts/coverage-diff-gate.test.ts": 593,"unit:test/scripts/data-safety-native-workflow.test.ts": 270,- "unit:test/scripts/e2e-matrix.test.ts": 1048,+ "unit:test/scripts/e2e-matrix.test.ts": 769,"unit:test/scripts/e2e-runner.test.ts": 10910,- "unit:test/scripts/e2e-wiring.test.ts": 217,+ "unit:test/scripts/e2e-wiring.test.ts": 252,"unit:test/scripts/evals-collection.test.ts": 1591,"unit:test/scripts/heavy-door-workflow.test.ts": 223,"unit:test/scripts/merge-lcov.test.ts": 1846,@@ -2139,7 +2091,7 @@"unit:test/scripts/native-compiled-cleanup.test.ts": 166,"unit:test/scripts/native-lock-prebuilds.test.ts": 282,"unit:test/scripts/native-only-workflow.test.ts": 270,- "unit:test/scripts/nightly-e2e.test.ts": 942,+ "unit:test/scripts/nightly-e2e.test.ts": 972,"unit:test/scripts/render-coverage-summary.test.ts": 354,"unit:test/scripts/run-serial-pool.test.ts": 9499,"unit:test/scripts/run-unit-parallel.test.ts": 16187,@@ -2160,6 +2112,7 @@"unit:test/search-mode.test.ts": 190,"unit:test/search-op-source-id.test.ts": 2301,"unit:test/search-projection-readiness.test.ts": 2305,+ "unit:test/search-readiness-http.test.ts": 7440,"unit:test/search-safe-index-probe.test.ts": 2392,"unit:test/search-snippet-cap.test.ts": 2800,"unit:test/search-telemetry.test.ts": 1429,@@ -2217,8 +2170,7 @@"unit:test/secret-scan-format-detectors-extra.test.ts": 215,"unit:test/secret-scan-perf.test.ts": 1257,"unit:test/secret-scan.test.ts": 270,- "unit:test/select-e2e.test.ts": 180,- "unit:test/self-fix.test.ts": 1278,+ "unit:test/select-e2e.test.ts": 210,"unit:test/self-upgrade-pending.test.ts": 176,"unit:test/self-upgrade.test.ts": 200,"unit:test/sensitivity-scan.test.ts": 320,@@ -2234,11 +2186,13 @@"unit:test/serve-http-oauth-token-rate-limit.test.ts": 550,"unit:test/serve-http-socket-tracking.test.ts": 1215,"unit:test/serve-http-stall-watchdog.test.ts": 378,+ "unit:test/serve-http-surface-ceiling.test.ts": 17528,"unit:test/serve-http-trust-proxy.test.ts": 542,"unit:test/serve-service.test.ts": 242,"unit:test/serve-skills-publish-nudge.test.ts": 873,"unit:test/serve-stdin-eof-drain.test.ts": 724,"unit:test/serve-stdio-lifecycle.test.ts": 1866,+ "unit:test/serve-stdio-roundtrip.test.ts": 22436,"unit:test/serve-sweep-runner-677.test.ts": 1213,"unit:test/server-degraded-scope.test.ts": 528,"unit:test/session-receipts.test.ts": 895,@@ -2309,6 +2263,7 @@"unit:test/skillpack-check.test.ts": 5710,"unit:test/skillpack-copy.test.ts": 210,"unit:test/skillpack-endorse.test.ts": 395,+ "unit:test/skillpack-flow.test.ts": 10126,"unit:test/skillpack-frontmatter-sources.test.ts": 237,"unit:test/skillpack-harness-bridge.test.ts": 480,"unit:test/skillpack-harvest-lint.test.ts": 175,@@ -2473,7 +2428,6 @@"unit:test/synthesize-chunk-budget.test.ts": 346,"unit:test/system-prompt.test.ts": 191,"unit:test/tailscale.test.ts": 8316,- "unit:test/take-forecast.test.ts": 164,"unit:test/take-proposals.test.ts": 1964,"unit:test/takes-command-source-scope.test.ts": 4845,"unit:test/takes-engine.test.ts": 1929,@@ -2532,6 +2486,7 @@"unit:test/transcription.test.ts": 187,"unit:test/transcripts-claude-code-workflow-drift.test.ts": 207,"unit:test/transcripts-expand-paths.test.ts": 262,+ "unit:test/transcripts-ingest-pglite.test.ts": 6542,"unit:test/transcripts-max-bytes.test.ts": 275,"unit:test/transcripts-nul.test.ts": 2293,"unit:test/transcripts-self-exclusion.test.ts": 266,@@ -2563,7 +2518,6 @@"unit:test/volunteer-context.test.ts": 1768,"unit:test/volunteer-events-delivery.test.ts": 177,"unit:test/voyage-multimodal.test.ts": 324,- "unit:test/voyage-response-cap.test.ts": 239,"unit:test/wait-for-completion.test.ts": 8601,"unit:test/watch-command.test.ts": 1926,"unit:test/wave-security-scan.test.ts": 2239,diff --git a/skills/brain-pdf/SKILL.md b/skills/brain-pdf/SKILL.mdindex 3ff6f2a232..f18f9eb8c5 100644--- a/skills/brain-pdf/SKILL.md+++ b/skills/brain-pdf/SKILL.md@@ -80,7 +80,7 @@ if [ -n "$BRAIN_DIR" ] && [ -f "$BRAIN_DIR/$SLUG.md" ]; thenRAW="$BRAIN_DIR/$SLUG.md"elseRAW=$(mktemp /tmp/brain-page-XXXXXX.md)- gbrain get "$SLUG" --raw > "$RAW" # whatever flag exposes raw body+ gbrain get "$SLUG" > "$RAW" # prints the page as markdown with frontmatterfi# 3. Strip YAML frontmatter — sed: skip the opening '---' through thediff --git a/skills/conventions/calibration.md b/skills/conventions/calibration.mdindex 606bd74a50..1f907f026b 100644--- a/skills/conventions/calibration.md+++ b/skills/conventions/calibration.md@@ -50,20 +50,11 @@ to LOWER an active threshold without an explicit `--allow-loosen-confidence`flag — because relaxing after data accumulates silently shifts whichhistorical resolutions count as auto-applied.-## Cross-brain semantics (D18)+## Cross-brain reads-For any read of a calibration profile across mounted brains:--1. **Local first.** Query local. If local has it, return; do not query mounts.-2. **Mount fallback.** Only if local is empty AND `canReadMountsForCtx(ctx)`- returns true. Mount-side rows must have `published=true`.-3. **Cross-brain attribution.** Returned profile carries- `source_brain_id` + `from_mount`. UI consumers MUST surface- "from mounted brain: X" so the user knows.-4. **Subagent prohibition.** `ctx.viaSubagent && !allowedSlugPrefixes`- cannot read mounts — subagent loops see only the local brain. Trusted-- workspace cycle phases (synthesize/patterns) pass- `allowedSlugPrefixes` set and ARE allowed.+Calibration profiles are read from the local brain only. Reading a+profile from a mounted brain is not implemented: the v0.36.1.0 D18+cross-brain helper never had a runtime caller and was removed.## Test seams@@ -84,8 +75,6 @@ the calibration wave has structural defense against:- BaseCyclePhase enforces `sourceScopeOpts(ctx)` threading at the type level.- Every new schema table has `source_id NOT NULL REFERENCES sources(id)`.-- Cross-brain reads route through `canReadMountsForCtx()` classifier.-- Tests pin all 4 D18 rules in `test/cross-brain-calibration.test.ts`.If you find yourself writing a `ctx.engine.executeRaw(...)` inside acalibration module that doesn't pass `sourceScopeOpts`, you've founddiff --git a/skills/migrations/v0.13.0.md b/skills/migrations/v0.13.0.mdindex 39d4e08e1f..3735946392 100644--- a/skills/migrations/v0.13.0.md+++ b/skills/migrations/v0.13.0.md@@ -60,8 +60,8 @@ gbrain stats# Sample a hub entity from your brain — depth-2 should return many more nodes than before.gbrain graph <hub-entity-slug> --depth 2-# Filter to specific edge types (new in v0.13).-gbrain graph <hub-entity-slug> --depth 2 --type yc_partner,invested_in+# Filter to one edge type.+gbrain graph <hub-entity-slug> --depth 2 --link-type invested_in# Count edges by provenance.gbrain call get_stats --json@@ -79,7 +79,7 @@ gbrain call get_stats --json**Agents using `put_page` see a new `unresolved` field in `auto_links`.** This is additive. Existing agents that ignore unknown response fields keep working. Agents that want to escalate unresolved names: read `response.auto_links.unresolved`.-**`attendee` vs `attended` type normalization.** Legacy rows with `link_type='attendee'` or `link_type='mention'` keep working. Normalization to the v0.13 canonical names (`attended`, `mentions`) is deliberately NOT in this migration — it's a separate semantic concern. The `gbrain normalize-types` command (v0.14) handles it opt-in.+**`attendee` vs `attended` type normalization.** Legacy rows with `link_type='attendee'` or `link_type='mention'` keep working. Normalization to the v0.13 canonical names (`attended`, `mentions`) is deliberately NOT in this migration — it's a separate semantic concern.## For downstream agent skill forksdiff --git a/skills/migrations/v0.14.0.md b/skills/migrations/v0.14.0.mdindex 694d29a4d0..1e2057ad38 100644--- a/skills/migrations/v0.14.0.md+++ b/skills/migrations/v0.14.0.md@@ -133,7 +133,7 @@ After rewriting ONE cron with the operator's approval:1. Wait for the next scheduled fire (or trigger manually: `gbrain jobssubmit shell --params '...' --follow`).-2. Check `gbrain jobs list --status completed --name shell --limit 5`+2. Check `gbrain jobs list --status completed --json | jq '[.[] | select(.name == "shell")][:5]'`for the result.3. `gbrain jobs get <id>` shows `exit_code`, `stdout_tail`, `stderr_tail`,`duration_ms`.@@ -152,7 +152,7 @@ deployments the warning scrolls past. Add this to the operator'sops-check runbook:```bash-gbrain jobs list --status waiting --name shell+gbrain jobs list --status waiting --json | jq '.[] | select(.name == "shell")'```If rows pile up here, either (a) no worker has the env flag set, or@@ -164,8 +164,8 @@ If rows pile up here, either (a) no worker has the env flag set, orcrontab-to-minions <file>` helper. P1 in TODOS.md.- **DB-backed scheduler.** `minion_schedules` table replaces hostcrontab entirely. P1 in TODOS.md.-- **Orphaned-shell-job stats.** `gbrain jobs stats --orphaned` would- surface the "no worker with env flag" case. P2 in TODOS.md.+- **Orphaned-shell-job stats.** An orphaned-job view in `gbrain jobs stats`+ would surface the "no worker with env flag" case. P2 in TODOS.md.- **Configurable buffer sizes.** Output tails are fixed at 64KB stdout/ 16KB stderr. P2 in TODOS.md.diff --git a/skills/migrations/v0.32.2.md b/skills/migrations/v0.32.2.mdindex ee5c2e7423..5ad76732c5 100644--- a/skills/migrations/v0.32.2.md+++ b/skills/migrations/v0.32.2.md@@ -59,7 +59,7 @@ the migration appear complete.1. **`gbrain forget <id>` now rewrites markdown.** Previously `gbrainforget` called `engine.expireFact(id)` which UPDATEd the DB only.- After `gbrain rebuild` (v0.32.3) the forget would evaporate. v0.32.2+ After a rebuild of the database from the repo the forget would evaporate. v0.32.2makes forget rewrite the fence: strikethrough the claim, set`valid_until=today`, append `forgotten: <reason>` to the contextcell. New optional `--reason <text>` flag.diff --git a/skills/migrations/v0.33.0.md b/skills/migrations/v0.33.0.mdindex 11a03daf11..798ba799a0 100644--- a/skills/migrations/v0.33.0.md+++ b/skills/migrations/v0.33.0.md@@ -100,8 +100,8 @@ Pass `--all-sources` to get the pre-v0.33 cross-source default.# 1. Confirm upgradegbrain --version # 0.33.0-# 2. Confirm migration v51 ran-gbrain apply-migrations --status | grep edges_backfilled_at_v0_34+# 2. Confirm schema migrations are current+gbrain doctor --json | jq '.checks[] | select(.name == "schema_version")'# 3. Confirm the new MCP ops are exposedgbrain --tools-json | jq '.[] | select(.name | startswith("code_")) | .name'@@ -127,7 +127,7 @@ Per the v0.34 design doc (`/Users/garrytan/.gstack/projects/garrytan-gbrain/garr- Recursive `code_blast` / `code_flow` MCP ops on top of the resolved graph- Leiden community detection (`code_clusters_list`, `code_cluster_get`) +inline mermaid diagrams-- `gbrain wiki` zero-LLM aggregator CLI+- `gbrain wiki` zero-LLM aggregator CLI <!-- gbrain-cli: historical -->- Per-op graph-traversal eval metrics extending v0.25.0's eval-capture- `imports` and `references` edge types for JS/TS/TSX + Python- Receiver-type scope walkers (e.g. `obj.method()` → `Class.method`)diff --git a/skills/migrations/v0.33.3.0.md b/skills/migrations/v0.33.3.0.mdindex f3d982ff4e..7ae42c1b40 100644--- a/skills/migrations/v0.33.3.0.md+++ b/skills/migrations/v0.33.3.0.md@@ -100,8 +100,8 @@ Pass `--all-sources` to get the pre-v0.33 cross-source default.# 1. Confirm upgradegbrain --version # 0.33.3.0-# 2. Confirm migration v51 ran-gbrain apply-migrations --status | grep edges_backfilled_at_v0_34+# 2. Confirm schema migrations are current+gbrain doctor --json | jq '.checks[] | select(.name == "schema_version")'# 3. Confirm the new MCP ops are exposedgbrain --tools-json | jq '.[] | select(.name | startswith("code_")) | .name'@@ -127,7 +127,7 @@ Per the v0.34 design doc (`/Users/garrytan/.gstack/projects/garrytan-gbrain/garr- Recursive `code_blast` / `code_flow` MCP ops on top of the resolved graph- Leiden community detection (`code_clusters_list`, `code_cluster_get`) +inline mermaid diagrams-- `gbrain wiki` zero-LLM aggregator CLI+- `gbrain wiki` zero-LLM aggregator CLI <!-- gbrain-cli: historical -->- Per-op graph-traversal eval metrics extending v0.25.0's eval-capture- `imports` and `references` edge types for JS/TS/TSX + Python- Receiver-type scope walkers (e.g. `obj.method()` → `Class.method`)diff --git a/skills/migrations/v0.34.0.0.md b/skills/migrations/v0.34.0.0.mdindex 174e3eae76..09ed8fd7f2 100644--- a/skills/migrations/v0.34.0.0.md+++ b/skills/migrations/v0.34.0.0.md@@ -29,7 +29,8 @@ MCP-exposed code-callers/callees/def/refs foundation:- W3b: `code_traversal_cache` table for memoizing blast/flow results.Cache invalidation honors the D3 cluster-generation counter.- W7: `src/core/eval-capture-graph.ts` — pure-function metrics module- for replay-driven regression checks.+ for replay-driven regression checks (never wired; removed in the+ test-reduction fix wave).## Mechanical migration@@ -65,8 +66,8 @@ v0.34.1 after operator brain validation:- **W4–5 Leiden clusters.** Cluster ship gate (≤0.03 clusters/node)requires real brain data; v0.34.0.0 ships without clusters.-- **`gbrain wiki`** — depends on clusters.-- **`gbrain blast` / `gbrain flow` CLI thin-shims.** Use `gbrain call+- **`gbrain wiki`** — depends on clusters. <!-- gbrain-cli: historical -->+- **`gbrain blast` / `gbrain flow` CLI thin-shims.** <!-- gbrain-cli: historical --> Use `gbrain callcode_blast --symbol <name>` for v0.34.0.0; CLI wrappers come withv0.34.1.- **eval-capture wiring** — the metric module ships in v0.34.0.0;diff --git a/skills/migrations/v0.40.5.md b/skills/migrations/v0.40.5.mdindex c2b02553b9..9f4f946c52 100644--- a/skills/migrations/v0.40.5.md+++ b/skills/migrations/v0.40.5.md@@ -62,10 +62,10 @@ To rotate later: `gbrain sources webhook rotate <source-id>`. The new secret invPer-source priority drives autopilot dispatch order. The default brain typically wants `high`; archival sources can use `low`:```bash-# Hand-edit sources.config via SQL or via a future `gbrain sources config set` command-# In v0.40.5 set via direct SQL:-gbrain exec "UPDATE sources SET config = jsonb_set(config, '{priority}', '\"high\"') WHERE id = 'default'"-gbrain exec "UPDATE sources SET config = jsonb_set(config, '{priority}', '\"low\"') WHERE id = 'media-corpus'"+# No gbrain command sets sources.config.priority; set it with SQL against the+# brain database (Postgres shown; run the same UPDATE in any SQL client):+psql "$DATABASE_URL" -c "UPDATE sources SET config = jsonb_set(config, '{priority}', '\"high\"') WHERE id = 'default'"+psql "$DATABASE_URL" -c "UPDATE sources SET config = jsonb_set(config, '{priority}', '\"low\"') WHERE id = 'media-corpus'"```Recognized values: `high` (priority -10), `normal` (0), `low` (5). Unknown values fall back to `normal` with a once-per-source stderr warning.diff --git a/skills/migrations/v0.41.11.0.md b/skills/migrations/v0.41.11.0.mdindex 7b16f1a113..b972c94c4f 100644--- a/skills/migrations/v0.41.11.0.md+++ b/skills/migrations/v0.41.11.0.md@@ -57,5 +57,5 @@ When the user mentions:- Pages over 25MB body are skipped (memory cap). Surface in doctor `details`; streaming for huge pages is a v0.42+ TODO.- If `facts.extraction_enabled` is false, the command refuses. Pass `--override-disabled` only when the user explicitly opted out and now wants this one-time run.-- Extracted facts use `source = 'cli:extract-conversation-facts'`. To remove them in bulk (rare), the only path today is raw SQL: `DELETE FROM facts WHERE source LIKE 'cli:extract-conversation-facts%'`. A `gbrain forget --where` bulk flag is a v0.42+ TODO.+- Extracted facts use `source = 'cli:extract-conversation-facts'`. To remove them in bulk (rare), the only path today is raw SQL: `DELETE FROM facts WHERE source LIKE 'cli:extract-conversation-facts%'`. A bulk `--where` filter for `gbrain forget` is a v0.42+ TODO.- The recall-quality eval (under `test/eval/conversation-extraction-quality.eval.ts` — added in this wave) is env-gated on `ANTHROPIC_API_KEY`. Run nightly or on-demand for quality verification; the hermetic wiring tests run in CI by default.diff --git a/skills/schema-unify/SKILL.md b/skills/schema-unify/SKILL.mdindex 9e2dd9927f..b61bd4019b 100644--- a/skills/schema-unify/SKILL.md+++ b/skills/schema-unify/SKILL.md@@ -143,7 +143,7 @@ Expected:### Phase 5: Post-migration-Anything that used `--type article` keeps working post-unify if your CLI calls go through the `expandTypeFilter` helper (it expands `article` to `media+subtype=article` automatically). Direct SQL against `pages.type` needs updating to the canonical types.+Search and query `--type article` keep returning those pages post-unify: `media` declares `article` as an alias, so the type filter expands through the active pack's alias closure (the results also include other `media` pages). Direct SQL against `pages.type` needs updating to the canonical types.Search queries get a small ranking signal: pages reached via `slug_aliases` (canonicals of one or more aliases) get a 1.05x boost. Visible via `gbrain search --explain`.@@ -219,7 +219,7 @@ Outputs:Side effects:- Source pages soft-deleted with 72h restore TTL (`gbrain restore <slug>`).- One-time cache invalidation on KNOBS_HASH_VERSION bump (5→6); self-healing in `cache.ttl_seconds`.-- Query-time `--type X` alias-expands via `expandTypeFilter` (back-compat).+- Search/query `--type X` expands through the active pack's alias closure (back-compat).Failure modes:- Concurrent submission rejected by the `gbrain-unify` db-lock; second call exits gracefully.diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex b27ab816e0..2051111db6 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -21,7 +21,7 @@"brain-link-discipline/SKILL.md": "489268f71a01abb6213df8a8bb5f4d16d587b09dd670ac3c47876a8ed808b5ae","brain-link-discipline/routing-eval.jsonl": "0adea4c6d72fdb849c12fe2cad718568b9ab704299b00b093c40c2284faf684c","brain-ops/SKILL.md": "566dcf7f12f18fab09967c5ab4f77ce949f1a2151dc707f678c0a9e3b835b3df",- "brain-pdf/SKILL.md": "13c3e3162763a4503685db0a10663475d3687c4874b5f04d539af83a990f643e",+ "brain-pdf/SKILL.md": "68eb85679718afe504179be780ced483b1fe5916b7b294bd202dceca2d9c9398","brain-pdf/routing-eval.jsonl": "119e4fa113ea45783cee4499e63a729fdeecb4d9a45d47497754b4f5b21d0734","brain-taxonomist/SKILL.md": "dea4557b540868ec2c56bf43ee7f63c5d03a22d4047cd0dfbeaf19adef334f60","brain-taxonomist/routing-eval.jsonl": "8b485b3d735aace60be703854f0f2e9d97c52d52564efdaf7334a0c39e8d20ae",@@ -46,7 +46,7 @@"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab","conventions/brain-first.md": "d9b18321150830d38586f5bd23ce9de735f08ac3b54d7ac63bc3184a61e17ef1","conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6",- "conventions/calibration.md": "dc357891a86987fbc39e06a21a190119b9900e03a2460af64b278307af1b4289",+ "conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198","conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933","conventions/cross-modal.yaml": "c012c3d72614a87b1ee698173dce2a0fb0d057a54df7aab87993c4b07fff6280","conventions/exec-output.md": "2bf371ac3ec4987eff7cc13cd3ea8cc97c46bd43f588eec024ff27f3171bc58f",@@ -106,8 +106,8 @@"migrations/v0.11.0.md": "ac45c6144eeee5033f2b24308a5063ceced2be7831b04e48154aa0b6f8ff55d8","migrations/v0.12.0.md": "f30b452caed5ce2679cbd60dc2d0b9e60449bab20c3a3e0c895e6cd167644f44","migrations/v0.12.1.md": "a461d8fcd6b19dabe3a0ce849a54e3c577667ae2af41870c6f456c6195e76064",- "migrations/v0.13.0.md": "3bf61eb1da933e6c3c35d67d0ea6d9dada5d5f878bbd14020616d4e1fe48feb2",- "migrations/v0.14.0.md": "1025395f033b91480451aad6a98dc10f2c18bfacd1b1a4e2a9fb4dc99f8fb571",+ "migrations/v0.13.0.md": "9725da5d889b488de14c312fadaa81800e5167e0ecf6adc5a083d721a329e5ba",+ "migrations/v0.14.0.md": "47a1326810af07c322740757740438f4d90f03bf2a8b1aea061535bff5ea8e1d","migrations/v0.15.2.md": "468a58e8a9f0f5c5867e0ed8eb9dd1bd60dbc8d66111647997ebd8d9d2119915","migrations/v0.17.0.md": "761dda3b6090bfe20c9b4354aff5248d5a9b6a79a24702ecc2b29873d4f5b413","migrations/v0.18.0.md": "94efc1d571070600a78aca13c2735866a987e6a8f188210b7062f81b54839986",@@ -120,18 +120,18 @@"migrations/v0.27.1.md": "719dd4ebcc7ac81413ee79af20f80de5141577e3860e5049a49fc8f6d09ddf89","migrations/v0.28.0.md": "21929a392af2e1f454272e80aade6c58c5f6ccd7253d24344d08c6b53bcdf4f9","migrations/v0.29.1.md": "7b85373a62a8500ee8c4238ffc9878318b44ee62543adb8b2462049c6c0cd1f8",- "migrations/v0.32.2.md": "7dc1198c02ab37534e04604c93c7e9a854ca9f04872af2a7c1fd4c0c8b78fbeb",+ "migrations/v0.32.2.md": "e32e60cba9179fb2429a1cec38ee91abd66937baf4ab393ab008660e59aaf12a","migrations/v0.32.6.md": "e9438a910afe8a1f7861c5222fd7db04a0f8d8b8283778476b07b7c3d539d3f0",- "migrations/v0.33.0.md": "11710cb11d6eb7dc3ea54b764e3c4a25f8679cf76590acd330f97bfa1c684945",- "migrations/v0.33.3.0.md": "188a03ca86a97a9aa697cbbc83cc8ca37843fab24db2bd82f1383c400173d5bd",- "migrations/v0.34.0.0.md": "d421c5ecff0765ac1de3592d3175734db7df52e8658ec101567779c7c56c2db2",+ "migrations/v0.33.0.md": "79febbe39b9518837acd1adc86c989a75b196f9fa5c7a217e64dc2eadc23ea01",+ "migrations/v0.33.3.0.md": "3747f72d050bf0d269227af2bf5636238d959fa0508f80470bad4874c725d96e",+ "migrations/v0.34.0.0.md": "eb98a3c702c4a0b606fae68c8b559a5e665ba7290c838d306c4d019aa1ef6706","migrations/v0.35.0.0.md": "b4cbc07fffaf4e291fcc035283d976498c5288da9b10ac7fc97947747acea150","migrations/v0.35.7.0.md": "c6d4454bd39e2aa243b3b3d9bc72fe5a4fd25d097be7be2bb14b25604b5c2cc5","migrations/v0.36.2.0.md": "18f72475a0c0de1489c518219128d331d8ed6b0cdcacfb329e18fbcc643d9c6e","migrations/v0.36.5.0.md": "889f42508c28835c99242ec20b610ab002f20cda821cb99039589a212cac2ce0","migrations/v0.40.3.0.md": "5f500f8c543c2b6f41778b0bd3beedada68f7284f7933ad8b769322b433a8fe9",- "migrations/v0.40.5.md": "b9837d52a030517698dfb31c439f562cde60a1015ae488dab09be2c16ff182e5",- "migrations/v0.41.11.0.md": "5c6873ab969d14def4a450d792f070f1259d08b3aca43bc7825d0a9114b2b36b",+ "migrations/v0.40.5.md": "f66047f1b6ef18b5b5e35445d61c0a1fe44e3c0f9e1c7a51c6b2342c67a0d92f",+ "migrations/v0.41.11.0.md": "75c9741617de4c163052609e64734b4696a1105d3d015ed451097eaf6ea1eb3c","migrations/v0.46.3.0.md": "add5bdace741f8f0a75a114e354aa8ea3bcadf4cb54e1823338fdc69a5ae3f5d","migrations/v0.46.35.0.md": "145c841d89c4b6b6f7089126354fae272df7db6ceaf9cfcec2797d3301cdab57","migrations/v0.48.3.0.md": "1d9a23b6078164717944c94791b18effc7af630b716e8fde2680d6b6de47ce81",@@ -177,7 +177,7 @@"resolve-before-asking/SKILL.md": "1882c45b2e603bbb1e251d388cc2682270ee7eae99211d5a5322430f4667fb39","resolve-before-asking/routing-eval.jsonl": "bac1bcf30337f5255ef4ce1a2a8a2b38d58ebcd576503c483190c79ec6e69489","schema-author/SKILL.md": "1dd11a44dabcb7d57244be4cf5f4903feb9d146bcbb4363fc150daefc01d04ce",- "schema-unify/SKILL.md": "31227b5a9d90e0f1482b52cfd6d23a71575cdbc36f2edcfa8f0170bfb7b95467",+ "schema-unify/SKILL.md": "03585d2155f43eedcf5f6e006785ee9f0142a8ae1a088c5e6456ecac675dc24d","setup/SKILL.md": "a0f9d72565b489c4a60f6546b89218ea9efc307b397ac5ea22f3ed4c737f73f1","signal-detector/SKILL.md": "ea090be2fedeb528c3b3a4b3c649abd3ff07b3ecdc6266bf2930364537683489","skill-autobench/SKILL.md": "144572ec76f3784a97645dfde587ab13d77e804f50b00dc7fbe678204de6ff21",diff --git a/src/cli.ts b/src/cli.tsindex 3e428295f1..8581fdc1cc 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -1025,11 +1025,6 @@ interface CachedIdentity {const IDENTITY_TTL_MS = 60_000;const identityCache = new Map<string, CachedIdentity>();-/** Test-only escape hatch — clears the in-memory cache between test runs. */-export function _clearIdentityCacheForTest(): void {- identityCache.clear();-}-export function bannerSuppressed(cliOpts: CliOptions): boolean {if (cliOpts.quiet) return true;if (process.env.GBRAIN_NO_BANNER === '1') return true;diff --git a/src/commands/dream.ts b/src/commands/dream.tsindex 3bbe53ef3f..6be766c177 100644--- a/src/commands/dream.ts+++ b/src/commands/dream.ts@@ -691,7 +691,7 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom// ─── IRON RULE: --help short-circuits BEFORE any engine-bearing work ─// Tests pin this ordering so `gbrain dream --help --source whatever`// ALWAYS prints help and exits 0, never reaching the engine-null gate- // below. If you reorder this, dream-cli-flags.test.ts will fail.+ // below. If you reorder this, test/dream.test.ts ("--help --source whatever") fails.if (opts.help) {printHelp();return;diff --git a/src/commands/eval-schema-authoring.ts b/src/commands/eval-schema-authoring.tsdeleted file mode 100644index de99ff522a..0000000000--- a/src/commands/eval-schema-authoring.ts+++ /dev/null@@ -1,176 +0,0 @@-// `gbrain eval schema-authoring` — real aggregator + honest not-implemented runner.-//-// v0.39 T16 shipped two things here. `aggregateVerdict` is the REAL pass-// criterion (codex finding #9 honored): it measures FILING ACCURACY DELTA-// (post-suggest vs baseline), NOT pack-manifest correctness — a "correct"-// manifest that doesn't improve real filing is not progress; an "imperfect"-// manifest that improves filing 20% is. The runner around it was a scaffold-// that answered every invocation with verdict:'inconclusive' + zeroed metrics-// for work it never ran — the dishonest-envelope class #4198 fixed for-// eval-synthesize-concepts and E4 swept for the remaining scaffolds.-//-// The runner now returns that module's UNAMBIGUOUS shape: ok:false,-// status:'not_implemented', and a nonzero exit from the CLI entry. There is-// deliberately no cli.ts/eval.ts dispatch branch yet — a subcommand appears-// when it evaluates something. The hermetic PGLite harness (fixture-brain-// replay through runDetect + runSuggest, per-page filing accuracy before and-// after) is the tracked T16 follow-through in TODOS.md; it flips ok/status-// when it lands. `aggregateVerdict` + `parseArgs` are real today and pinned-// by test/eval-schema-authoring.test.ts.--export interface EvalSchemaAuthoringArgs {- fixture?: string;- source?: string;- json?: boolean;-}--/** Shape the real harness will fill in per run; `aggregateVerdict` produces its core. */-export interface EvalVerdict {- verdict: 'pass' | 'fail' | 'inconclusive';- fixture: string | null;- filing_accuracy_baseline: number;- filing_accuracy_post_suggest: number;- delta: number;- reasoning: string;- suggestion_count: number;- low_confidence_count: number;-}--/** Envelope contract shared with eval-synthesize-concepts (#4198). */-export interface EvalSchemaAuthoringResult {- schema_version: 1;- ok: boolean;- reason: string;- status: 'not_implemented' | 'pass' | 'fail' | 'inconclusive';- details: Record<string, unknown>;-}--export function parseArgs(argv: string[]): EvalSchemaAuthoringArgs {- const args: EvalSchemaAuthoringArgs = {};- for (let i = 0; i < argv.length; i++) {- const a = argv[i];- if (a === '--fixture') args.fixture = argv[++i];- else if (a === '--source' || a === '--source-id') args.source = argv[++i];- else if (a === '--json') args.json = true;- }- return args;-}--/**- * Pure aggregator: given baseline + post-suggest filing-accuracy- * numbers, decide pass/fail/inconclusive. Pass requires non-trivial- * improvement (delta >= 0.1) AND no high-confidence suggestion was- * silently auto-applied below the 0.6 threshold (low_confidence_count- * is informational only).- */-export function aggregateVerdict(- baseline: number,- postSuggest: number,- suggestionCount: number,- lowConfidenceCount: number,-): Pick<EvalVerdict, 'verdict' | 'delta' | 'reasoning'> {- const delta = postSuggest - baseline;- if (suggestionCount === 0 && baseline >= 0.9) {- return {- verdict: 'pass',- delta,- reasoning: 'Active pack already matches brain shape; no suggestions needed.',- };- }- if (suggestionCount === 0) {- return {- verdict: 'inconclusive',- delta,- reasoning: `Baseline ${baseline.toFixed(2)} below 0.9 but runSuggest returned 0 suggestions. Check whether the brain has enough typed pages for detect to fire.`,- };- }- if (delta >= 0.1) {- return {- verdict: 'pass',- delta,- reasoning: `Filing accuracy improved ${(delta * 100).toFixed(1)}pp from ${(baseline * 100).toFixed(1)}% → ${(postSuggest * 100).toFixed(1)}%.`,- };- }- if (delta >= 0) {- return {- verdict: 'inconclusive',- delta,- reasoning: `Suggestions returned but filing accuracy delta is only ${(delta * 100).toFixed(1)}pp — below the 10pp pass threshold.`,- };- }- return {- verdict: 'fail',- delta,- reasoning: `Filing accuracy REGRESSED ${(Math.abs(delta) * 100).toFixed(1)}pp after applying suggestions. ${lowConfidenceCount} low-confidence suggestions were emitted; verify they were NOT auto-applied.`,- };-}--/**- * Runner. Records the arguments and returns an honest not-implemented- * verdict — nothing is evaluated until the fixture-brain harness lands.- */-export async function runEvalSchemaAuthoring(argv: string[]): Promise<EvalSchemaAuthoringResult> {- const args = parseArgs(argv);- return {- schema_version: 1,- // Honest verdict (#4198): an eval that ran nothing must not read as a- // pass (or as a data-bearing "inconclusive"). ok flips to true only when- // the real harness runs and aggregateVerdict says pass.- ok: false,- reason:- 'eval schema-authoring is not implemented yet — no fixture brain was replayed and no filing ' +- 'accuracy was measured. The hermetic harness (runDetect + runSuggest over a fixture brain, ' +- 'scored by aggregateVerdict) is a tracked follow-up.',- status: 'not_implemented',- details: {- fixture: args.fixture ?? null,- source: args.source ?? null,- planned:- 'Replay a fixture brain through runDetect + runSuggest on a hermetic PGLite engine; compute ' +- 'per-page filing accuracy before and after applying suggestions; gate on aggregateVerdict ' +- '(delta >= 10pp passes; manifest correctness is never the criterion).',- },- };-}--const HELP = `gbrain eval schema-authoring — schema-pack suggest filing-accuracy eval (NOT IMPLEMENTED)--Status: scaffold. Running it evaluates nothing and exits 1 with an-{ok:false, status:'not_implemented'} envelope so scripts cannot mistake-the scaffold for a passing eval. The aggregator (aggregateVerdict) is-real and unit-tested; the fixture-brain harness that feeds it is not-wired yet.--Usage (NOT yet dispatched from the CLI: 'gbrain eval schema-authoring' is not-a registered subcommand; the entry is runEvalSchemaAuthoringCli(args) and the-dispatch branch lands with the fixture-brain harness):- schema-authoring [--fixture <dir>] [--source <id>] [--json]--Options:- --fixture <dir> Fixture brain directory (recorded, unused yet)- --source <id> Source id for the replay; alias --source-id (recorded, unused yet)- --json Emit the machine envelope on stdout- --help Show this help (exit 0)--Pass criterion once the harness lands: filing-accuracy delta >= 10pp-post-suggest vs baseline (aggregateVerdict), never manifest correctness.-`;--/**- * CLI entry — parses flags, prints the envelope, returns the exit code- * (0 only for --help; the not-implemented scaffold exits 1).- */-export async function runEvalSchemaAuthoringCli(args: string[]): Promise<number> {- if (args.includes('--help') || args.includes('-h')) {- console.log(HELP);- return 0;- }- const result = await runEvalSchemaAuthoring(args);- if (parseArgs(args).json) {- console.log(JSON.stringify(result, null, 2));- } else {- console.error(`eval schema-authoring: ${result.status.toUpperCase()}`);- console.error(result.reason);- }- return result.ok ? 0 : 1;-}diff --git a/src/commands/migrations/v0_12_0.ts b/src/commands/migrations/v0_12_0.tsindex 4aa64b9b3b..206e5ed023 100644--- a/src/commands/migrations/v0_12_0.ts+++ b/src/commands/migrations/v0_12_0.ts@@ -250,13 +250,3 @@ export const v0_12_0: Migration = {},orchestrator,};--/** Exported for unit tests. */-export const __testing = {- phaseASchema,- phaseBConfigCheck,- phaseCBackfillLinks,- phaseDBackfillTimeline,- phaseEVerify,- readStats,-};diff --git a/src/commands/migrations/v0_12_2.ts b/src/commands/migrations/v0_12_2.tsindex 1902566dd7..28d61d0ba4 100644--- a/src/commands/migrations/v0_12_2.ts+++ b/src/commands/migrations/v0_12_2.ts@@ -137,10 +137,3 @@ export const v0_12_2: Migration = {},orchestrator,};--/** Exported for unit tests. */-export const __testing = {- phaseASchema,- phaseBRepair,- phaseCVerify,-};diff --git a/src/commands/migrations/v0_13_0.ts b/src/commands/migrations/v0_13_0.tsindex 68510339bb..076369725b 100644--- a/src/commands/migrations/v0_13_0.ts+++ b/src/commands/migrations/v0_13_0.ts@@ -159,10 +159,3 @@ export const v0_13_0: Migration = {},orchestrator,};--/** Exported for unit tests. */-export const __testing = {- phaseASchema,- phaseBBackfill,- phaseCVerify,-};diff --git a/src/commands/migrations/v0_21_0.ts b/src/commands/migrations/v0_21_0.tsindex d920b3c86f..c994f7db45 100644--- a/src/commands/migrations/v0_21_0.ts+++ b/src/commands/migrations/v0_21_0.ts@@ -141,10 +141,3 @@ export const v0_21_0: Migration = {},orchestrator,};--/** Exported for unit tests. */-export const __testing = {- phaseASchema,- phaseBBackfillPrompt,- phaseCVerify,-};diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 8359df0b47..36b8499817 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1373,7 +1373,7 @@ async function runWebhookSet(engine: BrainEngine, args: string[]): Promise<void>console.log(`Webhook configured for source "${id}":`);if (githubRepo) console.log(` github_repo: ${githubRepo}`);- console.log(` webhook_secret: ${secret}`);+ console.log(' webhook_secret: (shown once below)');console.log('');console.log('--- Paste this into GitHub repo settings → Webhooks → Add webhook ---');console.log(' Payload URL: <your gbrain serve --http URL>/webhooks/github');diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex e684503036..7dbb6a5e09 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -1348,9 +1348,6 @@ export const perplexityCompatFetch = (async (input: RequestInfo | URL, init?: Re* line on every search, and today's keyless state is stderr-silent.*/const _noKeyNoticed = new Set<string>();-export function _resetRerankWarningsForTest(): void {- _noKeyNoticed.clear();-}function noKeyOnce(modelStr: string, keyName: string, query: string, docCount: number): void {try {if (_noKeyNoticed.has(modelStr)) return;diff --git a/src/core/artifact/index.ts b/src/core/artifact/index.tsdeleted file mode 100644index b3a4f871c4..0000000000--- a/src/core/artifact/index.ts+++ /dev/null@@ -1,149 +0,0 @@-// v0.39 T14 — shared artifact abstraction.-//-// Codex finding #6 from plan-eng-review: the v0.37 skillpack pipeline-// has skillpack-specific filenames + state + registry + trust + copy-// semantics in 10+ files. Branching each in 10 places to also handle-// `.gbrain-schema` is a fan-out hazard. The structural fix is one-// artifact abstraction; skillpack and schemapack become two callers-// of the same helper.-//-// v0.39.0.0 ships the abstraction + the schemapack consumer. The-// skillpack consumer migration is the codex-flagged TODO that the-// v0.40 wave completes (skillpack code is load-bearing for many users;-// migrating it requires its own care + test coverage).--import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync } from 'node:fs';-import { dirname, join } from 'node:path';-import type { SchemaPackManifest } from '../schema-pack/manifest-v1.ts';--/**- * Discriminator for artifact type. Drives which manifest validator runs- * + which install target directory + which trust gate fires.- */-export type ArtifactKind = 'skillpack' | 'schemapack';--export interface ArtifactDescriptor {- kind: ArtifactKind;- name: string;- version: string;- /** Absolute path to the artifact root (file or directory). */- path: string;- /** Parsed + validated manifest object. Shape varies by kind. */- manifest: unknown;-}--/**- * Detect artifact kind from an on-disk source. Recognizes:- * - .gbrain-schema or .gbrain-skillpack file extension (tarball)- * - directory with pack.yaml + api_version 'gbrain-schema-pack-v1' (schemapack)- * - directory with skillpack.json + api_version 'gbrain-skillpack-v1' (skillpack)- *- * Returns null on unrecognized input.- */-export function detectArtifactKind(path: string): ArtifactKind | null {- if (path.endsWith('.gbrain-schema')) return 'schemapack';- if (path.endsWith('.gbrain-skillpack')) return 'skillpack';- if (!existsSync(path)) return null;- try {- // Directory: look for the canonical manifest file.- if (existsSync(join(path, 'pack.yaml'))) {- const raw = readFileSync(join(path, 'pack.yaml'), 'utf-8');- if (raw.includes('gbrain-schema-pack-v1')) return 'schemapack';- }- if (existsSync(join(path, 'pack.json'))) {- const raw = readFileSync(join(path, 'pack.json'), 'utf-8');- if (raw.includes('gbrain-schema-pack-v1')) return 'schemapack';- }- if (existsSync(join(path, 'skillpack.json'))) {- return 'skillpack';- }- } catch {- return null;- }- return null;-}--/**- * Install-target directory by kind. Both kinds land under ~/.gbrain/- * but at distinct subdirectories so doctor + uninstall can scope- * cleanly.- */-export function targetDirForKind(kind: ArtifactKind, gbrainHome: string): string {- return kind === 'schemapack'- ? join(gbrainHome, 'schema-packs')- : join(gbrainHome, 'skillpacks');-}--/**- * Validate a manifest by kind. For schemapack: shape check against- * SchemaPackManifest v1. For skillpack: shape check against- * gbrain-skillpack-v1. Throws on validation failure with a- * descriptive message.- */-export function validateManifestByKind(kind: ArtifactKind, manifest: unknown): void {- if (kind === 'schemapack') {- // Delegate to the schema-pack manifest validator. Throws on failure.- if (typeof manifest !== 'object' || manifest === null) {- throw new Error('schemapack manifest must be an object');- }- const m = manifest as { api_version?: unknown };- if (m.api_version !== 'gbrain-schema-pack-v1') {- throw new Error(`schemapack manifest api_version must be "gbrain-schema-pack-v1"; got ${JSON.stringify(m.api_version)}`);- }- return;- }- if (kind === 'skillpack') {- if (typeof manifest !== 'object' || manifest === null) {- throw new Error('skillpack manifest must be an object');- }- const m = manifest as { api_version?: unknown };- if (m.api_version !== 'gbrain-skillpack-v1') {- throw new Error(`skillpack manifest api_version must be "gbrain-skillpack-v1"; got ${JSON.stringify(m.api_version)}`);- }- return;- }- // Exhaustive switch — TS catches if a new kind is added without updating.- const _exhaustive: never = kind;- throw new Error(`Unknown artifact kind: ${_exhaustive}`);-}--/**- * Install an artifact from disk into its kind-appropriate target directory.- * Idempotent: re-installing the same version is a no-op. Different version- * replaces atomically (mkdir tmp → write → rename).- *- * This is the ONE install path. Skillpack + schemapack both go through here.- * Pre-fix (codex finding #6), the install path lived in skillpack-specific- * code; calling it for schemapack would have meant branching every line.- */-export function installArtifact(- desc: ArtifactDescriptor,- gbrainHome: string,- copyContent: (sourcePath: string, targetDir: string) => void,-): { installed_at: string; target: string; kind: ArtifactKind } {- validateManifestByKind(desc.kind, desc.manifest);- const targetParent = targetDirForKind(desc.kind, gbrainHome);- mkdirSync(targetParent, { recursive: true });- const target = join(targetParent, desc.name);- copyContent(desc.path, target);- return {- installed_at: new Date().toISOString(),- target,- kind: desc.kind,- };-}--/**- * List installed artifacts of a given kind. Pure filesystem walk; no- * SQL. Returns just the names — callers can hydrate manifest detail- * via the kind-specific loaders.- */-export function listInstalledArtifacts(kind: ArtifactKind, gbrainHome: string): string[] {- const dir = targetDirForKind(kind, gbrainHome);- if (!existsSync(dir)) return [];- try {- return readdirSync(dir).sort();- } catch {- return [];- }-}diff --git a/src/core/backfill-registry.ts b/src/core/backfill-registry.tsindex 6aa7abe3d2..fdb633da5f 100644--- a/src/core/backfill-registry.ts+++ b/src/core/backfill-registry.ts@@ -39,11 +39,6 @@ export function listBackfills(): RegisteredBackfill[] {return Array.from(_registry.values());}-export function clearRegistryForTests(): void {- _registry.clear();- registerCoreBackfills();-}-// ---------------------------------------------------------------------------// Core registrations// ---------------------------------------------------------------------------diff --git a/src/core/calibration/cross-brain.ts b/src/core/calibration/cross-brain.tsdeleted file mode 100644index 2d38fac282..0000000000--- a/src/core/calibration/cross-brain.ts+++ /dev/null@@ -1,169 +0,0 @@-/**- * v0.36.1.0 (T14 / E8 + D18) — cross-brain calibration query semantics.- *- * Team-brain sharing: when a holder's calibration profile is not present in- * the local brain, optionally fall back to mounted brains that have- * `published=true` profiles for that holder. The four cross-brain leak- * test cases from D18 are pinned in test/cross-brain-calibration.test.ts.- *- * D18 semantics (committed):- *- * 1. LOCAL-FIRST ORDERING. Query the local brain first. If a profile exists,- * return it. Do NOT also query mounts (avoids stale-mount-overrides-fresh-- * local).- *- * 2. MOUNT FALLBACK. Only when local has no profile AND the request context- * allows mount-read (CLI yes; MCP read-scope yes; SUBAGENT no), query- * mounts in priority order, filtered by published=true.- *- * 3. CROSS-BRAIN ATTRIBUTION. Every returned profile carries `source_brain_id`- * so consumers see which brain answered. Consumers MUST surface it in- * user-visible output.- *- * 4. SUBAGENT PROHIBITION. ctx.remote=true && !trustedWorkspace cannot read- * mounted profiles. Closes the OAuth-token-to-cross-brain-leak surface.- *- * E2E tests (D18 spec):- * - mounted brain has published=false profile → query returns null- * - published=true but consumer lacks mount-read scope → null- * - subagent context attempts mount fallback → returns local-only result- * - attribution test: profile returns with source_brain_id; consumer- * surfaces it in output- *- * v0.36.1.0 ship state scope:- * - The CALIBRATION query path supports cross-brain. The actual MOUNT- * infrastructure (gbrain mounts add — v0.19+) is reused as-is. This- * module adds the cross-brain READ filter on top of mount discovery.- * - Mount engine access is via injected `mountResolver` callback so tests- * drive the cross-brain shape without needing a real multi-brain setup.- */--import type { CalibrationProfileRow } from '../../commands/calibration.ts';-import type { BrainEngine } from '../engine.ts';-import { getLatestProfile } from '../../commands/calibration.ts';--/**- * Cross-brain query options. Tests drive these directly; production paths- * compose them from OperationContext.- */-export interface CrossBrainQueryOpts {- /** The holder to look up. */- holder: string;- /** Local brain's identifier (e.g. 'garry-personal'). */- localBrainId: string;- /** Local-side source scoping. */- sourceId?: string;- sourceIds?: string[];- /**- * When false, mount fallback is DISABLED (subagent / untrusted-context- * gate per D18 rule 4). The query short-circuits to local-only.- */- canReadMounts: boolean;- /**- * Mount resolver — production wires this to the mounts subsystem- * (gbrain mounts add). Tests inject a stub returning an ordered list- * of mounted-brain engines. Each mount must declare its brain id so- * the response can carry source_brain_id attribution.- */- mountResolver?: () => Promise<Array<{ brainId: string; engine: BrainEngine }>>;-}--/** Result type extends the canonical row with attribution. */-export interface CrossBrainProfileResult extends CalibrationProfileRow {- /** Brain id of the brain that answered. Local brain id when local hit; mount id when fallback. */- source_brain_id: string;- /** True when the profile came from a mount (not the local brain). */- from_mount: boolean;-}--/**- * Resolve the active calibration profile for a holder across local +- * mounted brains per the D18 4-rule contract. Returns null when no- * matching profile exists in any reachable brain.- */-export async function queryAcrossBrains(- localEngine: BrainEngine,- opts: CrossBrainQueryOpts,-): Promise<CrossBrainProfileResult | null> {- // Rule 1: LOCAL-FIRST.- const localProfile = await getLatestProfile(localEngine, {- holder: opts.holder,- ...(opts.sourceId !== undefined ? { sourceId: opts.sourceId } : {}),- ...(opts.sourceIds !== undefined ? { sourceIds: opts.sourceIds } : {}),- });- if (localProfile) {- return {- ...localProfile,- source_brain_id: opts.localBrainId,- from_mount: false,- };- }-- // Rule 4: SUBAGENT PROHIBITION. canReadMounts=false short-circuits to null.- if (!opts.canReadMounts) {- return null;- }-- // Rule 2: MOUNT FALLBACK. Walk mounts in priority order; first- // published=true match wins.- if (!opts.mountResolver) {- // No mounts configured → null is the right answer.- return null;- }- const mounts = await opts.mountResolver();- for (const mount of mounts) {- const mountProfile = await getLatestProfile(mount.engine, { holder: opts.holder });- if (!mountProfile) continue;- // Mount-side filter: only published=true profiles are visible to- // consumers. Authoring brain controls publication per D15 asymmetric- // opt-in.- if (!mountProfile.published) continue;- return {- ...mountProfile,- source_brain_id: mount.brainId,- from_mount: true,- };- }- return null;-}--/**- * Determine whether the current OperationContext is allowed to read- * mounted brains. Per D18:- *- * CLI → yes (trusted local operator)- * MCP read-scope → yes- * MCP subagent context (remote=true && !trustedWorkspace) → no- *- * The function returns FALSE when the context is a subagent loop because- * that's where the OAuth-token-to-cross-brain-leak surface lives. Anything- * else gets true.- */-export function canReadMountsForCtx(ctx: {- remote: boolean;- viaSubagent?: boolean;- allowedSlugPrefixes?: string[];-}): boolean {- // Local CLI: always yes.- if (ctx.remote === false) return true;- // Subagent tool-loop: never yes. (Trusted-workspace synthesize/patterns- // phases pass `allowedSlugPrefixes` set; those are still subagents per- // viaSubagent semantics, but they're trusted. Match that gate.)- if (ctx.viaSubagent === true) {- return Array.isArray(ctx.allowedSlugPrefixes) && ctx.allowedSlugPrefixes.length > 0;- }- // MCP non-subagent (regular OAuth-scoped read): yes.- return true;-}--/**- * Render the attribution suffix that consumers (E1 think rewrite, E3- * contradictions output, E7 nudge text, E6 dashboard) MUST surface so- * the user sees which brain answered.- */-export function attributionSuffix(result: CrossBrainProfileResult): string {- if (!result.from_mount) {- return ''; // local — no suffix needed (assume local is default)- }- return ` (from mounted brain: ${result.source_brain_id})`;-}diff --git a/src/core/calibration/nudge.ts b/src/core/calibration/nudge.tsdeleted file mode 100644index ae56a3f450..0000000000--- a/src/core/calibration/nudge.ts+++ /dev/null@@ -1,209 +0,0 @@-/**- * v0.36.1.0 (T13 / E7) — real-time pattern surfacing on take commit.- *- * The nudge surface that taps the user on the shoulder when a newly-committed- * take matches an active bias pattern. Conversational voice (D24 mode='nudge'),- * 14-day cooldown per (take_id, nudge_pattern) via take_nudge_log so the same- * pattern doesn't re-fire on every cycle.- *- * Threshold rules (D16 / F3):- * - conviction-weight > 0.7 → eligible- * - take's holder is the calibration profile's holder- * - take's domain hint matches an active bias tag (same heuristic as the- * calibration-aware contradictions join — see eval-contradictions/calibration-join.ts)- *- * Feedback-loop prevention (D16 F3):- * - take_nudge_log records every fire keyed on (take_id|proposal_id,- * nudge_pattern). The cooldown probe checks "was this same pattern fired- * on this same take in the last NUDGE_COOLDOWN_DAYS?" If yes, silently skip.- * - No CLI reset shim exists (#3697: an earlier draft named- * `gbrain takes nudge --reset`, which never shipped). Deleting the- * take's take_nudge_log rows clears the cooldown so the next sync- * re-fires fresh nudges.- *- * Output channel:- * v0.36.1.0 ship state: STDERR only. Multi-channel routing (webhook,- * admin SPA toast) is a v0.37+ follow-up — the schema's `channel` column- * already supports it.- */--import type { BrainEngine, Take } from '../engine.ts';-import type { CalibrationProfileRow } from '../../commands/calibration.ts';-import { nudgeTemplate } from './templates.ts';--export const NUDGE_COOLDOWN_DAYS = 14;-export const NUDGE_CONVICTION_THRESHOLD = 0.7;--export interface NudgeDecision {- /** Should the nudge fire? */- shouldFire: boolean;- /** Why not — surfaced for debugging + audit. */- reason?:- | 'no_profile'- | 'below_conviction_threshold'- | 'no_matching_bias_tag'- | 'cooldown_active'- | 'wrong_holder';- /** The bias tag matched (when shouldFire=true). */- matchedTag?: string;- /** The conversational nudge text (when shouldFire=true). */- text?: string;-}--/**- * Map a take's metadata to a domain hint that joins against bias tags.- * Same heuristic as eval-contradictions/calibration-join.ts to keep the- * surfaces consistent.- */-export function takeDomainHint(take: Take): string {- const slug = take.page_slug.toLowerCase();- if (slug.includes('/companies/') || slug.startsWith('companies/')) return 'hiring';- if (slug.includes('/people/') || slug.startsWith('people/')) return 'founder-behavior';- if (slug.includes('/deals/') || slug.startsWith('deals/')) return 'market-timing';- if (slug.includes('macro')) return 'macro';- if (slug.includes('geography')) return 'geography';- if (slug.includes('tactics')) return 'tactics';- if (slug.includes('/ai/') || slug.includes('-ai-')) return 'ai';- return '';-}--/** Pure: decide whether a take should fire a nudge given the active profile. */-export function evaluateNudgeRule(- take: Take,- profile: CalibrationProfileRow | null,-): { matched: boolean; reason?: NudgeDecision['reason']; matchedTag?: string } {- if (!profile) return { matched: false, reason: 'no_profile' };- if (take.holder !== profile.holder) return { matched: false, reason: 'wrong_holder' };- if (take.weight <= NUDGE_CONVICTION_THRESHOLD) {- return { matched: false, reason: 'below_conviction_threshold' };- }- const hint = takeDomainHint(take);- if (!hint) return { matched: false, reason: 'no_matching_bias_tag' };- for (const tag of profile.active_bias_tags) {- if (tag.toLowerCase().includes(hint)) {- return { matched: true, matchedTag: tag };- }- }- return { matched: false, reason: 'no_matching_bias_tag' };-}--/**- * Check the take_nudge_log for an active cooldown on this (take_id,- * pattern) within the last NUDGE_COOLDOWN_DAYS days.- */-export async function checkCooldown(- engine: BrainEngine,- takeId: number,- nudgePattern: string,-): Promise<boolean> {- const cutoffDate = new Date(Date.now() - NUDGE_COOLDOWN_DAYS * 24 * 60 * 60 * 1000);- const rows = await engine.executeRaw<{ id: number }>(- `SELECT id FROM take_nudge_log- WHERE take_id = $1 AND nudge_pattern = $2 AND fired_at >= $3- LIMIT 1`,- [takeId, nudgePattern, cutoffDate.toISOString()],- );- return rows.length > 0;-}--/**- * Write a take_nudge_log row with channel='stderr'.- */-export async function recordNudgeFire(- engine: BrainEngine,- opts: { sourceId: string; takeId: number; nudgePattern: string; channel?: string },-): Promise<void> {- await engine.executeRaw(- `INSERT INTO take_nudge_log (source_id, take_id, nudge_pattern, channel)- VALUES ($1, $2, $3, $4)`,- [opts.sourceId, opts.takeId, opts.nudgePattern, opts.channel ?? 'stderr'],- );-}--/**- * Build the conversational nudge text via the templates module. v0.36.1.0- * ship state: uses the template directly (no LLM-generation path). The- * voice gate (T6) wraps this surface at v0.37+ when we have enough- * production examples to tune the LLM prompt.- */-export function buildNudgeText(opts: {- matchedTag: string;- conviction: number;- /** Optional: count of recent misses in same conviction bucket. */- nRecentMisses?: number;- nRecentTotal?: number;-}): string {- // Domain extracted from tag — kebab-case last segment after axis prefix.- const domain = opts.matchedTag.split('-').slice(-1)[0] ?? 'this area';- return nudgeTemplate({- domain,- conviction: opts.conviction,- nRecentMisses: opts.nRecentMisses ?? 0,- nRecentTotal: opts.nRecentTotal ?? 0,- hushPattern: opts.matchedTag,- });-}--export interface EvaluateAndFireOpts {- engine: BrainEngine;- take: Take;- profile: CalibrationProfileRow | null;- sourceId: string;- /** Override the stderr stream (tests). Production: process.stderr. */- stderr?: { write: (s: string) => void };-}--/**- * Main entry point: evaluate, check cooldown, fire if appropriate, log.- * Returns the NudgeDecision so callers can audit / surface in UI.- *- * Always succeeds (no-fire is success). Errors surface in the result's- * reason field, not via throw.- */-export async function evaluateAndFireNudge(opts: EvaluateAndFireOpts): Promise<NudgeDecision> {- const rule = evaluateNudgeRule(opts.take, opts.profile);- if (!rule.matched) {- return {- shouldFire: false,- ...(rule.reason !== undefined ? { reason: rule.reason } : {}),- };- }- // Cooldown probe.- const onCooldown = await checkCooldown(opts.engine, opts.take.id, rule.matchedTag!);- if (onCooldown) {- return {- shouldFire: false,- reason: 'cooldown_active',- matchedTag: rule.matchedTag!,- };- }- // Build + fire.- const text = buildNudgeText({- matchedTag: rule.matchedTag!,- conviction: opts.take.weight,- });- const stream = opts.stderr ?? process.stderr;- stream.write(text + '\n');- // Log the fire (cooldown starts now).- await recordNudgeFire(opts.engine, {- sourceId: opts.sourceId,- takeId: opts.take.id,- nudgePattern: rule.matchedTag!,- });- return { shouldFire: true, matchedTag: rule.matchedTag!, text };-}--/**- * Reset cooldown for a take. Deletes the take's nudge_log rows so the- * next sync re-evaluates fresh.- */-export async function resetNudgeCooldown(- engine: BrainEngine,- takeId: number,-): Promise<{ deleted: number }> {- const rows = await engine.executeRaw<{ id: number }>(- `DELETE FROM take_nudge_log WHERE take_id = $1 RETURNING id`,- [takeId],- );- return { deleted: rows.length };-}diff --git a/src/core/calibration/recall-footer.ts b/src/core/calibration/recall-footer.tsdeleted file mode 100644index ddc5f618c6..0000000000--- a/src/core/calibration/recall-footer.ts+++ /dev/null@@ -1,81 +0,0 @@-/**- * v0.36.1.0 (T16) — calibration footer for `gbrain recall` morning pulse.- *- * Pure formatter. Given an active calibration profile, returns the- * conversational block to prepend or append to the recall output:- *- * Calibration this quarter:- * Brier 0.18 (was 0.22 90d ago — improving).- * Right on early-stage tactics, late on macro by 18 months.- * Over-confident on team execution; under-calibrated on regulatory risk.- *- * Threads you opened and never came back to:- * · AI search platform differentiation (17 months silent)- * · International expansion playbook (12 months silent)- *- * Cold-brain branch: returns empty string when no profile or- * insufficient resolved takes. The caller decides whether to prepend- * the block; cold-brain absence is the cleanest non-event.- *- * v0.36.1.0 ship state: opt-in via `gbrain recall --show-calibration`- * to keep R3 regression posture (existing recall text shape unchanged- * for users who don't pass the flag). v0.37 defaults to on.- *- * Trend computation: v0.36.1.0 has only ONE profile snapshot (the most- * recent generation). Trend ("was X 90d ago — improving/declining")- * arrives when we accumulate generated_at history.- */--import type { CalibrationProfileRow } from '../../commands/calibration.ts';--export interface AbandonedThreadSummary {- claim: string;- monthsSilent: number;-}--export interface RecallFooterOpts {- profile: CalibrationProfileRow | null;- abandonedThreads?: AbandonedThreadSummary[];- /** Width hint for column alignment on threads. Default 50. */- threadColumnWidth?: number;-}--export function buildRecallCalibrationFooter(opts: RecallFooterOpts): string {- const { profile, abandonedThreads } = opts;- if (!profile) return '';- if (profile.total_resolved < 5) return '';-- const lines: string[] = [];- lines.push('Calibration this quarter:');-- // Brier line. v0.36.1.0 has only the current snapshot — no 90d comparison.- if (profile.brier !== null) {- lines.push(` Brier ${profile.brier.toFixed(2)} ${trendNote(profile.brier)}`);- }- // Up to 4 pattern statements. Indent for readability.- for (const p of profile.pattern_statements.slice(0, 4)) {- lines.push(` ${p}`);- }-- if (abandonedThreads && abandonedThreads.length > 0) {- lines.push('');- lines.push('Threads you opened and never came back to:');- const colWidth = opts.threadColumnWidth ?? 50;- for (const t of abandonedThreads.slice(0, 5)) {- const claim = t.claim.length > colWidth ? t.claim.slice(0, colWidth - 1) + '…' : t.claim;- const padded = claim.padEnd(colWidth, ' ');- lines.push(` · ${padded}(${t.monthsSilent} months silent)`);- }- }-- return lines.join('\n');-}--function trendNote(brier: number): string {- // Map Brier to a conversational anchor. No history yet so we describe- // the absolute value rather than trend.- if (brier <= 0.1) return '(strong calibration).';- if (brier <= 0.2) return '(solid).';- if (brier <= 0.25) return '(near baseline).';- return '(worse than always-50% baseline — review your high-conviction calls).';-}diff --git a/src/core/calibration/take-forecast.ts b/src/core/calibration/take-forecast.tsdeleted file mode 100644index 38f3adeeea..0000000000--- a/src/core/calibration/take-forecast.ts+++ /dev/null@@ -1,170 +0,0 @@-/**- * v0.36.1.0 (T10 / E5) — Brier-trend forecasting on new takes.- *- * Pure math over existing `TakesScorecard` data. Zero new LLM cost,- * zero new schema. Surface: an inline blurb the user sees at write time- * (gbrain takes show / propose --review) reminding them of their- * historical track record at this conviction + domain.- *- * v0.36.1.0 ship state:- * Looks up scorecard by (holder, domainPrefix). The bucket dimension is- * the domain — not the conviction-weight bucket (full conviction-bucket- * math would need a new engine method). Returns "insufficient data"- * when n < 5 (avoid noise on cold brains).- *- * v0.37+ enhancement:- * Add conviction-bucket dimension via engine.batchGetTakeBucketStats()- * (per F11). For now the forecast is per-domain only.- *- * Output goes through the voice gate's forecast_blurb template when- * surfaced to the user (E5 inline rendering). This module is the pure- * data layer; templates.ts has the user-facing string.- */--import type { BrainEngine, TakesScorecard } from '../engine.ts';--export interface TakeForecastInput {- /** Take's holder, e.g. 'garry' or 'people/charlie-example'. */- holder: string;- /**- * Optional domain prefix, e.g. 'macro' or 'geography'. When omitted, the- * forecast uses the holder's overall scorecard.- */- domain?: string;- /** The conviction-weight of the new take in [0,1]. Carried into the response. */- conviction: number;-}--export interface TakeForecast {- /**- * Predicted Brier score for this conviction in this domain. Null when- * the bucket has insufficient data (n < MIN_BUCKET_N).- */- predicted_brier: number | null;- /** Sample size of the bucket. */- bucket_n: number;- /** Holder's overall Brier for comparison ("worse than your average"). */- overall_brier: number | null;- /** The domain the forecast bucket scoped to ('overall' when no domain). */- bucket_domain: string;- /** True when the bucket lacks enough data for a stable forecast. */- insufficient_data: boolean;-}--/** Minimum bucket size before we report a forecast. Below this → null. */-export const MIN_BUCKET_N = 5;--/**- * Map a free-form domain hint (e.g. 'macro tech', 'geography', or- * 'startup-tactics') to a `domainPrefix` the scorecard query understands.- *- * The TakesScorecard's `domainPrefix` is a slug-prefix filter (e.g.- * 'companies/'). For v0.36.1.0, we pass domain hints through as-is when- * they look like slug prefixes; otherwise fall back to undefined (overall- * scorecard). v0.37+ takes get a structured domain enum and this mapping- * tightens.- */-export function resolveDomainPrefix(domain: string | undefined): string | undefined {- if (!domain) return undefined;- const lower = domain.toLowerCase().trim();- if (lower.length === 0) return undefined;- // Slug-prefix-looking values: keep as-is.- if (lower.endsWith('/')) return lower;- if (lower.startsWith('wiki/') || lower.startsWith('companies/') || lower.startsWith('people/')) {- return lower;- }- // Free-form word (e.g. 'macro tech', 'geography') — no slug prefix path,- // so the bucket falls back to "overall" for now. v0.37+ Hindsight-style- // structured domain on takes (CDX-11 mitigation TODO) tightens this.- return undefined;-}--/**- * Pure math: given the holder's overall scorecard AND optional bucketed- * scorecard, compute the forecast struct.- *- * Caller is responsible for fetching the scorecards via engine.getScorecard.- * Pure function so tests can drive it without an engine.- */-export function computeForecast(input: {- conviction: number;- domain?: string;- overallScorecard: TakesScorecard;- bucketScorecard?: TakesScorecard;-}): TakeForecast {- const overall_brier = input.overallScorecard.brier;- const bucket = input.bucketScorecard ?? input.overallScorecard;- const bucket_domain = input.domain ?? 'overall';- const bucket_n = bucket.resolved;- const insufficient_data = bucket_n < MIN_BUCKET_N;- const predicted_brier = insufficient_data ? null : bucket.brier;- return { predicted_brier, bucket_n, overall_brier, bucket_domain, insufficient_data };-}--/**- * Wrapper that fetches the scorecards from the engine + computes the- * forecast. Convenience for callers that don't need to share scorecard- * data across multiple forecasts.- */-export async function forecastForTake(- engine: BrainEngine,- input: TakeForecastInput,-): Promise<TakeForecast> {- const overallScorecard = await engine.getScorecard({ holder: input.holder }, undefined);- const domainPrefix = resolveDomainPrefix(input.domain);- let bucketScorecard: TakesScorecard | undefined;- if (domainPrefix) {- bucketScorecard = await engine.getScorecard(- { holder: input.holder, domainPrefix },- undefined,- );- }- return computeForecast({- conviction: input.conviction,- ...(input.domain !== undefined ? { domain: input.domain } : {}),- overallScorecard,- ...(bucketScorecard !== undefined ? { bucketScorecard } : {}),- });-}--/**- * Batched forecast over a list of takes (F11 perf finding). Returns one- * TakeForecast per input. v0.36.1.0 ship state: per-take engine round-trip.- * v0.37+ adds engine.batchGetTakeBucketStats for a single roundtrip across- * all (holder, domain) pairs.- */-export async function batchForecast(- engine: BrainEngine,- inputs: TakeForecastInput[],-): Promise<TakeForecast[]> {- // Memoize per (holder, domainPrefix) so repeated queries collapse.- const cache = new Map<string, TakesScorecard>();- const getOrFetch = async (holder: string, domainPrefix?: string): Promise<TakesScorecard> => {- const key = `${holder}|${domainPrefix ?? ''}`;- const hit = cache.get(key);- if (hit) return hit;- const sc = await engine.getScorecard(- { holder, ...(domainPrefix !== undefined ? { domainPrefix } : {}) },- undefined,- );- cache.set(key, sc);- return sc;- };- const results: TakeForecast[] = [];- for (const input of inputs) {- const overallScorecard = await getOrFetch(input.holder);- const domainPrefix = resolveDomainPrefix(input.domain);- const bucketScorecard = domainPrefix- ? await getOrFetch(input.holder, domainPrefix)- : undefined;- results.push(- computeForecast({- conviction: input.conviction,- ...(input.domain !== undefined ? { domain: input.domain } : {}),- overallScorecard,- ...(bucketScorecard !== undefined ? { bucketScorecard } : {}),- }),- );- }- return results;-}diff --git a/src/core/config.ts b/src/core/config.tsindex aa919f57ba..e839d4c129 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1412,8 +1412,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// personal brains and never auto-enables anything.'brain.audience',// Conversation parser LLM fallback. Deliberately register the exact key,- // not a conversation_parser.* prefix: fallback is the only live opt-in- // consumer, while the polish scaffold remains unwired.+ // not a conversation_parser.* prefix: fallback is the only opt-in consumer.'conversation_parser.llm_fallback_enabled',// Dream cycle config'dream.synthesize.session_corpus_dir',diff --git a/src/core/conversation-parser/llm-base.ts b/src/core/conversation-parser/llm-base.tsindex 50b4046c6e..1ba6a4a7f0 100644--- a/src/core/conversation-parser/llm-base.ts+++ b/src/core/conversation-parser/llm-base.ts@@ -307,6 +307,6 @@ function splitCacheKey(key: string): [string?, string?, string?] {}// Tolerant LLM-output JSON decoder. Re-exported from the leaf util so existing-// importers (llm-fallback, llm-polish) keep their import path while the gateway+// importers (llm-fallback) keep their import path while the gateway// can reuse it without a dependency cycle.export { parseLlmJson } from '../llm-json.ts';diff --git a/src/core/conversation-parser/llm-polish.ts b/src/core/conversation-parser/llm-polish.tsdeleted file mode 100644index a85e650110..0000000000--- a/src/core/conversation-parser/llm-polish.ts+++ /dev/null@@ -1,231 +0,0 @@-/**- * v0.41.16.0 — LLM polish for regex-matched conversation output.- *- * Runs on regex-matched pages when:- * - `conversation_parser.llm_polish_enabled` is true (D15: opt-IN- * by default for privacy).- * - Active BudgetTracker has > $0.10 headroom (the polish headroom- * guard — never starve the actual facts extraction by burning- * budget on cosmetic polish at the end of a cycle).- *- * Polish takes BOTH the regex-parsed `MatchedMessage[]` AND the- * original body, asks Haiku to surface a `MessagePolish` describing- * which messages to merge / drop / annotate. Returns the refined- * `MatchedMessage[]` (or the input unchanged on fail-open).- *- * Cache: same shape as fallback; keyed on- * `(content_sha256, model_id, 'polish')`. The orchestrator's- * winning pattern_id is folded into the content hash via prepending- * it to the content body before hashing, so polish-of-Telegram and- * polish-of-Discord on the same body produce different cache rows.- */--import { runLlmCall, parseLlmJson, type ChatTransport } from './llm-base.ts';-import type { BrainEngine } from '../engine.ts';-import { getCurrentBudgetTracker } from '../ai/gateway.ts';-import type { MatchedMessage } from './types.ts';--const POLISH_HEADROOM_USD = 0.1;--const POLISH_SYSTEM_PROMPT = `You polish a list of chat messages parsed from a chat-log body by a regex.--Input: the original body text plus the regex's parsed JSON.--Output a JSON object describing the polish operations:- {- "merge_indices": [[i, j, ...], ...],- // Groups of message indices to merge into one (a continuation- // line was split incorrectly). The first index is the keeper;- // others are merged INTO it. Empty array if no merges needed.-- "drop_indices": [i, j, ...],- // Indices to drop (system messages, reactions, attachments,- // notification footers that slipped through the regex).-- "edits": [{"index": i, "field": "speaker" | "text", "value": "..."}, ...],- // Per-message field corrections (strip trailing "(edited)",- // remove emoji clutter, fix obvious speaker-name typos).- }--If the parse looks already-clean, return {"merge_indices": [], "drop_indices": [], "edits": []}.--Output ONLY the JSON object. No prose, no fences.`;--interface PolishOps {- merge_indices: number[][];- drop_indices: number[];- edits: Array<{ index: number; field: 'speaker' | 'text'; value: string }>;-}--export interface RunLlmPolishOpts {- modelStr: string;- /** The full page body the regex saw. */- body: string;- /** Regex-parsed messages (the polish target). */- messages: MatchedMessage[];- /** Pattern id the regex matched on (folded into cache key). */- patternId: string;- /** Caller's abort signal. */- signal?: AbortSignal;- /** Engine for DB cache (optional). */- engine?: BrainEngine;- /** Test seam. */- chatTransport?: ChatTransport;-}--/**- * Returns the polished `MatchedMessage[]` OR the input `messages`- * unchanged on any failure (fail-open).- *- * Headroom guard: when an active BudgetTracker is within- * POLISH_HEADROOM_USD of its cap, polish is skipped and the input- * is returned unchanged. This prevents polish from starving the- * actual facts extraction at the end of a cycle.- *- * Returns the polish delta as the second tuple element so callers- * (orchestrator → ParseResult) can surface it for debug.- */-export async function runLlmPolish(- opts: RunLlmPolishOpts,-): Promise<{- messages: MatchedMessage[];- delta: { merged: number; dropped: number; edits: number };- skipped?: 'headroom' | 'provider' | 'parse_failed';-}> {- // Headroom guard.- const tracker = getCurrentBudgetTracker();- if (tracker) {- const snapshot = tracker.snapshot();- if (- snapshot.maxCostUsd !== undefined &&- snapshot.maxCostUsd - snapshot.cumulativeCostUsd < POLISH_HEADROOM_USD- ) {- return {- messages: opts.messages,- delta: { merged: 0, dropped: 0, edits: 0 },- skipped: 'headroom',- };- }- }-- // Fold pattern_id into cache content so polish-of-Telegram and- // polish-of-Discord on the same body produce different cache rows.- const cacheContent = `${opts.patternId}\n---\n${opts.body}`;-- const promptContent = `BODY:\n${opts.body}\n\nPARSED:\n${JSON.stringify(opts.messages, null, 2)}`;-- const ops = await runLlmCall<PolishOps>({- shape: 'polish',- modelStr: opts.modelStr,- content: cacheContent,- system: POLISH_SYSTEM_PROMPT,- signal: opts.signal,- engine: opts.engine,- chatTransport: opts.chatTransport,- parse: (text) => {- const parsed = parseLlmJson<PolishOps>(text, { array: false });- if (parsed === null) return null;- // Shape validation.- if (- !Array.isArray(parsed.merge_indices) ||- !Array.isArray(parsed.drop_indices) ||- !Array.isArray(parsed.edits)- ) {- return null;- }- return parsed;- },- });-- // Pass the prompt content as the actual user message via a custom- // call shape. We can't easily do that with runLlmCall's current- // shape (which uses content as both prompt + cache key). For v1- // this is fine because the polish prompt's whole signal lives in- // the body text — see POLISH_SYSTEM_PROMPT.- //- // Reality check: runLlmCall sends `content` as the user message,- // and we passed cacheContent which IS just patternId + body, NOT- // the full prompt. The polish call gets less context than the- // prompt template intends. v0.41.14+ TODO: extend runLlmCall to- // separate cache_key_content from prompt_content. For now,- // polish's effectiveness is gated by cacheContent (sufficient- // because patternId + body IS the full signal — the JSON dump in- // promptContent is informational only).- void promptContent;-- if (ops === null) {- return {- messages: opts.messages,- delta: { merged: 0, dropped: 0, edits: 0 },- skipped: 'provider',- };- }-- // Apply polish ops.- const merged = applyPolish(opts.messages, ops);- return {- messages: merged.messages,- delta: merged.delta,- };-}--/**- * Apply a `PolishOps` to a `MatchedMessage[]`. Pure function;- * exported for unit tests.- */-export function applyPolish(- messages: MatchedMessage[],- ops: PolishOps,-): {- messages: MatchedMessage[];- delta: { merged: number; dropped: number; edits: number };-} {- const dropSet = new Set(ops.drop_indices.filter((i) => Number.isInteger(i) && i >= 0));- const out: MatchedMessage[] = [];- const idxMap: Map<number, number> = new Map();-- for (let i = 0; i < messages.length; i++) {- if (dropSet.has(i)) continue;- // Skip if this index is being merged INTO a prior group (not the keeper).- let mergedInto = -1;- for (const group of ops.merge_indices) {- if (group.length < 2) continue;- if (group.slice(1).includes(i)) {- mergedInto = group[0];- break;- }- }- if (mergedInto >= 0) {- // Append this message's text to the keeper if the keeper is- // already in `out`.- const keeperOutIdx = idxMap.get(mergedInto);- if (keeperOutIdx !== undefined) {- out[keeperOutIdx].text = `${out[keeperOutIdx].text}\n${messages[i].text}`;- }- continue;- }- idxMap.set(i, out.length);- out.push({ ...messages[i] });- }-- // Apply edits.- for (const edit of ops.edits) {- if (!Number.isInteger(edit.index) || edit.index < 0) continue;- const outIdx = idxMap.get(edit.index);- if (outIdx === undefined) continue;- if (edit.field === 'speaker' && typeof edit.value === 'string') {- out[outIdx].speaker = edit.value;- } else if (edit.field === 'text' && typeof edit.value === 'string') {- out[outIdx].text = edit.value;- }- }-- return {- messages: out,- delta: {- merged: ops.merge_indices.filter((g) => g.length >= 2).length,- dropped: dropSet.size,- edits: ops.edits.length,- },- };-}diff --git a/src/core/conversation-parser/parse.ts b/src/core/conversation-parser/parse.tsindex 6a323b55dc..9973eceb9f 100644--- a/src/core/conversation-parser/parse.ts+++ b/src/core/conversation-parser/parse.ts@@ -20,9 +20,8 @@* adapter in `extract-conversation-facts.ts` (T5 retrofit).** Pure-function inner core: no I/O, no LLM calls except via the- * polish/fallback wrappers in `llm-polish.ts` + `llm-fallback.ts`- * (T4). Those wrappers are passed in via opts so this file stays- * test-isolatable.+ * fallback wrapper in `llm-fallback.ts` (T4). That wrapper is passed+ * in via opts so this file stays test-isolatable.*/import {diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 731f0fbfd6..b697f1af6c 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -38,7 +38,7 @@ import { postprocessManagedSynthesis } from './synthesize-postprocess.ts';* written ONLY on success (codex finding #5 deferral: no auto git commit* in v1).* - Idempotency via `dream:synth-v2:<source>:filename:<basename>:<hash16>`- * job keys (byte-stable — pinned by test/e2e/dream-synthesize-chunking).+ * job keys (byte-stable — pinned by test/dream-synthesize-chunking.serial.test.ts).* - Edited transcripts produce slugs with content-hash suffix → no overwrite.* - Degenerate triage verdicts (truncated / refusal / unparseable /* score out of [0,1]) are never cached — the next cycle re-judges.diff --git a/src/core/data-research.ts b/src/core/data-research.tsdeleted file mode 100644index b9ca3fb0ea..0000000000--- a/src/core/data-research.ts+++ /dev/null@@ -1,435 +0,0 @@-/**- * Data research utilities: recipe loading/validation, field extraction,- * deduplication, tracker page parsing, date windowing, HTML stripping.- *- * Used by the data-research skill and supporting agent workflows.- */--// ----------------------------------------------------------------------------// Types-// -----------------------------------------------------------------------------export interface ResearchRecipe {- name: string;- source_queries: {- gmail?: string[];- brain?: string[];- web?: string[];- date_windowing?: 'quarterly' | 'monthly';- };- classification: {- include_patterns?: string[];- exclude_patterns?: string[];- receipt_indicators?: string[];- marketing_indicators?: string[];- };- extraction_schema: Record<string, string>;- tracker_page: string;- tracker_format: {- group_by: string;- columns: string[];- sort?: string;- totals?: string[];- };- schedule?: {- cron: string;- notify?: boolean;- quiet_hours?: boolean;- };-}--export interface ValidationResult {- valid: boolean;- errors: string[];-}--export interface TrackerEntry {- [key: string]: string | number | string[];-}--export interface DedupConfig {- amountTolerance?: number; // e.g., 5 for $5 tolerance- dateExact?: boolean; // exact date match required- entityFuzzy?: boolean; // fuzzy entity name matching-}--export interface DedupResult {- isDuplicate: boolean;- type: 'exact' | 'fuzzy' | 'different_amount' | 'new';- matchedEntry?: TrackerEntry;-}--export interface DateWindow {- start: string; // YYYY/MM/DD- end: string;- label: string; // e.g., "Q1 2026"-}--// ----------------------------------------------------------------------------// Recipe loading and validation-// -----------------------------------------------------------------------------/** Validate a research recipe has required fields and valid patterns. */-export function validateRecipe(recipe: Partial<ResearchRecipe>): ValidationResult {- const errors: string[] = [];-- if (!recipe.name) errors.push('Missing required field: name');- if (!recipe.source_queries) errors.push('Missing required field: source_queries');- if (!recipe.extraction_schema) errors.push('Missing required field: extraction_schema');- if (!recipe.tracker_page) errors.push('Missing required field: tracker_page');- if (!recipe.tracker_format) errors.push('Missing required field: tracker_format');-- if (recipe.tracker_format) {- if (!recipe.tracker_format.group_by) errors.push('tracker_format missing group_by');- if (!recipe.tracker_format.columns || recipe.tracker_format.columns.length === 0) {- errors.push('tracker_format missing columns');- }- }-- if (recipe.source_queries) {- const sq = recipe.source_queries;- if (!sq.gmail && !sq.brain && !sq.web) {- errors.push('source_queries must have at least one of: gmail, brain, web');- }- }-- // Validate regex patterns are compilable- const patternArrays = [- recipe.classification?.include_patterns,- recipe.classification?.exclude_patterns,- recipe.classification?.receipt_indicators,- recipe.classification?.marketing_indicators,- ].filter(Boolean);-- for (const patterns of patternArrays) {- for (const p of patterns!) {- try {- // Patterns are stored as strings like "/regex/flags"- const match = p.match(/^\/(.+)\/([gimsuy]*)$/);- if (match) new RegExp(match[1], match[2]);- } catch (e: any) {- errors.push(`Invalid regex pattern '${p}': ${e.message}`);- }- }- }-- return { valid: errors.length === 0, errors };-}--// ----------------------------------------------------------------------------// Field extraction-// -----------------------------------------------------------------------------/** Common financial metric regex patterns. */-const METRIC_PATTERNS: Record<string, RegExp[]> = {- mrr: [- /MRR[:\s]+(?:of\s+)?\$?([\d,]+\.?\d*\s*[KkMm]?)/i,- /MRR\s+(?:hit|is|at|reached|now|of)\s+\$?([\d,]+\.?\d*\s*[KkMm]?)/i,- /\$([\d,]+\.?\d*\s*[KkMm])\s*MRR/i,- ],- arr: [- /ARR[:\s]+(?:of\s+)?\$?([\d,]+\.?\d*\s*[KkMmBb]?)/i,- /ARR\s+(?:hit|is|at|reached|now|of)\s+\$?([\d,]+\.?\d*\s*[KkMmBb]?)/i,- /\$([\d,]+\.?\d*\s*[KkMmBb])\s*ARR/i,- ],- growth_mom: [- /(\+?-?\d+\.?\d*%)\s*(?:MoM|month[ -]over[ -]month)/i,- /(?:grew|growth|increased|up)\s+(?:by\s+)?(\+?\d+\.?\d*%)/i,- ],- runway_months: [- /runway[:\s]+(?:of\s+)?(?:about\s+)?(\d+)\s*(?:months?|mo)/i,- /(\d+)\s*(?:months?|mo)\s*(?:of\s+)?runway/i,- ],- headcount: [- /(\d+)\s*(?:employees?|team members?|people|headcount|FTEs?)/i,- /team\s+(?:of|size[:\s]+)\s*(\d+)/i,- ],- customers: [- /(\d[\d,]*)\s*(?:customers?|clients?|users?|accounts?)/i,- ],- amount: [- /Total Charged\s*\n?\s*\$([\d,]+\.\d{2})/i,- /receipt for your \$([\d,]+\.\d{2})/i,- /\$([\d,]+(?:\.\d{1,2})?)/g,- ],-};--/** Extract structured fields from raw text using regex patterns. */-export function extractFields(- rawText: string,- schema: Record<string, string>,-): Record<string, string | null> {- const result: Record<string, string | null> = {};-- for (const [field, type] of Object.entries(schema)) {- // Check if we have built-in patterns for this field- const patterns = METRIC_PATTERNS[field];- if (patterns) {- let matched = false;- for (const pattern of patterns) {- const match = rawText.match(pattern);- if (match && match[1]) {- result[field] = match[1].trim();- matched = true;- break;- }- }- if (!matched) result[field] = null;- } else if (type === 'date') {- // Extract dates in common formats- const dateMatch = rawText.match(/(\d{4}-\d{2}-\d{2}|\d{1,2}\/\d{1,2}\/\d{2,4})/);- result[field] = dateMatch ? dateMatch[1] : null;- } else {- result[field] = null; // No built-in pattern, needs LLM or custom regex- }- }-- return result;-}--/** Verify extracted fields match what was saved to file (extraction integrity). */-export function verifyExtraction(- savedFields: Record<string, any>,- reportedFields: Record<string, any>,-): { verified: boolean; mismatches: string[] } {- const mismatches: string[] = [];- for (const [key, savedValue] of Object.entries(savedFields)) {- const reported = reportedFields[key];- if (reported !== undefined && String(reported) !== String(savedValue)) {- mismatches.push(`${key}: saved="${savedValue}" reported="${reported}"`);- }- }- return { verified: mismatches.length === 0, mismatches };-}--// ----------------------------------------------------------------------------// Deduplication-// -----------------------------------------------------------------------------/** Check if an entry duplicates an existing tracker entry. */-export function isDuplicate(- existing: TrackerEntry[],- candidate: TrackerEntry,- keyFields: string[],- config?: DedupConfig,-): DedupResult {- const tolerance = config?.amountTolerance || 0;-- for (const entry of existing) {- // Check if all key fields match- let allMatch = true;- let nonAmountFieldsMatch = true;- let amountDiffers = false;-- for (const key of keyFields) {- const existingVal = String(entry[key] || '');- const candidateVal = String(candidate[key] || '');-- if (key === 'amount') {- const existingNum = parseFloat(existingVal.replace(/[$,]/g, ''));- const candidateNum = parseFloat(candidateVal.replace(/[$,]/g, ''));- if (tolerance > 0 && Math.abs(existingNum - candidateNum) > tolerance) {- amountDiffers = true;- allMatch = false;- } else if (existingVal.toLowerCase() !== candidateVal.toLowerCase()) {- amountDiffers = true;- allMatch = false;- }- } else if (config?.entityFuzzy && (key === 'recipient' || key === 'company')) {- if (existingVal.slice(0, 15).toLowerCase() !== candidateVal.slice(0, 15).toLowerCase()) {- allMatch = false;- nonAmountFieldsMatch = false;- }- } else {- if (existingVal.toLowerCase() !== candidateVal.toLowerCase()) {- allMatch = false;- nonAmountFieldsMatch = false;- }- }- }-- if (allMatch) {- return { isDuplicate: true, type: 'exact', matchedEntry: entry };- }- if (amountDiffers && nonAmountFieldsMatch) {- return { isDuplicate: false, type: 'different_amount', matchedEntry: entry };- }- }-- return { isDuplicate: false, type: 'new' };-}--// ----------------------------------------------------------------------------// Tracker page parsing-// -----------------------------------------------------------------------------/** Parse a markdown table into structured entries. */-export function parseTrackerPage(markdown: string, columns: string[]): TrackerEntry[] {- const entries: TrackerEntry[] = [];- const lines = markdown.split('\n');-- for (const line of lines) {- if (!line.startsWith('|') || line.includes('---')) continue;- const cells = line.split('|').map(c => c.trim()).filter(Boolean);- // Skip header row- if (cells.length >= columns.length && cells[0] !== columns[0]) {- const entry: TrackerEntry = {};- for (let i = 0; i < columns.length && i < cells.length; i++) {- entry[columns[i]] = cells[i];- }- entries.push(entry);- }- }-- return entries;-}--/** Append entries to a tracker page's markdown table. */-export function appendToTracker(- markdown: string,- entries: TrackerEntry[],- columns: string[],- section?: string,-): string {- const newRows = entries.map(entry => {- const cells = columns.map(col => String(entry[col] || ''));- return `| ${cells.join(' | ')} |`;- }).join('\n');-- if (section) {- // Find the section and append before the next section or end- const sectionPattern = new RegExp(`(### ${section}[\\s\\S]*?)(\\n### |$)`);- const match = markdown.match(sectionPattern);- if (match) {- const insertPoint = match.index! + match[1].length;- return markdown.slice(0, insertPoint) + '\n' + newRows + '\n' + markdown.slice(insertPoint);- }- }-- // Append to end- return markdown + '\n' + newRows + '\n';-}--/** Compute running totals for specified columns. */-export function computeTotals(- entries: TrackerEntry[],- totalColumns: string[],-): Record<string, number> {- const totals: Record<string, number> = {};- for (const col of totalColumns) {- totals[col] = 0;- for (const entry of entries) {- const val = String(entry[col] || '0').replace(/[$,]/g, '');- const num = parseFloat(val);- if (!isNaN(num)) totals[col] += num;- }- }- return totals;-}--// ----------------------------------------------------------------------------// Date windowing-// -----------------------------------------------------------------------------/** Build quarterly or monthly date windows for Gmail queries. */-export function buildDateWindows(- startYear: number,- endYear: number,- granularity: 'quarterly' | 'monthly' = 'quarterly',-): DateWindow[] {- if (endYear < startYear) {- throw new Error(`endYear (${endYear}) must be >= startYear (${startYear})`);- }-- const windows: DateWindow[] = [];-- for (let year = startYear; year <= endYear; year++) {- if (granularity === 'quarterly') {- windows.push(- { start: `${year}/01/01`, end: `${year}/04/01`, label: `Q1 ${year}` },- { start: `${year}/04/01`, end: `${year}/07/01`, label: `Q2 ${year}` },- { start: `${year}/07/01`, end: `${year}/10/01`, label: `Q3 ${year}` },- { start: `${year}/10/01`, end: `${year + 1}/01/01`, label: `Q4 ${year}` },- );- } else {- for (let month = 1; month <= 12; month++) {- const nextMonth = month === 12 ? 1 : month + 1;- const nextYear = month === 12 ? year + 1 : year;- windows.push({- start: `${year}/${String(month).padStart(2, '0')}/01`,- end: `${nextYear}/${String(nextMonth).padStart(2, '0')}/01`,- label: `${year}-${String(month).padStart(2, '0')}`,- });- }- }- }-- return windows;-}--// ----------------------------------------------------------------------------// HTML email stripping-// -----------------------------------------------------------------------------const MAX_HTML_SIZE = 500 * 1024; // 500KB cap (ReDoS prevention)-const EMAIL_HTML_TAGS = new Set((- 'a abbr acronym address area article aside audio b base basefont bdi bdo big blockquote body br button ' +- 'canvas caption center cite code col colgroup data datalist dd del details dfn dialog dir div dl dt em embed ' +- 'fieldset figcaption figure font footer form frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe ' +- 'img input ins kbd label legend li link main map mark marquee menu meta meter nav noframes noscript object ' +- 'ol optgroup option output p param picture plaintext pre progress q rp rt ruby s samp script search section ' +- 'select slot small source span strike strong style sub summary sup table tbody td template textarea tfoot ' +- 'th thead time title tr track tt u ul var video wbr xmp'-).split(' '));--function stripEmailMarkup(text: string): string {- return text- .replace(/<!--[\s\S]*?-->/g, '')- .replace(/<(style|script)(?=[\s>])(?:[^<>"']|"[^"]*"|'[^']*')*>[\s\S]*?<\/\1\s*>/gi, '')- .replace(/<br\s*\/?>/gi, '\n')- .replace(/<\/(p|div|tr|li|h[1-6])>/gi, '\n')- .replace(/<\/?([a-z][a-z0-9:-]*)(?=[\s/>])(?:[^<>"']|"[^"]*"|'[^']*')*>|<![^>]*>|<\?[^>]*\?>/gi,- (tag, name: string | undefined) => name && !EMAIL_HTML_TAGS.has(name.toLowerCase()) ? tag : '');-}--/** Strip HTML from email bodies with bounded entity decoding and an input size cap. */-export function stripEmailHtml(html: string): string {- let text = html;- if (text.length > MAX_HTML_SIZE) {- text = text.slice(0, MAX_HTML_SIZE) + '\n...[truncated]';- }-- for (let pass = 0; pass < 2; pass++) {- text = stripEmailMarkup(text);- text = text.replace(/&(nbsp|amp|lt|gt|quot|#\d+);/gi, (entity, code: string) => {- switch (code.toLowerCase()) {- case 'nbsp': return ' ';- case 'amp': return '&';- case 'lt': return '<';- case 'gt': return '>';- case 'quot': return '"';- default: {- const value = Number(code.slice(1));- if (!Number.isInteger(value) || value > 0x10FFFF || (value >= 0xD800 && value <= 0xDFFF)) {- return entity;- }- return String.fromCodePoint(value);- }- }- });- }-- text = stripEmailMarkup(text);-- if (text.length < 100000) {- text = text.replace(/@media[^{]*\{[^}]*\}/g, '');- text = text.replace(/\.[a-zA-Z][\w-]*\s*\{[^}]*\}/g, '');- text = text.replace(/#[a-zA-Z][\w-]*\s*\{[^}]*\}/g, '');- }-- text = text.replace(/[ \t]+/g, ' ');- text = text.replace(/\n{3,}/g, '\n\n');- text = text.trim();-- return text;-}diff --git a/src/core/diarize/payload-fitter.ts b/src/core/diarize/payload-fitter.tsdeleted file mode 100644index 4d58e5fd2c..0000000000--- a/src/core/diarize/payload-fitter.ts+++ /dev/null@@ -1,268 +0,0 @@-/**- * v0.37.x — payload-fitter (P6) with two strategies + a quality gate.- *- * Generic utility for fitting an arbitrarily large list of items into a- * downstream caller's per-call token budget.- *- * Strategies (Q3 + codex finding #4):- * - 'batch' deterministic token-budgeted chunking. The caller- * receives a flat fit list shaped like the input; the- * chunking decision is left to the caller (e.g. the- * brainstorm judge concatenates results across batches).- * No LLM calls.- * - 'summarize' embed-cluster (k = ceil(items/4)), Haiku-summarize each- * cluster, return the fitted payload (summary nodes- * instead of every original item). Composes the active- * BudgetTracker via the gateway's AsyncLocalStorage scope- * (T3) — every Haiku call shows up in the cost ledger.- * Promise.allSettled at parallelism=4 (Perf1) so a single- * cluster-failure does not stall the whole pass.- *- * Quality gate (codex outside-voice finding #4):- * When the summarize strategy returns less than `min_success_ratio`- * (default 0.75) of attempted clusters, the result is flagged- * `degraded: true` and the caller decides whether to surface a partial- * result or abort. Brainstorm aborts on degraded; defaults can be- * relaxed per-caller.- */--import type { ChatOpts, ChatResult } from '../ai/gateway.ts';--/** Local ChatFn shape — kept here so payload-fitter doesn't depend on- * src/core/brainstorm/judges.ts (which is the canonical owner of the- * ChatFn alias today). */-type ChatFn = (opts: ChatOpts) => Promise<ChatResult>;--export type FitStrategy = 'batch' | 'summarize';--export interface FitOptions<T> {- items: T[];- strategy: FitStrategy;- /** Hard per-call token budget. 'batch' chunks under this; 'summarize'- * shapes its k-clusters so each cluster fits this budget. */- maxTokensPerCall: number;- /** Token estimator. Caller-supplied so payload-fitter is generic. */- estimateTokens: (item: T) => number;- // ---- summarize-only ----- /** Optional embed function (only used by 'summarize'). Caller supplies- * the active gateway.embed binding. */- embedFn?: (text: string) => Promise<Float32Array>;- /** Optional chat function for summarization. Caller supplies the- * active gateway.chat binding. */- chatFn?: ChatFn;- /** Summarize-only: convert an item to text for embed + summarize. */- itemToText?: (item: T) => string;- /** Summarize-only: convert a Haiku summary string back into an item-- * shaped fitted node. Caller-supplied so the fitted list has the- * caller's own type. */- summaryToItem?: (summary: string, cluster: T[]) => T;- /** Summarize parallelism. Default 4 per Perf1. */- parallelism?: number;- /** Quality gate threshold. Default 0.75. When the success ratio drops- * below this, result.degraded === true. */- min_success_ratio?: number;- /** Override the summarization model (e.g. 'anthropic:claude-haiku-4-5').- * Default falls back to the gateway's configured chat model. */- summarizeModel?: string;-}--export interface FitResult<T> {- fitted: T[];- strategy: FitStrategy;- /** Count of clusters that failed (summarize) or 0 (batch). */- dropped: number;- /** Ratio of successful clusters: 1.0 for batch / clean summarize. */- success_ratio: number;- /** True when success_ratio < min_success_ratio. */- degraded: boolean;- /** Total LLM usage rolled up across summarize calls. Undefined for batch. */- usage?: ChatResult['usage'];-}--const DEFAULT_PARALLELISM = 4;-const DEFAULT_MIN_SUCCESS_RATIO = 0.75;--/**- * Public entry point. Dispatches on strategy. Pure typecheck failures- * (e.g. summarize without embedFn/chatFn) throw `Error` synchronously so- * caller misuse fails loud.- */-export async function fit<T>(opts: FitOptions<T>): Promise<FitResult<T>> {- if (opts.strategy === 'batch') {- return fitBatch(opts);- }- if (opts.strategy === 'summarize') {- return fitSummarize(opts);- }- throw new Error(`payload-fitter: unknown strategy "${(opts as { strategy: string }).strategy}"`);-}--/**- * 'batch' strategy: deterministic, token-budgeted chunking. Returns the- * original items unchanged (no LLM calls). `dropped` is the count of- * items that exceeded the per-call budget all on their own — these are- * preserved in `fitted` (caller decides whether to surface a warning)- * but they signal a budgeting mismatch the caller should know about.- */-function fitBatch<T>(opts: FitOptions<T>): FitResult<T> {- const dropped = opts.items.filter((it) => opts.estimateTokens(it) > opts.maxTokensPerCall).length;- return {- fitted: opts.items.slice(),- strategy: 'batch',- dropped,- success_ratio: opts.items.length === 0 ? 1.0 : (opts.items.length - dropped) / opts.items.length,- degraded: false,- };-}--/**- * 'summarize' strategy: embed-cluster then Haiku-summarize each cluster.- *- * 1. embed every item (caller-supplied embedFn).- * 2. cluster into k = ceil(items/4) groups via cheap greedy nearest-- * neighbor on cosine similarity (deterministic; no sklearn).- * 3. parallel Haiku-summarize each cluster via Promise.allSettled- * with parallelism `opts.parallelism ?? 4` (Perf1).- * 4. drop failed clusters; surface a `degraded: true` flag when the- * success ratio falls below `min_success_ratio`.- *- * Each Haiku call composes the active BudgetTracker via AsyncLocalStorage- * (no per-call injection). On BudgetExhausted the call throws — caller's- * outer catch handles persistence.- */-async function fitSummarize<T>(opts: FitOptions<T>): Promise<FitResult<T>> {- if (!opts.embedFn || !opts.chatFn || !opts.itemToText || !opts.summaryToItem) {- throw new Error(- `payload-fitter: strategy='summarize' requires embedFn + chatFn + itemToText + summaryToItem`,- );- }- const minRatio = opts.min_success_ratio ?? DEFAULT_MIN_SUCCESS_RATIO;- const parallelism = Math.max(1, opts.parallelism ?? DEFAULT_PARALLELISM);-- if (opts.items.length === 0) {- return { fitted: [], strategy: 'summarize', dropped: 0, success_ratio: 1.0, degraded: false };- }-- // 1. Embed every item. The gateway.embed call composes the active- // tracker; a budget throw here propagates cleanly.- const texts = opts.items.map((it) => opts.itemToText!(it));- const embeds: Float32Array[] = [];- for (const text of texts) {- embeds.push(await opts.embedFn(text));- }-- // 2. Greedy clustering. Pick the first un-clustered item as the seed;- // add the (k-1) closest remaining items by cosine. Deterministic- // given the input order. k = ceil(items / 4).- const k = Math.max(1, Math.ceil(opts.items.length / 4));- const clusterSize = Math.ceil(opts.items.length / k);- const claimed = new Set<number>();- const clusters: number[][] = [];- for (let c = 0; c < k && claimed.size < opts.items.length; c++) {- let seedIdx = -1;- for (let i = 0; i < opts.items.length; i++) {- if (!claimed.has(i)) {- seedIdx = i;- break;- }- }- if (seedIdx === -1) break;- claimed.add(seedIdx);- const group = [seedIdx];- const seedVec = embeds[seedIdx];- // Score remaining un-claimed by similarity to seed; pick closest until cluster is full.- const remaining = opts.items- .map((_, idx) => idx)- .filter((idx) => idx !== seedIdx && !claimed.has(idx))- .map((idx) => ({ idx, sim: cosine(seedVec, embeds[idx]) }))- .sort((a, b) => b.sim - a.sim);- for (const cand of remaining) {- if (group.length >= clusterSize) break;- claimed.add(cand.idx);- group.push(cand.idx);- }- clusters.push(group);- }-- // 3. Parallel summarize via allSettled with bounded concurrency.- const fitted: T[] = [];- const totalUsage: ChatResult['usage'] = {- input_tokens: 0,- output_tokens: 0,- cache_read_tokens: 0,- cache_creation_tokens: 0,- };- let failed = 0;- for (let i = 0; i < clusters.length; i += parallelism) {- const wave = clusters.slice(i, i + parallelism);- const results = await Promise.allSettled(- wave.map((group) => summarizeCluster(group, opts, texts)),- );- for (let j = 0; j < results.length; j++) {- const r = results[j];- const group = wave[j];- if (r.status === 'fulfilled') {- fitted.push(opts.summaryToItem!(r.value.summary, group.map((idx) => opts.items[idx])));- totalUsage.input_tokens += r.value.usage.input_tokens;- totalUsage.output_tokens += r.value.usage.output_tokens;- if (typeof r.value.usage.cache_read_tokens === 'number') {- totalUsage.cache_read_tokens =- (totalUsage.cache_read_tokens ?? 0) + r.value.usage.cache_read_tokens;- }- if (typeof r.value.usage.cache_creation_tokens === 'number') {- totalUsage.cache_creation_tokens =- (totalUsage.cache_creation_tokens ?? 0) + r.value.usage.cache_creation_tokens;- }- } else {- failed++;- }- }- }-- const succeeded = clusters.length - failed;- const success_ratio = clusters.length === 0 ? 1.0 : succeeded / clusters.length;- const degraded = success_ratio < minRatio;- return {- fitted,- strategy: 'summarize',- dropped: failed,- success_ratio,- degraded,- usage: totalUsage,- };-}--interface SummarizeOutcome {- summary: string;- usage: ChatResult['usage'];-}--async function summarizeCluster<T>(- group: number[],- opts: FitOptions<T>,- texts: string[],-): Promise<SummarizeOutcome> {- const chat = opts.chatFn!;- const lines = group.map((idx) => `- ${texts[idx]}`).join('\n');- const prompt = `Summarize the following items in ~3 sentences capturing the load-bearing themes. Do not paraphrase verbatim.\n\n${lines}`;- const res = await chat({- model: opts.summarizeModel,- messages: [{ role: 'user', content: prompt }],- maxTokens: 400,- });- return { summary: res.text.trim(), usage: res.usage };-}--function cosine(a: Float32Array, b: Float32Array): number {- const len = Math.min(a.length, b.length);- let dot = 0;- let na = 0;- let nb = 0;- for (let i = 0; i < len; i++) {- dot += a[i] * b[i];- na += a[i] * a[i];- nb += b[i] * b[i];- }- if (na === 0 || nb === 0) return 0;- return dot / (Math.sqrt(na) * Math.sqrt(nb));-}diff --git a/src/core/distribution/index.ts b/src/core/distribution/index.tsdeleted file mode 100644index 481ff2f98e..0000000000--- a/src/core/distribution/index.ts+++ /dev/null@@ -1,124 +0,0 @@-// v0.38 distribution layer — shared tarball + trust + registry helpers.-//-// E2: shared helpers that both `src/core/skillpack/` (v0.37) and-// `src/core/schema-pack/` (v0.38) consume. Promoting them out of the-// skillpack module reflects what they always were: artifact-shape--// agnostic tarball processing, TOFU trust prompts, registry HTTP,-// remote source handling. Naming them `distribution` makes the-// reuse contract legible and prevents schema-pack code from-// importing through a skillpack-named module.-//-// Physical layout (Option B from eng-review E2): the implementations-// stay at `src/core/skillpack/` for now to avoid a big-bang move that-// would touch ~15 v0.37 callers + risk breaking the just-shipped-// skillpack pipeline. This module re-exports the shared surface as-// the canonical name; schema-pack imports from here. v0.39+ may-// physically move the implementations if signal warrants it.-//-// Codex F6 (circular imports): this module MUST only import from-// `src/core/skillpack/{tarball,trust-prompt,registry-client,-// remote-source,registry-schema,scaffold-third-party}.ts`. It must-// NOT import from `commands/`, `schema-pack/`, engines, or config-// resolution. Pinned by the import-boundary test below.-//-// Codex F7 (backwards-compat): existing skillpack callers continue-// to import from `src/core/skillpack/` directly — this module does-// NOT change v0.37 behavior. Schema-pack callers use this module's-// exports to avoid the schema-pack-imports-from-skillpack semantic-// awkwardness.--// Tarball processing: extract caps, symlink rejection, magic-byte-// sniff. v0.37 used this for `.tgz` skillpacks; v0.38 extends to-// `.gbrain-schema` and `.gbrain-skillpack`. The tarball implementation-// is artifact-shape-agnostic — the manifest validator runs separately-// after extraction.-export {- DEFAULT_EXTRACT_CAPS,- extractTarball,- fileSha256,- packTarball,- TarballError,- type ExtractCaps,- type TarballErrorCode,- type TarballExtractOptions,- type TarballExtractResult,- type TarballPackOptions,- type TarballPackResult,-} from '../skillpack/tarball.ts';--// TOFU trust prompts. v0.37 fingerprints by author + pinned-commit +-// tarball SHA + tier; v0.38 reuses this for schema packs (same trust-// model — community-published artifacts need explicit operator ack).-export {- askTrust,- renderIdentityBlock,- type AskTrustOptions,- type SkillpackTier,- type TrustPromptDecision,- type TrustPromptInput,-} from '../skillpack/trust-prompt.ts';--// Registry HTTP client (fetch + etag + soft-TTL + stale-fallback).-// Artifact-shape-agnostic — the JSON schema for the registry entry is-// the same regardless of whether it's a skillpack or schema-pack.-export {- DEFAULT_ENDORSEMENTS_URL,- DEFAULT_REGISTRY_URL,- findPack,- findPackWithTier,- loadRegistry,- RegistryClientError,- resolveRegistryUrl,- searchPacks,- type LoadedRegistry,- type LoadRegistryOptions,- type RegistryClientErrorCode,-} from '../skillpack/registry-client.ts';--// Remote source resolution (git clone via git-remote.ts SSRF-hardened-// path; tarball URL download). Used by `scaffold` for both skillpack-// and schema-pack remote refs.-export {- classifySpec,- RemoteSourceError,- resolveSource,- type RemoteSourceErrorCode,- type ResolvedSource,- type ResolvedSourceKind,- type ResolveSourceOptions,- type SpecKind,-} from '../skillpack/remote-source.ts';--// Registry schema definitions for tier rubric (CORE / BADGES /-// effective_tier). v0.37 used for skillpacks; v0.38 schema-packs-// share the same tier vocabulary so users learn one quality model.-export {- effectiveTier,- ENDORSEMENTS_SCHEMA_VERSION,- REGISTRY_SCHEMA_VERSION,- RegistrySchemaError,- validateEndorsementsFile,- validateRegistryCatalog,- validateRegistryEntry,- type EndorsementRecord,- type EndorsementsFile,- type RegistryBundles,- type RegistryCatalog,- type RegistryEntry,- type RegistrySchemaErrorCode,- type RegistrySource,- type RegistryTier,-} from '../skillpack/registry-schema.ts';--// Third-party scaffold pipeline. v0.37's `scaffold` command pattern —-// resolve spec → fetch → validate → cache → display runbook. v0.38-// schema-packs use the same pipeline with a different manifest-// validator.-export {- defaultStatePath,- runScaffoldThirdParty,- ScaffoldThirdPartyError,- type ScaffoldThirdPartyOptions,- type ScaffoldThirdPartyResult,- type ScaffoldThirdPartyStatus,-} from '../skillpack/scaffold-third-party.ts';diff --git a/src/core/embedding-dim-check.ts b/src/core/embedding-dim-check.tsindex 851b3ca3b3..4be1e87775 100644--- a/src/core/embedding-dim-check.ts+++ b/src/core/embedding-dim-check.ts@@ -642,17 +642,10 @@ export function buildFactsAlterRecipe(* probe is a cheap SELECT but runs at the top of every fact-writing* call site; caching keeps the cost off the hot path. The cache* stores the engine's `kind + a synthetic instance marker` so a fresh- * engine connection in the same process re-probes. Test seam below- * clears the cache between cases.+ * engine connection in the same process re-probes.*/const _factsDimCheckCache = new WeakMap<BrainEngine, { ok: true } | { err: FactsEmbeddingDimMismatchError }>();-/** Test seam: clear the per-process facts-dim cache. */-export function _resetFactsDimCheckCacheForTest(): void {- // WeakMap has no clear() — but tests can pass fresh engine instances- // to get fresh probes. This noop helper documents the intent.-}-/*** Preflight check: throws FactsEmbeddingDimMismatchError when the* configured embedding dimensions don't match the facts.embeddingdiff --git a/src/core/enrichment/budget.ts b/src/core/enrichment/budget.tsdeleted file mode 100644index 514de83d2e..0000000000--- a/src/core/enrichment/budget.ts+++ /dev/null@@ -1,369 +0,0 @@-/**- * BudgetLedger — daily spend cap for resolver calls, scope + resolver granular.- *- * Every paid resolver (Perplexity, Mistral OCR, etc.) should call reserve()- * before the API call and commit() or rollback() after. The ledger tracks- * reserved_usd + committed_usd per {scope, resolver_id, local_date} row and- * refuses reservations that would take committed + reserved over the cap.- *- * Midnight rollover: the primary key includes local_date derived from an- * IANA timezone (default America/Los_Angeles, overridable via config key- * `budget.tz`). A new calendar day means a new row — no race between the- * rollover thread and concurrent reserves, because there's no rollover- * thread. We just upsert into {scope, resolver_id, today}.- *- * Process-death protection: reservations carry a TTL. If the process- * crashes between reserve() and commit(), the reserved dollars stay held- * until TTL expiry, after which cleanupExpired() zeroes them out. Worst- * case is a few minutes of over-reservation; never an over-spend.- *- * Concurrency: uses SELECT FOR UPDATE on the ledger row to serialize- * concurrent reserves for the same (scope, resolver_id, date). 10 parallel- * callers can't double-spend. PGLite supports FOR UPDATE in its Postgres- * compat layer.- */--import type { BrainEngine } from '../engine.ts';--// ----------------------------------------------------------------------------// Types-// -----------------------------------------------------------------------------export interface ReserveInput {- /** Partition for multi-tenant teams; single-user installs use 'default'. */- scope?: string;- resolverId: string;- /** Pre-call cost estimate in USD. */- estimateUsd: number;- /** Daily cap in USD for (scope, resolverId). Null/undefined = no cap. */- capUsd?: number;- /** Reservation TTL in seconds. Default 60s. */- ttlSeconds?: number;-}--export type ReservationResult =- | { kind: 'held'; reservationId: string; scope: string; resolverId: string; date: string; estimateUsd: number; reservedAt: Date; expiresAt: Date }- | { kind: 'exhausted'; reason: string; spent: number; pending: number; cap: number };--export interface BudgetStateRow {- scope: string;- resolverId: string;- date: string;- reservedUsd: number;- committedUsd: number;- capUsd: number | null;-}--// ----------------------------------------------------------------------------// Errors-// -----------------------------------------------------------------------------export type BudgetErrorCode =- | 'reservation_not_found'- | 'already_finalized'- | 'invalid_input'- | 'cap_exceeded';--export class BudgetError extends Error {- constructor(public code: BudgetErrorCode, message: string, public reservationId?: string) {- super(message);- this.name = 'BudgetError';- }-}--// ----------------------------------------------------------------------------// Constants-// -----------------------------------------------------------------------------const DEFAULT_SCOPE = 'default';-const DEFAULT_TTL_SECONDS = 60;-const DEFAULT_TZ = 'America/Los_Angeles';--// ----------------------------------------------------------------------------// BudgetLedger-// -----------------------------------------------------------------------------export class BudgetLedger {- /** IANA timezone for midnight-rollover. Settable per-instance for tests. */- private tz: string;-- constructor(private engine: BrainEngine, opts: { tz?: string } = {}) {- this.tz = opts.tz ?? DEFAULT_TZ;- }-- /** Reserve spend against (scope, resolverId, today). Atomic via FOR UPDATE. */- async reserve(input: ReserveInput): Promise<ReservationResult> {- const estimate = Number(input.estimateUsd);- if (!Number.isFinite(estimate) || estimate < 0) {- throw new BudgetError('invalid_input', `reserve: estimateUsd must be non-negative, got ${input.estimateUsd}`);- }- const scope = input.scope ?? DEFAULT_SCOPE;- const resolverId = input.resolverId;- const date = todayInTz(this.tz);- const ttl = input.ttlSeconds ?? DEFAULT_TTL_SECONDS;- const cap = input.capUsd ?? null;-- // Reclaim any expired reservations opportunistically before reading.- await this.reclaimExpiredRow(scope, resolverId, date);-- return await this.engine.transaction(async (tx) => {- // Upsert the ledger row so FOR UPDATE has something to lock.- await tx.executeRaw(- `INSERT INTO budget_ledger (scope, resolver_id, local_date, reserved_usd, committed_usd, cap_usd)- VALUES ($1, $2, $3, 0, 0, $4)- ON CONFLICT (scope, resolver_id, local_date) DO NOTHING`,- [scope, resolverId, date, cap],- );-- const rows = await tx.executeRaw<{ reserved_usd: string | number; committed_usd: string | number; cap_usd: string | number | null }>(- `SELECT reserved_usd, committed_usd, cap_usd- FROM budget_ledger- WHERE scope = $1 AND resolver_id = $2 AND local_date = $3- FOR UPDATE`,- [scope, resolverId, date],- );- const row = rows[0];- const reserved = toNum(row.reserved_usd);- const committed = toNum(row.committed_usd);- const effectiveCap = cap ?? (row.cap_usd != null ? toNum(row.cap_usd) : null);-- if (effectiveCap != null && committed + reserved + estimate > effectiveCap + 1e-9) {- return {- kind: 'exhausted',- reason: `${scope}/${resolverId}@${date}: committed ${committed.toFixed(4)} + reserved ${reserved.toFixed(4)} + estimate ${estimate.toFixed(4)} > cap ${effectiveCap.toFixed(4)}`,- spent: committed,- pending: reserved,- cap: effectiveCap,- } as ReservationResult;- }-- const reservationId = makeReservationId(scope, resolverId, date);- const reservedAt = new Date();- const expiresAt = new Date(reservedAt.getTime() + ttl * 1000);-- await tx.executeRaw(- `INSERT INTO budget_reservations (reservation_id, scope, resolver_id, local_date, estimate_usd, reserved_at, expires_at, status)- VALUES ($1, $2, $3, $4, $5, $6, $7, 'held')`,- [reservationId, scope, resolverId, date, estimate, reservedAt, expiresAt],- );-- await tx.executeRaw(- `UPDATE budget_ledger- SET reserved_usd = reserved_usd + $1, cap_usd = COALESCE($2, cap_usd), updated_at = now()- WHERE scope = $3 AND resolver_id = $4 AND local_date = $5`,- [estimate, cap, scope, resolverId, date],- );-- return {- kind: 'held',- reservationId,- scope,- resolverId,- date,- estimateUsd: estimate,- reservedAt,- expiresAt,- };- });- }-- /**- * Commit an actual spend. actualUsd may differ from the reservation's- * estimate — the ledger adjusts reserved_usd down by the estimate and- * committed_usd up by the actual.- *- * Re-checks the cap against the post-commit total: reserving $0.01 then- * committing $100 against a $1 cap must not silently blow through. The API- * call has already happened, so actualUsd is recorded in full (truthful- * accounting), the reservation is finalized, and a cap_exceeded error is- * thrown only AFTER the transaction commits. Throwing inside the transaction- * would roll back both writes and leave a paid call looking pending.- *- * Negative actuals are rejected — refunds should be a separate operation,- * not a side-channel on commit().- */- async commit(reservationId: string, actualUsd: number): Promise<void> {- if (!Number.isFinite(actualUsd)) {- throw new BudgetError('invalid_input', `commit: actualUsd must be finite, got ${actualUsd}`);- }- if (actualUsd < 0) {- throw new BudgetError('invalid_input', `commit: actualUsd must be non-negative (got ${actualUsd}). Use a dedicated refund API instead.`);- }-- const capError = await this.engine.transaction(async (tx) => {- const rows = await tx.executeRaw<{ scope: string; resolver_id: string; local_date: string; estimate_usd: string | number; status: string }>(- `SELECT scope, resolver_id, local_date, estimate_usd, status- FROM budget_reservations- WHERE reservation_id = $1- FOR UPDATE`,- [reservationId],- );- const r = rows[0];- if (!r) throw new BudgetError('reservation_not_found', `Reservation ${reservationId} not found`);- if (r.status !== 'held') throw new BudgetError('already_finalized', `Reservation ${reservationId} is already ${r.status}`, reservationId);-- const estimate = toNum(r.estimate_usd);-- // Re-check the cap against what the post-commit total would be.- // Lock the ledger row so a concurrent reserve cannot race us into overspend.- const ledgerRows = await tx.executeRaw<{ reserved_usd: string | number; committed_usd: string | number; cap_usd: string | number | null }>(- `SELECT reserved_usd, committed_usd, cap_usd- FROM budget_ledger- WHERE scope = $1 AND resolver_id = $2 AND local_date = $3- FOR UPDATE`,- [r.scope, r.resolver_id, r.local_date],- );- const ledger = ledgerRows[0];- const cap = ledger?.cap_usd != null ? toNum(ledger.cap_usd) : null;- const committedSoFar = ledger ? toNum(ledger.committed_usd) : 0;- const reservedSoFar = ledger ? toNum(ledger.reserved_usd) : 0;-- let capExceededBy: number | null = null;- if (cap != null) {- // Project against committed spend plus every OTHER held reservation.- // This reservation leaves the held pool as part of this transaction.- const otherReserved = Math.max(0, reservedSoFar - estimate);- const projected = committedSoFar + otherReserved + actualUsd;- if (projected > cap + 1e-9) {- capExceededBy = projected - cap;- }- }-- await tx.executeRaw(- `UPDATE budget_reservations SET status = 'committed' WHERE reservation_id = $1`,- [reservationId],- );-- await tx.executeRaw(- `UPDATE budget_ledger- SET reserved_usd = GREATEST(0, reserved_usd - $1),- committed_usd = committed_usd + $2,- updated_at = now()- WHERE scope = $3 AND resolver_id = $4 AND local_date = $5`,- [estimate, actualUsd, r.scope, r.resolver_id, r.local_date],- );-- if (capExceededBy !== null && capExceededBy > 0) {- return new BudgetError(- 'cap_exceeded',- `commit: actualUsd ${actualUsd.toFixed(4)} exceeded the available cap by ${capExceededBy.toFixed(4)}. ` +- 'The provider call already happened, so actual spend was recorded and future reservations remain blocked.',- reservationId,- );- }- return null;- });-- if (capError) throw capError;- }-- /** Cancel a held reservation; reserved_usd drops back. Idempotent-ish. */- async rollback(reservationId: string): Promise<void> {- return await this.engine.transaction(async (tx) => {- const rows = await tx.executeRaw<{ scope: string; resolver_id: string; local_date: string; estimate_usd: string | number; status: string }>(- `SELECT scope, resolver_id, local_date, estimate_usd, status- FROM budget_reservations- WHERE reservation_id = $1- FOR UPDATE`,- [reservationId],- );- const r = rows[0];- if (!r) throw new BudgetError('reservation_not_found', `Reservation ${reservationId} not found`);- if (r.status !== 'held') {- // Rollback-after-commit or rollback-after-rollback are no-ops, not errors —- // callers shouldn't have to guard defensively.- return;- }-- const estimate = toNum(r.estimate_usd);- await tx.executeRaw(- `UPDATE budget_reservations SET status = 'rolled_back' WHERE reservation_id = $1`,- [reservationId],- );- await tx.executeRaw(- `UPDATE budget_ledger- SET reserved_usd = GREATEST(0, reserved_usd - $1), updated_at = now()- WHERE scope = $2 AND resolver_id = $3 AND local_date = $4`,- [estimate, r.scope, r.resolver_id, r.local_date],- );- });- }-- /** Read current state for (scope, resolverId, date=today). */- async state(scope: string, resolverId: string): Promise<BudgetStateRow | null> {- const date = todayInTz(this.tz);- const rows = await this.engine.executeRaw<{ reserved_usd: string | number; committed_usd: string | number; cap_usd: string | number | null }>(- `SELECT reserved_usd, committed_usd, cap_usd- FROM budget_ledger- WHERE scope = $1 AND resolver_id = $2 AND local_date = $3`,- [scope, resolverId, date],- );- const row = rows[0];- if (!row) return null;- return {- scope,- resolverId,- date,- reservedUsd: toNum(row.reserved_usd),- committedUsd: toNum(row.committed_usd),- capUsd: row.cap_usd == null ? null : toNum(row.cap_usd),- };- }-- /** Global sweep for TTL-expired held reservations. Safe to run anytime. */- async cleanupExpired(): Promise<{ reclaimed: number }> {- const expired = await this.engine.executeRaw<{ reservation_id: string; scope: string; resolver_id: string; local_date: string; estimate_usd: string | number }>(- `SELECT reservation_id, scope, resolver_id, local_date, estimate_usd- FROM budget_reservations- WHERE status = 'held' AND expires_at < now()`,- );- let reclaimed = 0;- for (const r of expired) {- try {- await this.rollback(r.reservation_id);- reclaimed++;- } catch (e: unknown) {- if (e instanceof BudgetError && e.code === 'already_finalized') continue;- throw e;- }- }- return { reclaimed };- }-- private async reclaimExpiredRow(scope: string, resolverId: string, date: string): Promise<void> {- const expired = await this.engine.executeRaw<{ reservation_id: string }>(- `SELECT reservation_id FROM budget_reservations- WHERE scope = $1 AND resolver_id = $2 AND local_date = $3- AND status = 'held' AND expires_at < now()`,- [scope, resolverId, date],- );- for (const r of expired) {- try { await this.rollback(r.reservation_id); } catch { /* non-fatal */ }- }- }-}--// ----------------------------------------------------------------------------// Helpers-// -----------------------------------------------------------------------------function todayInTz(tz: string): string {- // Intl.DateTimeFormat with the en-CA locale yields YYYY-MM-DD formatting.- const fmt = new Intl.DateTimeFormat('en-CA', {- timeZone: tz,- year: 'numeric', month: '2-digit', day: '2-digit',- });- return fmt.format(new Date());-}--function toNum(v: string | number | null): number {- if (v == null) return 0;- const n = typeof v === 'string' ? parseFloat(v) : Number(v);- return Number.isFinite(n) ? n : 0;-}--function makeReservationId(scope: string, resolverId: string, date: string): string {- const rand = Math.floor(Math.random() * 1e12).toString(36);- const ts = Date.now().toString(36);- return `${scope}:${resolverId}:${date}:${ts}-${rand}`;-}diff --git a/src/core/enrichment/completeness.ts b/src/core/enrichment/completeness.tsdeleted file mode 100644index 692d8846ef..0000000000--- a/src/core/enrichment/completeness.ts+++ /dev/null@@ -1,275 +0,0 @@-/**- * CompletenessScorer — per-entity-type rubrics, 0.0–1.0 score per page.- *- * Replaces Garry's OpenClaw's length-based heuristic ("compiled_truth > 500 chars")- * with a weighted rubric that actually reflects whether a page would be- * useful to answer a query. Runs on demand; BrainWriter invokes it on- * write to cache the score in frontmatter.- *- * Seven core rubrics + a default for user-registered types. Each dimension- * returns 0.0–1.0 and the page score is the weighted sum. Weights sum to 1.0- * per rubric (checked at module load).- */--import type { Page, PageType } from '../types.ts';--// ----------------------------------------------------------------------------// Types-// -----------------------------------------------------------------------------export interface CompletenessDimension {- name: string;- weight: number;- check: (page: Page) => number;-}--export interface Rubric {- entityType: PageType | 'default';- dimensions: CompletenessDimension[];-}--export interface CompletenessScore {- slug: string;- entityType: string;- score: number;- dimensionScores: Record<string, number>;- rubric: PageType | 'default';-}--// ----------------------------------------------------------------------------// Shared dimension helpers-// -----------------------------------------------------------------------------function hasTimelineEntries(page: Page): number {- const tl = (page.timeline ?? '').trim();- if (tl.length === 0) return 0;- const bulletCount = (tl.match(/^\s*-\s/gm) ?? []).length;- return bulletCount > 0 ? 1 : 0.5;-}--function hasCitations(page: Page): number {- const body = page.compiled_truth ?? '';- const count = (body.match(/\[Source:[^\]]*\]/g) ?? []).length;- const urlLinkCount = (body.match(/\]\(https?:\/\/[^)]+\)/g) ?? []).length;- const total = count + urlLinkCount;- if (total === 0) return 0;- if (total >= 3) return 1;- return total / 3;-}--function hasSourceUrls(page: Page): number {- const body = page.compiled_truth ?? '';- const urls = (body.match(/https?:\/\/[^\s)\]]+/g) ?? []).length;- if (urls === 0) return 0;- if (urls >= 2) return 1;- return 0.6;-}--function hasFrontmatterField(page: Page, keys: string[]): number {- const fm = page.frontmatter ?? {};- for (const k of keys) {- const v = fm[k];- if (typeof v === 'string' && v.trim().length > 0) return 1;- if (typeof v === 'number' && Number.isFinite(v)) return 1;- if (Array.isArray(v) && v.length > 0) return 1;- }- return 0;-}--function hasBacklinkHint(page: Page): number {- // Crude: count wikilinks out; a page that links out is much more likely- // to have inbound references. Real backlink count requires an engine call- // (we stay pure here). If the rubric needs engine-backed signal, a later- // variant of scorer can inject backlinkCount.- const body = page.compiled_truth ?? '';- const wikiLinks = (body.match(/\[[^\]]+\]\([^)]*\.md(?:#[^)]*)?\)/g) ?? []).length;- if (wikiLinks === 0) return 0;- if (wikiLinks >= 3) return 1;- return wikiLinks / 3;-}--function recencyScore(page: Page): number {- // Prefer frontmatter.last_verified → page.updated_at → 0.- const fm = page.frontmatter ?? {};- const verified = typeof fm.last_verified === 'string' ? parseDate(fm.last_verified) : null;- const updated = page.updated_at instanceof Date ? page.updated_at : null;- const reference = verified ?? updated;- if (!reference) return 0;- const ageDays = Math.floor((Date.now() - reference.getTime()) / (1000 * 60 * 60 * 24));- if (ageDays <= 90) return 1;- if (ageDays <= 180) return 0.7;- if (ageDays <= 365) return 0.4;- return 0.1;-}--function nonRedundancy(page: Page): number {- const body = page.compiled_truth ?? '';- if (body.length < 200) return 0.5;- const lines = body.split('\n').map(l => l.trim()).filter(l => l.length > 0);- if (lines.length === 0) return 0;- const unique = new Set(lines);- return unique.size / lines.length;-}--function hasTitle(page: Page): number {- // Coerce (issue #1939): a malformed YAML date/number title could be non-string.- return String(page.title ?? '').trim().length > 0 ? 1 : 0;-}--function hasBody(page: Page): number {- return (page.compiled_truth ?? '').trim().length > 0 ? 1 : 0;-}--function parseDate(s: string): Date | null {- const d = new Date(s);- return Number.isNaN(d.getTime()) ? null : d;-}--// ----------------------------------------------------------------------------// Seven core rubrics + default-// -----------------------------------------------------------------------------export const personRubric: Rubric = {- entityType: 'person',- dimensions: [- { name: 'has_role_and_company', weight: 0.20, check: p => hasFrontmatterField(p, ['role', 'title', 'company']) },- { name: 'has_source_urls', weight: 0.20, check: hasSourceUrls },- { name: 'has_timeline_entries', weight: 0.15, check: hasTimelineEntries },- { name: 'has_citations', weight: 0.15, check: hasCitations },- { name: 'has_backlinks', weight: 0.10, check: hasBacklinkHint },- { name: 'recency_score', weight: 0.10, check: recencyScore },- { name: 'non_redundancy', weight: 0.10, check: nonRedundancy },- ],-};--export const companyRubric: Rubric = {- entityType: 'company',- dimensions: [- { name: 'has_description', weight: 0.20, check: hasBody },- { name: 'has_founders', weight: 0.15, check: p => hasFrontmatterField(p, ['founders', 'founder', 'ceo']) },- { name: 'has_funding', weight: 0.15, check: p => hasFrontmatterField(p, ['funding', 'raised', 'round', 'investors']) },- { name: 'has_source_urls', weight: 0.15, check: hasSourceUrls },- { name: 'has_citations', weight: 0.15, check: hasCitations },- { name: 'has_employees_or_investors', weight: 0.10, check: hasBacklinkHint },- { name: 'recency_score', weight: 0.10, check: recencyScore },- ],-};--export const projectRubric: Rubric = {- entityType: 'project',- dimensions: [- { name: 'has_description', weight: 0.25, check: hasBody },- { name: 'has_owners', weight: 0.20, check: p => hasFrontmatterField(p, ['owner', 'owners', 'lead']) },- { name: 'has_timeline_entries', weight: 0.15, check: hasTimelineEntries },- { name: 'has_citations', weight: 0.15, check: hasCitations },- { name: 'has_status', weight: 0.15, check: p => hasFrontmatterField(p, ['status', 'state', 'phase']) },- { name: 'recency_score', weight: 0.10, check: recencyScore },- ],-};--export const dealRubric: Rubric = {- entityType: 'deal',- dimensions: [- { name: 'has_company', weight: 0.25, check: p => hasFrontmatterField(p, ['company', 'target']) },- { name: 'has_terms', weight: 0.25, check: p => hasFrontmatterField(p, ['terms', 'amount', 'valuation', 'round']) },- { name: 'has_date', weight: 0.15, check: p => hasFrontmatterField(p, ['date', 'closed', 'announced']) },- { name: 'has_source_urls', weight: 0.15, check: hasSourceUrls },- { name: 'has_citations', weight: 0.20, check: hasCitations },- ],-};--export const conceptRubric: Rubric = {- entityType: 'concept',- dimensions: [- { name: 'has_definition', weight: 0.35, check: hasBody },- { name: 'has_citations', weight: 0.30, check: hasCitations },- { name: 'has_examples', weight: 0.20, check: p => countListItems(p.compiled_truth) >= 2 ? 1 : countListItems(p.compiled_truth) / 2 },- { name: 'has_related', weight: 0.15, check: hasBacklinkHint },- ],-};--export const sourceRubric: Rubric = {- entityType: 'source',- dimensions: [- { name: 'has_url', weight: 0.35, check: p => hasFrontmatterField(p, ['url', 'link', 'source_url']) },- { name: 'has_author', weight: 0.20, check: p => hasFrontmatterField(p, ['author', 'authors', 'by']) },- { name: 'has_date', weight: 0.20, check: p => hasFrontmatterField(p, ['date', 'published', 'year']) },- { name: 'has_summary', weight: 0.25, check: hasBody },- ],-};--export const mediaRubric: Rubric = {- entityType: 'media',- dimensions: [- { name: 'has_type', weight: 0.20, check: p => hasFrontmatterField(p, ['media_type', 'type', 'format']) },- { name: 'has_url', weight: 0.25, check: p => hasFrontmatterField(p, ['url', 'link']) },- { name: 'has_title', weight: 0.20, check: hasTitle },- { name: 'has_date', weight: 0.15, check: p => hasFrontmatterField(p, ['date', 'published', 'recorded']) },- { name: 'has_transcript_or_summary', weight: 0.20, check: hasBody },- ],-};--export const defaultRubric: Rubric = {- entityType: 'default',- dimensions: [- { name: 'has_title', weight: 0.30, check: hasTitle },- { name: 'has_content', weight: 0.30, check: hasBody },- { name: 'has_source_urls', weight: 0.20, check: hasSourceUrls },- { name: 'has_citations', weight: 0.20, check: hasCitations },- ],-};--const RUBRICS_BY_TYPE = new Map<PageType | 'default', Rubric>([- ['person', personRubric],- ['company', companyRubric],- ['project', projectRubric],- ['deal', dealRubric],- ['concept', conceptRubric],- ['source', sourceRubric],- ['media', mediaRubric],- ['default', defaultRubric],-]);--// Validate rubric weights at module load (catches copy-paste bugs).-for (const [type, rubric] of RUBRICS_BY_TYPE) {- const sum = rubric.dimensions.reduce((acc, d) => acc + d.weight, 0);- if (Math.abs(sum - 1.0) > 1e-6) {- throw new Error(`Rubric for ${type} has dimension weights summing to ${sum}, not 1.0`);- }-}--// ----------------------------------------------------------------------------// Scorer-// -----------------------------------------------------------------------------export function scorePage(page: Page): CompletenessScore {- const rubric = RUBRICS_BY_TYPE.get(page.type as string) ?? defaultRubric;- const dimensionScores: Record<string, number> = {};- let total = 0;- for (const d of rubric.dimensions) {- const raw = clamp(d.check(page), 0, 1);- dimensionScores[d.name] = raw;- total += raw * d.weight;- }- return {- slug: page.slug,- entityType: page.type,- score: Math.round(total * 1000) / 1000,- dimensionScores,- rubric: rubric.entityType,- };-}--export function getRubric(type: PageType | string): Rubric {- const r = RUBRICS_BY_TYPE.get(type as string);- return r ?? defaultRubric;-}--function clamp(v: number, lo: number, hi: number): number {- if (!Number.isFinite(v)) return lo;- return Math.max(lo, Math.min(hi, v));-}--function countListItems(body: string): number {- return (body.match(/^\s*[-*]\s/gm) ?? []).length;-}diff --git a/src/core/eval-capture-graph.ts b/src/core/eval-capture-graph.tsdeleted file mode 100644index 93fffc4712..0000000000Binary files a/src/core/eval-capture-graph.ts and /dev/null differdiff --git a/src/core/eval-contradictions/calibration-join.ts b/src/core/eval-contradictions/calibration-join.tsdeleted file mode 100644index 7c5a949ba8..0000000000--- a/src/core/eval-contradictions/calibration-join.ts+++ /dev/null@@ -1,102 +0,0 @@-/**- * v0.36.1.0 (T9 / E3) — calibration-aware contradictions.- *- * The v0.32.6 contradictions probe surfaces pairs of takes/chunks that- * conflict across time. E3: cross-reference each finding against the- * user's active calibration profile so the operator sees WHICH bias- * pattern (if any) the contradiction fits.- *- * Pure functions only. No DB writes, no LLM calls. The probe runner- * imports tagFindingWithCalibration() and applies it to each finding- * before emitting. When no profile exists, the helper returns null and- * the runner emits the unchanged finding (regression R2 — no calibration- * profile → contradictions output is byte-identical to v0.32.6).- */--import type { ContradictionFinding } from './types.ts';-import type { CalibrationProfileRow } from '../../commands/calibration.ts';--/**- * The bias-tag context the runner can splice into the output. Keep this- * shape forward-compatible — additive only.- */-export interface CalibrationJoinTag {- /** The active bias tag this contradiction matches (kebab-case slug). */- bias_tag: string;- /** One-line explanation surface for the operator. */- context: string;-}--/**- * Tag a finding with the bias context if it matches an active pattern.- * Returns null when no calibration profile is present OR no tags match.- *- * Match heuristic (v0.36.1.0 ship-state):- * - Each bias tag has a structure like 'over-confident-geography' or- * 'late-on-macro-tech' — axis-then-domain.- * - We compute a domain hint from the finding's pair members (slug- * prefix + holder + verdict). The finding matches a tag when the- * domain hint substring appears in the tag.- * - Match is fuzzy by design; the contradictions probe doesn't have- * structured domain metadata yet, and the bias tags are kebab-case- * slugs that need a textual surface. Future v0.37+: structured- * domain on takes (Hindsight-style enum) tightens this.- */-export function tagFindingWithCalibration(- finding: ContradictionFinding,- profile: CalibrationProfileRow | null,-): CalibrationJoinTag | null {- if (!profile || profile.active_bias_tags.length === 0) return null;- const hint = computeDomainHint(finding).toLowerCase();- if (!hint) return null;- for (const tag of profile.active_bias_tags) {- if (tag.toLowerCase().includes(hint)) {- return {- bias_tag: tag,- context: buildBiasContextString(tag, finding, profile),- };- }- }- return null;-}--/**- * Compute a domain hint from a finding's pair members. Uses slug prefixes- * (people/, companies/, deals/, daily/, ...) + holder + verdict text.- * Pure; deterministic.- */-export function computeDomainHint(finding: ContradictionFinding): string {- // Slug-prefix → axis-domain candidates. Ordered by specificity.- const candidates: string[] = [];- for (const member of [finding.a, finding.b]) {- const slug = member.slug.toLowerCase();- // Pull the kebab-cased segment most likely to match a bias-tag domain.- if (slug.startsWith('wiki/companies/') || slug.startsWith('companies/')) candidates.push('hiring', 'market-timing');- if (slug.startsWith('wiki/people/') || slug.startsWith('people/')) candidates.push('founder-behavior', 'hiring');- if (slug.startsWith('wiki/deals/') || slug.startsWith('deals/')) candidates.push('market-timing');- if (slug.startsWith('wiki/macro') || slug.includes('/macro/') || slug.includes('macro-')) candidates.push('macro');- if (slug.startsWith('wiki/geography') || slug.includes('/geography/') || slug.includes('geography-')) candidates.push('geography');- if (slug.startsWith('wiki/tactics') || slug.includes('/tactics/') || slug.includes('tactics-')) candidates.push('tactics');- if (slug.startsWith('wiki/ai/') || slug.includes('/ai-') || slug.includes('-ai-')) candidates.push('ai');- }- // Holder hint: 'world' takes vs 'people/...' takes give different bias surfaces.- for (const member of [finding.a, finding.b]) {- if (member.holder && member.holder.startsWith('people/')) candidates.push('founder-behavior');- }- // Return the first candidate (most specific match shown first).- return candidates[0] ?? '';-}--/** One-line operator-facing string. */-export function buildBiasContextString(- tag: string,- finding: ContradictionFinding,- profile: CalibrationProfileRow,-): string {- const brierStr = profile.brier !== null ? ` (Brier ${profile.brier.toFixed(2)})` : '';- return (- `This contradiction fits your active bias pattern "${tag}"${brierStr}. ` +- `Verdict: ${finding.verdict}; severity: ${finding.severity}. ` +- `Consider reviewing both sides through the lens of that pattern.`- );-}diff --git a/src/core/extract/rollup-writer.ts b/src/core/extract/rollup-writer.tsindex 791eb13151..93874a2433 100644--- a/src/core/extract/rollup-writer.ts+++ b/src/core/extract/rollup-writer.ts@@ -178,11 +178,3 @@ function rollupErrorLogOnce(kind: string, day: string, msg: string): void {`[extract-rollup] write failed (best-effort; audit JSONL remains source of truth): ${msg}`,);}--/**- * Test seam: clear the logged-errors set so repeated test invocations- * surface stderr each time.- */-export function _resetRollupErrorLogForTests(): void {- _loggedRollupErrors.clear();-}diff --git a/src/core/fail-improve.ts b/src/core/fail-improve.tsdeleted file mode 100644index 8d91dd31fe..0000000000--- a/src/core/fail-improve.ts+++ /dev/null@@ -1,287 +0,0 @@-/**- * Fail-improve loop: deterministic-first, LLM-fallback pattern.- *- * Tries deterministic code first (regex, parser). If it fails, falls back- * to LLM. Logs every fallback as a JSONL entry for future improvement.- * Over time, failure patterns reveal which regex rules are missing.- *- * Each operation writes to its own JSONL file (~/.gbrain/fail-improve/{operation}.jsonl).- * Atomic append assumption: individual log entries are <1KB, well under OS page size.- * No cross-operation file conflicts since each operation has its own file.- */--import { appendFileSync, readFileSync, existsSync, mkdirSync, writeFileSync, renameSync } from 'fs';-import { join, dirname } from 'path';-import { gbrainPath } from './config.ts';--// ----------------------------------------------------------------------------// Types-// -----------------------------------------------------------------------------export interface FailureEntry {- timestamp: string;- operation: string;- input: string;- deterministic_result: string | null;- llm_result: string | null;- metadata?: Record<string, any>;-}--export interface FailureAnalysis {- operation: string;- total_failures: number;- failures_by_pattern: Map<string, number>;- total_improvements: number;- last_improvement?: string;- total_calls: number;- deterministic_hits: number;- deterministic_rate: number;-}--export interface TestCase {- name: string;- input: string;- expected: string;- source: 'fail-improve-loop';-}--// Lazy: GBRAIN_HOME may be set after module load, so resolve at call time.-const getLogDir = () => gbrainPath('fail-improve');-const MAX_ENTRIES = 1000;--// ----------------------------------------------------------------------------// AbortSignal helpers-// -----------------------------------------------------------------------------/**- * Construct a DOM-style AbortError. Matches what fetch() throws on- * AbortController.abort(), so downstream callers that already branch on- * `err.name === 'AbortError'` work without change.- */-function makeAbortError(where: string): Error {- const err = new Error(`Aborted at ${where}`);- err.name = 'AbortError';- return err;-}--function isAbortError(err: unknown): boolean {- return !!err && typeof err === 'object' &&- ('name' in err && (err as { name: string }).name === 'AbortError');-}--// ----------------------------------------------------------------------------// Core class-// -----------------------------------------------------------------------------export class FailImproveLoop {- private logDir: string;-- constructor(logDir?: string) {- this.logDir = logDir || getLogDir();- }-- /**- * Try deterministic first, fall back to LLM, log mismatches.- * When both fail, throws the LLM error and logs both failures.- *- * Optional `opts.signal` threads an AbortSignal through the flow:- * - Checked before the deterministic call and again before the LLM call.- * - Forwarded to both callbacks as an optional second arg. Existing- * callbacks that take only `(input: string)` are structurally compatible- * and ignore the extra arg (TypeScript widens on call).- * - When aborted, throws an Error with name='AbortError' (standard Web- * AbortController semantics). Does not write a failure log entry for- * aborted runs since they're not informative.- */- async execute<T>(- operation: string,- input: string,- deterministicFn: (input: string, signal?: AbortSignal) => T | null,- llmFallbackFn: (input: string, signal?: AbortSignal) => Promise<T>,- opts?: { signal?: AbortSignal },- ): Promise<T> {- // Pre-flight abort check- if (opts?.signal?.aborted) throw makeAbortError('fail-improve:before-start');-- // Track call- this.incrementCallCount(operation, 'total');-- // Try deterministic first- const deterResult = deterministicFn(input, opts?.signal);- if (deterResult !== null && deterResult !== undefined) {- this.incrementCallCount(operation, 'deterministic');- return deterResult;- }-- // Abort check between deterministic miss and LLM call- if (opts?.signal?.aborted) throw makeAbortError('fail-improve:before-fallback');-- // Deterministic failed, try LLM- let llmResult: T;- try {- llmResult = await llmFallbackFn(input, opts?.signal);- } catch (llmError: any) {- // Abort propagates unlogged — not a useful failure record- if (isAbortError(llmError)) throw llmError;-- // Both failed — log both, throw LLM error- this.logFailure({- timestamp: new Date().toISOString(),- operation,- input: input.slice(0, 1000),- deterministic_result: null,- llm_result: `error: ${llmError.message || String(llmError)}`,- metadata: { cascade_failure: true },- });- throw llmError;- }-- // Log the failure (deterministic failed, LLM succeeded)- this.logFailure({- timestamp: new Date().toISOString(),- operation,- input: input.slice(0, 1000),- deterministic_result: null,- llm_result: JSON.stringify(llmResult).slice(0, 1000),- });-- return llmResult;- }-- /** Append a failure entry to the operation's JSONL file. */- logFailure(entry: FailureEntry): void {- const filePath = this.getLogPath(entry.operation);- this.ensureDir(filePath);- const line = JSON.stringify(entry) + '\n';- appendFileSync(filePath, line, 'utf-8');- this.rotateIfNeeded(entry.operation);- }-- /** Read all failures for an operation. */- getFailures(operation: string): FailureEntry[] {- const filePath = this.getLogPath(operation);- if (!existsSync(filePath)) return [];- try {- return readFileSync(filePath, 'utf-8')- .split('\n')- .filter(Boolean)- .map(line => {- try { return JSON.parse(line); }- catch { return null; }- })- .filter(Boolean) as FailureEntry[];- } catch {- return [];- }- }-- /** Group failures by a key derived from the input (first 50 chars). */- getFailuresByPattern(operation: string): Map<string, FailureEntry[]> {- const failures = this.getFailures(operation);- const groups = new Map<string, FailureEntry[]>();- for (const f of failures) {- const key = f.input.slice(0, 50).replace(/\s+/g, ' ').trim();- if (!groups.has(key)) groups.set(key, []);- groups.get(key)!.push(f);- }- return groups;- }-- /** Analyze failures and compute metrics. */- analyzeFailures(operation: string): FailureAnalysis {- const failures = this.getFailures(operation);- const patterns = this.getFailuresByPattern(operation);- const stats = this.getCallCounts(operation);- const improvements = this.getImprovements(operation);-- return {- operation,- total_failures: failures.length,- failures_by_pattern: new Map([...patterns.entries()].map(([k, v]) => [k, v.length])),- total_improvements: improvements.length,- last_improvement: improvements.length > 0 ? improvements[improvements.length - 1].timestamp : undefined,- total_calls: stats.total,- deterministic_hits: stats.deterministic,- deterministic_rate: stats.total > 0 ? stats.deterministic / stats.total : 0,- };- }-- /** Generate test cases from failure logs where LLM produced good results. */- generateTestCases(operation: string): TestCase[] {- const failures = this.getFailures(operation);- return failures- .filter(f => f.llm_result && !f.llm_result.startsWith('error:') && !f.metadata?.cascade_failure)- .map((f, i) => ({- name: `auto_${operation}_${i + 1}`,- input: f.input,- expected: f.llm_result!,- source: 'fail-improve-loop' as const,- }));- }-- /** Log an improvement (when a new deterministic pattern is added). */- logImprovement(operation: string, description: string): void {- const filePath = join(this.logDir, operation, 'improvements.json');- this.ensureDir(filePath);- let improvements: any[] = [];- if (existsSync(filePath)) {- try { improvements = JSON.parse(readFileSync(filePath, 'utf-8')); } catch {}- }- improvements.push({ timestamp: new Date().toISOString(), description });- writeFileSync(filePath, JSON.stringify(improvements, null, 2), 'utf-8');- }-- // -------------------------------------------------------------------------- // Private helpers- // --------------------------------------------------------------------------- private getLogPath(operation: string): string {- return join(this.logDir, `${operation}.jsonl`);- }-- private getCallCountPath(operation: string): string {- return join(this.logDir, `${operation}.counts.json`);- }-- private ensureDir(filePath: string): void {- const dir = dirname(filePath);- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });- }-- private incrementCallCount(operation: string, type: 'total' | 'deterministic'): void {- const filePath = this.getCallCountPath(operation);- this.ensureDir(filePath);- let counts = { total: 0, deterministic: 0 };- if (existsSync(filePath)) {- try { counts = JSON.parse(readFileSync(filePath, 'utf-8')); } catch {}- }- counts[type]++;- writeFileSync(filePath, JSON.stringify(counts), 'utf-8');- }-- private getCallCounts(operation: string): { total: number; deterministic: number } {- const filePath = this.getCallCountPath(operation);- if (!existsSync(filePath)) return { total: 0, deterministic: 0 };- try { return JSON.parse(readFileSync(filePath, 'utf-8')); }- catch { return { total: 0, deterministic: 0 }; }- }-- private getImprovements(operation: string): Array<{ timestamp: string; description: string }> {- const filePath = join(this.logDir, operation, 'improvements.json');- if (!existsSync(filePath)) return [];- try { return JSON.parse(readFileSync(filePath, 'utf-8')); }- catch { return []; }- }-- private rotateIfNeeded(operation: string): void {- const filePath = this.getLogPath(operation);- if (!existsSync(filePath)) return;- const content = readFileSync(filePath, 'utf-8');- const lines = content.split('\n').filter(Boolean);- if (lines.length > MAX_ENTRIES) {- // Keep last MAX_ENTRIES entries- const kept = lines.slice(-MAX_ENTRIES);- writeFileSync(filePath, kept.join('\n') + '\n', 'utf-8');- }- }-}diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex e5772783d2..8bcaec3288 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -1939,15 +1939,6 @@ async function maybeOcr(return { text, successful };}-/** #3973: body of maybeOcr past the opt-in check; exported for budget tests. */-export async function _maybeOcrGatedForTests(- engine: BrainEngine,- imgBuf: Buffer,- mime: string,-): Promise<string> {- return maybeOcrGated(engine, imgBuf, mime);-}-async function maybeOcrGated(engine: BrainEngine,imgBuf: Buffer,diff --git a/src/core/minions/batch-projection.ts b/src/core/minions/batch-projection.tsdeleted file mode 100644index 45e16c375a..0000000000--- a/src/core/minions/batch-projection.ts+++ /dev/null@@ -1,186 +0,0 @@-/**- * v0.41 D4 — submit-time cost + duration projection for batch jobs.- *- * Closes the "wake up to a $300 Anthropic bill" failure mode at the source.- * Before `gbrain jobs submit` queues a batch, this projection prints- * "this batch will take ~30 min and cost ~$2.40 at current cap of 32".- * TTY users get a confirmation prompt above the configurable threshold;- * cron / non-TTY callers see the projection on stderr and proceed.- *- * Math is deliberately rough — heavy-tailed (codex pass-2 #11) so we- * carry a ±30% confidence band rather than pretending precision.- *- * Cold-start fallback (no historical jobs for the model/name): model-- * default per-token pricing + 5s mean latency estimate. Operators see- * `(no history; estimate is a wide guess)` so they don't trust the- * number more than it deserves.- *- * Unknown model: returns the `cost_estimate_unavailable` tagged variant- * with the model name. The `--budget-usd` flag refuses to gate against- * an unavailable cost estimate; same precedent as cross-modal-eval.- */--import { ANTHROPIC_PRICING } from '../anthropic-pricing.ts';-import { splitProviderModelId } from '../model-id.ts';--export interface RecentJobStats {- /** How many jobs informed this window. 0 → cold start. */- sample_size: number;- /** Mean wall-clock duration per job. ms. Undefined when cold start. */- mean_latency_ms?: number;- /** Mean USD cost per job. Undefined when cold start OR cost unavailable. */- mean_cost_usd?: number;- /** Standard deviation of cost per job. Used for ±band. */- stddev_cost_usd?: number;- /** Effective concurrency seen recently (min of worker pool + lease cap). */- effective_concurrency: number;- /** Lease cap headroom; informational. */- lease_headroom?: number;-}--export interface BatchProjection {- /** Total wall-clock estimate in ms. */- total_duration_ms: number;- /** Total cost estimate USD. NaN-safe; null when unknown model. */- total_cost_usd: number | null;- /** ±USD band (≈30% of cost OR derived from sample stddev). */- cost_band_usd: number | null;- /** ±ms band on duration. */- duration_band_ms: number;- /** Concurrency used for the math. */- effective_concurrency: number;- /** True when no historical data was available; estimate is a wide guess. */- cold_start: boolean;- /** When non-null, model name that has no pricing entry. */- unknown_model?: string;- /** Suggested cap-raise (informational; printed in stderr). */- raise_cap_hint?: string;-}--/**- * Resolve per-token cost for a model. Returns null for unknown models.- * Conservative: uses output-side pricing as a tight upper bound when- * we don't have per-call usage stats yet.- *- * v0.41.21.0: routes through splitProviderModelId so slash-prefixed ids- * (`anthropic/claude-sonnet-4-6`) strip to the bare model name. Pre-fix- * the inline `bareModel(model)` helper only handled `:`-form.- */-function modelDefaultMeanCostUsd(model: string): number | null {- // Match the alias map's behavior loosely: bare names + the few we know.- const bare = splitProviderModelId(model).model;- const p = ANTHROPIC_PRICING[bare];- if (!p) return null;- // Assume a typical subagent turn: ~2k input + ~1k output tokens.- // Heavy bound; real avgs will be smaller for simple jobs, larger for- // tool-loop heavy jobs. The cold-start `(no history)` annotation tells- // the operator the number is approximate.- const COLD_INPUT = 2000;- const COLD_OUTPUT = 1000;- return (COLD_INPUT * p.input + COLD_OUTPUT * p.output) / 1_000_000;-}--const COLD_LATENCY_MS = 5000;--export interface ProjectBatchInput {- job_count: number;- /** `provider:model` or bare model id. Used for pricing lookup. */- model: string;- stats: RecentJobStats;- /** Current rate-lease cap; used for the raise-cap hint. */- current_lease_cap: number;-}--export function projectBatch(input: ProjectBatchInput): BatchProjection {- const { job_count, model, stats, current_lease_cap } = input;- const bare = splitProviderModelId(model).model;- const cold = stats.sample_size === 0;-- // Mean latency: historical → use it. Cold → 5s guess.- const meanLatencyMs = stats.mean_latency_ms ?? COLD_LATENCY_MS;-- // Mean cost: historical → use it. Cold → model-default guess. Unknown- // model → return the tagged variant.- let meanCostUsd: number | null = stats.mean_cost_usd ?? modelDefaultMeanCostUsd(model);- if (meanCostUsd === null && !(bare in ANTHROPIC_PRICING)) {- // Unknown model — projection lacks a cost surface.- const concurrency = Math.max(1, Math.min(stats.effective_concurrency, current_lease_cap));- return {- total_duration_ms: Math.ceil((job_count / concurrency) * meanLatencyMs),- total_cost_usd: null,- cost_band_usd: null,- duration_band_ms: Math.ceil(meanLatencyMs * 0.5),- effective_concurrency: concurrency,- cold_start: cold,- unknown_model: bare,- };- }- if (meanCostUsd === null) meanCostUsd = 0; // defensive; shouldn't reach-- // Effective concurrency is min of worker pool seen recently + lease cap.- const concurrency = Math.max(1, Math.min(stats.effective_concurrency, current_lease_cap));-- const totalDurationMs = Math.ceil((job_count / concurrency) * meanLatencyMs);- const totalCostUsd = job_count * meanCostUsd;-- // Confidence band: when we have stddev, use it (×1.96 ≈ 95%). Cold- // start or no stddev → ±30% blanket.- const costBand = stats.stddev_cost_usd- ? job_count * stats.stddev_cost_usd * 1.96- : totalCostUsd * 0.30;- const durationBand = totalDurationMs * 0.30;-- // Raise-cap hint when lease cap is the binding constraint. If raising- // the cap by 4x would meaningfully shrink wall-clock, suggest it.- let raise_cap_hint: string | undefined;- if (stats.lease_headroom !== undefined && stats.lease_headroom <= 0.1 && current_lease_cap < 128) {- const suggestedCap = Math.min(current_lease_cap * 4, 128);- const projectedFasterMs = Math.ceil((job_count / Math.min(suggestedCap, stats.effective_concurrency)) * meanLatencyMs);- if (projectedFasterMs < totalDurationMs * 0.75) {- raise_cap_hint =- `raise GBRAIN_ANTHROPIC_MAX_INFLIGHT to ${suggestedCap} to finish in ~${Math.ceil(projectedFasterMs / 60_000)}min`;- }- }-- return {- total_duration_ms: totalDurationMs,- total_cost_usd: totalCostUsd,- cost_band_usd: costBand,- duration_band_ms: durationBand,- effective_concurrency: concurrency,- cold_start: cold,- raise_cap_hint,- };-}--/**- * Format a projection as a human-readable single line for stderr / TTY.- * Matches the style of the doctor + jobs stats output: concise, with- * confidence band when meaningful, with the paste-ready hint when- * applicable.- */-export function formatProjection(p: BatchProjection): string {- const mins = Math.max(1, Math.ceil(p.total_duration_ms / 60_000));- const minsBand = Math.ceil(p.duration_band_ms / 60_000);- if (p.unknown_model) {- return `[batch] est duration ~${mins}min (±${minsBand}min) at concurrency=${p.effective_concurrency}; cost estimate unavailable (model "${p.unknown_model}" not in pricing maps).`;- }- const dollars = (p.total_cost_usd ?? 0).toFixed(2);- const dollarsBand = (p.cost_band_usd ?? 0).toFixed(2);- const coldNote = p.cold_start ? ' (no history; estimate is a wide guess)' : '';- const hint = p.raise_cap_hint ? ` — ${p.raise_cap_hint}` : '';- return `[batch] est cost ~$${dollars} (±$${dollarsBand}), est duration ~${mins}min (±${minsBand}min) at concurrency=${p.effective_concurrency}${coldNote}${hint}`;-}--/**- * Threshold gating: should the TTY prompt for confirmation?- * Defaults: prompt above $5 OR 30min. Overridable via env vars- * matching the plan's spec.- */-export function shouldPromptAtThreshold(p: BatchProjection): boolean {- const usdThreshold = Number(process.env.GBRAIN_BATCH_PROMPT_THRESHOLD_USD ?? '5');- const minThreshold = Number(process.env.GBRAIN_BATCH_PROMPT_THRESHOLD_MIN ?? '30');- const usdOverThreshold = (p.total_cost_usd ?? 0) >= usdThreshold;- const minutesOverThreshold = p.total_duration_ms >= minThreshold * 60_000;- return usdOverThreshold || minutesOverThreshold;-}diff --git a/src/core/minions/budget-tracker.ts b/src/core/minions/budget-tracker.tsdeleted file mode 100644index a9952316aa..0000000000--- a/src/core/minions/budget-tracker.ts+++ /dev/null@@ -1,291 +0,0 @@-/**- * v0.41 D5 — `--budget-usd N` enforcement via reservation pattern (Eng D7 + D10).- *- * Closes the "wake up to a $300 Anthropic bill" failure mode all the way:- * D4 (batch-projection) shows the cost UP FRONT; D5 enforces a hard- * ceiling at runtime. Together they make "fire-and-forget batches" a- * real promise, not honor system.- *- * Reservation pattern (Eng D7, eng-review pass 2 — codex caught CAS-only- * could overspend across N parallel children of one budget owner):- *- * 1. Worker calls `reserveBudget(ownerId, expectedMaxTurnCostCents)`- * BEFORE each turn.- * 2. SQL UPDATE with CAS: `WHERE budget_remaining_cents >= cost- * RETURNING balance`. On miss → BudgetExhausted thrown.- * 3. On turn return → `refundBudget(ownerId, unspentCents)`.- *- * Even with N concurrent children, parallel CAS UPDATEs serialize at the- * row level — the worst-case overspend is bounded by the per-turn- * reservation amount (NOT N × turn-cost as CAS-only would be).- *- * Eng D10 NULL-bypass (codex pass-3 #3 + #4): jobs without a budget- * owner skip reservation entirely. Disambiguation via the immutable- * `budget_root_owner_id` denormalized column — when the FK- * `budget_owner_job_id` is NULL but `budget_root_owner_id` is set, the- * owner was DELETED (not "never had a budget"); throw `BudgetOwnerDeleted`- * so the child halts cleanly.- *- * Recursive halt (codex pass-2 #3): when owner balance hits 0, the worker- * walks `WHERE budget_owner_job_id = X AND status IN ('waiting','delayed')`- * to flip the entire subtree to `dead` with reason `budget_exhausted`.- *- * Audit (Eng D8 / codex pass-3 #7): every reserve/refund/lost/halted- * event writes one row to `minion_budget_log` with denormalized model +- * owner context so post-prune forensic queries still work.- */--import type { BrainEngine } from '../engine.ts';--/** Status of a reservation attempt. */-export type ReservationOutcome =- | { kind: 'reserved'; new_balance_cents: number; reserved_cents: number }- | { kind: 'exhausted'; balance_at_attempt: number; requested_cents: number }- | { kind: 'no_budget' } // job has no owner; bypass entirely (Eng D10)- | { kind: 'owner_deleted'; root_owner_id: number }; // pruned mid-batch--/** Throw to signal budget exhaustion to the worker / subagent handler. */-export class BudgetExhausted extends Error {- constructor(public owner_id: number, public balance_at_attempt_cents: number) {- super(`budget owner ${owner_id} exhausted: balance ${balance_at_attempt_cents} cents`);- this.name = 'BudgetExhausted';- }-}--/** Throw when the budget owner row was deleted mid-batch (Eng D10). */-export class BudgetOwnerDeleted extends Error {- constructor(public root_owner_id: number) {- super(`budget owner ${root_owner_id} was deleted; child cannot continue safely`);- this.name = 'BudgetOwnerDeleted';- }-}--/** What we learn about a job's budget ownership at reservation time. */-export interface BudgetOwnerInfo {- job_id: number;- budget_owner_job_id: number | null;- budget_root_owner_id: number | null;- budget_remaining_cents: number | null;-}--/**- * Look up budget ownership for a job. Returns 'no_budget' when neither- * the FK nor the denormalized root is set. Returns 'owner_deleted' when- * the denormalized root is set but the FK is NULL (owner was pruned).- */-export async function getBudgetOwner(- engine: BrainEngine,- jobId: number,-): Promise<BudgetOwnerInfo | null> {- const rows = await engine.executeRaw<BudgetOwnerInfo>(- `SELECT id AS job_id, budget_owner_job_id, budget_root_owner_id, budget_remaining_cents- FROM minion_jobs WHERE id = $1`,- [jobId],- );- return rows[0] ?? null;-}--/**- * Set the budget on the OWNER job (the parent). Called when an operator- * submits `gbrain agent run ... --budget-usd N`. Sets budget_remaining_cents- * on the owner row AND populates budget_root_owner_id to its own id (self-- * reference) so subsequent children inherit it.- */-export async function setOwnerBudget(- engine: BrainEngine,- ownerJobId: number,- budgetUsd: number,-): Promise<void> {- const cents = Math.round(budgetUsd * 100);- await engine.executeRaw(- `UPDATE minion_jobs- SET budget_remaining_cents = $2,- budget_owner_job_id = $1,- budget_root_owner_id = $1- WHERE id = $1`,- [ownerJobId, cents],- );-}--/**- * Inherit budget ownership at child-submit time. Call from the path- * that submits a child of a budget-bearing parent (or grandparent). The- * child's budget_owner_job_id + budget_root_owner_id mirror the parent's,- * not the parent's own id. Same-row UPDATE; cheap.- *- * Children DO NOT copy budget_remaining_cents — only the owner row holds- * spendable balance. Codex pass-3 #5 caught the contradiction in the- * original plan that suggested copying balance.- */-export async function inheritBudgetOwner(- engine: BrainEngine,- childJobId: number,- parentJobId: number,-): Promise<void> {- await engine.executeRaw(- `UPDATE minion_jobs SET- budget_owner_job_id = (SELECT COALESCE(budget_owner_job_id, NULL) FROM minion_jobs WHERE id = $2),- budget_root_owner_id = (SELECT COALESCE(budget_root_owner_id, NULL) FROM minion_jobs WHERE id = $2)- WHERE id = $1`,- [childJobId, parentJobId],- );-}--/**- * Reserve `expected_max_turn_cost_cents` from the budget owner BEFORE- * the turn runs. CAS guarantees no overspend: parallel reservations- * serialize at the row level.- *- * Eng D10 NULL-bypass: jobs without an owner return 'no_budget' and- * the worker SHOULD proceed without budget gating.- *- * Eng D10 deleted-owner disambiguation: when FK is NULL but the- * denormalized root is set, return 'owner_deleted' and the worker- * SHOULD halt cleanly.- */-export async function reserveBudget(- engine: BrainEngine,- childJobId: number,- expectedMaxTurnCostCents: number,-): Promise<ReservationOutcome> {- const info = await getBudgetOwner(engine, childJobId);- if (!info) {- // Job row vanished — shouldn't happen mid-claim but defensive.- return { kind: 'no_budget' };- }-- // Eng D10 disambiguation.- if (info.budget_owner_job_id === null) {- if (info.budget_root_owner_id !== null) {- return { kind: 'owner_deleted', root_owner_id: info.budget_root_owner_id };- }- return { kind: 'no_budget' };- }-- const rows = await engine.executeRaw<{ budget_remaining_cents: number }>(- `UPDATE minion_jobs- SET budget_remaining_cents = budget_remaining_cents - $2- WHERE id = $1 AND budget_remaining_cents >= $2- RETURNING budget_remaining_cents`,- [info.budget_owner_job_id, expectedMaxTurnCostCents],- );- if (rows.length === 0) {- // CAS miss — owner exhausted. Read current balance for the audit row.- const peek = await engine.executeRaw<{ budget_remaining_cents: number }>(- `SELECT budget_remaining_cents FROM minion_jobs WHERE id = $1`,- [info.budget_owner_job_id],- );- const balance = peek[0]?.budget_remaining_cents ?? 0;- await logBudgetEvent(engine, {- job_id: childJobId,- owner_id: info.budget_owner_job_id,- event_type: 'halted',- cents_delta: 0,- });- return { kind: 'exhausted', balance_at_attempt: balance, requested_cents: expectedMaxTurnCostCents };- }-- await logBudgetEvent(engine, {- job_id: childJobId,- owner_id: info.budget_owner_job_id,- event_type: 'reserved',- cents_delta: -expectedMaxTurnCostCents,- });- return { kind: 'reserved', new_balance_cents: rows[0]!.budget_remaining_cents, reserved_cents: expectedMaxTurnCostCents };-}--/**- * Refund unspent cents AFTER the turn returns. Pass the unspent amount- * (reserved - actual). Defensive: caller can pass 0 with no harm.- */-export async function refundBudget(- engine: BrainEngine,- childJobId: number,- ownerJobId: number,- refundCents: number,-): Promise<void> {- if (refundCents <= 0) return;- await engine.executeRaw(- `UPDATE minion_jobs SET budget_remaining_cents = budget_remaining_cents + $2- WHERE id = $1`,- [ownerJobId, refundCents],- );- await logBudgetEvent(engine, {- job_id: childJobId,- owner_id: ownerJobId,- event_type: 'refunded',- cents_delta: refundCents,- });-}--/**- * Recursive halt sweep — codex pass-2 #3. When the owner is exhausted,- * walk `budget_owner_job_id = X` and flip every waiting/delayed- * descendant to dead. Active jobs DO NOT get flipped here; their- * turn-boundary reserveBudget call will throw BudgetExhausted on the- * next turn (or, if mid-tool-dispatch, they complete the current turn- * cleanly and the next reservation fails).- *- * Returns the count of jobs halted.- */-export async function haltBudgetSubtree(- engine: BrainEngine,- ownerJobId: number,- reason: 'budget_exhausted' | 'owner_deleted',-): Promise<number> {- // Exclude the owner row itself — setOwnerBudget sets the owner's- // budget_owner_job_id to its own id (self-referencing so children can- // inherit via parent.budget_owner_job_id), which means the owner row- // would match its own subtree filter. The owner has its own state- // machine independent of budget halt; we just halt its DESCENDANTS.- const rows = await engine.executeRaw<{ id: number }>(- `UPDATE minion_jobs SET- status = 'dead',- error_text = $2,- finished_at = now(),- updated_at = now()- WHERE budget_owner_job_id = $1- AND id != $1- AND status IN ('waiting', 'delayed')- RETURNING id`,- [ownerJobId, `${reason}: parent ${ownerJobId} hit cap or was deleted`],- );- return rows.length;-}--/** Audit table row shape. Mirrors the columns from migration v94. */-export interface BudgetEventRecord {- job_id: number;- owner_id: number;- event_type: 'reserved' | 'refunded' | 'spent' | 'lost' | 'halted' | 'owner_deleted';- cents_delta: number;- turn_index?: number;- model?: string;-}--/** Best-effort write to minion_budget_log. Mirror of lease-pressure-audit. */-export async function logBudgetEvent(- engine: BrainEngine,- record: BudgetEventRecord,-): Promise<void> {- try {- await engine.executeRaw(- `INSERT INTO minion_budget_log- (job_id, owner_id, event_type, cents_delta, turn_index, model)- VALUES ($1, $2, $3, $4, $5, $6)`,- [- record.job_id,- record.owner_id,- record.event_type,- record.cents_delta,- record.turn_index ?? null,- record.model ?? null,- ],- );- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- process.stderr.write(- `[budget-tracker] WARN: audit write failed for job ${record.job_id}: ${msg}\n`,- );- }-}diff --git a/src/core/minions/lease-cap-controller.ts b/src/core/minions/lease-cap-controller.tsdeleted file mode 100644index 30efc2f278..0000000000--- a/src/core/minions/lease-cap-controller.ts+++ /dev/null@@ -1,285 +0,0 @@-/**- * v0.41 E5 (reframed per codex pass-1, corrected per codex pass-2 #9) —- * auto-adaptive rate-lease cap.- *- * Original E5 (pre-reframe) tuned WORKER concurrency. Codex pass-1 caught- * the fundamental design flaw: worker concurrency is downstream of the- * rate-lease. If the lease is full at 32 in-flight, easing worker- * concurrency from 10 to 5 just moves jobs from `active+bouncing` to- * `waiting` — same throughput. The adaptive knob has to be the LEASE CAP- * itself.- *- * Codex pass-2 #9 caught a sign error in the original lease-cap control- * law: my first draft said "ramp DOWN on bounces > 5/min OR 429s > 0.5/min."- * That's WRONG. Bounces happen when workers want more concurrency than the- * cap allows — internal queue pressure. Without upstream pushback (429s- * + latency unstable), bounces alone say "we're starving, raise the cap."- * The Eng D6 corrected control law:- *- * - Ramp DOWN: ONLY when upstream pushes back (429s > Y/min OR latency- * unstable). These are the "cap is too high" signals.- * - Ramp UP slow: 0 bounces + 0 429s + util > 50% + latency stable.- * We have headroom + jobs running; can probably go higher.- * - Ramp UP fast: bounces > X/min + 0 429s + latency stable. Workers- * are starving inside our artificial cap; raise it.- * - Deadband: middle region (some pressure but mixed signals).- *- * Per-tick election via tryWithDbElection (Eng D9): only one worker per- * cluster runs the WRITE side per tick. All workers READ the lease cap- * fresh from the DB on every acquire (short-TTL cache).- *- * Latency signal source: UPSTREAM (Anthropic SDK round-trip), NOT local- * DB query latency. Local DB latency is noise; upstream latency is the- * actual congestion signal. Codex pass-3 #2.- */--import type { BrainEngine } from '../engine.ts';-import { tryWithDbElection } from '../db-lock.ts';--/** Rolling-window stats the controller reads each tick. */-export interface ControllerWindowStats {- /** How many lease-full bounces happened in `window_ms`. */- bounce_count: number;- /** How many upstream 429s happened in `window_ms` (per worker, sum). */- upstream_429_count: number;- /** Mean (active / max_concurrent) over the window. NaN-safe → 0. */- lease_utilization: number;- /** Upstream round-trip latency stability. True when p95/p50 ratio < 2 in window. */- latency_stable: boolean;- /** Window size used for the rate calculations. ms. */- window_ms: number;-}--export interface ControllerOpts {- /** Lease cap to start from on first tick (matches GBRAIN_ANTHROPIC_MAX_INFLIGHT default). */- initial_cap: number;- /** Per-step ramp-up amount (additive). */- ramp_up_step: number;- /** Per-step ramp-down amount (additive; asymmetric > ramp_up_step for AIMD-style backoff). */- ramp_down_step: number;- /** Lower bound — never below this. */- min_floor: number;- /** Upper bound — never above this. CLI flag wins over env override (codex pass-2 #9). */- max_ceiling: number;- /** Bounce-rate threshold to consider "workers are starving" (events / min). */- bounce_rate_starving_threshold: number;- /** 429-rate threshold to consider "upstream is pushing back" (events / min). */- upstream_429_threshold_per_min: number;- /** Lease-utilization threshold below which we don't ramp-up-slow (no headroom signal needed). */- utilization_ramp_threshold: number;-}--export const DEFAULT_CONTROLLER_OPTS: ControllerOpts = {- initial_cap: 32,- ramp_up_step: 4,- ramp_down_step: 8, // AIMD-style asymmetric: back off faster than ramp up- min_floor: 4,- max_ceiling: 128,- bounce_rate_starving_threshold: 1, // > 1 bounce/min with no upstream pushback = starving- upstream_429_threshold_per_min: 0.5,- utilization_ramp_threshold: 0.5,-};--/**- * Pure decision function: given current cap + window stats, what's the- * next cap? No I/O — fully testable for every signal combination.- *- * Decision tree (in order):- * 1. Upstream pushback (429s OR latency unstable) → ramp DOWN. ONLY- * time we shrink the cap; without this, the controller would crater- * cap during healthy bursts (codex pass-2 #9 caught this).- * 2. Workers starving (bounces > threshold + no upstream pushback) →- * ramp UP fast. Internal demand exceeding our artificial cap.- * 3. Headroom available (no bounces + no 429s + util > threshold +- * latency stable) → ramp UP slow. We have work flowing through- * and the upstream has room.- * 4. Otherwise → deadband (no change). Mixed signals = don't move.- */-export function nextLeaseCap(- current: number,- window: ControllerWindowStats,- opts: ControllerOpts = DEFAULT_CONTROLLER_OPTS,-): number {- const windowMin = Math.max(1e-6, window.window_ms / 60_000);- const bounceRatePerMin = window.bounce_count / windowMin;- const upstream429PerMin = window.upstream_429_count / windowMin;-- // 1. Ramp DOWN — upstream pushback. Either 429s OR latency-unstable.- // These are the only signals saying "cap is too high."- if (upstream429PerMin > opts.upstream_429_threshold_per_min || !window.latency_stable) {- return Math.max(current - opts.ramp_down_step, opts.min_floor);- }-- // 2. Ramp UP fast — workers are starving.- // Bounces > threshold AND no upstream pushback AND latency stable- // AND room to grow.- if (- bounceRatePerMin > opts.bounce_rate_starving_threshold &&- upstream429PerMin === 0 &&- window.latency_stable- ) {- return Math.min(current + opts.ramp_up_step, opts.max_ceiling);- }-- // 3. Ramp UP slow — no pressure but utilization shows we're using the cap.- // Probes for headroom: small step, low risk.- if (- bounceRatePerMin === 0 &&- upstream429PerMin === 0 &&- window.lease_utilization > opts.utilization_ramp_threshold &&- window.latency_stable- ) {- return Math.min(current + opts.ramp_up_step, opts.max_ceiling);- }-- // 4. Deadband — mixed signals or no work happening.- return current;-}--/**- * Read the controller window stats from the DB. Reads- * minion_lease_pressure_log + minion_jobs for the last `windowMs`.- *- * Pure-SQL function so the controller tick is one round-trip per source.- * Latency signal is approximate today (uses subagent job durations as a- * proxy — full upstream-latency tracking is filed as v0.42 follow-up).- */-export async function readControllerWindow(- engine: BrainEngine,- windowMs: number,-): Promise<ControllerWindowStats> {- // Bounce count over window. Pre-v93 brains return 0 silently.- let bounceCount = 0;- try {- const rows = await engine.executeRaw<{ count: string }>(- `SELECT count(*)::text AS count FROM minion_lease_pressure_log- WHERE bounced_at > now() - ($1::double precision * interval '1 millisecond')`,- [windowMs],- );- bounceCount = parseInt(rows[0]?.count ?? '0', 10);- } catch {- /* pre-v93 brain */- }-- // Upstream 429 count proxied via dead-letter classifier; this is rough- // until v0.42 wires direct SDK 429 events into a counter table. For now,- // count jobs whose last_error contains "429" or "rate limit" in the- // window (classifier reuse keeps the signal cheap).- let upstream429Count = 0;- try {- const rows = await engine.executeRaw<{ count: string }>(- `SELECT count(*)::text AS count FROM minion_jobs- WHERE finished_at > now() - ($1::double precision * interval '1 millisecond')- AND status IN ('failed', 'dead')- AND (error_text ILIKE '%429%' OR error_text ILIKE '%rate limit%')`,- [windowMs],- );- upstream429Count = parseInt(rows[0]?.count ?? '0', 10);- } catch {- /* DB unavailable */- }-- // Lease utilization: mean of (active_at_bounce / max_concurrent) per- // bounce row. When 0 bounces, utilization is 0 (no signal — controller- // treats this as "not enough data to ramp" → deadband).- let leaseUtilization = 0;- try {- const rows = await engine.executeRaw<{ util: string | number }>(- `SELECT COALESCE(AVG(active_at_bounce::double precision / NULLIF(max_concurrent, 0)), 0) AS util- FROM minion_lease_pressure_log- WHERE bounced_at > now() - ($1::double precision * interval '1 millisecond')`,- [windowMs],- );- const raw = parseFloat(String(rows[0]?.util ?? '0'));- leaseUtilization = Number.isFinite(raw) ? raw : 0;- } catch {- /* pre-v93 brain */- }-- // Latency stability proxy: subagent job durations in window. If we have- // at least 3 jobs with started_at + finished_at, compute p95/p50 ratio.- // If < 2, stable; if >= 2 or insufficient samples, NOT stable.- let latencyStable = true; // default true so first-tick controller can ramp up- try {- const rows = await engine.executeRaw<{ p50: number; p95: number; samples: string }>(- `SELECT- COALESCE(percentile_cont(0.50) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (finished_at - started_at))), 0) AS p50,- COALESCE(percentile_cont(0.95) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (finished_at - started_at))), 0) AS p95,- count(*)::text AS samples- FROM minion_jobs- WHERE status = 'completed'- AND name = 'subagent'- AND started_at IS NOT NULL- AND finished_at IS NOT NULL- AND finished_at > now() - ($1::double precision * interval '1 millisecond')`,- [windowMs],- );- const p50 = Number(rows[0]?.p50 ?? 0);- const p95 = Number(rows[0]?.p95 ?? 0);- const samples = parseInt(String(rows[0]?.samples ?? '0'), 10);- if (samples >= 3 && p50 > 0) {- latencyStable = (p95 / p50) < 2;- }- } catch {- /* DB unavailable; default stable */- }-- return {- bounce_count: bounceCount,- upstream_429_count: upstream429Count,- lease_utilization: leaseUtilization,- latency_stable: latencyStable,- window_ms: windowMs,- };-}--/**- * Read the current lease cap from config (write target for the controller).- * Falls back to opts.initial_cap when unset. Workers read this on every- * acquire so they pick up controller writes within the cache TTL.- */-export async function readCurrentLeaseCap(- engine: BrainEngine,- opts: ControllerOpts = DEFAULT_CONTROLLER_OPTS,-): Promise<number> {- try {- const v = await engine.getConfig('minions.lease_cap_current').catch(() => null);- if (v) {- const n = Number(v);- if (Number.isFinite(n) && n >= opts.min_floor && n <= opts.max_ceiling) return n;- }- } catch {- /* config unavailable */- }- return opts.initial_cap;-}--/**- * Write the new lease cap to config. Called by the elected worker after- * a controller decision. Workers reading via readCurrentLeaseCap pick up- * the new value within their cache TTL.- */-export async function writeLeaseCap(engine: BrainEngine, cap: number): Promise<void> {- await engine.setConfig('minions.lease_cap_current', String(cap));-}--/**- * Run one controller tick. Elects a single mutator via tryWithDbElection;- * other workers no-op. Returns the cap change tuple when elected, null- * otherwise.- */-export async function controllerTick(- engine: BrainEngine,- opts: ControllerOpts = DEFAULT_CONTROLLER_OPTS,- windowMs: number = 60_000,-): Promise<{ previous: number; next: number; changed: boolean } | null> {- return tryWithDbElection(engine, 'minions-lease-cap-controller', 2, async () => {- const window = await readControllerWindow(engine, windowMs);- const current = await readCurrentLeaseCap(engine, opts);- const next = nextLeaseCap(current, window, opts);- if (next !== current) {- await writeLeaseCap(engine, next);- }- return { previous: current, next, changed: next !== current };- });-}diff --git a/src/core/minions/self-fix.ts b/src/core/minions/self-fix.tsdeleted file mode 100644index 5549d4499d..0000000000--- a/src/core/minions/self-fix.ts+++ /dev/null@@ -1,275 +0,0 @@-/**- * v0.41 E6 (corrected per codex pass-2 #4 + pass-1 #11) — subagent- * failure-mode self-fix.- *- * When a subagent job terminates with a classified-recoverable failure- * AND chain depth < `minions.self_fix_max_depth` AND no prior self-fix- * at the same fingerprint, submit a follow-up job with the failure- * context as the user message. One layer of self-healing; capped so it- * cannot infinite-loop.- *- * **Classifier scope (codex pass-2 #4 — narrowed):**- *- * Only three buckets qualify for self-fix:- *- * prompt_too_long — semantic-aware reduction can fix- * tool_schema_mismatch — surface schema error to model, retry with valid input- * malformed_json — ask model to retry, response must be JSON- *- * EXPLICITLY NOT self-fixable:- * tool_crash — likely a real bug; masking via retry is worse- * tool_unavailable — registry config issue; retry won't help- * tool_permission — capability decision; needs human intervention- *- * **prompt_too_long reduction (codex pass-1 #11):** generic truncation- * deletes the actual task. Right strategy: walk the conversation, drop- * tool_result blocks first (largest non-task content), summarize older- * user/asst pairs via Haiku if still over, never delete the leaf user- * task. v0.41 ships the foundation (the policy + dispatch); full- * semantic reduction can land as a follow-up since the worst-case fix- * — truncate-then-fail — is still safe.- *- * **Chain depth:** configurable, default 2 (D15). Hard cap = N from- * config; chain-walk idempotency check prevents double self-fix at the- * same fingerprint.- *- * **Budget:** self-fix children inherit the budget owner (NOT a copy- * of remaining balance — codex pass-3 #5). Self-fix spend counts- * against the same owner as the parent.- *- * **Default state:** ON for fresh install AND on upgrade (D9 + D15).- * Off-switch: `gbrain config set minions.self_fix_enabled false`- * (global) or `data.no_self_fix: true` (per-job).- */--import type { BrainEngine } from '../engine.ts';-import type { MinionQueue } from './queue.ts';-import { classifyJobError, RECOVERABLE_CLUSTERS, type ErrorCluster } from './error-classify.ts';-import type { SubagentHandlerData } from './types.ts';-import { inheritBudgetOwner } from './budget-tracker.ts';--export interface SelfFixDecision {- /** Should we self-fix this failure? */- should_fix: boolean;- /** When should_fix=true, the cluster that matched. */- cluster?: ErrorCluster;- /** Reason text (always present; explains the decision). */- reason: string;-}--export interface SelfFixOpts {- /** Hard cap on chain depth. Default 2 (D15). */- max_depth?: number;- /** Global on/off (from config). Default true. */- enabled?: boolean;-}--const DEFAULT_OPTS: Required<SelfFixOpts> = {- max_depth: 2,- enabled: true,-};--/**- * Compute the chain depth of a job. Walks `parent_job_id` chain looking- * for ancestors with `data.is_self_fix_child = true`. Each such ancestor- * adds 1 to the depth.- */-export async function computeChainDepth(engine: BrainEngine, jobId: number): Promise<number> {- let depth = 0;- let cursor: number | null = jobId;- while (cursor !== null && depth < 10 /* safety cap */) {- const rows: Array<{ parent_job_id: number | null; data: unknown }> =- await engine.executeRaw(- `SELECT parent_job_id, data FROM minion_jobs WHERE id = $1`,- [cursor],- );- if (rows.length === 0) break;- const data = rows[0]!.data as Record<string, unknown> | null;- if (data && data.is_self_fix_child === true) {- depth += 1;- }- cursor = rows[0]!.parent_job_id;- }- return depth;-}--/**- * Decide whether a job should self-fix. Pure-ish (one SQL for depth);- * the decision logic itself is unit-testable in isolation.- */-export async function decideSelfFix(- engine: BrainEngine,- jobId: number,- jobData: SubagentHandlerData,- lastError: string | null,- opts: SelfFixOpts = {},-): Promise<SelfFixDecision> {- const merged = { ...DEFAULT_OPTS, ...opts };- if (!merged.enabled) {- return { should_fix: false, reason: 'self_fix_disabled_globally' };- }- if (jobData.no_self_fix) {- return { should_fix: false, reason: 'no_self_fix_flag_on_job' };- }- const cluster = classifyJobError(lastError);- if (!RECOVERABLE_CLUSTERS.has(cluster)) {- return { should_fix: false, cluster, reason: `cluster_not_recoverable:${cluster}` };- }- const depth = await computeChainDepth(engine, jobId);- if (depth >= merged.max_depth) {- return { should_fix: false, cluster, reason: `max_depth_reached:${depth}` };- }- return { should_fix: true, cluster, reason: `recoverable:${cluster}_at_depth_${depth}` };-}--/**- * Build the user-message text for the self-fix child. Per-cluster prep:- *- * prompt_too_long — truncate-then-prepend (v0.41 ships truncate;- * semantic reduction follow-up in v0.42)- * tool_schema_mismatch — surface schema error verbatim; ask for retry- * with valid arguments- * malformed_json — instruct model to respond with JSON only- */-export function buildSelfFixPrompt(- originalPrompt: string,- cluster: ErrorCluster,- lastError: string,-): string {- switch (cluster) {- case 'prompt_too_long': {- // Truncation strategy: keep first 1000 chars + last 2000 chars of- // the original prompt so the leaf task survives. Honest scope — v0.42- // will replace with semantic reduction (drop tool_results first,- // then Haiku-summarize older pairs).- const first = originalPrompt.slice(0, 1000);- const last = originalPrompt.length > 3000- ? '\n\n... (middle truncated) ...\n\n' + originalPrompt.slice(-2000)- : '';- return [- `[self-fix retry] Your previous attempt failed because the prompt was too long.`,- `Original task (truncated to fit context):`,- '',- first + last,- '',- `Provide your answer based on the truncated task. If critical context is missing, say so.`,- ].join('\n');- }- case 'tool_schema_mismatch':- return [- `[self-fix retry] Your previous attempt failed because a tool call had invalid arguments.`,- `Error: ${lastError}`,- '',- `Original task:`,- originalPrompt,- '',- `Retry the task. Double-check tool arguments against each tool's input_schema before calling.`,- ].join('\n');- case 'malformed_json':- return [- `[self-fix retry] Your previous attempt failed because the response was not valid JSON.`,- `Error: ${lastError}`,- '',- `Original task:`,- originalPrompt,- '',- `Retry. Your final response MUST be valid JSON — no prose, no markdown fences, no commentary.`,- ].join('\n');- default:- return `[self-fix retry] ${originalPrompt}`;- }-}--/**- * Submit a self-fix child job. Returns the submitted child or null on- * failure (audit row written either way). Caller has already decided- * via decideSelfFix; this just does the submission.- *- * Child inherits budget owner from parent (Eng D7 + D10).- */-export async function submitSelfFixChild(- engine: BrainEngine,- queue: MinionQueue,- parent: {- id: number;- data: SubagentHandlerData;- last_error: string;- },- cluster: ErrorCluster,-): Promise<{ child_id: number } | null> {- try {- const childPrompt = buildSelfFixPrompt(parent.data.prompt, cluster, parent.last_error);- const childData: SubagentHandlerData & { is_self_fix_child: true; self_fix_cluster: ErrorCluster } = {- ...parent.data,- prompt: childPrompt,- is_self_fix_child: true,- self_fix_cluster: cluster,- };- const child = await queue.add(- 'subagent',- childData as unknown as Record<string, unknown>,- { parent_job_id: parent.id, max_attempts: 1 }, // single attempt; if self-fix fails, that's terminal- { allowProtectedSubmit: true },- );- // Inherit budget owner if parent has one.- await inheritBudgetOwner(engine, child.id, parent.id);- // Audit row.- await logSelfFixEvent(engine, {- parent_id: parent.id,- child_id: child.id,- classifier_bucket: cluster,- chain_depth: 1, // depth from parent's perspective — refined at next-tier check- policy_applied: `buildSelfFixPrompt:${cluster}`,- outcome: 'submitted',- });- return { child_id: child.id };- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- process.stderr.write(`[self-fix] WARN: child submit failed for parent ${parent.id}: ${msg}\n`);- await logSelfFixEvent(engine, {- parent_id: parent.id,- child_id: 0, // sentinel — submit failed; no child exists- classifier_bucket: cluster,- chain_depth: 1,- policy_applied: `buildSelfFixPrompt:${cluster}`,- outcome: `failed_to_submit:${msg.slice(0, 200)}`,- });- return null;- }-}--export interface SelfFixEventRecord {- parent_id: number;- child_id: number;- classifier_bucket: string;- chain_depth: number;- policy_applied?: string;- outcome: string;-}--/** Best-effort write to minion_self_fix_log (audit table from migration v94). */-export async function logSelfFixEvent(- engine: BrainEngine,- record: SelfFixEventRecord,-): Promise<void> {- try {- await engine.executeRaw(- `INSERT INTO minion_self_fix_log- (parent_id, child_id, classifier_bucket, chain_depth, policy_applied, outcome)- VALUES ($1, $2, $3, $4, $5, $6)`,- [- record.parent_id,- record.child_id || null, // 0 → NULL (submit failed)- record.classifier_bucket,- record.chain_depth,- record.policy_applied ?? null,- record.outcome,- ],- );- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- process.stderr.write(- `[self-fix-audit] WARN: write failed for parent ${record.parent_id}: ${msg}\n`,- );- }-}diff --git a/src/core/minions/stagger.ts b/src/core/minions/stagger.tsdeleted file mode 100644index 5d992b0988..0000000000--- a/src/core/minions/stagger.ts+++ /dev/null@@ -1,35 +0,0 @@-/**- * Deterministic stagger slots.- *- * Jobs sharing a stagger_key (e.g., "social-radar", "x-ingest") get a- * minute-offset between 0 and 59 computed from the key itself. Same key →- * same slot, always. Different keys → different slots (collision rate- * proportional to 1/60).- *- * Used by Minions' delayed-promotion path: a cron that fires at minute 0- * can set `delay_until = now() + stagger_offset_seconds` so 10 jobs- * scheduled for the same minute don't actually hit the queue at the same- * moment.- *- * Not a general-purpose hash. FNV-1a is tiny, deterministic across- * runtimes, and enough distinguishing entropy for 60 buckets.- */--const FNV_OFFSET = 0x811c9dc5 >>> 0;-const FNV_PRIME = 0x01000193;--/** Minutes offset in [0, 59] for the given stagger key. */-export function staggerMinuteOffset(key: string): number {- if (!key || typeof key !== 'string') return 0;- let h = FNV_OFFSET;- for (let i = 0; i < key.length; i++) {- h ^= key.charCodeAt(i);- h = Math.imul(h, FNV_PRIME) >>> 0;- }- return h % 60;-}--/** Seconds offset — same thing scaled for convenience. */-export function staggerSecondOffset(key: string): number {- return staggerMinuteOffset(key) * 60;-}diff --git a/src/core/model-pricing.ts b/src/core/model-pricing.tsindex c00414f474..23a4648058 100644--- a/src/core/model-pricing.ts+++ b/src/core/model-pricing.ts@@ -8,8 +8,8 @@* - eval-contradictions/cost-tracker.ts (silent-Haiku-fallback view)* - cross-modal-eval/runner.ts (multi-provider eval panel)* - skillopt/preflight.ts (Sonnet-fallback warn-only estimate)- * The bare-keyed `ANTHROPIC_PRICING` view is itself consumed by budget/budget-tracker.ts,- * minions/batch-projection.ts, and cycle/budget-meter.ts — so those inherit canonical too.+ * The bare-keyed `ANTHROPIC_PRICING` view is itself consumed by budget/budget-tracker.ts+ * and cycle/budget-meter.ts — so those inherit canonical too.** The dollar amounts live HERE ONCE — update prices in this file only. Each* consumer keeps its own key allowlist and miss-handling policy (fail-closeddiff --git a/src/core/ops/sources.ts b/src/core/ops/sources.tsindex 3609773547..5087ab7afd 100644--- a/src/core/ops/sources.ts+++ b/src/core/ops/sources.ts@@ -145,7 +145,9 @@ const sources_add: Operation = {p.federated === undefined ? null : (p.federated as boolean),cloneDir: remoteCloneDir,});- return row;+ const { redactSourceConfig } = await import('../source-config-redact.ts');+ const { parseSourceConfig } = await import('../sources-load.ts');+ return { ...row, config: redactSourceConfig(parseSourceConfig(row.config)) };},cliHints: { name: 'sources_add', hidden: true },};diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.tsindex 8c44c41427..82af918658 100644--- a/src/core/persistence/source-lifecycle.ts+++ b/src/core/persistence/source-lifecycle.ts@@ -6,6 +6,7 @@ import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';import { isValidSourceId } from '../source-id.ts';import { parseSourceConfig } from '../sources-load.ts';+import { redactSourceConfig } from '../source-config-redact.ts';import { discoverGitRoot } from '../sync-git.ts';import { isInsideGitRepo, hasTrackedContent } from '../git-remote.ts';import { containsPath, getWorktreeBinding, type WorktreeBinding, worktreeManifest } from './ownership.ts';@@ -186,7 +187,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLawait refreshManagedFilesystemRoots(tx,managedFilesystemDatastorePath(engine));return {operation:input.operation,source_id:input.sourceId,source_incarnation:incarnation,invalidated_requests:invalidated,...(root?{local_path:root.source}:{}),...(['remove','purge'].includes(input.operation)?{storage_retained:true,local_path:ownedSourcePath??null,pages_deleted:pagesDeleted}:{}),- ...(input.operation==='add'?{name:input.name??source?.name??input.sourceId,config:{...source?.config,...input.config},id:input.sourceId}: {})};+ ...(input.operation==='add'?{name:input.name??source?.name??input.sourceId,config:redactSourceConfig({...source?.config,...input.config}),id:input.sourceId}: {})};});if(admission) await admission.after(tx,String(result.source_incarnation));const row=await recordTopologyChange(tx,{principal,requestId,intent,operation:input.operation,sourceId:input.sourceId,incarnation:source?.incarnation??String(result.source_incarnation),worktrees},result);diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex d4a1ca99b6..5fe1e810e7 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -4357,11 +4357,6 @@ export class PostgresEngine implements BrainEngine {*/private _factsEmbeddingCastSuffix: '::vector' | '::halfvec' | null = null;- /** Test seam: clear the cached cast suffix so tests can re-probe. */- __resetFactsEmbeddingCastCacheForTest(): void {- this._factsEmbeddingCastSuffix = null;- }-private async resolveFactsEmbeddingCast(): Promise<'::vector' | '::halfvec'> {if (this._factsEmbeddingCastSuffix !== null) return this._factsEmbeddingCastSuffix;const sql = this.sql;diff --git a/src/core/process-cleanup.ts b/src/core/process-cleanup.tsindex dc78d133d7..e5ec19518c 100644--- a/src/core/process-cleanup.ts+++ b/src/core/process-cleanup.ts@@ -23,9 +23,10 @@* cancel belongs in the AbortController path, not in a parallel* signal handler.*- * - Idempotent: a second signal during the cleanup pass is a NO-OP.- * First pass runs to its 3s deadline; users who want a forced exit- * can SIGKILL.+ * - Idempotent: callbacks run once. A second signal during the cleanup+ * pass waits for that pass (bounded by its 3s deadline) before+ * exiting, so it cannot exit ahead of the lock DELETE; users who want+ * a forced exit can SIGKILL.** - Single ownership: `tryAcquireDbLock` auto-registers; the returned* handle's `release()` deregisters. `withRefreshingLock` just@@ -51,7 +52,7 @@ interface CleanupEntry {const registry = new Map<symbol, CleanupEntry>();let installed = false;-let cleanupInFlight = false;+let cleanupPass: Promise<void> | null = null;/** Refs to every listener attached by installSignalHandlers, keyed by* target+event, so _resetForTests can DETACH them — without this, a test* that installs and "resets" leaves a live SIGTERM→exit(143) listener on@@ -101,10 +102,12 @@ export async function triggerCleanupAndExit(code: number): Promise<void> {process.exit(code);}-async function runCleanupPass(): Promise<void> {- if (cleanupInFlight) return; // Idempotent: second signal during cleanup is NO-OP.- cleanupInFlight = true;+function runCleanupPass(): Promise<void> {+ cleanupPass ??= runCleanupCallbacks();+ return cleanupPass;+}+async function runCleanupCallbacks(): Promise<void> {const entries = Array.from(registry.values());if (entries.length === 0) return;@@ -166,9 +169,8 @@ export function installSignalHandlers(): void {attach(process, 'SIGTERM', () => handleSignal('SIGTERM'));attach(process, 'SIGHUP', () => handleSignal('SIGHUP'));- // SIGPIPE in Node is rarely raised directly (Node ignores it by default- // and surfaces an EPIPE write error on the stream instead). Listen anyway- // for environments where it does fire.+ // Bun delivers SIGPIPE on a broken pipe (Node ignores it by default and+ // surfaces only an EPIPE write error on the stream, handled below).attach(process, 'SIGPIPE', () => handleSignal('SIGPIPE'));attach(process, 'uncaughtException', (err: unknown) => {@@ -216,5 +218,5 @@ export function _resetForTests(): void {}installedListeners.length = 0;installed = false;- cleanupInFlight = false;+ cleanupPass = null;}diff --git a/src/core/resolvers/builtin/url-reachable.ts b/src/core/resolvers/builtin/url-reachable.tsindex 489fc8f5a6..bae2b54b1f 100644--- a/src/core/resolvers/builtin/url-reachable.ts+++ b/src/core/resolvers/builtin/url-reachable.ts@@ -18,7 +18,7 @@* Abort token threads through both.*/-import { fetchWithSSRFGuard, HttpProxyError, SSRFError, validateAndResolveUrl } from '../../ssrf-validate.ts';+import { fetchWithSSRFGuard, HttpProxyError, SSRFError } from '../../ssrf-validate.ts';import type {Resolver,ResolverContext,@@ -117,22 +117,3 @@ export const urlReachableResolver: Resolver<UrlReachableInput, UrlReachableOutpu}},};--// ----------------------------------------------------------------------------// Helpers-// -----------------------------------------------------------------------------function errMessage(err: unknown): string {- if (err instanceof Error) return err.message;- return String(err);-}--/** Compatibility helper; the shared validator is the only address policy. */-export async function checkDnsRebinding(urlStr: string): Promise<string | null> {- try {- await validateAndResolveUrl(urlStr);- return null;- } catch (err) {- return errMessage(err);- }-}diff --git a/src/core/schema-pack/enrichable.ts b/src/core/schema-pack/enrichable.tsindex 104a45816c..d43aaab4e9 100644--- a/src/core/schema-pack/enrichable.ts+++ b/src/core/schema-pack/enrichable.ts@@ -3,7 +3,7 @@// Pre-v0.38:// src/core/enrichment-service.ts:25 hardcoded:// entityType: 'person' | 'company';-// src/core/enrichment/completeness.ts:221 hardcoded:+// the completeness scorer hardcoded:// const RUBRICS_BY_TYPE = new Map([// ['person', personRubric], ['company', companyRubric],// ['deal', dealRubric], ...@@ -21,8 +21,8 @@// if (!enrichable.has(parsed.type)) { skip; }// const rubricName = rubricNameForType(activePack, parsed.type) ?? 'default';//-// Until the wiring lands, legacy enrichment-service + completeness-// callers continue to hardcode person/company/deal — which gbrain-base+// Until the wiring lands, legacy enrichment-service callers continue+// to hardcode person/company/deal — which gbrain-base// also declares, so behavior is preserved.import type { SchemaPackManifest } from './manifest-v1.ts';@@ -36,11 +36,8 @@ export function enrichableTypesFromPack(/*** Return the rubric slot name for a type, or null if the type isn't- * declared as enrichable. Rubric names map to in-source Rubric objects- * via `src/core/enrichment/completeness.ts` registries — the pack- * specifies the NAME; the in-code module owns the implementation. This- * keeps rubric authoring deterministic without serializing the rubric- * structure into YAML.+ * declared as enrichable. The pack specifies the rubric NAME only; no+ * in-code rubric registry consumes it yet.*/export function rubricNameForType(pack: Pick<SchemaPackManifest, 'enrichable_types'>,diff --git a/src/core/schema-pack/expand-type-filter.ts b/src/core/schema-pack/expand-type-filter.tsdeleted file mode 100644index 613b641a24..0000000000--- a/src/core/schema-pack/expand-type-filter.ts+++ /dev/null@@ -1,186 +0,0 @@-// v0.42 (T20, plan D14) — type filter back-compat helper.-//-// Problem: after unify-types runs, pages with type='article' become-// type='media' with frontmatter.subtype='article'. Existing scripts that-// run `gbrain extract --type article` would return zero pages.-//-// Fix: expand the user-supplied type at query construction time. If the-// type is declared as an ALIAS of a canonical type (per the active-// pack's page_types[].aliases), AND the canonical type declares a-// matching subtype rule, expand to match BOTH:-// - residual pre-unify pages: type = 'article'-// - post-unify pages: type = 'media' AND frontmatter->>'subtype' = 'article'-//-// Single source of truth — both extract CLI + future operations.ts-// list_pages adopt this helper to avoid drift.-//-// D4 EMPTY FILTER contract: pack-load failure → degrades to exact-match-// behavior (the helper returns { canonical: type, isAliasExpansion: false }).-// Existing tests pass unchanged on pack-less brains.--import type { SchemaPackManifest } from './manifest-v1.ts';--export interface ExpandedTypeFilter {- /** The canonical type to match (always present). */- canonical: string;- /**- * If non-null: also match (type = canonical AND frontmatter[field] = value).- * Use the SQL OR semantics:- * (type = $1 OR (type = $2 AND frontmatter->>$3 = $4))- *- * When null: simple `type = $canonical` lookup.- */- subtypeFilter: { canonical: string; subtypeField: string; subtypeValue: string } | null;- /** True when the input was an alias that mapped to a canonical type. */- isAliasExpansion: boolean;- /** The original input type (preserved for residual-match SQL). */- originalInput: string;-}--/**- * Expand a user-supplied --type value against the active pack. When the- * input is an alias declared on a canonical type, and that canonical- * declares a matching subtype rule, expand to the canonical+subtype- * tuple. Otherwise, return the input unchanged (exact-match semantics).- *- * Examples (against gbrain-base-v2):- * expandTypeFilter('article', pack)- * → { canonical: 'media', subtypeFilter: { canonical: 'media',- * subtypeField: 'subtype', subtypeValue: 'article' },- * isAliasExpansion: true, originalInput: 'article' }- * expandTypeFilter('media', pack)- * → { canonical: 'media', subtypeFilter: null,- * isAliasExpansion: false, originalInput: 'media' }- * expandTypeFilter('unknown-type', pack)- * → { canonical: 'unknown-type', subtypeFilter: null,- * isAliasExpansion: false, originalInput: 'unknown-type' }- *- * Subtype-rule matching: prefers frontmatter-keyed rules; falls back to- * path-pattern rules (matched against the alias's expected canonical- * subtype name). For now, only frontmatter-based subtypes drive query- * expansion — path-pattern subtypes (like `media:video` from `^videos/`)- * are handled by the legacy `type = 'video'` literal during the- * pre-unify residual phase.- */-export function expandTypeFilter(- type: string,- pack: Pick<SchemaPackManifest, 'page_types'> | null | undefined,-): ExpandedTypeFilter {- if (!pack) {- return {- canonical: type,- subtypeFilter: null,- isAliasExpansion: false,- originalInput: type,- };- }- // 1. If `type` is itself a canonical (declared in page_types), pass through.- if (pack.page_types.some((pt) => pt.name === type)) {- return {- canonical: type,- subtypeFilter: null,- isAliasExpansion: false,- originalInput: type,- };- }- // 2. Search for `type` as an alias of any canonical.- for (const pt of pack.page_types) {- if (!pt.aliases?.includes(type)) continue;- // 2a. CANONICAL ANSWER — consult mapping_rules. The retype rule for- // `from_type: type` is the source of truth for what subtype value- // the unify pass stamped on the page's frontmatter. Use that- // rule's subtype + subtype_field for the query expansion.- const mappingRules = (pack as { mapping_rules?: unknown[] }).mapping_rules;- if (Array.isArray(mappingRules)) {- for (const rule of mappingRules) {- if (typeof rule !== 'object' || rule === null) continue;- const r = rule as { kind?: unknown; from_type?: unknown; subtype?: unknown; subtype_field?: unknown };- if (r.kind !== 'retype') continue;- if (r.from_type !== type) continue;- if (typeof r.subtype !== 'string') continue;- return {- canonical: pt.name,- subtypeFilter: {- canonical: pt.name,- subtypeField: typeof r.subtype_field === 'string' ? r.subtype_field : 'subtype',- subtypeValue: r.subtype,- },- isAliasExpansion: true,- originalInput: type,- };- }- }- // 2b. FALLBACK 1: subtype rule on the page_type whose `name === type`.- // Common case for hand-written packs that declare subtypes but don't- // wire mapping_rules.- const subtypeRule = pt.subtypes?.find((s) => s.name === type);- if (subtypeRule?.when.frontmatter_field !== undefined- && subtypeRule.when.frontmatter_value !== undefined) {- const v = subtypeRule.when.frontmatter_value;- const subtypeValue = typeof v === 'boolean' ? String(v)- : typeof v === 'number' ? String(v)- : String(v);- return {- canonical: pt.name,- subtypeFilter: {- canonical: pt.name,- subtypeField: subtypeRule.when.frontmatter_field,- subtypeValue,- },- isAliasExpansion: true,- originalInput: type,- };- }- // 2c. FALLBACK 2: no mapping_rule + no matching subtype rule. Use- // subtype=alias-name (assumes the unify pass stamped subtype as the- // alias name itself, which is the catch-all behavior).- return {- canonical: pt.name,- subtypeFilter: {- canonical: pt.name,- subtypeField: 'subtype',- subtypeValue: type,- },- isAliasExpansion: true,- originalInput: type,- };- }- // 4. Not in page_types AND not in any aliases list. Pass through unchanged- // (legacy/unknown type — let the SQL match-or-not naturally).- return {- canonical: type,- subtypeFilter: null,- isAliasExpansion: false,- originalInput: type,- };-}--/**- * Build the SQL WHERE fragment for an expanded type filter. Returns the- * fragment with `$1`-style placeholders + the params array (in order).- *- * Callers must offset the placeholder indices via their own param counter- * — this helper assumes the WHERE is being built from scratch (starts at $1).- * Use `renumberPlaceholders` if composing with other clauses.- */-export function buildTypeFilterSql(- expanded: ExpandedTypeFilter,- startParamIndex: number = 1,-): { sql: string; params: string[] } {- if (!expanded.isAliasExpansion || !expanded.subtypeFilter) {- return {- sql: `type = $${startParamIndex}`,- params: [expanded.originalInput],- };- }- const i = startParamIndex;- return {- sql: `(type = $${i} OR (type = $${i + 1} AND frontmatter ->> $${i + 2} = $${i + 3}))`,- params: [- expanded.originalInput,- expanded.subtypeFilter.canonical,- expanded.subtypeFilter.subtypeField,- expanded.subtypeFilter.subtypeValue,- ],- };-}diff --git a/src/core/schema-pack/rewrite-links-batch.ts b/src/core/schema-pack/rewrite-links-batch.tsdeleted file mode 100644index 53c4aa899d..0000000000--- a/src/core/schema-pack/rewrite-links-batch.ts+++ /dev/null@@ -1,91 +0,0 @@-import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';-// v0.42 Type Unification (T9) — rewriteLinksBatch primitive.-//-// Eng review Finding 1.2: rewriteLinks() called per-page (N calls) is fine-// at ~65 page-to-link conversions but becomes a bottleneck on 1M-page brains-// (~5min just for link rewrites). This is the batched form using-// `UPDATE FROM unnest()` — N pairs in 1-2 statements regardless of array-// size.-//-// Codex Finding F9: source-scoped. Each pair carries its own sourceId so-// federated brains don't accidentally rewrite cross-source link rows.-//-// Note: the existing `engine.rewriteLinks(oldSlug, newSlug)` is intentionally-// a stub (links use integer page_id FKs that don't change on slug rename;-// textual [[wiki-links]] are not rewritten by it). This helper is for-// future code paths that need real bulk slug FK rewrite — v0.42 page-to-link-// uses it ONLY if/when the slug FK side actually changes; today's page-to-link-// uses soft-delete + alias-table semantics per D15 and doesn't need-// rewriteLinksBatch on the alias case.-//-// API: callers pass an array of `{from, to, sourceId}` triples. Behavior:-// for each pair, UPDATE `links` rows where the `from_page_id` OR-// `to_page_id` references a page with old slug (in the given sourceId),-// updating the FK to the new slug's page_id. Returns total rows touched.--import type { BrainEngine } from '../engine.ts';--export interface RewriteLinkPair {- from_slug: string;- to_slug: string;- source_id: string;-}--/**- * Batched link rewrite. v0.42 ships the API surface; production callers- * are deferred to v0.43+ when page-to-link variants actually mutate the- * link FK shape. v0.42's page-to-link soft-deletes the source page and- * inserts a NEW link row; existing inbound link rows stay valid because- * they reference page_ids (not slugs).- *- * The helper is here because the plan locked it (Finding 1.2) and tests- * can validate the batched-UPDATE shape works on both engines.- *- * Returns count of links table rows updated across all pairs (sum).- */-export async function rewriteLinksBatch(- engine: BrainEngine,- pairs: ReadonlyArray<RewriteLinkPair>,-): Promise<number> {- if (pairs.length === 0) return 0;- await assertUnmanagedCanonicalWriter(engine, 'schema link rewrite');- // Looking up new page_id for each (to_slug, source_id) pair in one query- // via unnest, then updating links.from_page_id + links.to_page_id +- // links.origin_page_id via correlated subquery against the resolved- // pairs. For v0.42 we do it pair-by-pair to keep the SQL simple +- // engine-parity-safe; v0.43+ can optimize via a single CTE if needed.- let total = 0;- for (const p of pairs) {- // Resolve old + new page ids- const oldRows = await engine.executeRaw<{ id: number }>(- `SELECT id FROM pages WHERE slug = $1 AND source_id = $2 LIMIT 1`,- [p.from_slug, p.source_id],- );- const newRows = await engine.executeRaw<{ id: number }>(- `SELECT id FROM pages WHERE slug = $1 AND source_id = $2 LIMIT 1`,- [p.to_slug, p.source_id],- );- if (oldRows.length === 0 || newRows.length === 0) continue;- const oldId = oldRows[0].id;- const newId = newRows[0].id;- const fromRes = await engine.executeRaw<{ updated: string }>(- `WITH upd AS (UPDATE links SET from_page_id = $1 WHERE from_page_id = $2 RETURNING 1)- SELECT COUNT(*)::text AS updated FROM upd`,- [newId, oldId],- );- const toRes = await engine.executeRaw<{ updated: string }>(- `WITH upd AS (UPDATE links SET to_page_id = $1 WHERE to_page_id = $2 RETURNING 1)- SELECT COUNT(*)::text AS updated FROM upd`,- [newId, oldId],- );- const originRes = await engine.executeRaw<{ updated: string }>(- `WITH upd AS (UPDATE links SET origin_page_id = $1 WHERE origin_page_id = $2 RETURNING 1)- SELECT COUNT(*)::text AS updated FROM upd`,- [newId, oldId],- );- total += parseInt(fromRes[0]?.updated ?? '0', 10) || 0;- total += parseInt(toRes[0]?.updated ?? '0', 10) || 0;- total += parseInt(originRes[0]?.updated ?? '0', 10) || 0;- }- return total;-}diff --git a/src/core/schema-pack/suggest.ts b/src/core/schema-pack/suggest.tsindex 09ded88e03..118c6e7a63 100644--- a/src/core/schema-pack/suggest.ts+++ b/src/core/schema-pack/suggest.ts@@ -94,9 +94,8 @@ export async function runSuggest(raw = heuristicSuggestions(detected);} else {// Real gateway call deferred to a future wave; v0.39.0.0 ships the- // hermetic heuristic-by-default path and the test seam. The full- // LLM prompt-tuning loop is in test/eval-schema-authoring (T16)- // which uses the same `suggestFn` seam.+ // hermetic heuristic-by-default path and the test seam. The planned+ // T16 schema-authoring eval would drive the same `suggestFn` seam.notes.push('LLM refinement deferred to v0.39.1+; using heuristic fallback.');raw = heuristicSuggestions(detected);}diff --git a/src/core/search/telemetry.ts b/src/core/search/telemetry.tsindex db4e1cdf1d..55ff9c53ca 100644--- a/src/core/search/telemetry.ts+++ b/src/core/search/telemetry.ts@@ -330,7 +330,7 @@ class TelemetryWriter {// alive past beforeExit — short-lived CLI invocations (`gbrain query "the"`// exiting after 100ms of work) ended up waiting on the DB write to settle.// On a slow or busy PGLite, the write never settled and the CLI hung- // forever. That deadlock surfaced as the `test/e2e/claw-test.test.ts`+ // forever. That deadlock surfaced as the `test/claw-test.slow.test.ts`// hang (the harness spawns short-lived gbrain queries that should exit// in <1s but never did).//diff --git a/src/core/search/title-match.ts b/src/core/search/title-match.tsindex ad57fc005f..f1a75fe44d 100644--- a/src/core/search/title-match.ts+++ b/src/core/search/title-match.ts@@ -109,6 +109,3 @@ export function isTitleMentionedInQuery(query: string, title: string): boolean {if (tContent.length < MIN_CONTENT_TOKENS && tContent[0].length < MIN_SINGLE_TOKEN_TITLE_CHARS) return false;return containsTokenRun(qTokens, tTokens);}--// Exported for unit tests.-export const __test__ = { tokenizeTitle, contentTokens, containsTokenRun, STOPWORDS, MIN_CONTENT_TOKENS };diff --git a/src/core/skillpack/brain-pack-lint.ts b/src/core/skillpack/brain-pack-lint.tsdeleted file mode 100644index 4d1166aab4..0000000000--- a/src/core/skillpack/brain-pack-lint.ts+++ /dev/null@@ -1,69 +0,0 @@-/**- * skillpack/brain-pack-lint.ts — E6 version-skew lint for brain-resident packs.- *- * A brain ships skills that call gbrain operations. If the connecting gbrain is- * older/newer than the pack assumed, a skill's declared `tools:` may reference- * ops that don't exist on this binary — silent breakage when the harness tries- * to call them. This lint reads every pack skill's SKILL.md frontmatter `tools:`- * and flags any tool not present in the serving op set, so packs fail loud on- * drift instead of mysteriously half-working.- *- * Pure-ish: filesystem reads only, no mutation. Used by- * `gbrain skillpack init-brain-pack` (lint the freshly-generated pack) and- * `gbrain skillpack check` (lint an existing brain repo's pack).- */--import { existsSync, readFileSync } from 'fs';-import { join } from 'path';--import { parseMarkdown } from '../markdown.ts';-import { loadSkillpackManifest, type SkillpackManifest } from './manifest-v1.ts';--export interface ToolSkewFinding {- /** Skill path relative to the pack root (e.g. "skills/diligence"). */- skill: string;- /** The declared tool name that is not in the serving op set. */- tool: string;-}--export interface BrainPackLintResult {- packRoot: string;- manifest: SkillpackManifest;- /** Every `tools:` value across the pack that the serving binary cannot satisfy. */- unknownTools: ToolSkewFinding[];-}--/**- * Lint a brain-resident pack's declared `tools:` against the set of op names the- * serving gbrain actually exposes. `knownOps` is the authoritative op-name set- * (callers pass `new Set(operations.map(o => o.name))`).- *- * A skill with no `tools:` frontmatter contributes nothing (the common case for- * a freshly-scaffolded pack). Skills whose SKILL.md is missing or unparseable- * are skipped silently — discovery is fail-open, this is a quality lint, not a- * gate that should explode on a half-written pack.- */-export function lintBrainPackTools(packRoot: string, knownOps: Set<string>): BrainPackLintResult {- const manifest = loadSkillpackManifest(packRoot);- const unknownTools: ToolSkewFinding[] = [];-- for (const skillDir of manifest.skills) {- const skillMd = join(packRoot, skillDir, 'SKILL.md');- if (!existsSync(skillMd)) continue;- let tools: unknown;- try {- tools = parseMarkdown(readFileSync(skillMd, 'utf-8'), skillMd).frontmatter.tools;- } catch {- continue;- }- if (!Array.isArray(tools)) continue;- for (const tool of tools) {- if (typeof tool !== 'string' || tool.length === 0) continue;- if (!knownOps.has(tool)) {- unknownTools.push({ skill: skillDir, tool });- }- }- }-- return { packRoot, manifest, unknownTools };-}diff --git a/src/core/skillpack/init-brain-pack.ts b/src/core/skillpack/init-brain-pack.tsindex 2a1965c192..430c90ee24 100644--- a/src/core/skillpack/init-brain-pack.ts+++ b/src/core/skillpack/init-brain-pack.ts@@ -119,8 +119,7 @@ export function runInitBrainPack(opts: InitBrainPackOptions): InitBrainPackResul'triggers:',` - example trigger phrase 1 for ${firstSlug}`,` - example trigger phrase 2 for ${firstSlug}`,- '# tools: list gbrain ops this skill calls (e.g. [search, put_page]); used by the',- '# version-skew lint to fail loud if a connecting gbrain lacks them.',+ '# tools: list gbrain ops this skill calls (e.g. [search, put_page]).','---','',`# ${firstSlug}`,diff --git a/src/core/source-config-redact.ts b/src/core/source-config-redact.tsindex 2328e26d3b..8fb3ceda59 100644--- a/src/core/source-config-redact.ts+++ b/src/core/source-config-redact.ts@@ -10,6 +10,7 @@* `scripts/check-source-config-leak.sh` grep-guards against future drift.*/+/** Audited key classification: see the header of scripts/check-source-config-leak.sh. */const SECRET_KEYS: ReadonlySet<string> = new Set(['webhook_secret',]);diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.tsindex 2952e73181..0eb01df9b9 100644--- a/src/core/source-resolver.ts+++ b/src/core/source-resolver.ts@@ -602,15 +602,6 @@ export async function assessUnscopedDefaultWrite(return { warning: assessment.shouldGuard ? formatDefaultWriteWarning(assessment) : null, assessed: true };}-/** The warning-only projection of assessUnscopedDefaultWrite. */-export async function maybeWarnUnscopedDefaultWrite(- engine: BrainEngine,- tier: SourceTier,- mutating: boolean,-): Promise<string | null> {- return (await assessUnscopedDefaultWrite(engine, tier, mutating)).warning;-}-async function assertSourceExists(engine: BrainEngine, id: string): Promise<void> {const rows = await engine.executeRaw<{ id: string }>(`SELECT id FROM sources WHERE id = $1 AND archived = false`,diff --git a/src/core/thin-client-upgrade-prompt.ts b/src/core/thin-client-upgrade-prompt.tsindex f75ba99eb3..33174e5503 100644--- a/src/core/thin-client-upgrade-prompt.ts+++ b/src/core/thin-client-upgrade-prompt.ts@@ -322,17 +322,6 @@ export function _setUpgradeRunnerForTest(fn: UpgradeRunner | null): void {_upgradeRunner = fn ?? defaultRunUpgrade;}-// ============================================================================-// Test escape: clear in-process state file path memo (none today, but matches-// the _clearIdentityCacheForTest pattern for future-proofing).-// ============================================================================--export function _clearPromptStateForTest(): void {- // No in-process state to clear today; the file lives on disk and tests use- // GBRAIN_HOME tempdirs for isolation. This stub exists for symmetry with- // _clearIdentityCacheForTest in src/cli.ts so future caching can hook here.-}-// ============================================================================// Orchestrator// ============================================================================diff --git a/src/core/upgrade-checkpoint.ts b/src/core/upgrade-checkpoint.tsdeleted file mode 100644index addb8b7618..0000000000--- a/src/core/upgrade-checkpoint.ts+++ /dev/null@@ -1,160 +0,0 @@-/**- * Upgrade pipeline checkpoint (v0.30.1 Cherry D5 + Codex X2).- *- * Persists step-by-step progress through `gbrain post-upgrade` so a partial- * failure can be resumed via `gbrain upgrade --resume` instead of- * re-running every step from scratch.- *- * Codex X2 fix: checkpoint is bound to the brain it was created for, via- * a sha256(database_url) hash. brain-registry.ts:300 manages multiple- * mounted brains; without identity binding, a checkpoint from brain A can- * be applied against brain B (corruption vector). The validate() helper- * is the F4 fall-through gate — when called with a no-checkpoint or- * mismatched-brain state, the upgrade pipeline silently runs the full path.- */--import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync } from 'node:fs';-import { dirname } from 'node:path';-import { createHash } from 'node:crypto';-import { gbrainPath, loadConfig } from './config.ts';--export type UpgradeStep = 'pull' | 'install' | 'schema' | 'features' | 'backfills' | 'verify';--export interface UpgradeCheckpoint {- /** Stable hash of the brain's database_url. Detects multi-brain mismatch (X2). */- brain_id: string;- /** ISO 8601 timestamp of when the upgrade started. */- started_at: string;- /** Source version (the binary that started the upgrade). */- from_version: string;- /** Target version (the binary that's running the pipeline). */- to_version: string;- /** Steps that completed successfully. */- completed_steps: UpgradeStep[];- /** Step that failed (set on error). */- failed_step?: UpgradeStep;- /** Error info from the failed step. */- failed_step_error?: { message: string; code?: string };-}--const CHECKPOINT_FILENAME = 'upgrade-checkpoint.json';-const ALL_STEPS: UpgradeStep[] = ['pull', 'install', 'schema', 'features', 'backfills', 'verify'];--function checkpointPath(): string {- return gbrainPath(CHECKPOINT_FILENAME);-}--/**- * Compute a stable brain identity hash from the database URL. Strips- * userinfo to avoid creds in the hash input collision space (anyone- * comparing hashes can't reverse to find a password). Falls back to- * 'unknown' when no URL is configured.- */-export function computeBrainId(databaseUrl?: string | null): string {- if (!databaseUrl) {- // PGLite or no config — derive from the configured database_path- // when present, else 'pglite-default'.- const cfg = loadConfig();- const path = cfg?.database_path;- return createHash('sha256').update(`pglite:${path ?? 'default'}`).digest('hex').slice(0, 16);- }- // Strip userinfo so the hash is stable across credential rotations.- const stripped = databaseUrl.replace(/\/\/[^@]*@/, '//');- return createHash('sha256').update(stripped).digest('hex').slice(0, 16);-}--/**- * Read the checkpoint from disk. Returns null when missing or unreadable.- */-export function loadCheckpoint(): UpgradeCheckpoint | null {- const path = checkpointPath();- if (!existsSync(path)) return null;- try {- const raw = readFileSync(path, 'utf-8');- const parsed = JSON.parse(raw) as UpgradeCheckpoint;- // Defensive: must have brain_id + completed_steps shape.- if (typeof parsed.brain_id !== 'string') return null;- if (!Array.isArray(parsed.completed_steps)) return null;- return parsed;- } catch {- return null;- }-}--export function writeCheckpoint(state: UpgradeCheckpoint): void {- const path = checkpointPath();- try {- mkdirSync(dirname(path), { recursive: true });- writeFileSync(path, JSON.stringify(state, null, 2), 'utf-8');- } catch (err) {- process.stderr.write(`[upgrade-checkpoint] write failed: ${(err as Error).message}\n`);- }-}--export function clearCheckpoint(): void {- const path = checkpointPath();- try {- if (existsSync(path)) unlinkSync(path);- } catch {- /* best-effort */- }-}--export interface CheckpointValidation {- valid: boolean;- /** Reason for invalidation. */- reason?: 'no_checkpoint' | 'brain_mismatch' | 'malformed' | 'all_complete';- /** Step to resume at (next un-completed step). */- resumeAt?: UpgradeStep;- /** The loaded checkpoint when valid + has unfinished work. */- checkpoint?: UpgradeCheckpoint;-}--/**- * Validate a checkpoint against the current brain. Returns:- * - valid=false reason=no_checkpoint → caller falls through to full upgrade (F4)- * - valid=false reason=brain_mismatch → operator must --force or remove checkpoint- * - valid=false reason=all_complete → checkpoint is stale; clear it and run full- * - valid=true → resume from resumeAt- */-export function validateCheckpoint(currentBrainId: string): CheckpointValidation {- const checkpoint = loadCheckpoint();- if (!checkpoint) return { valid: false, reason: 'no_checkpoint' };- if (checkpoint.brain_id !== currentBrainId) {- return { valid: false, reason: 'brain_mismatch', checkpoint };- }- // Find the first step NOT in completed_steps.- const nextStep = ALL_STEPS.find(s => !checkpoint.completed_steps.includes(s));- if (!nextStep) {- return { valid: false, reason: 'all_complete', checkpoint };- }- return { valid: true, resumeAt: nextStep, checkpoint };-}--/**- * Mark a step complete in-place. Caller writes back via writeCheckpoint().- */-export function markStepComplete(checkpoint: UpgradeCheckpoint, step: UpgradeStep): UpgradeCheckpoint {- if (!checkpoint.completed_steps.includes(step)) {- checkpoint.completed_steps.push(step);- }- // Clear failed_step when a step completes successfully (could be a re-run).- delete checkpoint.failed_step;- delete checkpoint.failed_step_error;- return checkpoint;-}--export function markStepFailed(- checkpoint: UpgradeCheckpoint,- step: UpgradeStep,- err: Error,-): UpgradeCheckpoint {- checkpoint.failed_step = step;- checkpoint.failed_step_error = {- message: err.message,- code: (err as { code?: string }).code,- };- return checkpoint;-}--export const ALL_UPGRADE_STEPS = ALL_STEPS;diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex d8de9be222..44b887a794 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.59.18.0 -->+<!-- gbrain-template-stamp: 0.59.20.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/agent-install-backup.serial.test.ts b/test/agent-install-backup.serial.test.tsindex d91499de2b..6d0020f36a 100644--- a/test/agent-install-backup.serial.test.ts+++ b/test/agent-install-backup.serial.test.ts@@ -244,11 +244,12 @@ test('full backup restores DB-only facts/files, rebases sources, quarantines allawait writeBackupArchive(renamedArchive, {}, [{ path: 'private-record', file: join(root, 'memory', 'prior.gbrain-backup') }]);writeFileSync(join(root, 'memory', 'credentials.md'), '# Remembered credential rotation procedure\nNo actual credential.\n');const connectorCommandMarker = join(temporary, 'connector-command-ran');+ const webhookSecret = `whsec-sentinel-${crypto.randomUUID()}`;await withFixtureWrite(root, ['google-fixture'], async engine => {await engine.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");await engine.executeRaw('INSERT INTO sources (id, name, local_path, config) VALUES ($1, $2, $3, $4::text::jsonb)', ['google-fixture', 'Google fixture', join(root, 'memory', 'google'),- JSON.stringify({ kind: 'google', federated: true, g_account: 'fixture-account', g_services: 'gmail', g_access: 'command', g_token_command: `touch '${connectorCommandMarker}'`, syncEnabled: true }),+ JSON.stringify({ kind: 'google', federated: true, g_account: 'fixture-account', g_services: 'gmail', g_access: 'command', g_token_command: `touch '${connectorCommandMarker}'`, syncEnabled: true, webhook_secret: webhookSecret }),]);await engine.setConfig('connectors.chatgpt.auto_sync', 'true');await engine.setConfig('autopilot.auto_drain.enabled', 'true');@@ -257,6 +258,9 @@ test('full backup restores DB-only facts/files, rebases sources, quarantines all});const created = await createPgliteBackup({ root, output: archive });expect(created.manifest.classification).toBe('sensitive-full-database-state');+ // Source-config secrets stay inside the documented full-database payload,+ // never in backup metadata or the restore log.+ expect(JSON.stringify(created.manifest)).not.toContain(webhookSecret);expect(statSync(archive).mode & 0o777).toBe(0o600);expect(created.manifest.entries.some(e => e.path.includes('credential-deliveries'))).toBe(false);for (const path of excludedManaged) expect(created.manifest.entries.some(e => e.path === `files/${path}`)).toBe(false);@@ -269,6 +273,8 @@ test('full backup restores DB-only facts/files, rebases sources, quarantines allconst restored = join(temporary, 'restored');const result = await restorePgliteBackup({ archive, into: restored });expect(result.quarantined_jobs).toBe(5);+ expect(result.reconnect_required.join('\n')).not.toContain(webhookSecret);+ expect(readFileSync(join(restored, 'restore-receipt.json'), 'utf8')).not.toContain(webhookSecret);expect(readFileSync(join(restored, 'memory', 'note.md'), 'utf8')).toContain('must survive');for (const path of excludedManaged) expect(existsSync(join(restored, path))).toBe(false);expect(readFileSync(join(restored, 'memory', 'credentials.md'), 'utf8')).toContain('Remembered credential rotation');diff --git a/test/ai/gateway-chat.test.ts b/test/ai/gateway-chat.test.tsindex fcdb0390de..9b0b1a4ac9 100644--- a/test/ai/gateway-chat.test.ts+++ b/test/ai/gateway-chat.test.ts@@ -290,32 +290,6 @@ describe('chat touchpoint — config alias resolution', () => {});});-describe('chat touchpoint — chat() smoke + stop-reason mapping (Codex D8)', () => {- // We exercise chat() against a mocked AI-SDK 'generateText' to assert the- // gateway's structural-signal mapping (mapStopReason) covers refusal,- // content_filter, tool_calls, end, length without the regex layer (commit 3).- // A full integration test against real provider HTTP lives in- // test/e2e/agent-multi-provider.test.ts (commit 2).- //- // We can't easily monkey-patch ESM imports inside Bun's runtime; instead we- // write an end-to-end assertion against the resolver logic + verify the- // chat() function exists with the documented signature.-- test('chat() function is exported with the expected signature', async () => {- const mod = await import('../../src/core/ai/gateway.ts');- expect(typeof mod.chat).toBe('function');- // Signature check: must accept ChatOpts. We don't call it without a real- // provider key — that's the e2e job.- });-- test('ChatBlock + ChatMessage + ChatResult types are exported', async () => {- // Type-only assertion: if these imports compile, we're good. The test- // body is just a runtime touch.- const mod = await import('../../src/core/ai/gateway.ts');- expect(mod).toBeDefined();- });-});-describe('chat touchpoint — provider_chat_options passthrough', () => {beforeEach(() => {resetGateway();diff --git a/test/ambient-recall-templates.test.ts b/test/ambient-recall-templates.test.tsindex 2f7be58d8a..8af286823f 100644--- a/test/ambient-recall-templates.test.ts+++ b/test/ambient-recall-templates.test.ts@@ -1,21 +1,18 @@/**- * Ambient recall (v0.45.7) — template + doc content pins.+ * Ambient recall (v0.45.7) — shipped template pin.** The context_pack/delta verbs only deliver value if the shipped guidance- * points agents at them. These pins keep the four guidance surfaces from- * silently dropping the boundary instructions:- * - HEARTBEAT.md.template carries the ambient-delta row (heartbeats pull- * `gbrain delta`; session start / post-compaction pairs with- * `gbrain context-pack`)- * - the RENDERED template-repo HEARTBEAT.md carries the same row- * - docs/mcp/CODEX.md names context_pack for the session boundary (Codex- * has no lifecycle hooks — the pull path is the only path)- * - docs/guides/ambient-recall.md exists and names both verbs+ * points agents at them. HEARTBEAT.md.template is rendered into users'+ * workspaces, so it must carry the ambient-delta row (heartbeats pull+ * `gbrain delta`; session start / post-compaction pairs with+ * `gbrain context-pack`). The rendered template-repo copy is byte-diffed+ * against the generator by scripts/check-bootstrap-templates.sh. The guide the+ * row points at must exist.** Assertions pin stable substrings (verb + command names), not full sentences.*/import { describe, expect, test } from 'bun:test';-import { readFileSync, existsSync } from 'node:fs';+import { existsSync, readFileSync } from 'node:fs';import { dirname, join } from 'node:path';const ROOT = dirname(import.meta.dir);@@ -31,30 +28,7 @@ describe('HEARTBEAT ambient-delta row', () => {expect(tpl).toContain('gbrain delta');expect(tpl).toContain('gbrain context-pack');expect(tpl).toContain('docs/guides/ambient-recall.md');- });-- test('rendered template-repo HEARTBEAT.md carries the same row', () => {- const rendered = read('templates/bootstrap/template-repo/HEARTBEAT.md');- expect(rendered).toContain('ambient-delta');- expect(rendered).toContain('gbrain delta');- expect(rendered).toContain('gbrain context-pack');- });-});--describe('docs surfaces', () => {- test('CODEX.md session-boundary instruction names both verbs (pull path)', () => {- const codex = read('docs/mcp/CODEX.md');- expect(codex).toContain('context_pack');- expect(codex).toContain('delta');- // Codex has no lifecycle hooks, so the doc must route boundary calls to- // the guide's placement frontier.- expect(codex).toContain('ambient-recall.md');- });-- test('ambient-recall guide exists and names both verbs', () => {expect(existsSync(join(ROOT, 'docs/guides/ambient-recall.md'))).toBe(true);- const guide = read('docs/guides/ambient-recall.md');- expect(guide).toContain('context_pack');- expect(guide).toContain('delta');});+});diff --git a/test/artifact-abstraction.test.ts b/test/artifact-abstraction.test.tsdeleted file mode 100644index 1cdad4b469..0000000000--- a/test/artifact-abstraction.test.ts+++ /dev/null@@ -1,50 +0,0 @@-// v0.39 T14 — artifact abstraction unit test.-// Pins detectArtifactKind dispatch + targetDirForKind + manifest validation-// so the cross-discriminator surface stays MECE.--import { describe, test, expect } from 'bun:test';-import { sep } from 'path';-import {- detectArtifactKind,- targetDirForKind,- validateManifestByKind,-} from '../src/core/artifact/index.ts';--// targetDirForKind builds its result with path.join(), which is correct:-// it emits native separators on every platform. The fixture below is-// therefore platform-selected rather than a shared POSIX literal — on-// Windows, join('/home/u/.gbrain', 'skillpacks') is '\home\u\.gbrain\-// skillpacks', which is right, not a bug. Only the separator comes from-// `path`; the subdirectory names being asserted are still hand-written.-const GBRAIN_HOME = process.platform === 'win32' ? 'C:\\gb' : '/home/u/.gbrain';--describe('v0.39 T14 — artifact abstraction', () => {- test('detectArtifactKind by extension', () => {- expect(detectArtifactKind('/tmp/foo.gbrain-schema')).toBe('schemapack');- expect(detectArtifactKind('/tmp/foo.gbrain-skillpack')).toBe('skillpack');- expect(detectArtifactKind('/tmp/foo.tar.gz')).toBe(null);- });-- test('targetDirForKind routes to distinct subdirectories', () => {- expect(targetDirForKind('schemapack', GBRAIN_HOME)).toBe(`${GBRAIN_HOME}${sep}schema-packs`);- expect(targetDirForKind('skillpack', GBRAIN_HOME)).toBe(`${GBRAIN_HOME}${sep}skillpacks`);- });-- test('validateManifestByKind: schemapack happy path', () => {- expect(() => validateManifestByKind('schemapack', { api_version: 'gbrain-schema-pack-v1' })).not.toThrow();- });-- test('validateManifestByKind: skillpack happy path', () => {- expect(() => validateManifestByKind('skillpack', { api_version: 'gbrain-skillpack-v1' })).not.toThrow();- });-- test('validateManifestByKind: rejects wrong api_version', () => {- expect(() => validateManifestByKind('schemapack', { api_version: 'gbrain-skillpack-v1' })).toThrow(/api_version/);- expect(() => validateManifestByKind('skillpack', { api_version: 'gbrain-schema-pack-v1' })).toThrow(/api_version/);- });-- test('validateManifestByKind: rejects non-object', () => {- expect(() => validateManifestByKind('schemapack', null)).toThrow();- expect(() => validateManifestByKind('skillpack', 'string')).toThrow();- });-});diff --git a/test/asymmetric-encoding-contract.test.ts b/test/asymmetric-encoding-contract.test.tsindex ac62785a11..68897dc840 100644--- a/test/asymmetric-encoding-contract.test.ts+++ b/test/asymmetric-encoding-contract.test.ts@@ -8,19 +8,15 @@** Why this test exists (D17):* The original audit was a source-text grep — fragile under refactors- * that rename `gateway` to `gw` or alias-import `{ embed }`. This test- * uses the `__setEmbedTransportForTests` mock to capture every HTTP- * body the transport sees during a representative search call, then- * asserts the query call carries `input_type: 'query'`.- *- * The complementary source-text check stays here as a SECOND layer- * (cheap belt-and-suspenders): if `hybrid.ts` ever stops importing- * `embedQuery`, this test fails before the regression ships.+ * that rename `gateway` to `gw` or alias-import `{ embed }`. These tests+ * use the `__setEmbedTransportForTests` mock to capture the provider+ * options the transport sees, both for the gateway primitives and for+ * `embedQueryBounded` — the helper both hybridSearch query-embed call+ * sites go through — and assert the query call carries+ * `input_type: 'query'`.*/import { describe, test, expect, afterEach } from 'bun:test';-import { readFileSync } from 'fs';-import { resolve } from 'path';import {configureGateway,resetGateway,@@ -28,6 +24,7 @@ import {embedQuery,__setEmbedTransportForTests,} from '../src/core/ai/gateway.ts';+import { embedQueryBounded, makeQueryEmbedDeadline } from '../src/core/search/hybrid.ts';function configureVoyage() {configureGateway({@@ -76,41 +73,17 @@ describe('Search read path uses embedQuery (D17 behavior contract)', () => {});});-describe('Source-text contract (cheap belt + suspenders)', () => {- // These tests fail-fast if a refactor accidentally swaps embedQuery → embed- // on the search read path. The behavior test above catches the runtime- // regression; this catches the static one (broken import, renamed helper).-- test('src/core/search/hybrid.ts imports embedQuery from embedding.ts', () => {- const src = readFileSync(- resolve(process.cwd(), 'src/core/search/hybrid.ts'),- 'utf8',- );- // The import must include embedQuery; matches both `embedQuery` and `{ embed, embedQuery }`.- expect(src).toMatch(/from '..\/embedding.ts'/);- expect(src).toContain('embedQuery');- });-- test('src/core/search/hybrid.ts calls embedQuery at the search-time query path', () => {- const src = readFileSync(- resolve(process.cwd(), 'src/core/search/hybrid.ts'),- 'utf8',- );- // Look for the call site (any whitespace shape). The line at 414 today is- // `await Promise.all(queries.map(q => embedQuery(q)))`. The regex stays- // permissive: match `embedQuery(` anywhere in the file body.- expect(src).toMatch(/embedQuery\s*\(/);- });+describe('hybridSearch query embedding uses query encoding', () => {+ test('embedQueryBounded sends input_type=query for Voyage', async () => {+ configureVoyage();+ let capturedOpts: any = null;+ __setEmbedTransportForTests((async (args: any) => {+ capturedOpts = args.providerOptions;+ return fakeEmbeddings(1, 1024);+ }) as any);- test('src/core/embedding.ts re-exports both embed and embedQuery', () => {- const src = readFileSync(- resolve(process.cwd(), 'src/core/embedding.ts'),- 'utf8',- );- // The embedding module is the seam between gateway and search.- // Both functions MUST be exported so consumers can route correctly.- expect(src).toMatch(/export\s+(?:async\s+)?function\s+embed\s*\(|export\s*\{[^}]*\bembed\b/);- expect(src).toMatch(/export\s+(?:async\s+)?function\s+embedQuery\s*\(|export\s*\{[^}]*\bembedQuery\b/);+ await embedQueryBounded('what does foo bar do?', undefined, makeQueryEmbedDeadline());+ expect(capturedOpts?.openaiCompatible?.input_type).toBe('query');});});diff --git a/test/attendance-repair.test.ts b/test/attendance-repair.test.tsindex 5517b852da..5afbfae110 100644--- a/test/attendance-repair.test.ts+++ b/test/attendance-repair.test.ts@@ -12,6 +12,7 @@ import { softDeleteSource, restoreSource } from '../src/core/destructive-guard.timport { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';import { attendanceRepairConnectionIdentity } from '../src/commands/extract-attendance-repair.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';const sourceId = 'repair-fixture';const person = 'people/alice-example';@@ -20,7 +21,7 @@ const positive = 'Attendees: [Alice Example](../people/alice-example.md)';const pack = { api_version: 'gbrain-schema-pack-v1', name: 'repair-fixture', version: '1.0.0', extends: null,page_types: [], link_types: [], frontmatter_links: [] };-for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]) {+for (const kind of testBackends()) {describe(`preview-bound attendance repair (${kind}; repair-fixture non-overridden person_to_meeting)`, () => {let engine: BrainEngine;let close: () => Promise<void>;diff --git a/test/attendance-retrieval.test.ts b/test/attendance-retrieval.test.tsindex 75043bb502..2f8fc65707 100644--- a/test/attendance-retrieval.test.ts+++ b/test/attendance-retrieval.test.ts@@ -17,13 +17,14 @@ import { bundledPackPath } from '../src/core/schema-pack/bundled-assets.ts';import { loadActivePackForLocalEngine } from '../src/core/schema-pack/best-effort.ts';import { installFixtureChunks } from './helpers/page-projection.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';const sourceId = 'attendance-fixture';const person = 'people/alice-example';const meeting = 'meetings/planning';const positive = 'Attendees: [Alice](../people/alice-example.md)';-for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]) {+for (const kind of testBackends()) {describe(`non-overridden canonical attendance lifecycle (${kind})`, () => {let engine: BrainEngine;let close: () => Promise<void>;diff --git a/test/auto-link-targeted-probe-2544.test.ts b/test/auto-link-targeted-probe-2544.test.tsindex 0a39e4c81a..16cfacda38 100644--- a/test/auto-link-targeted-probe-2544.test.ts+++ b/test/auto-link-targeted-probe-2544.test.ts@@ -129,7 +129,7 @@ describe('#2544 — auto-link behavior through put_page (targeted probe)', () =>// array parameter without server-side type context, so a bare ANY($1)// relies on inference the house style never does (cf. dropPrivateSlugs in// the same file). Pin the cast on EVERY slug-array probe in pages.ts.- // test-reads-source-ok: postgres.js-only bind-cast bug is invisible on the PGLite runtime path; the ::text[] cast pin is the unit-testable seam+ // test-reads-source-ok[structural]: postgres.js-only bind-cast bug is invisible on the PGLite runtime path; the ::text[] cast pin is the unit-testable seamconst src = readFileSync(join(import.meta.dir, '../src/core/persistence/links-preparation.ts'), 'utf8');const probes = src.match(/slug\s*=\s*ANY\(\$\d+[^)]*\)/g) ?? [];expect(probes.length).toBe(1); // one source-scoped publication probediff --git a/test/backfill-base.test.ts b/test/backfill-base.test.tsindex b6605deadc..832c5f1711 100644--- a/test/backfill-base.test.ts+++ b/test/backfill-base.test.ts@@ -1,6 +1,8 @@-import { describe, expect, test } from 'bun:test';+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { runBackfill, ensureBackfillIndex, clearBackfillCheckpoint } from '../src/core/backfill-base.ts';import type { BackfillSpec } from '../src/core/backfill-base.ts';+import { getBackfill, listBackfills } from '../src/core/backfill-registry.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';interface FakeRow {id: number;@@ -176,3 +178,38 @@ describe('ensureBackfillIndex — P2/X4', () => {expect(result.created).toBe(false);});});++describe('backfill registry', () => {+ test('listBackfills returns the canonical registry entries', () => {+ const names = listBackfills().map(e => e.spec.name).sort();+ expect(names).toEqual(['effective_date', 'embedding_voyage', 'emotional_weight', 'modality']);+ });++ test('embedding_voyage is declared-only', () => {+ expect(getBackfill('embedding_voyage')?.v030_1_status).toBe('declared-only');+ });+});++describe('implemented backfills against a freshly initialized PGLite brain', () => {+ let engine: PGLiteEngine;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });++ afterAll(async () => {+ await engine.disconnect();+ });++ for (const name of ['effective_date', 'emotional_weight', 'modality']) {+ test(`${name} finds every column it reads and has no work on an empty brain`, async () => {+ const reg = getBackfill(name);+ expect(reg?.v030_1_status).toBe('implemented');+ const result = await runBackfill(engine, reg!.spec, { batchSize: 100 });+ expect(result.examined).toBe(0);+ expect(result.errors).toBe(0);+ });+ }+});diff --git a/test/e2e/backfill-perf-pglite.test.ts b/test/backfill-perf-pglite.test.tssimilarity index 84%rename from test/e2e/backfill-perf-pglite.test.tsrename to test/backfill-perf-pglite.test.tsindex 05df3a0dac..3a7a90f98b 100644--- a/test/e2e/backfill-perf-pglite.test.ts+++ b/test/backfill-perf-pglite.test.ts@@ -10,11 +10,15 @@* wall-clock < 5s on the same fixture pattern. Goal is to catch a regression* to N+1 — a fast machine on PGLite in-memory should finish in well under* a second; the 5s budget is generous for slow CI.+ *+ * Lane: unit. Run: `bun test test/backfill-perf-pglite.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { runPhaseRecomputeEmotionalWeight } from '../../src/core/cycle/recompute-emotional-weight.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runPhaseRecomputeEmotionalWeight } from '../src/core/cycle/recompute-emotional-weight.ts';let engine: PGLiteEngine;diff --git a/test/backlinks-job-default.test.ts b/test/backlinks-job-default.test.tsdeleted file mode 100644index 399273438d..0000000000--- a/test/backlinks-job-default.test.ts+++ /dev/null@@ -1,47 +0,0 @@-/**- * Structural regression for the backlinks Minion handler default.- *- * Backlinks jobs submitted with an EMPTY payload (the sync→embed→backlinks- * chains enqueued after every ingestion) must run as 'check', never 'fix'.- * The pre-fix handler inverted the default (`=== 'check' ? 'check' : 'fix'`),- * so every routine post-ingestion job rewrote tracked brain pages with- * generated "Referenced in" timeline bullets — contradicting the documented- * intent in src/core/cycle.ts (runPhaseBacklinks): "Maintenance cycles must- * not rewrite tracked brain pages with generated 'Referenced in' timeline- * bullets."- *- * Source-grep is the right tool here (see fix-wave-structural.test.ts): the- * handler dynamically imports runBacklinksCore and walks a real repo dir, so- * a behavioral test would require heavy mocking that hides the regression- * behind a test seam. The rule is "this specific default must stay 'check'".- */-import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'fs';--describe('backlinks Minion handler — empty payload defaults to check, not fix', () => {- const src = readFileSync('src/commands/jobs.ts', 'utf8');-- // Isolate the backlinks register block so assertions can't accidentally- // match another handler's action parsing.- const blockMatch = src.match(- /worker\.register\('backlinks',[\s\S]*?runBacklinksCore\(\{[\s\S]*?\}\);/- );-- test('the backlinks handler block exists', () => {- expect(blockMatch).not.toBeNull();- });-- test("default action is 'check' (explicit opt-in required for 'fix')", () => {- const block = blockMatch![0];- expect(block).toMatch(- /job\.data\.action\s*===\s*'fix'\s*\?\s*'fix'\s*:\s*'check'/- );- });-- test('the inverted (fix-by-default) shape stays absent', () => {- const block = blockMatch![0];- expect(block).not.toMatch(- /job\.data\.action\s*===\s*'check'\s*\?\s*'check'\s*:\s*'fix'/- );- });-});diff --git a/test/backoff.test.ts b/test/backoff.test.tsindex 9873e56b09..cfa5cdee23 100644--- a/test/backoff.test.ts+++ b/test/backoff.test.ts@@ -19,20 +19,12 @@ describe('backoff', () => {});test('concurrent process limit blocks when exceeded', () => {- // Directly simulate 2 active processes by calling preflight with infinite thresholds- // Even on a loaded system, we need the counter to increment- // So we use complete() in reverse: start at 0, manually register via internals- // Actually, just call shouldProceed after manually setting state- const allPermissive = { loadStopPct: 1.0, loadSlowPct: 1.0, memoryStopPct: 1.0 };+ // Infinite thresholds: host load and memory can never block, so only the+ // concurrency counter decides.+ const allPermissive = { loadStopPct: Infinity, loadSlowPct: Infinity, memoryStopPct: Infinity };// First check: should proceed (0 active)- const r1 = shouldProceed(allPermissive);- // If even fully permissive fails, system is truly overloaded beyond our control- if (!r1.proceed) {- // Can't test concurrency on a system where even permissive fails- expect(true).toBe(true);- return;- }+ expect(shouldProceed(allPermissive).proceed).toBe(true);// Register 2 processes by calling preflight with permissive configpreflight('a', allPermissive);@@ -45,11 +37,9 @@ describe('backoff', () => {});test('complete decrements active process count', async () => {- const cfg = { loadStopPct: 1.0, loadSlowPct: 1.0, memoryStopPct: 1.0 };- const ok1 = await preflight('test-1', cfg);- if (!ok1) { expect(true).toBe(true); return; } // system too loaded to test- const ok2 = await preflight('test-2', cfg);- if (!ok2) { expect(true).toBe(true); return; }+ const cfg = { loadStopPct: Infinity, loadSlowPct: Infinity, memoryStopPct: Infinity };+ expect(await preflight('test-1', cfg)).toBe(true);+ expect(await preflight('test-2', cfg)).toBe(true);complete();const state = getThrottleState();expect(state.activeProcesses).toBe(1);@@ -111,14 +101,6 @@ describe('backoff', () => {}});- test('_resetForTest clears module state', async () => {- const cfg = { loadStopPct: 1.0, loadSlowPct: 1.0, memoryStopPct: 1.0 };- await preflight('a', cfg);- _resetForTest();- const state = getThrottleState();- expect(state.activeProcesses).toBe(0);- });-test('delay is a non-negative number', () => {const result = shouldProceed();expect(result.delay).toBeGreaterThanOrEqual(0);diff --git a/test/batch-projection.test.ts b/test/batch-projection.test.tsdeleted file mode 100644index f2a969b23e..0000000000--- a/test/batch-projection.test.ts+++ /dev/null@@ -1,282 +0,0 @@-/**- * v0.41 D4 — batch projection unit tests.- *- * Pure-function math; no DB or LLM needed. Pins the 4 critical contracts:- *- * 1. Cold-start fallback (no history → wide-guess with annotation)- * 2. Unknown model → cost_estimate_unavailable tagged variant- * 3. ±30% confidence band (or sample-stddev-derived when historical)- * 4. Threshold gating respects env-var overrides- * 5. Raise-cap hint fires only when lease cap is binding + meaningful speedup- */--import { describe, test, expect } from 'bun:test';-import {- projectBatch,- formatProjection,- shouldPromptAtThreshold,- type RecentJobStats,-} from '../src/core/minions/batch-projection.ts';-import { withEnv } from './helpers/with-env.ts';--function coldStats(opts: Partial<RecentJobStats> = {}): RecentJobStats {- return {- sample_size: 0,- effective_concurrency: 8,- ...opts,- };-}--function warmStats(opts: Partial<RecentJobStats> = {}): RecentJobStats {- return {- sample_size: 100,- mean_latency_ms: 4000,- mean_cost_usd: 0.03,- stddev_cost_usd: 0.01,- effective_concurrency: 8,- ...opts,- };-}--describe('projectBatch', () => {- test('cold start: no history → cold_start=true with model-default cost guess', () => {- const p = projectBatch({- job_count: 100,- model: 'anthropic:claude-sonnet-4-6',- stats: coldStats(),- current_lease_cap: 32,- });- expect(p.cold_start).toBe(true);- expect(p.total_cost_usd).toBeGreaterThan(0);- expect(p.total_duration_ms).toBeGreaterThan(0);- // 100 jobs at concurrency=8, ~5s each → ≈63s.- expect(p.effective_concurrency).toBe(8);- });-- test('unknown model → unknown_model tagged variant, total_cost_usd=null', () => {- const p = projectBatch({- job_count: 100,- model: 'mystery:foo-2',- stats: coldStats(),- current_lease_cap: 32,- });- expect(p.unknown_model).toBe('foo-2');- expect(p.total_cost_usd).toBeNull();- expect(p.cost_band_usd).toBeNull();- // Duration is still computable from latency × jobs / concurrency.- expect(p.total_duration_ms).toBeGreaterThan(0);- });-- test('warm window with stddev → uses stddev-derived band (×1.96 ≈ 95%)', () => {- const p = projectBatch({- job_count: 100,- model: 'anthropic:claude-sonnet-4-6',- stats: warmStats({ mean_cost_usd: 0.05, stddev_cost_usd: 0.02 }),- current_lease_cap: 32,- });- expect(p.cold_start).toBe(false);- expect(p.total_cost_usd).toBeCloseTo(5.00, 2); // 100 × $0.05- expect(p.cost_band_usd).toBeCloseTo(100 * 0.02 * 1.96, 1); // ≈ $3.92- });-- test('warm window without stddev → blanket ±30% band', () => {- const p = projectBatch({- job_count: 100,- model: 'anthropic:claude-sonnet-4-6',- stats: warmStats({ stddev_cost_usd: undefined, mean_cost_usd: 0.05 }),- current_lease_cap: 32,- });- expect(p.cost_band_usd).toBeCloseTo(p.total_cost_usd! * 0.30, 2);- });-- test('effective_concurrency clamps to min(seen, lease_cap)', () => {- const p = projectBatch({- job_count: 100,- model: 'anthropic:claude-sonnet-4-6',- stats: warmStats({ effective_concurrency: 16 }),- current_lease_cap: 4, // tighter than seen- });- expect(p.effective_concurrency).toBe(4);- });-- test('raise_cap_hint fires when lease is binding AND a 4x raise meaningfully helps', () => {- const p = projectBatch({- job_count: 1000,- model: 'anthropic:claude-sonnet-4-6',- stats: warmStats({- effective_concurrency: 32, // seen lots; lease is the constraint- lease_headroom: 0.05, // hot — nearly saturated- }),- current_lease_cap: 8,- });- expect(p.raise_cap_hint).toBeDefined();- expect(p.raise_cap_hint).toContain('GBRAIN_ANTHROPIC_MAX_INFLIGHT');- });-- test('no raise_cap_hint when not binding', () => {- const p = projectBatch({- job_count: 100,- model: 'anthropic:claude-sonnet-4-6',- stats: warmStats({ lease_headroom: 0.8 }), // plenty of room- current_lease_cap: 32,- });- expect(p.raise_cap_hint).toBeUndefined();- });-- test('no raise_cap_hint when already at the ceiling', () => {- const p = projectBatch({- job_count: 100,- model: 'anthropic:claude-sonnet-4-6',- stats: warmStats({ lease_headroom: 0.05 }),- current_lease_cap: 128, // at ceiling- });- expect(p.raise_cap_hint).toBeUndefined();- });-- describe('v0.41.20.0 — slash-prefix model id routing (THE FIX)', () => {- test('slash-form anthropic/claude-sonnet-4-6 strips to bare name + pricing hits', () => {- // Pre-fix: inline bareModel(model) only handled `:`; slash-form fell- // through to the unknown_model branch silently. Post-fix: parseModelId- // handles both forms; pricing lookup succeeds; cold-start path produces- // a non-null cost estimate.- const p = projectBatch({- job_count: 100,- model: 'anthropic/claude-sonnet-4-6',- stats: { sample_size: 0, effective_concurrency: 4 },- current_lease_cap: 32,- });- expect(p.unknown_model).toBeUndefined();- expect(p.total_cost_usd).not.toBeNull();- expect(p.total_cost_usd).toBeGreaterThan(0);- });-- test('double-separator openrouter:anthropic/X → unknown_model branch fires', () => {- // Per D2: colon wins; tail is `anthropic/claude-sonnet-4-6` which- // doesn't match ANTHROPIC_PRICING keys. Confirms the deliberate- // OpenRouter-out-of-scope posture is observable downstream.- const p = projectBatch({- job_count: 100,- model: 'openrouter:anthropic/claude-sonnet-4-6',- stats: { sample_size: 0, effective_concurrency: 4 },- current_lease_cap: 32,- });- expect(p.unknown_model).toBe('anthropic/claude-sonnet-4-6');- expect(p.total_cost_usd).toBeNull();- });- });-});--describe('formatProjection', () => {- test('known model: prints cost + duration + bands', () => {- const s = formatProjection({- total_duration_ms: 600_000, // 10 min- total_cost_usd: 2.40,- cost_band_usd: 0.72,- duration_band_ms: 180_000,- effective_concurrency: 8,- cold_start: false,- });- expect(s).toContain('$2.40');- expect(s).toContain('±$0.72');- expect(s).toContain('10min');- expect(s).toContain('concurrency=8');- expect(s).not.toContain('no history');- });-- test('cold start: includes annotation', () => {- const s = formatProjection({- total_duration_ms: 600_000,- total_cost_usd: 2.40,- cost_band_usd: 0.72,- duration_band_ms: 180_000,- effective_concurrency: 8,- cold_start: true,- });- expect(s).toContain('no history');- expect(s).toContain('wide guess');- });-- test('unknown model: replaces cost section with explanation', () => {- const s = formatProjection({- total_duration_ms: 600_000,- total_cost_usd: null,- cost_band_usd: null,- duration_band_ms: 180_000,- effective_concurrency: 8,- cold_start: true,- unknown_model: 'foo-2',- });- expect(s).toContain('cost estimate unavailable');- expect(s).toContain('foo-2');- expect(s).toContain('pricing maps');- });-- test('raise-cap hint surfaces inline', () => {- const s = formatProjection({- total_duration_ms: 600_000,- total_cost_usd: 2.40,- cost_band_usd: 0.72,- duration_band_ms: 180_000,- effective_concurrency: 8,- cold_start: false,- raise_cap_hint: 'raise GBRAIN_ANTHROPIC_MAX_INFLIGHT to 32 to finish in ~3min',- });- expect(s).toContain('raise GBRAIN_ANTHROPIC_MAX_INFLIGHT to 32');- });-});--describe('shouldPromptAtThreshold', () => {- test('prompts at >$5 default threshold', () => {- expect(- shouldPromptAtThreshold({- total_duration_ms: 60_000,- total_cost_usd: 5.01,- cost_band_usd: 1,- duration_band_ms: 10_000,- effective_concurrency: 8,- cold_start: false,- }),- ).toBe(true);- });-- test('prompts at >30min default threshold', () => {- expect(- shouldPromptAtThreshold({- total_duration_ms: 31 * 60_000,- total_cost_usd: 0.50,- cost_band_usd: 0.10,- duration_band_ms: 60_000,- effective_concurrency: 8,- cold_start: false,- }),- ).toBe(true);- });-- test('does NOT prompt below both thresholds', () => {- expect(- shouldPromptAtThreshold({- total_duration_ms: 60_000,- total_cost_usd: 2.00,- cost_band_usd: 0.50,- duration_band_ms: 10_000,- effective_concurrency: 8,- cold_start: false,- }),- ).toBe(false);- });-- test('env var GBRAIN_BATCH_PROMPT_THRESHOLD_USD lowers the prompt floor', async () => {- await withEnv({ GBRAIN_BATCH_PROMPT_THRESHOLD_USD: '1' }, async () => {- expect(- shouldPromptAtThreshold({- total_duration_ms: 60_000,- total_cost_usd: 1.50,- cost_band_usd: 0.20,- duration_band_ms: 10_000,- effective_concurrency: 8,- cold_start: false,- }),- ).toBe(true);- });- });-});diff --git a/test/book-mirror.test.ts b/test/book-mirror.test.tsindex 0ee65994c3..b9a7b0f23c 100644--- a/test/book-mirror.test.ts+++ b/test/book-mirror.test.ts@@ -91,17 +91,6 @@ describe('gbrain book-mirror — source file invariants', () => {'utf-8',);- it('exports runBookMirrorCmd', () => {- expect(source).toContain('export async function runBookMirrorCmd');- });-- it('documents the trust contract (codex HIGH-1 fix is in the file)', () => {- // codex HIGH-1 fix: the trust contract narrowing must not silently- // regress in a refactor.- expect(source).toContain('media/books/');- expect(source).toContain('codex HIGH-1');- });-it('uses read-only allowed_tools for subagent fan-out (codex HIGH-1)', () => {// The trust narrowing actually happens at the tool-allowlist layer:// subagents get ['get_page', 'search'] — read-only — so they CANNOT@@ -120,23 +109,4 @@ describe('gbrain book-mirror — source file invariants', () => {// contract by adding the wrong fields.expect(source).toContain('viaSubagent intentionally omitted');});-- it('prints a cost-estimate confirmation before launching (P1)', () => {- expect(source).toContain('estimateCost');- expect(source).toContain('confirmInteractive');- });-- it('uses idempotency keys for child jobs (retry-friendly)', () => {- // Re-running the CLI on the same input should dedupe completed- // chapters at the queue layer.- expect(source).toContain('idempotency_key');- expect(source).toContain('book-mirror:');- });-- it('handles partial-failure (continues + flags failed chapters)', () => {- // The plan said: assemble with completed chapters + a failed-list- // section. Don't abort the whole run on one chapter failure.- expect(source).toContain('Failed chapters');- expect(source).toContain('chapters_failed');- });});diff --git a/test/e2e/bootstrap-harness-lifecycle.serial.test.ts b/test/bootstrap-harness-lifecycle.serial.test.tssimilarity index 95%rename from test/e2e/bootstrap-harness-lifecycle.serial.test.tsrename to test/bootstrap-harness-lifecycle.serial.test.tsindex 8a948dc60e..3f2cd79454 100644--- a/test/e2e/bootstrap-harness-lifecycle.serial.test.ts+++ b/test/bootstrap-harness-lifecycle.serial.test.ts@@ -13,6 +13,10 @@* remapped so user-scope writes land in the sandbox.** Serial: env remapping (HOME / CODEX_HOME / GBRAIN_HOME) + a spawned serve.+ *+ * Lane: serial. Run: `bash scripts/run-serial-tests.sh test/bootstrap-harness-lifecycle.serial.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';@@ -21,11 +25,11 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSyncimport { tmpdir } from 'os';import { join } from 'path';-import { runBootstrap } from '../../src/commands/bootstrap.ts';-import type { ExecRunner } from '../../src/core/bootstrap/repo.ts';-import { readHarnessReceiptState, writeHarnessReceipt } from '../../src/core/bootstrap/format.ts';-import { CODEX_TOML_BLOCK_BEGIN } from '../../src/core/bootstrap/host-specs.ts';-import { withEnv } from '../helpers/with-env.ts';+import { runBootstrap } from '../src/commands/bootstrap.ts';+import type { ExecRunner } from '../src/core/bootstrap/repo.ts';+import { readHarnessReceiptState, writeHarnessReceipt } from '../src/core/bootstrap/format.ts';+import { CODEX_TOML_BLOCK_BEGIN } from '../src/core/bootstrap/host-specs.ts';+import { withEnv } from './helpers/with-env.ts';const PORT = 19741; // unique to this suite (19735 = connect-bearer, 19131 = oauth)const BASE = `http://127.0.0.1:${PORT}`;@@ -111,7 +115,7 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {// carrying an executable no-op `claude` stub — the recording runner seam// intercepts every real exec, so the stub only ever satisfies detection.PATH: `${stubBin}:${process.env.PATH ?? ''}`,- // The e2e lane exports DATABASE_URL; the IN-PROCESS runBootstrap calls+ // With an ambient DATABASE_URL, the IN-PROCESS runBootstrap calls// (unlike the spawned children scrubbed in beforeAll) would otherwise// resolve it via loadConfig's env>file precedence and mint tokens// against Postgres while the live serve is PGLite-backed — turning thediff --git a/test/e2e/bootstrap-hook-under-serve.serial.test.ts b/test/bootstrap-hook-under-serve.serial.test.tssimilarity index 96%rename from test/e2e/bootstrap-hook-under-serve.serial.test.tsrename to test/bootstrap-hook-under-serve.serial.test.tsindex 36bf7a3efa..802d482f93 100644--- a/test/e2e/bootstrap-hook-under-serve.serial.test.ts+++ b/test/bootstrap-hook-under-serve.serial.test.ts@@ -27,6 +27,10 @@** Serial: spawns a subprocess + cold PGLite init; explicit timeouts* everywhere; the serve child is killed in afterAll no matter what.+ *+ * Lane: serial. Run: `bash scripts/run-serial-tests.sh test/bootstrap-hook-under-serve.serial.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import {@@ -42,17 +46,17 @@ import {import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';-import { runHook, readHeartbeatTail } from '../../src/commands/hook.ts';-import { resolveSocketPath, ipcSecretPath } from '../../src/core/context/resolve-ipc.ts';-import { LiveServeLockError } from '../../src/core/pglite-lock.ts';-import { createEngine } from '../../src/core/engine-factory.ts';-import { addSource } from '../../src/core/sources-ops.ts';+import { runHook, readHeartbeatTail } from '../src/commands/hook.ts';+import { resolveSocketPath, ipcSecretPath } from '../src/core/context/resolve-ipc.ts';+import { LiveServeLockError } from '../src/core/pglite-lock.ts';+import { createEngine } from '../src/core/engine-factory.ts';+import { addSource } from '../src/core/sources-ops.ts';import {loadCorpusPages,loadCorpusBeliefs,loadCorpusBeliefData,loadCorpusQueries,-} from '../helpers/bootstrap-corpus.ts';+} from './helpers/bootstrap-corpus.ts';// The serve appends its own checkpoint-harvest/writeback heartbeats to the same// JSONL asynchronously, so the hook's entry is the newest non-serve line.@@ -63,7 +67,7 @@ async function lastHookHeartbeat() {return entry;}-const REPO_ROOT = resolve(import.meta.dir, '..', '..');+const REPO_ROOT = resolve(import.meta.dir, '..');const TRANSCRIPT_FIXTURE = join(REPO_ROOT, 'test', 'fixtures', 'conversation-formats', 'claude-code.jsonl');/**diff --git a/test/bootstrap.test.ts b/test/bootstrap.test.tsindex 401ed56be7..5299b9142d 100644--- a/test/bootstrap.test.ts+++ b/test/bootstrap.test.ts@@ -406,4 +406,42 @@ describe('PGLiteEngine#applyForwardReferenceBootstrap', () => {}}, 30000);+ test('compounded pre-v34 brain (v0.20 + v0.26.3 + v0.27 + v39-v41 gaps) walks forward to LATEST', async () => {+ const engine = new PGLiteEngine();+ await engine.connect({});+ try {+ await engine.initSchema();+ const dropped: Array<[string, string]> = [+ ['content_chunks', 'parent_symbol_path'], ['content_chunks', 'doc_comment'],+ ['content_chunks', 'symbol_name_qualified'], ['content_chunks', 'search_vector'],+ ['mcp_request_log', 'agent_name'], ['mcp_request_log', 'params'], ['mcp_request_log', 'error_message'],+ ['subagent_messages', 'provider_id'],+ ['content_chunks', 'embedding_image'], ['content_chunks', 'modality'],+ ['pages', 'emotional_weight'], ['pages', 'effective_date'], ['pages', 'effective_date_source'],+ ['pages', 'import_filename'], ['pages', 'salience_touched_at'],+ ];+ await (engine as any).db.exec(`+ DROP INDEX IF EXISTS idx_chunks_search_vector;+ DROP INDEX IF EXISTS idx_chunks_symbol_qualified;+ DROP TRIGGER IF EXISTS chunk_search_vector_trigger ON content_chunks;+ DROP FUNCTION IF EXISTS update_chunk_search_vector;+ DROP INDEX IF EXISTS idx_mcp_log_agent_time;+ DROP INDEX IF EXISTS idx_subagent_messages_provider;+ DROP INDEX IF EXISTS idx_chunks_embedding_image;+ ${dropped.map(([table, column]) => `ALTER TABLE ${table} DROP COLUMN IF EXISTS ${column} CASCADE;`).join('\n ')}+ UPDATE config SET value = '13' WHERE key = 'version';+ `);++ await engine.initSchema();++ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));+ const present = await engine.executeRaw<{ table_name: string; column_name: string }>(+ `SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = 'public'`,+ );+ const have = new Set(present.map(r => `${r.table_name}.${r.column_name}`));+ expect(dropped.map(([table, column]) => `${table}.${column}`).filter(c => !have.has(c))).toEqual([]);+ } finally {+ await engine.disconnect();+ }+ }, 30000);});diff --git a/test/budget-tracker.test.ts b/test/budget-tracker.test.tsdeleted file mode 100644index f1d07d51d0..0000000000--- a/test/budget-tracker.test.ts+++ /dev/null@@ -1,230 +0,0 @@-/**- * v0.41 D5 + Eng D7 + Eng D10 — budget-tracker tests.- *- * Pins the reservation pattern's load-bearing contracts:- *- * - reserveBudget: CAS UPDATE prevents overspend even across parallel- * children of the same owner.- * - Eng D10 NULL-bypass: jobs without an owner skip reservation cleanly.- * - Eng D10 owner-deleted disambiguation: pruned-owner orphans throw- * BudgetOwnerDeleted instead of silently bypassing.- * - refundBudget returns unspent cents to the owner row.- * - haltBudgetSubtree walks all waiting/delayed descendants of an owner.- * - Audit rows written to minion_budget_log per event.- */--import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { MinionQueue } from '../src/core/minions/queue.ts';-import {- reserveBudget,- refundBudget,- setOwnerBudget,- inheritBudgetOwner,- haltBudgetSubtree,- getBudgetOwner,-} from '../src/core/minions/budget-tracker.ts';--let engine: PGLiteEngine;-let queue: MinionQueue;--beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({ database_url: '' });- await engine.initSchema();- queue = new MinionQueue(engine);-});--afterAll(async () => {- await engine.disconnect();-});--beforeEach(async () => {- await engine.executeRaw('DELETE FROM minion_budget_log');- await engine.executeRaw('DELETE FROM minion_jobs');-});--describe('reserveBudget (CAS pattern)', () => {- test('reserves cents from owner balance; CAS succeeds when balance >= cost', async () => {- const owner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, owner.id, 1.0); // $1.00 = 100¢- const child = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await inheritBudgetOwner(engine, child.id, owner.id);-- const outcome = await reserveBudget(engine, child.id, 30);- expect(outcome.kind).toBe('reserved');- if (outcome.kind === 'reserved') {- expect(outcome.new_balance_cents).toBe(70);- expect(outcome.reserved_cents).toBe(30);- }- // Audit row written.- const audit = await engine.executeRaw<{ count: string }>(- `SELECT count(*)::text AS count FROM minion_budget_log WHERE event_type = 'reserved'`,- );- expect(parseInt(audit[0]!.count, 10)).toBe(1);- });-- test('CAS miss returns exhausted; balance + requested visible for audit', async () => {- const owner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, owner.id, 0.10); // $0.10 = 10¢- const child = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await inheritBudgetOwner(engine, child.id, owner.id);-- const outcome = await reserveBudget(engine, child.id, 50);- expect(outcome.kind).toBe('exhausted');- if (outcome.kind === 'exhausted') {- expect(outcome.balance_at_attempt).toBe(10);- expect(outcome.requested_cents).toBe(50);- }- // Halted audit row written.- const audit = await engine.executeRaw<{ count: string }>(- `SELECT count(*)::text AS count FROM minion_budget_log WHERE event_type = 'halted'`,- );- expect(parseInt(audit[0]!.count, 10)).toBe(1);- });-- test('Eng D10: job with no owner returns no_budget (clean bypass)', async () => {- const child = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- // No setOwnerBudget call → budget_owner_job_id stays NULL.- const outcome = await reserveBudget(engine, child.id, 50);- expect(outcome.kind).toBe('no_budget');- });-- test('Eng D10: deleted owner (FK NULL but root denormalized) throws owner_deleted', async () => {- const owner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, owner.id, 1.0);- const child = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await inheritBudgetOwner(engine, child.id, owner.id);-- // Hard-delete the owner — simulates `gbrain jobs prune` race.- // SET NULL FK fires on the child's budget_owner_job_id but the- // immutable budget_root_owner_id persists.- await engine.executeRaw('DELETE FROM minion_jobs WHERE id = $1', [owner.id]);-- const outcome = await reserveBudget(engine, child.id, 50);- expect(outcome.kind).toBe('owner_deleted');- if (outcome.kind === 'owner_deleted') {- expect(outcome.root_owner_id).toBe(owner.id);- }- });-});--describe('refundBudget', () => {- test('returns unspent cents to owner', async () => {- const owner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, owner.id, 1.0);- const child = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await inheritBudgetOwner(engine, child.id, owner.id);-- await reserveBudget(engine, child.id, 50); // balance 100→50- await refundBudget(engine, child.id, owner.id, 30); // balance 50→80-- const after = await getBudgetOwner(engine, owner.id);- expect(after!.budget_remaining_cents).toBe(80);-- // Refund audit row.- const audit = await engine.executeRaw<{ count: string }>(- `SELECT count(*)::text AS count FROM minion_budget_log WHERE event_type = 'refunded'`,- );- expect(parseInt(audit[0]!.count, 10)).toBe(1);- });-- test('refund of 0 cents is a no-op', async () => {- const owner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, owner.id, 1.0);- const child = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await inheritBudgetOwner(engine, child.id, owner.id);- await reserveBudget(engine, child.id, 50);-- await refundBudget(engine, child.id, owner.id, 0);- const after = await getBudgetOwner(engine, owner.id);- expect(after!.budget_remaining_cents).toBe(50); // unchanged-- const audit = await engine.executeRaw<{ count: string }>(- `SELECT count(*)::text AS count FROM minion_budget_log WHERE event_type = 'refunded'`,- );- expect(parseInt(audit[0]!.count, 10)).toBe(0); // no audit row either- });-});--describe('haltBudgetSubtree', () => {- test('flips waiting + delayed children to dead with reason', async () => {- const owner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, owner.id, 1.0);- const c1 = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- const c2 = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- const c3 = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- for (const c of [c1, c2, c3]) {- await inheritBudgetOwner(engine, c.id, owner.id);- }-- // Move c2 to 'delayed' to verify both waiting AND delayed are halted.- await engine.executeRaw(- `UPDATE minion_jobs SET status = 'delayed', delay_until = now() + interval '1 hour' WHERE id = $1`,- [c2.id],- );-- const halted = await haltBudgetSubtree(engine, owner.id, 'budget_exhausted');- expect(halted).toBe(3);-- // Verify each child is dead.- for (const c of [c1, c2, c3]) {- const r = await engine.executeRaw<{ status: string; error_text: string }>(- `SELECT status, error_text FROM minion_jobs WHERE id = $1`,- [c.id],- );- expect(r[0]!.status).toBe('dead');- expect(r[0]!.error_text).toContain('budget_exhausted');- }- });-- test('does NOT touch active children (they finish their current turn cleanly)', async () => {- const owner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, owner.id, 1.0);- const c1 = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await inheritBudgetOwner(engine, c1.id, owner.id);- // Move c1 to 'active' to simulate in-flight.- await engine.executeRaw(- `UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1, lock_token = 'lock', lock_until = now() + interval '1 minute' WHERE id = $1`,- [c1.id],- );-- const halted = await haltBudgetSubtree(engine, owner.id, 'budget_exhausted');- expect(halted).toBe(0); // active jobs not flipped-- const r = await engine.executeRaw<{ status: string }>(- `SELECT status FROM minion_jobs WHERE id = $1`,- [c1.id],- );- expect(r[0]!.status).toBe('active');- });-});--describe('inheritBudgetOwner', () => {- test('child mirrors parent owner + root_owner; does NOT copy balance', async () => {- const owner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, owner.id, 1.0);- const child = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await inheritBudgetOwner(engine, child.id, owner.id);-- const info = await getBudgetOwner(engine, child.id);- expect(info!.budget_owner_job_id).toBe(owner.id);- expect(info!.budget_root_owner_id).toBe(owner.id);- // Critical: child's balance stays NULL — only owner row holds spendable cents.- expect(info!.budget_remaining_cents).toBeNull();- });-- test('grandchild inherits the original owner (chain depth 2)', async () => {- const owner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, owner.id, 1.0);- const child = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await inheritBudgetOwner(engine, child.id, owner.id);- const grand = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await inheritBudgetOwner(engine, grand.id, child.id);-- const info = await getBudgetOwner(engine, grand.id);- // Grandchild should point at the ORIGINAL owner, not its immediate parent.- expect(info!.budget_owner_job_id).toBe(owner.id);- expect(info!.budget_root_owner_id).toBe(owner.id);- });-});diff --git a/test/chat-key-plane.test.ts b/test/chat-key-plane.test.tsindex eb153e6391..f826ae5239 100644--- a/test/chat-key-plane.test.ts+++ b/test/chat-key-plane.test.ts@@ -51,14 +51,14 @@ describe('#3944 both planner surfaces share the helper (source guard)', () => {// queue + timers) — not unit-runnable, so the plane choice is pinned// structurally. The helper's BEHAVIOR is covered above.test('autopilot no longer probes the DB plane for the chat key', () => {- // test-reads-source-ok: the dispatch loop cannot run hermetically; this pins that the DB-plane read does not creep back.+ // test-reads-source-ok[structural]: the dispatch loop cannot run hermetically; this pins that the DB-plane read does not creep back.const src = readFileSync(join(import.meta.dir, '../src/commands/autopilot.ts'), 'utf-8');expect(src).not.toContain("getConfig('anthropic_api_key')");expect(src).toContain('chatApiKeyConfigured(fileCfg)');});test('doctor context uses the same shared helper', () => {- // test-reads-source-ok: pins that context.ts and autopilot resolve the chat key through ONE helper, not two drifting copies.+ // test-reads-source-ok[structural]: pins that context.ts and autopilot resolve the chat key through ONE helper, not two drifting copies.const src = readFileSync(join(import.meta.dir, '../src/core/remediation/context.ts'), 'utf-8');expect(src).toContain('chatApiKeyConfigured(fileCfg)');expect(src).not.toContain('process.env.ANTHROPIC_API_KEY ||');diff --git a/test/check-bootstrap-guards.test.ts b/test/check-bootstrap-guards.test.tsindex 317acb00f6..8cbbc86b01 100644--- a/test/check-bootstrap-guards.test.ts+++ b/test/check-bootstrap-guards.test.ts@@ -11,7 +11,7 @@import { describe, expect, test } from 'bun:test';import { spawnSync } from 'node:child_process';-import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join, resolve } from 'node:path';@@ -78,11 +78,6 @@ const BANK_JSON = JSON.stringify({const RUNBOOK_PINS = 'Claude Code and opencode\nDo NOT offer an MCP scope choice\nNO trust prompt\n';describe('check-bootstrap-tag.sh', () => {- test('exists and is executable', () => {- expect(existsSync(TAG_GUARD)).toBe(true);- expect((statSync(TAG_GUARD).mode & 0o100) !== 0).toBe(true);- });-test('passes on this repo', () => {const r = runGuard(TAG_GUARD, ROOT);expect(r.status).toBe(0);@@ -189,11 +184,6 @@ describe('check-bootstrap-tag.sh', () => {});describe('check-bootstrap-templates.sh', () => {- test('exists and is executable', () => {- expect(existsSync(TPL_GUARD)).toBe(true);- expect((statSync(TPL_GUARD).mode & 0o100) !== 0).toBe(true);- });-test('passes on this repo', () => {const r = runGuard(TPL_GUARD, ROOT);expect(r.status).toBe(0);@@ -448,22 +438,6 @@ describe('check-bootstrap-templates.sh', () => {});describe('verify + workflow wiring', () => {- test('both guards are registered in the verify dispatcher', () => {- const r = spawnSync('bash', [join(ROOT, 'scripts/run-verify-parallel.sh'), '--dry-list'], {- cwd: ROOT,- encoding: 'utf-8',- });- expect(r.status).toBe(0);- const checks = new Set(r.stdout.trim().split('\n'));- expect(checks).toContain('check:bootstrap-tag');- expect(checks).toContain('check:bootstrap-templates');- });-- test('package.json carries both check scripts', () => {- const pkg = require(join(ROOT, 'package.json'));- expect(pkg.scripts['check:bootstrap-tag']).toContain('check-bootstrap-tag.sh');- expect(pkg.scripts['check:bootstrap-templates']).toContain('check-bootstrap-templates.sh');- });test('bootstrap guards run for documentation changes without a result-cache bypass [C2]', () => {const workflow = require('node:fs').readFileSync(join(ROOT, '.github/workflows/test.yml'), 'utf8');@@ -695,12 +669,6 @@ describe('check-grok-pin.sh', () => {});});- test('verify wiring: run-verify-parallel CHECKS + package.json both carry check:grok-pin', () => {- const verify = require('node:fs').readFileSync(join(ROOT, 'scripts/run-verify-parallel.sh'), 'utf-8');- expect(verify).toContain('"check:grok-pin"');- const pkg = require('node:fs').readFileSync(join(ROOT, 'package.json'), 'utf-8');- expect(pkg).toContain('"check:grok-pin": "bash scripts/check-grok-pin.sh"');- });});// ── check-opencode-pin.sh ────────────────────────────────────────────────────diff --git a/test/check-resolvable.test.ts b/test/check-resolvable.test.tsindex 9de673b8dc..1a7933a7ea 100644--- a/test/check-resolvable.test.ts+++ b/test/check-resolvable.test.ts@@ -270,26 +270,6 @@ describe("checkResolvable — real skills directory", () => {expect(Array.isArray(report.issues)).toBe(true);});- test("all manifest skills are reachable from RESOLVER.md", () => {- const unreachableIssues = report.issues.filter(i => i.type === "unreachable");- if (unreachableIssues.length > 0) {- const names = unreachableIssues.map(i => i.skill).join(", ");- console.warn(`Unreachable skills: ${names}`);- }- // Currently expect all 24 skills to be reachable- expect(report.summary.unreachable).toBe(0);- });-- test("no missing files referenced by RESOLVER.md", () => {- const missingFiles = report.issues.filter(i => i.type === "missing_file");- expect(missingFiles.length).toBe(0);- });-- test("no orphan triggers (in resolver but not manifest)", () => {- const orphans = report.issues.filter(i => i.type === "orphan_trigger");- expect(orphans.length).toBe(0);- });-test("action strings are specific (contain file paths)", () => {for (const issue of report.issues) {expect(issue.action.length).toBeGreaterThan(10);@@ -720,3 +700,68 @@ describe("missing_file is reported once per skill path, not once per trigger row}});});++// ---------------------------------------------------------------------------+// Fixture trees for the unreachable-skill fix shape and the MECE whitelist.+// The real skills/ tree has no unreachable skills and no overlaps, so these+// contracts need their own inputs.+// ---------------------------------------------------------------------------++function writeSkillTree(skills: { name: string; triggers: string[]; resolverRow?: string }[]): string {+ const dir = mkdtempSync(join(tmpdir(), "gbrain-resolvable-"));+ const rows = skills.filter(s => s.resolverRow).map(s => `| "${s.resolverRow}" | \`skills/${s.name}/SKILL.md\` |`).join("\n");+ writeFileSync(join(dir, "RESOLVER.md"), `## Brain operations\n| Trigger | Skill |\n|-----|-----|\n${rows}\n`);+ writeFileSync(join(dir, "manifest.json"), JSON.stringify({ skills: skills.map(s => ({ name: s.name, path: `${s.name}/SKILL.md` })) }, null, 2));+ for (const s of skills) {+ mkdirSync(join(dir, s.name), { recursive: true });+ const triggers = s.triggers.length ? `triggers:\n${s.triggers.map(t => ` - "${t}"`).join("\n")}\n` : "";+ writeFileSync(join(dir, s.name, "SKILL.md"), `---\nname: ${s.name}\ndescription: fixture\n${triggers}---\n# ${s.name}\n`);+ }+ return dir;+}++describe("checkResolvable — fixture trees", () => {+ test("a manifest skill with no trigger anywhere is an unreachable error carrying an add_trigger fix for RESOLVER.md", () => {+ const dir = writeSkillTree([+ { name: "alpha-notes", triggers: ["file an alpha note"] },+ { name: "orphan-skill", triggers: [] },+ ]);+ try {+ const report = checkResolvable(dir);+ const unreachable = report.issues.filter(i => i.type === "unreachable");+ expect(unreachable.map(i => i.skill)).toEqual(["orphan-skill"]);+ expect(unreachable[0].severity).toBe("error");+ expect(unreachable[0].fix).toEqual({+ type: "add_trigger",+ file: join(dir, "RESOLVER.md"),+ section: "Brain operations",+ skill_path: "skills/orphan-skill/SKILL.md",+ });+ expect(report.ok).toBe(false);+ expect(report.summary).toMatchObject({ total_skills: 2, reachable: 1, unreachable: 1 });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("shared triggers report a MECE overlap among non-whitelisted skills only; whitelisted skills need no triggers", () => {+ const dir = writeSkillTree([+ { name: "alpha-notes", triggers: ["capture this", "save a note"] },+ { name: "beta-notes", triggers: ["capture this"] },+ { name: "brain-ops", triggers: ["capture this", "save a note"] },+ { name: "signal-detector", triggers: ["save a note"] },+ { name: "ingest", triggers: [], resolverRow: "ingest anything" },+ ]);+ try {+ const report = checkResolvable(dir);+ const overlaps = report.issues.filter(i => i.type === "mece_overlap");+ expect(overlaps.map(i => [i.skill, i.message])).toEqual([+ ["alpha-notes, beta-notes", "Trigger 'capture this' matches multiple skills: alpha-notes, beta-notes"],+ ]);+ expect(report.summary.overlaps).toBe(1);+ expect(report.issues.filter(i => i.type === "mece_gap")).toEqual([]);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/test/chronicle-extract.test.ts b/test/chronicle-extract.test.tsindex ce4cd9cdc5..32266824a9 100644--- a/test/chronicle-extract.test.ts+++ b/test/chronicle-extract.test.ts@@ -146,7 +146,7 @@ describe('runChronicleExtract', () => {// The default judge is not exported; pin the load-bearing line so the// bare-`{events: []}` regression can't silently return.const { readFileSync } = await import('fs');- // test-reads-source-ok: defaultJudge is module-private and needs a live gateway; the text pin is the only unit-testable seam (#2608)+ // test-reads-source-ok[structural]: defaultJudge is module-private and needs a live gateway; the text pin is the only unit-testable seam (#2608)const src = readFileSync('src/core/chronicle/extract-events.ts', 'utf8');expect(src).toMatch(/isAvailable\('chat'\)\)\s*return \{ events: \[\], failure: 'llm_unavailable' \}/);});diff --git a/test/claw-test-cli.test.ts b/test/claw-test-cli.test.tsindex ef5dae3e05..4ca8528349 100644--- a/test/claw-test-cli.test.ts+++ b/test/claw-test-cli.test.ts@@ -5,7 +5,7 @@* agent registry resolution, and friction-report path. They do NOT spawn* real gbrain commands (no built binary in CI yet); the canonical scripted* E2E that walks `gbrain init → import → query → extract → verify` lives- * in test/e2e/claw-test.test.ts and gates on a built binary.+ * in test/claw-test.slow.test.ts and gates on a built binary.*/import { describe, test, expect, beforeEach, afterEach } from 'bun:test';@@ -603,7 +603,7 @@ describe('spawnWithCapture — stdin EOF (no payload)', () => {// wipes the registry and bun caches the command module, so the test would// have to re-register the runners itself and would pass even if the command// module dropped its registrations. The HONEST integration check lives in-// test/e2e/claw-test.test.ts ("--list-agents reports both built-in runners"),+// test/claw-test.slow.test.ts ("--list-agents reports both built-in runners"),// which spawns the real CLI and asserts both runner lines.describe('OpencodeRunner detection (reliable on box without opencode)', () => {diff --git a/test/e2e/claw-test.test.ts b/test/claw-test.slow.test.tssimilarity index 98%rename from test/e2e/claw-test.test.tsrename to test/claw-test.slow.test.tsindex a1feecfaa6..a87d4fc031 100644--- a/test/e2e/claw-test.test.ts+++ b/test/claw-test.slow.test.ts@@ -14,6 +14,10 @@** Tagged-skip env: CLAW_TEST_SKIP_E2E=1 to opt out (e.g. when PGLite* WASM is broken on the host — the macOS 26.3 #223 bug class).+ *+ * Lane: slow. Run: `bash scripts/run-slow-tests.sh test/claw-test.slow.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test, expect, beforeAll } from 'bun:test';@@ -22,7 +26,7 @@ import { mkdirSync, existsSync, mkdtempSync, rmSync, readFileSync, readdirSync,import { tmpdir } from 'os';import { join, resolve } from 'path';-const REPO_ROOT = resolve(import.meta.dir, '..', '..');+const REPO_ROOT = resolve(import.meta.dir, '..');const BIN_CACHE = join(REPO_ROOT, 'test', '.cache');const BIN_PATH = join(BIN_CACHE, 'gbrain.sh');const SCENARIOS_DIR = join(REPO_ROOT, 'test', 'fixtures', 'claw-test-scenarios');diff --git a/test/cli-dispatch-thin-client.test.ts b/test/cli-dispatch-thin-client.test.tsindex 66f59a3988..dc88bc81ae 100644--- a/test/cli-dispatch-thin-client.test.ts+++ b/test/cli-dispatch-thin-client.test.ts@@ -17,7 +17,7 @@* GBRAIN_REMOTE_CLIENT_SECRET is stripped per-call — the helper doesn't do* it and an ambient secret would alter thin-client auth routing.*- * The 9 refusedCommands spawns run ONCE through runCliBatch (width 2 — the+ * The refusedCommands spawns run ONCE through runCliBatch (width 2 — the* machine-wide cap, see cli-spawn.ts) in the describe's beforeAll against a* single seeded thin-client home; the loop's tests assert on the cached* results. Sharing the home is safe because refusal happens at the dispatch@@ -98,6 +98,20 @@ describe('thin-client dispatch guard refuses DB-bound commands', () => {['orphans'],['integrity', 'check'],['serve'],+ // v0.32 audit REFUSE additions (no MCP route, or localOnly ops) and the+ // v0.31.1-era refusals not covered above.+ ['pages', 'purge-deleted'],+ ['files', 'list'],+ ['eval', 'export'],+ ['code-def', 'fixture'],+ ['code-refs', 'fixture'],+ ['code-callers', 'fixture'],+ ['code-callees', 'fixture'],+ ['dream'],+ ['transcripts', 'ingest'],+ ['storage', 'status'],+ ['takes', 'extract'],+ ['sources', 'list'],];// One shared seeded home for the batch (see file header for why sharing@@ -239,6 +253,8 @@ describe('thin-client scratch-DB guard — jobs partial dispatch + config refusatest('`gbrain jobs list` never fabricates a scratch local engine', async () => {seedThinClientConfig(tmp, { engine: 'pglite' });const r = await run(['jobs', 'list']);+ // Partial dispatch owns `jobs`: list/get route over MCP, never refused.+ expect(r.stderr).not.toContain('not routable');expect(existsSync(join(tmp, '.gbrain', 'brain.pglite'))).toBe(false);expect(r.stdout + r.stderr).not.toContain('Schema version');expect(r.stdout + r.stderr).not.toContain('Setting up brain schema');diff --git a/test/cli-help-discoverability.test.ts b/test/cli-help-discoverability.test.tsindex d3ef0de9ee..3063fa21db 100644--- a/test/cli-help-discoverability.test.ts+++ b/test/cli-help-discoverability.test.ts@@ -162,6 +162,15 @@ describe('#4003 — `gbrain auth --help` reaches the detailed usage block', () =expect(stdout).not.toContain('run gbrain --help for the full command list');});+ test('auth help points at the owner login flow without inventing a CLI command', async () => {+ const { stdout, exitCode } = await help(['auth', '--help']);+ expect(exitCode).toBe(0);+ expect(stdout).toContain('Admin dashboard login (running HTTP server):');+ expect(stdout).toContain('POST /admin/api/issue-magic-link');+ expect(stdout).toContain('do not GET the generated link');+ expect(stdout).toContain('See docs/mcp/DEPLOY.md.');+ });+test('-h short flag also works', async () => {const { stdout, exitCode } = await help(['auth', '-h']);expect(exitCode).toBe(0);diff --git a/test/cli.test.ts b/test/cli.test.tsindex 06d89da664..641b421cb3 100644--- a/test/cli.test.ts+++ b/test/cli.test.ts@@ -3,7 +3,7 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-// Read cli.ts source for structural checks+// test-reads-source-ok[structural]: two kept pins need the dispatcher's text: the handleCliOnly case-label census (switch labels cannot be enumerated at runtime) and the local-op normalize call site (bigints only reach it from Postgres, never PGLite).const cliSource = readFileSync(new URL('../src/cli.ts', import.meta.url), 'utf-8');const repoRoot = new URL('..', import.meta.url).pathname;@@ -19,35 +19,30 @@ function isolatedEnv(home: string): Record<string, string> {}describe('CLI structure', () => {- test('imports operations from operations.ts', () => {- expect(cliSource).toContain("from './core/operations.ts'");- });-- test('builds cliOps map from operations', () => {- expect(cliSource).toContain('cliOps');- });-- test('CLI_ONLY set contains expected commands', () => {- expect(cliSource).toContain("'init'");- expect(cliSource).toContain("'upgrade'");- expect(cliSource).toContain("'import'");- expect(cliSource).toContain("'export'");- expect(cliSource).toContain("'embed'");- expect(cliSource).toContain("'files'");- });-- // v0.41.11 #1451 regression — `reindex` had a `case 'reindex':` handler- // at src/cli.ts:1334 but was missing from CLI_ONLY, so the dispatcher- // rejected `gbrain reindex` with "Unknown command: reindex" before the- // handler ever ran. Cherry-picked from kylma-code-adjacent PR #1354.- test('reindex is in CLI_ONLY (does not get "Unknown command")', () => {- const onlyMatch = cliSource.match(/const CLI_ONLY = new Set\(\[([\s\S]*?)\]\)/);- expect(onlyMatch).not.toBeNull();- expect(onlyMatch![1]).toContain(`'reindex'`);- });-- test('has formatResult function for CLI output', () => {- expect(cliSource).toContain('function formatResult');+ // #1451 regression class: a command with a live handleCliOnly case but no+ // CLI_ONLY entry is rejected as "Unknown command" before its handler runs+ // (reindex shipped that way). Spawned so dispatch, not the set, is judged.+ test('CLI-only commands reach their handlers instead of "Unknown command"', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-only-'));+ try {+ const results = await Promise.all(['reindex', 'import', 'export', 'embed', 'files'].map(async (command) => {+ const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', command, '--help'], {+ cwd: repoRoot,+ stdout: 'pipe',+ stderr: 'pipe',+ env: isolatedEnv(home),+ });+ const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);+ await proc.exited;+ return { command, output: stdout + stderr };+ }));+ for (const { command, output } of results) {+ expect(output, command).not.toContain('Unknown command');+ }+ expect(results.find(r => r.command === 'reindex')!.output).toContain('gbrain reindex');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }});// #2035-class dispatch-gap guard: every `case '...'` label inside@@ -150,9 +145,16 @@ describe('CLI version', () => {});describe('ask alias', () => {- test('ask alias maps to query in source', () => {- expect(cliSource).toContain("if (command === 'ask')");- expect(cliSource).toContain("command = 'query'");+ test('ask dispatches to the query op', async () => {+ const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'ask', '--help'], {+ cwd: repoRoot,+ stdout: 'pipe',+ stderr: 'pipe',+ });+ const stdout = await new Response(proc.stdout).text();+ const exitCode = await proc.exited;+ expect(stdout).toContain('Usage: gbrain query');+ expect(exitCode).toBe(0);});test('ask does NOT appear in --tools-json output', async () => {diff --git a/test/code-callers-cli.test.ts b/test/code-callers-cli.test.tsdeleted file mode 100644index fa9f1ff7f8..0000000000--- a/test/code-callers-cli.test.ts+++ /dev/null@@ -1,24 +0,0 @@-/**- * v0.20.0 Cathedral II Layer 10 (C4 + C5) — code-callers + code-callees CLI tests.- *- * The CLI commands are thin wrappers over engine.getCallersOf /- * engine.getCalleesOf. Tests validate:- * - the commands are exported and can be called- * - JSON output shape is stable (agent-consumable)- * - missing symbol exits with UsageError envelope- * End-to-end engine round-trip lives in test/code-edges.test.ts.- */--import { describe, test, expect } from 'bun:test';--describe('Layer 10 C4/C5 — commands export runCodeCallers / runCodeCallees', () => {- test('code-callers module exports runCodeCallers', async () => {- const mod = await import('../src/commands/code-callers.ts');- expect(typeof mod.runCodeCallers).toBe('function');- });-- test('code-callees module exports runCodeCallees', async () => {- const mod = await import('../src/commands/code-callees.ts');- expect(typeof mod.runCodeCallees).toBe('function');- });-});diff --git a/test/code-intel/eval-capture-graph.test.ts b/test/code-intel/eval-capture-graph.test.tsdeleted file mode 100644index d1ed24c23f..0000000000--- a/test/code-intel/eval-capture-graph.test.ts+++ /dev/null@@ -1,150 +0,0 @@-/**- * v0.34 W7 — per-op graph metrics tests.- * Pure-function tests; no engine needed.- */-import { describe, test, expect } from 'bun:test';-import {- nodeSetJaccard,- depthGroupStability,- truncationMatch,- adjustedRandIndex,- compareCodeWalk,-} from '../../src/core/eval-capture-graph.ts';--describe('W7: nodeSetJaccard', () => {- test('identical sets → 1.0', () => {- const a = [{ symbol: 'foo' }, { symbol: 'bar' }];- const b = [{ symbol: 'foo' }, { symbol: 'bar' }];- expect(nodeSetJaccard(a, b)).toBe(1);- });-- test('disjoint sets → 0', () => {- expect(nodeSetJaccard([{ symbol: 'a' }], [{ symbol: 'b' }])).toBe(0);- });-- test('partial overlap (3 shared of 4 total)', () => {- const a = [{ symbol: 'x' }, { symbol: 'y' }, { symbol: 'z' }];- const b = [{ symbol: 'x' }, { symbol: 'y' }, { symbol: 'w' }];- // intersection=2, union=4 → 0.5- expect(nodeSetJaccard(a, b)).toBe(0.5);- });-- test('both empty → NaN (degenerate)', () => {- expect(Number.isNaN(nodeSetJaccard([], []))).toBe(true);- });-- test('one empty → 0', () => {- expect(nodeSetJaccard([], [{ symbol: 'foo' }])).toBe(0);- });-- test('file + line distinguish same-name symbols', () => {- const a = [{ symbol: 'foo', file: 'a.ts', line: 1 }];- const b = [{ symbol: 'foo', file: 'a.ts', line: 2 }];- expect(nodeSetJaccard(a, b)).toBe(0);- });-- test('dedup within a single side', () => {- const a = [{ symbol: 'foo' }, { symbol: 'foo' }];- const b = [{ symbol: 'foo' }];- expect(nodeSetJaccard(a, b)).toBe(1);- });-});--describe('W7: depthGroupStability', () => {- test('all nodes in same depth → 1.0', () => {- const a = [{ depth: 1, nodes: [{ symbol: 'a' }, { symbol: 'b' }] }];- const b = [{ depth: 1, nodes: [{ symbol: 'a' }, { symbol: 'b' }] }];- expect(depthGroupStability(a, b)).toBe(1);- });-- test('one node moved buckets → 0.5 with 2 nodes', () => {- const a = [{ depth: 1, nodes: [{ symbol: 'a' }, { symbol: 'b' }] }];- const b = [- { depth: 1, nodes: [{ symbol: 'a' }] },- { depth: 2, nodes: [{ symbol: 'b' }] },- ];- expect(depthGroupStability(a, b)).toBe(0.5);- });-- test('both empty → 1.0', () => {- expect(depthGroupStability([], [])).toBe(1);- });-- test('completely reshuffled → 0', () => {- const a = [{ depth: 1, nodes: [{ symbol: 'a' }] }];- const b = [{ depth: 2, nodes: [{ symbol: 'a' }] }];- expect(depthGroupStability(a, b)).toBe(0);- });-});--describe('W7: truncationMatch', () => {- test('both none → 1', () => {- expect(truncationMatch('none', 'none')).toBe(1);- expect(truncationMatch(undefined, undefined)).toBe(1);- });-- test('mismatch → 0', () => {- expect(truncationMatch('max_nodes', 'depth_cap')).toBe(0);- });-- test('undefined treated as none', () => {- expect(truncationMatch('none', undefined)).toBe(1);- });-});--describe('W7: adjustedRandIndex', () => {- test('identical clusterings → 1', () => {- const a = ['A', 'A', 'B', 'B'];- const b = ['X', 'X', 'Y', 'Y'];- // Same partition, different labels — ARI should be 1.- expect(adjustedRandIndex(a, b)).toBeCloseTo(1, 5);- });-- test('all items in one cluster vs all in distinct → expected 0', () => {- const a = ['A', 'A', 'A', 'A'];- const b = ['W', 'X', 'Y', 'Z'];- // Singleton vs single-group clustering: ARI should be 0 (no agreement- // beyond chance).- const ari = adjustedRandIndex(a, b);- expect(ari).toBeCloseTo(0, 5);- });-- test('equal-length contract enforced', () => {- expect(() => adjustedRandIndex(['A'], ['X', 'Y'])).toThrow(/equal length/);- });-- test('singleton input → 1.0', () => {- expect(adjustedRandIndex(['A'], ['X'])).toBe(1);- });-});--describe('W7: compareCodeWalk', () => {- test('shared depth_groups → high jaccard + stability', () => {- const a = {- depth_groups: [{ depth: 1, nodes: [{ symbol: 'x' }, { symbol: 'y' }] }],- truncation: 'none',- };- const b = {- depth_groups: [{ depth: 1, nodes: [{ symbol: 'x' }, { symbol: 'y' }] }],- truncation: 'none',- };- const cmp = compareCodeWalk(a, b);- expect(cmp.jaccard).toBe(1);- expect(cmp.depth_stability).toBe(1);- expect(cmp.truncation_match).toBe(1);- });-- test('no overlap → low jaccard, full reshuffle → low stability', () => {- const a = {- depth_groups: [{ depth: 1, nodes: [{ symbol: 'x' }] }],- truncation: 'none',- };- const b = {- depth_groups: [{ depth: 1, nodes: [{ symbol: 'y' }] }],- truncation: 'max_nodes',- };- const cmp = compareCodeWalk(a, b);- expect(cmp.jaccard).toBe(0);- expect(cmp.truncation_match).toBe(0);- });-});diff --git a/test/company-brain-schema.test.ts b/test/company-brain-schema.test.tsindex 8be6403153..d9d0d7b20c 100644--- a/test/company-brain-schema.test.ts+++ b/test/company-brain-schema.test.ts@@ -8,7 +8,6 @@ import { mergeInheritedManifest } from '../src/core/schema-pack/merge.ts';import { buildAliasGraph, expandClosure } from '../src/core/schema-pack/closure.ts';import { runFilePlaneLintRules } from '../src/core/schema-pack/lint-rules.ts';import { locateMutablePackFile, SchemaPackMutationError } from '../src/core/schema-pack/mutate.ts';-import { expandTypeFilter } from '../src/core/schema-pack/expand-type-filter.ts';import { inferTypeFromPack, parseMarkdown } from '../src/core/markdown.ts';const parent = loadPackFromFile(bundledPackPath('gbrain-base-v2')!);@@ -44,7 +43,6 @@ describe('bundled company-brain schema', () => {const graph = buildAliasGraph(pack);expect(expandClosure('company', graph)).not.toContain('product');expect(expandClosure('product', graph)).toEqual(['product']);- expect(expandTypeFilter('product', pack).canonical).toBe('product');expect(parent.page_types.find(type => type.name === 'company')!.aliases).toContain('product');expect(inferTypeFromPack('products/widget-example.md', parent)).toBe('company');});diff --git a/test/e2e/connect-bearer.test.ts b/test/connect-bearer.test.tssimilarity index 96%rename from test/e2e/connect-bearer.test.tsrename to test/connect-bearer.test.tsindex 2ad7c99249..094a11e9a2 100644--- a/test/e2e/connect-bearer.test.ts+++ b/test/connect-bearer.test.ts@@ -10,6 +10,10 @@** This is the integration coverage the unit tests (injected deps) can't give:* the actual StreamableHTTP initialize handshake + tools/call over bearer auth.+ *+ * Lane: unit. Run: `bun test test/connect-bearer.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';@@ -17,8 +21,8 @@ import { spawn, spawnSync, execFileSync, type ChildProcess } from 'child_processimport { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { probeBrainIdentity } from '../../src/core/connect-probe.ts';-import { discoverOAuth, mintClientCredentialsToken } from '../../src/core/remote-mcp-probe.ts';+import { probeBrainIdentity } from '../src/core/connect-probe.ts';+import { discoverOAuth, mintClientCredentialsToken } from '../src/core/remote-mcp-probe.ts';const PORT = 19735; // avoid the production 3131 + the oauth E2E's 19131const BASE = `http://127.0.0.1:${PORT}`;@@ -102,7 +106,7 @@ describe('connect bearer probe E2E (PGLite + real serve --http)', () => {// had no instructions coverage. A real SDK initialize against the live// runServeHttp process must surface GBRAIN_MCP_INSTRUCTIONS verbatim.expect(serverReady).toBe(true);- const { GBRAIN_MCP_INSTRUCTIONS } = await import('../../src/mcp/instructions.ts');+ const { GBRAIN_MCP_INSTRUCTIONS } = await import('../src/mcp/instructions.ts');const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');const { StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js');diff --git a/test/connect.test.ts b/test/connect.test.tsindex df7dce19c9..468eacb274 100644--- a/test/connect.test.ts+++ b/test/connect.test.ts@@ -769,7 +769,7 @@ describe('AGENT_IDS', () => {describe('LEARN_INSTRUCTION names only real MCP tools', () => {// The self-orientation block is pasted into a connected agent verbatim. Every// tool it names MUST be MCP-exposed, or the agent calls an "unknown tool".- // The exposed set is pinned end-to-end by test/e2e/serve-stdio-roundtrip.ts.+ // The exposed set is pinned end-to-end by test/serve-stdio-roundtrip.test.ts.test('every named tool is a real op, and capture (now an MCP op, gap-closure wave) is on the starter surface', async () => {expect(LEARN_INSTRUCTION).toContain('put_page');expect(LEARN_INSTRUCTION).toContain('capture');diff --git a/test/connection-resilience.test.ts b/test/connection-resilience.test.tsindex e52809e7fd..3c2b6d1043 100644--- a/test/connection-resilience.test.ts+++ b/test/connection-resilience.test.ts@@ -1,246 +1,6 @@import { describe, it, expect } from 'bun:test';--/**- * Tests for connection resilience features:- * 1. PostgresEngine.executeRaw retries on connection errors- * 2. PostgresEngine.reconnect creates fresh connection pool- * 3. Supervisor health check tracks consecutive failures- * 4. Supervisor classifies worker exit reasons- */--// --- Unit tests for isConnectionError (extracted pattern) -----const CONNECTION_ERROR_PATTERNS = [- 'ECONNREFUSED',- 'ECONNRESET',- 'EPIPE',- 'connection terminated',- 'Client has encountered a connection error',- 'password authentication failed',- 'Connection terminated unexpectedly',- 'no pg_hba.conf entry',- 'server closed the connection unexpectedly',- 'SSL connection has been closed unexpectedly',- 'connection is insecure',- 'too many connections',- 'remaining connection slots are reserved',-];--function isConnectionError(err: unknown): boolean {- if (!err) return false;- const msg = err instanceof Error ? err.message : String(err);- const code = (err as NodeJS.ErrnoException)?.code;- if (code && CONNECTION_ERROR_PATTERNS.includes(code)) return true;- return CONNECTION_ERROR_PATTERNS.some(p => msg.includes(p));-}--describe('isConnectionError', () => {- it('detects password authentication failure', () => {- expect(isConnectionError(new Error('password authentication failed for user "postgres"'))).toBe(true);- });-- it('detects ECONNREFUSED via error code', () => {- const err = new Error('connect ECONNREFUSED 127.0.0.1:5432') as NodeJS.ErrnoException;- err.code = 'ECONNREFUSED';- expect(isConnectionError(err)).toBe(true);- });-- it('detects ECONNRESET via error code', () => {- const err = new Error('read ECONNRESET') as NodeJS.ErrnoException;- err.code = 'ECONNRESET';- expect(isConnectionError(err)).toBe(true);- });-- it('detects connection terminated message', () => {- expect(isConnectionError(new Error('connection terminated'))).toBe(true);- });-- it('detects Connection terminated unexpectedly', () => {- expect(isConnectionError(new Error('Connection terminated unexpectedly'))).toBe(true);- });-- it('detects server closed the connection', () => {- expect(isConnectionError(new Error('server closed the connection unexpectedly'))).toBe(true);- });-- it('detects SSL connection closed', () => {- expect(isConnectionError(new Error('SSL connection has been closed unexpectedly'))).toBe(true);- });-- it('detects too many connections', () => {- expect(isConnectionError(new Error('FATAL: too many connections for role "postgres"'))).toBe(true);- });-- it('does not match regular query errors', () => {- expect(isConnectionError(new Error('relation "foo" does not exist'))).toBe(false);- });-- it('does not match null/undefined', () => {- expect(isConnectionError(null)).toBe(false);- expect(isConnectionError(undefined)).toBe(false);- });-- it('does not match syntax errors', () => {- expect(isConnectionError(new Error('syntax error at or near "SELECT"'))).toBe(false);- });-- it('does not match constraint violations', () => {- expect(isConnectionError(new Error('duplicate key value violates unique constraint'))).toBe(false);- });-});--// --- Unit tests for worker exit classification -----function classifyWorkerExit(code: number | null, signal: string | null): string {- if (signal === 'SIGKILL') return 'oom_or_external_kill';- if (signal === 'SIGTERM') return 'graceful_shutdown';- if (code === 1) return 'runtime_error';- if (code === 0) return 'clean_exit';- return 'unknown';-}--describe('classifyWorkerExit', () => {- it('classifies SIGKILL as OOM/external kill', () => {- expect(classifyWorkerExit(null, 'SIGKILL')).toBe('oom_or_external_kill');- });-- it('classifies SIGTERM as graceful shutdown', () => {- expect(classifyWorkerExit(null, 'SIGTERM')).toBe('graceful_shutdown');- });-- it('classifies exit code 1 as runtime error', () => {- expect(classifyWorkerExit(1, null)).toBe('runtime_error');- });-- it('classifies exit code 0 as clean exit', () => {- expect(classifyWorkerExit(0, null)).toBe('clean_exit');- });-- it('classifies unknown codes as unknown', () => {- expect(classifyWorkerExit(137, null)).toBe('unknown');- expect(classifyWorkerExit(null, null)).toBe('unknown');- });-- // Signal takes precedence over code- it('SIGKILL takes precedence over any exit code', () => {- expect(classifyWorkerExit(1, 'SIGKILL')).toBe('oom_or_external_kill');- });-});--// --- Mock-based tests for reconnect logic -----describe('PostgresEngine reconnect behavior', () => {- it('executeRaw retry does not infinite-loop on persistent connection failure', async () => {- // Simulate: first call fails (connection error), reconnect succeeds,- // but retry also fails with a NON-connection error- let callCount = 0;-- async function executeRawWithRetry(): Promise<unknown[]> {- callCount++;- if (callCount === 1) {- throw new Error('connection terminated'); // connection error → triggers retry- }- if (callCount === 2) {- throw new Error('relation "foo" does not exist'); // NOT a connection error → throw- }- return [{ ok: true }];- }-- try {- await (async () => {- try {- return await executeRawWithRetry();- } catch (err) {- if (isConnectionError(err)) {- // "reconnect" would happen here- return await executeRawWithRetry();- }- throw err;- }- })();- } catch (err) {- expect((err as Error).message).toBe('relation "foo" does not exist');- }-- expect(callCount).toBe(2); // Only 2 attempts, no infinite loop- });-- it('executeRaw succeeds on retry after connection error', async () => {- let callCount = 0;-- async function executeRawWithRetry(): Promise<unknown[]> {- callCount++;- if (callCount === 1) {- throw new Error('password authentication failed for user "postgres"');- }- return [{ ok: true }];- }-- const result = await (async () => {- try {- return await executeRawWithRetry();- } catch (err) {- if (isConnectionError(err)) {- // reconnect would happen here- return await executeRawWithRetry();- }- throw err;- }- })();-- expect(result).toEqual([{ ok: true }]);- expect(callCount).toBe(2);- });-});--// --- Supervisor health check failure tracking -----describe('Supervisor health check failure tracking', () => {- it('emits db_connection_degraded after 3 consecutive failures', () => {- let consecutiveFailures = 0;- const emitted: Array<{ event: string; reason?: string }> = [];-- function emit(event: string, fields: Record<string, unknown> = {}) {- emitted.push({ event, ...fields } as { event: string; reason?: string });- }-- // Simulate 3 health check failures- for (let i = 0; i < 4; i++) {- consecutiveFailures++;- if (consecutiveFailures >= 3) {- emit('health_warn', { reason: 'db_connection_degraded', consecutive_failures: consecutiveFailures });- } else {- emit('health_error', { error: 'connection terminated' });- }- }-- const degradedWarnings = emitted.filter(e => e.reason === 'db_connection_degraded');- expect(degradedWarnings.length).toBe(2); // fires at count 3 and 4-- // First two were regular health_error- expect(emitted[0].event).toBe('health_error');- expect(emitted[1].event).toBe('health_error');- // Third triggers the degraded warning- expect(emitted[2].reason).toBe('db_connection_degraded');- });-- it('resets failure counter on successful health check', () => {- let consecutiveFailures = 0;-- // 2 failures- consecutiveFailures++;- consecutiveFailures++;- expect(consecutiveFailures).toBe(2);-- // Success resets- consecutiveFailures = 0;- expect(consecutiveFailures).toBe(0);-- // 1 more failure — should not trigger degraded (need 3 consecutive)- consecutiveFailures++;- expect(consecutiveFailures).toBeLessThan(3);- });-});+import { readFileSync } from 'fs';+import { resolve } from 'path';// ─────────────────────────────────────────────────────────────────// Eng-review D3 regression guards — executeRaw retry wrapper dropped@@ -255,9 +15,6 @@ describe('Supervisor health check failure tracking', () => {// These guards prevent reintroduction of the per-call retry without// a typed-idempotency boundary.-import { readFileSync } from 'fs';-import { resolve } from 'path';-describe('Eng-review D3 — executeRaw has no per-call retry wrapper', () => {it('PostgresEngine.executeRaw is a single-statement passthrough (no try/catch on connection errors)', () => {const src = readFileSync(resolve('src/core/postgres-engine.ts'), 'utf-8');diff --git a/test/context-audit-skill.test.ts b/test/context-audit-skill.test.tsindex b19cf8698a..4116dc7711 100644--- a/test/context-audit-skill.test.ts+++ b/test/context-audit-skill.test.ts@@ -1,34 +1,35 @@import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'node:fs';+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';import { join } from 'node:path';-// #4988: the skill's bash pre-pass divided byte counts by 4 and labelled the-// result "measured"; on Claude-loaded markdown (backticks, paths, punctuation)-// that undercounts 25-35%. The skill must state the divisor it uses in the-// report and defer to the host client's exact context breakdown when one exists.+// #4988/#5009: the skill's bash pre-pass once divided byte counts by 4 (then+// 3.5), undercounting Claude-loaded markdown by 13-35%. The shipped snippet is+// executed here on fixture files of known size: each estimate must be+// ceil(bytes / 2.8). The report must state that basis and defer to the host+// client's exact context breakdown when one exists.const skill = readFileSync(join(import.meta.dir, '..', 'skills/context-audit/SKILL.md'), 'utf8');-describe('#4988 context-audit skill states its token-estimate basis', () => {- test('pre-pass no longer hard-codes a bare chars/4 divisor', () => {- expect(skill).not.toMatch(/\/ 4 \)\)/);- expect(skill).not.toContain('chars/4');+describe('#4988 context-audit skill token estimate', () => {+ test('the stack-enumeration snippet estimates ceil(bytes / 2.8) tokens per always-loaded file', () => {+ const section = skill.split('### 1. Enumerate the stack')[1]!.split('### 2.')[0]!;+ const snippet = section.match(/```bash\n([\s\S]*?)\n```/)?.[1];+ expect(snippet).toBeDefined();+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-context-audit-'));+ const sizes: Record<string, number> = { 'CLAUDE.md': 1, 'AGENTS.md': 28, 'SOUL.md': 29, 'MEMORY.md': 10_000 };+ try {+ for (const [name, bytes] of Object.entries(sizes)) writeFileSync(join(dir, name), 'x'.repeat(bytes));+ const child = Bun.spawnSync(['bash', '-c', snippet!], { cwd: dir, env: { PATH: process.env.PATH ?? '' }, stdout: 'pipe', stderr: 'pipe', timeout: 10_000 });+ const expected = Object.entries(sizes).map(([name, bytes]) => `${name}: ${bytes} bytes (~${Math.ceil(bytes / 2.8)} tokens)`);+ expect(child.stdout.toString().trim().split('\n').sort()).toEqual(expected.sort());+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }});test('report header carries the estimate basis and defers to the host figure', () => {- expect(skill).toContain('Estimate basis');- // Anchor to the deferral clause itself — a bare /\/context/ is satisfied by- // the `/tmp/context-audit-draft.md` scratch path on the pre-fix file.+ expect(skill).toContain('Estimate basis: bytes/2.8');expect(skill).toContain('Claude Code `/context`');expect(skill).toContain('host-reported exact total (e.g. `/context`)');});-- // #5009: the divisor is the one the issue measured (2.65-3.03 bytes/token on- // always-loaded markdown). 3.5 was the top of the range, i.e. still a ~13-24%- // undercount; the pre-pass rounds UP so integer math never adds to it.- test('divisor is the calibrated bytes/2.8 with ceil arithmetic, not the 3.5 floor', () => {- expect(skill).toContain('bytes/2.8');- expect(skill).not.toContain('bytes/3.5');- expect(skill).not.toContain('* 2 / 7');- expect(skill).toContain('* 10 + 27 ) / 28');- });});diff --git a/test/conversation-parser/llm-polish.test.ts b/test/conversation-parser/llm-polish.test.tsdeleted file mode 100644index 1a872120a8..0000000000--- a/test/conversation-parser/llm-polish.test.ts+++ /dev/null@@ -1,174 +0,0 @@-/**- * v0.41.16.0 — LLM polish unit tests.- *- * Pins:- * - applyPolish pure function: merge + drop + edits- * - Headroom guard skip path- * - Provider unavailable → input messages unchanged- * - Cache hit doesn't re-call- */--import { describe, expect, test, beforeEach } from 'bun:test';-import { withEnv } from '../helpers/with-env.ts';-import {- runLlmPolish,- applyPolish,-} from '../../src/core/conversation-parser/llm-polish.ts';-import { _resetLlmCacheForTests } from '../../src/core/conversation-parser/llm-base.ts';-import { BudgetTracker } from '../../src/core/budget/budget-tracker.ts';-import { withBudgetTracker } from '../../src/core/ai/gateway.ts';-import type { MatchedMessage } from '../../src/core/conversation-parser/types.ts';-import { makeChatResult } from './helpers.ts';--beforeEach(() => {- _resetLlmCacheForTests();-});--const SAMPLE: MatchedMessage[] = [- { speaker: 'Alice', timestamp: '2024-03-15T18:37:00Z', text: 'hello' },- { speaker: 'Alice', timestamp: '2024-03-15T18:37:30Z', text: 'continuation' },- { speaker: 'system', timestamp: '2024-03-15T18:38:00Z', text: 'Bob joined' },- { speaker: 'Bob', timestamp: '2024-03-15T18:39:00Z', text: 'world (edited)' },-];--describe('applyPolish — pure function', () => {- test('merge two indices into one', () => {- const r = applyPolish(SAMPLE, {- merge_indices: [[0, 1]],- drop_indices: [],- edits: [],- });- expect(r.messages).toHaveLength(3);- expect(r.messages[0].text).toBe('hello\ncontinuation');- expect(r.delta.merged).toBe(1);- });-- test('drop indices', () => {- const r = applyPolish(SAMPLE, {- merge_indices: [],- drop_indices: [2],- edits: [],- });- expect(r.messages).toHaveLength(3);- expect(r.messages.find((m) => m.text === 'Bob joined')).toBeUndefined();- expect(r.delta.dropped).toBe(1);- });-- test('edit speaker and text', () => {- const r = applyPolish(SAMPLE, {- merge_indices: [],- drop_indices: [],- edits: [- { index: 3, field: 'text', value: 'world' },- ],- });- expect(r.messages[3].text).toBe('world');- expect(r.delta.edits).toBe(1);- });-- test('combined: drop system msg, merge two, edit edited marker', () => {- const r = applyPolish(SAMPLE, {- merge_indices: [[0, 1]],- drop_indices: [2],- edits: [{ index: 3, field: 'text', value: 'world' }],- });- expect(r.messages).toHaveLength(2);- expect(r.messages[0].text).toBe('hello\ncontinuation');- expect(r.messages[1].text).toBe('world');- });-- test('no-op: returns messages unchanged', () => {- const r = applyPolish(SAMPLE, {- merge_indices: [],- drop_indices: [],- edits: [],- });- expect(r.messages).toHaveLength(4);- expect(r.delta).toEqual({ merged: 0, dropped: 0, edits: 0 });- });-});--describe('runLlmPolish', () => {- test('happy path: LLM returns polish ops, applied', async () => {- await withEnv({ ANTHROPIC_API_KEY: 'sk-test' }, async () => {- const r = await runLlmPolish({- modelStr: 'claude-haiku-4-5',- body: '...full body...',- messages: SAMPLE,- patternId: 'imessage-slack',- chatTransport: async () =>- makeChatResult(- JSON.stringify({- merge_indices: [[0, 1]],- drop_indices: [2],- edits: [{ index: 3, field: 'text', value: 'world' }],- }),- { input_tokens: 100, output_tokens: 50 },- ),- });- expect(r.skipped).toBeUndefined();- expect(r.messages).toHaveLength(2);- expect(r.delta.merged).toBe(1);- expect(r.delta.dropped).toBe(1);- expect(r.delta.edits).toBe(1);- });- });-- test('headroom guard: skips when tracker within $0.10 of cap', async () => {- await withEnv({ ANTHROPIC_API_KEY: 'sk-test' }, async () => {- const t = new BudgetTracker({ label: 'unit', maxCostUsd: 0.05 });- let calls = 0;- await withBudgetTracker(t, async () => {- const r = await runLlmPolish({- modelStr: 'claude-haiku-4-5',- body: 'b',- messages: SAMPLE,- patternId: 'imessage-slack',- chatTransport: async () => {- calls++;- return makeChatResult('{"merge_indices":[],"drop_indices":[],"edits":[]}', { input_tokens: 1, output_tokens: 1 });- },- });- expect(r.skipped).toBe('headroom');- expect(r.messages).toBe(SAMPLE); // unchanged input- });- expect(calls).toBe(0);- });- });-- test('provider unavailable: returns input unchanged + skipped=provider', async () => {- await withEnv(- { ANTHROPIC_API_KEY: undefined as unknown as string },- async () => {- const r = await runLlmPolish({- modelStr: 'claude-haiku-4-5',- body: 'b',- messages: SAMPLE,- patternId: 'imessage-slack',- chatTransport: async () => makeChatResult('{}', { input_tokens: 1, output_tokens: 1 }),- });- expect(r.skipped).toBe('provider');- expect(r.messages).toEqual(SAMPLE);- },- );- });-- test('cache hit on same (body, patternId) pair', async () => {- await withEnv({ ANTHROPIC_API_KEY: 'sk-test' }, async () => {- let calls = 0;- const opts = {- modelStr: 'claude-haiku-4-5',- body: 'stable',- messages: SAMPLE,- patternId: 'imessage-slack',- chatTransport: async () => {- calls++;- return makeChatResult('{"merge_indices":[],"drop_indices":[],"edits":[]}', { input_tokens: 1, output_tokens: 1 });- },- };- await runLlmPolish(opts);- await runLlmPolish(opts);- expect(calls).toBe(1);- });- });-});diff --git a/test/conversation-parser/parse.test.ts b/test/conversation-parser/parse.test.tsindex f85a1b35d7..a0ffde5147 100644--- a/test/conversation-parser/parse.test.ts+++ b/test/conversation-parser/parse.test.ts@@ -11,9 +11,8 @@* - Disabled-builtin honored* - Timezone warning (D19) emitted when frontmatter timezone missing*- * Pure-function tests; no PGLite, no LLM. The LLM polish/fallback- * tests live in `llm-base.test.ts`, `llm-polish.test.ts`,- * `llm-fallback.test.ts` (T4).+ * Pure-function tests; no PGLite, no LLM. The LLM fallback tests+ * live in `llm-base.test.ts` and `llm-fallback.test.ts` (T4).*/import { describe, expect, test } from 'bun:test';diff --git a/test/core/background-work.test.ts b/test/core/background-work.test.tsindex 32430f502e..642b808b00 100644--- a/test/core/background-work.test.ts+++ b/test/core/background-work.test.ts@@ -130,9 +130,8 @@ describe('background-work registry', () => {test('empty registry (no test drainers) resolves fast', async () => {// Production sinks may be registered, but they fast-path on empty pending- // sets. This just asserts the call resolves without throwing.- await drainAllBackgroundWorkForCliExit({ timeoutMs: 10 });- expect(true).toBe(true);+ // sets. The exit drain must resolve, never reject.+ await expect(drainAllBackgroundWorkForCliExit({ timeoutMs: 10 })).resolves.toBeUndefined();});});diff --git a/test/core/cycle.serial.test.ts b/test/core/cycle.serial.test.tsindex 89e25156ca..0d06b360f9 100644--- a/test/core/cycle.serial.test.ts+++ b/test/core/cycle.serial.test.ts@@ -315,6 +315,23 @@ describe('runCycle — cycle_already_running skip', () => {expect(report.status).not.toBe('skipped');expect(syncCalls.length).toBe(1); // cycle ran});++ test('a held cycle lock expires 5 minutes out (crash recovery window)', async () => {+ let ttlSeconds: number | null = null;+ await runCycle(sharedEngine, {+ brainDir: '/tmp/brain',+ phases: ['lint'],+ yieldBetweenPhases: async () => {+ const { rows } = await (sharedEngine as any).db.query(+ `SELECT EXTRACT(EPOCH FROM (ttl_expires_at - NOW()))::float AS s FROM gbrain_cycle_locks WHERE id = 'gbrain-cycle'`,+ );+ ttlSeconds = rows[0]?.s ?? null;+ },+ });+ expect(ttlSeconds).not.toBeNull();+ expect(ttlSeconds!).toBeGreaterThan(4 * 60);+ expect(ttlSeconds!).toBeLessThanOrEqual(5 * 60);+ });});// ─── Engine null path ─────────────────────────────────────────────@@ -367,6 +384,19 @@ describe('runCycle — engine = null (filesystem-only mode)', () => {expect(lintCalls.length).toBe(0);expect(backlinksCalls.length).toBe(0);});++ test('a live holder whose lock file is older than 5 minutes is treated as stale', async () => {+ const { writeFileSync, mkdirSync, utimesSync } = require('fs');+ const path = require('path');+ mkdirSync(path.dirname(lockFile), { recursive: true });+ writeFileSync(lockFile, `1\n${new Date().toISOString()}\n`);+ const sixMinutesAgo = new Date(Date.now() - 6 * 60 * 1000);+ utimesSync(lockFile, sixMinutesAgo, sixMinutesAgo);++ const report = await runCycle(null, { brainDir: '/tmp/brain' });+ expect(report.reason).not.toBe('cycle_already_running');+ expect(lintCalls.length).toBe(1);+ });});// ─── Status derivation ─────────────────────────────────────────────diff --git a/test/core/diarize/payload-fitter-summarize.test.ts b/test/core/diarize/payload-fitter-summarize.test.tsdeleted file mode 100644index 3b2c0f914d..0000000000--- a/test/core/diarize/payload-fitter-summarize.test.ts+++ /dev/null@@ -1,217 +0,0 @@-/**- * v0.37.x — payload-fitter summarize strategy + quality gate (T3 amended).- *- * Four cases:- * - Happy: 5 clusters all succeed, degraded=false.- * - Partial-failure: 1 of 5 fails (success_ratio=0.8 > default 0.75),- * degraded=false, dropped=1.- * - High-failure: 3 of 5 fail (success_ratio=0.4 < 0.75), degraded=true.- * The caller (brainstorm) treats degraded as a signal to abort; the- * fitter itself preserves whatever succeeded so the caller can decide.- * - Budget-respecting: chatFn that throws BudgetExhausted on the 2nd- * cluster — remaining clusters NOT attempted (the gateway-layer- * scope short-circuits via the throw, mirrored here at the test- * boundary).- *- * Hermetic — embedFn and chatFn are caller-supplied stubs.- */--import { describe, test, expect } from 'bun:test';-import { fit } from '../../../src/core/diarize/payload-fitter.ts';-import type { ChatResult } from '../../../src/core/ai/gateway.ts';-import { BudgetExhausted } from '../../../src/core/budget/budget-tracker.ts';--function fakeEmbed(text: string): Promise<Float32Array> {- // Deterministic shape: a 4-dim vector seeded from string length + first char code.- const v = new Float32Array(4);- const seed = (text.length % 7) + 1;- for (let i = 0; i < 4; i++) v[i] = (seed * (i + 1)) % 5;- return Promise.resolve(v);-}--interface StubChat {- fn: (opts: unknown) => Promise<ChatResult>;- state: { calls: number };-}--function makeOkChat(usage = { input_tokens: 100, output_tokens: 50 }): StubChat {- const state = { calls: 0 };- const fn = async (_opts: unknown): Promise<ChatResult> => {- state.calls++;- return {- text: `summary-${state.calls}`,- blocks: [{ type: 'text', text: `summary-${state.calls}` }],- stopReason: 'end',- model: 'fake-haiku',- providerId: 'fake',- usage: { input_tokens: usage.input_tokens, output_tokens: usage.output_tokens, cache_read_tokens: 0, cache_creation_tokens: 0 },- };- };- return { fn, state };-}--function makeFailingChat(failOnCallIndexes: Set<number>): StubChat {- const state = { calls: 0 };- const fn = async (_opts: unknown): Promise<ChatResult> => {- state.calls++;- if (failOnCallIndexes.has(state.calls)) {- throw new Error(`fake provider error on call ${state.calls}`);- }- return {- text: `summary-${state.calls}`,- blocks: [{ type: 'text', text: `summary-${state.calls}` }],- stopReason: 'end',- model: 'fake-haiku',- providerId: 'fake',- usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },- };- };- return { fn, state };-}--interface ItemShape { id: string; text: string }--const wrapSummary = (summary: string, _cluster: ItemShape[]): ItemShape => ({ id: 'summary', text: summary });--describe('fit summarize — happy path', () => {- test('5 clusters all succeed → degraded=false, every fitted node carries a summary', async () => {- const items: ItemShape[] = Array.from({ length: 20 }, (_, i) => ({ id: String(i), text: `item-${i}` }));- // 20 items / 4 = 5 clusters.- const chat = makeOkChat();- const r = await fit<ItemShape>({- items,- strategy: 'summarize',- maxTokensPerCall: 1000,- estimateTokens: (it) => it.text.length,- embedFn: fakeEmbed,- chatFn: chat.fn,- itemToText: (it) => it.text,- summaryToItem: wrapSummary,- parallelism: 4,- });- expect(r.dropped).toBe(0);- expect(r.degraded).toBe(false);- expect(r.success_ratio).toBe(1.0);- expect(r.fitted.length).toBe(5);- for (const f of r.fitted) expect(f.text).toMatch(/^summary-\d+$/);- expect(chat.state.calls).toBe(5);- });-});--describe('fit summarize — partial failure tolerated', () => {- test('1 of 5 fails → success_ratio=0.8 > 0.75, degraded=false', async () => {- const items: ItemShape[] = Array.from({ length: 20 }, (_, i) => ({ id: String(i), text: `item-${i}` }));- // Fail only call #3 (out of 5).- const chat = makeFailingChat(new Set([3]));- const r = await fit<ItemShape>({- items,- strategy: 'summarize',- maxTokensPerCall: 1000,- estimateTokens: (it) => it.text.length,- embedFn: fakeEmbed,- chatFn: chat.fn,- itemToText: (it) => it.text,- summaryToItem: wrapSummary,- parallelism: 4,- });- expect(r.dropped).toBe(1);- expect(r.success_ratio).toBeCloseTo(0.8, 6);- expect(r.degraded).toBe(false);- expect(r.fitted.length).toBe(4);- });-});--describe('fit summarize — high-failure rate flips degraded', () => {- test('3 of 5 fail → success_ratio=0.4 < 0.75, degraded=true', async () => {- const items: ItemShape[] = Array.from({ length: 20 }, (_, i) => ({ id: String(i), text: `item-${i}` }));- const chat = makeFailingChat(new Set([1, 2, 3]));- const r = await fit<ItemShape>({- items,- strategy: 'summarize',- maxTokensPerCall: 1000,- estimateTokens: (it) => it.text.length,- embedFn: fakeEmbed,- chatFn: chat.fn,- itemToText: (it) => it.text,- summaryToItem: wrapSummary,- parallelism: 4,- });- expect(r.dropped).toBe(3);- expect(r.success_ratio).toBeCloseTo(0.4, 6);- expect(r.degraded).toBe(true);- // Fitter still surfaces the 2 successful clusters; caller decides- // whether to use them.- expect(r.fitted.length).toBe(2);- });-- test('custom min_success_ratio shifts the gate', async () => {- const items: ItemShape[] = Array.from({ length: 20 }, (_, i) => ({ id: String(i), text: `item-${i}` }));- const chat = makeFailingChat(new Set([3]));- // Tighten gate to 0.9 — 4/5 = 0.8 < 0.9 → degraded.- const r = await fit<ItemShape>({- items,- strategy: 'summarize',- maxTokensPerCall: 1000,- estimateTokens: (it) => it.text.length,- embedFn: fakeEmbed,- chatFn: chat.fn,- itemToText: (it) => it.text,- summaryToItem: wrapSummary,- parallelism: 4,- min_success_ratio: 0.9,- });- expect(r.degraded).toBe(true);- });-});--describe('fit summarize — caller misuse', () => {- test('throws when summarize strategy is missing embedFn / chatFn / mappers', async () => {- await expect(- fit({- items: [{ id: 'a', text: 'a' }],- strategy: 'summarize',- maxTokensPerCall: 100,- estimateTokens: () => 1,- }),- ).rejects.toThrow(/embedFn \+ chatFn \+ itemToText \+ summaryToItem/);- });-});--describe('fit summarize — budget-respecting (TX1 mid-cluster abort)', () => {- test('BudgetExhausted thrown by chatFn propagates and halts remaining clusters', async () => {- const items: ItemShape[] = Array.from({ length: 20 }, (_, i) => ({ id: String(i), text: `item-${i}` }));- // Throw BudgetExhausted on call #2 — proves the throw type propagates.- let calls = 0;- const chat = async (): Promise<ChatResult> => {- calls++;- if (calls === 2) {- throw new BudgetExhausted('cap blown', { reason: 'cost', spent: 10, cap: 1 });- }- return {- text: `summary-${calls}`,- blocks: [{ type: 'text', text: `summary-${calls}` }],- stopReason: 'end',- model: 'fake-haiku',- providerId: 'fake',- usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },- };- };-- const r = await fit<ItemShape>({- items,- strategy: 'summarize',- maxTokensPerCall: 1000,- estimateTokens: (it) => it.text.length,- embedFn: fakeEmbed,- chatFn: chat,- itemToText: (it) => it.text,- summaryToItem: wrapSummary,- // Run 5 clusters serially so call #2 = cluster #2.- parallelism: 1,- });- // Because the failure is treated as a dropped cluster (Promise.allSettled- // catches it), the run completes and surfaces dropped=1.- expect(r.dropped).toBeGreaterThanOrEqual(1);- expect(r.fitted.length).toBeLessThan(5);- });-});diff --git a/test/core/diarize/payload-fitter.test.ts b/test/core/diarize/payload-fitter.test.tsdeleted file mode 100644index 6979e01ba3..0000000000--- a/test/core/diarize/payload-fitter.test.ts+++ /dev/null@@ -1,70 +0,0 @@-/**- * v0.37.x — payload-fitter batch strategy contract.- *- * Hermetic. No LLM, no embed. Just the deterministic chunking gate.- */--import { describe, test, expect } from 'bun:test';-import { fit } from '../../../src/core/diarize/payload-fitter.ts';--describe('fit batch', () => {- test('returns input items unchanged when all fit', async () => {- const items = ['short', 'also-short', 'tiny'];- const r = await fit({- items,- strategy: 'batch',- maxTokensPerCall: 1000,- estimateTokens: (s) => s.length,- });- expect(r.fitted).toEqual(items);- expect(r.dropped).toBe(0);- expect(r.degraded).toBe(false);- expect(r.success_ratio).toBe(1.0);- });-- test('reports dropped count for over-budget items', async () => {- const items = ['a'.repeat(10), 'b'.repeat(2000), 'c'.repeat(50)];- const r = await fit({- items,- strategy: 'batch',- maxTokensPerCall: 100,- estimateTokens: (s) => s.length,- });- expect(r.dropped).toBe(1);- expect(r.success_ratio).toBeCloseTo(2 / 3, 6);- // batch never flags degraded; it surfaces dropped count for caller- expect(r.degraded).toBe(false);- });-- test('empty input is a no-op success', async () => {- const r = await fit({- items: [],- strategy: 'batch',- maxTokensPerCall: 100,- estimateTokens: () => 0,- });- expect(r.fitted).toEqual([]);- expect(r.success_ratio).toBe(1.0);- });-- test('deterministic — same input yields the same fitted list', async () => {- const items = ['one', 'two', 'three'];- const a = await fit({ items, strategy: 'batch', maxTokensPerCall: 100, estimateTokens: (s) => s.length });- const b = await fit({ items, strategy: 'batch', maxTokensPerCall: 100, estimateTokens: (s) => s.length });- expect(a.fitted).toEqual(b.fitted);- });-});--describe('fit unknown strategy', () => {- test('throws synchronously on unknown strategy', async () => {- await expect(- fit({- items: ['x'],- // @ts-expect-error — intentional unknown for the error path- strategy: 'mystery',- maxTokensPerCall: 100,- estimateTokens: (s) => s.length,- }),- ).rejects.toThrow(/unknown strategy/);- });-});diff --git a/test/core/git-head.test.ts b/test/core/git-head.test.tsindex 763e66432e..8e8f2be36e 100644--- a/test/core/git-head.test.ts+++ b/test/core/git-head.test.ts@@ -15,8 +15,6 @@ import {probeSourceGitState,_setGitHeadProbeForTests,_setGitCleanProbeForTests,- type GitHeadProbe,- type GitCleanProbe,} from '../../src/core/git-head.ts';// Reset both probe seams between every test so case order can't leak state.@@ -120,27 +118,6 @@ describe('isSourceUnchangedSinceSync — shell-injection regression guard', () =});});-describe('isSourceUnchangedSinceSync — test-seam round-trip', () => {- test('case 10: _setGitHeadProbeForTests + _setGitCleanProbeForTests round-trip', () => {- // Install custom probes- const customHead: GitHeadProbe = () => 'custom-head';- const customClean: GitCleanProbe = () => true;- _setGitHeadProbeForTests(customHead);- _setGitCleanProbeForTests(customClean);-- expect(isSourceUnchangedSinceSync('/x', 'custom-head', { requireCleanWorkingTree: true })).toBe(true);-- // Restore defaults via null- _setGitHeadProbeForTests(null);- _setGitCleanProbeForTests(null);-- // After restoration, the real probes run. Against a non-git path,- // both probes return null → predicate returns false. This proves the- // restore worked without depending on a git repo in the test env.- expect(isSourceUnchangedSinceSync('/definitely-not-a-git-repo-xyz', 'custom-head')).toBe(false);- });-});-describe('isSourceUnchangedSinceSync — requireCleanWorkingTree (D7)', () => {test('case 11: HEAD match + clean tree + requireCleanWorkingTree=true → true', () => {_setGitHeadProbeForTests(() => 'abc123');diff --git a/test/cross-brain-calibration.test.ts b/test/cross-brain-calibration.test.tsdeleted file mode 100644index d4bb95c313..0000000000--- a/test/cross-brain-calibration.test.ts+++ /dev/null@@ -1,259 +0,0 @@-/**- * v0.36.1.0 (T14 / E8 + D18) — cross-brain calibration query tests.- *- * Hermetic. Mock engines stand in for local + mounted brains. The four- * D18 e2e test cases are pinned here so cross-brain leak surfaces don't- * regress silently.- *- * Tests cover:- * D18-1: published=false profile on mount → returns null (no leak)- * D18-2: published=true but consumer lacks mount-read scope → null (subagent)- * D18-3: subagent context attempts mount fallback → returns local-only- * D18-4: attribution: profile returns with source_brain_id surfaced- * + local-first ordering (rule 1)- * + mount priority order (first match wins)- * + null when neither local nor mount has it- * + canReadMountsForCtx classifier table- */--import { describe, test, expect } from 'bun:test';-import {- queryAcrossBrains,- canReadMountsForCtx,- attributionSuffix,- type CrossBrainQueryOpts,-} from '../src/core/calibration/cross-brain.ts';-import type { BrainEngine } from '../src/core/engine.ts';-import type { CalibrationProfileRow } from '../src/commands/calibration.ts';--function buildProfile(opts: { published: boolean; source_id?: string; holder?: string } = { published: false }): CalibrationProfileRow {- return {- id: '1',- source_id: opts.source_id ?? 'default',- holder: opts.holder ?? 'garry',- wave_version: 'v0.36.1.0',- generated_at: '2026-05-17T00:00:00Z',- published: opts.published,- total_resolved: 12,- brier: 0.21,- accuracy: 0.6,- partial_rate: 0.1,- grade_completion: 1.0,- pattern_statements: ['some pattern'],- active_bias_tags: ['over-confident-geography'],- voice_gate_passed: true,- voice_gate_attempts: 1,- model_id: 'claude-sonnet-4-6',- };-}--function buildEngine(profile: CalibrationProfileRow | null): BrainEngine {- return {- kind: 'pglite',- async executeRaw<T>(_sql: string): Promise<T[]> {- return profile ? ([profile] as unknown as T[]) : ([] as T[]);- },- } as unknown as BrainEngine;-}--// ─── D18-1: published=false on mount → null ────────────────────────--describe('D18-1: published=false profile on mount stays hidden', () => {- test('returns null when local empty AND only mount profile has published=false', async () => {- const localEngine = buildEngine(null);- const mountEngine = buildEngine(buildProfile({ published: false, source_id: 'mount-team' }));- const out = await queryAcrossBrains(localEngine, {- holder: 'garry',- localBrainId: 'garry-personal',- canReadMounts: true,- mountResolver: async () => [{ brainId: 'team-brain', engine: mountEngine }],- });- expect(out).toBeNull();- });-});--// ─── D18-2 / D18-3: subagent context cannot read mounts ────────────--describe('D18-2/3: subagent context cannot fall back to mounts', () => {- test('canReadMounts=false short-circuits to null when local has no profile', async () => {- const localEngine = buildEngine(null);- const mountEngine = buildEngine(buildProfile({ published: true }));- const out = await queryAcrossBrains(localEngine, {- holder: 'garry',- localBrainId: 'garry-personal',- canReadMounts: false,- mountResolver: async () => [{ brainId: 'team-brain', engine: mountEngine }],- });- expect(out).toBeNull();- });-- test('canReadMounts=false but local hit → local result still returned', async () => {- const localEngine = buildEngine(buildProfile({ published: false }));- const out = await queryAcrossBrains(localEngine, {- holder: 'garry',- localBrainId: 'garry-personal',- canReadMounts: false,- });- expect(out).not.toBeNull();- expect(out!.from_mount).toBe(false);- expect(out!.source_brain_id).toBe('garry-personal');- });-});--// ─── D18-4: attribution surfaces source_brain_id ───────────────────--describe('D18-4: cross-brain attribution', () => {- test('mount answer carries from_mount=true + source_brain_id', async () => {- const localEngine = buildEngine(null);- const mountEngine = buildEngine(buildProfile({ published: true, source_id: 'team-default' }));- const out = await queryAcrossBrains(localEngine, {- holder: 'garry',- localBrainId: 'garry-personal',- canReadMounts: true,- mountResolver: async () => [{ brainId: 'partners-team', engine: mountEngine }],- });- expect(out).not.toBeNull();- expect(out!.from_mount).toBe(true);- expect(out!.source_brain_id).toBe('partners-team');- });-- test('local hit carries from_mount=false + local brain id', async () => {- const localEngine = buildEngine(buildProfile({ published: false }));- const out = await queryAcrossBrains(localEngine, {- holder: 'garry',- localBrainId: 'garry-personal',- canReadMounts: true,- });- expect(out!.from_mount).toBe(false);- expect(out!.source_brain_id).toBe('garry-personal');- });-- test('attributionSuffix emits "from mounted brain" only when from_mount=true', () => {- const mountResult = {- ...buildProfile({ published: true }),- source_brain_id: 'team-brain',- from_mount: true,- };- expect(attributionSuffix(mountResult)).toContain('from mounted brain: team-brain');-- const localResult = {- ...buildProfile({ published: false }),- source_brain_id: 'garry-personal',- from_mount: false,- };- expect(attributionSuffix(localResult)).toBe('');- });-});--// ─── Rule 1: LOCAL-FIRST ordering ──────────────────────────────────--describe('local-first ordering (D18 rule 1)', () => {- test('local hit short-circuits — mountResolver NOT called', async () => {- const localEngine = buildEngine(buildProfile({ published: false }));- let mountResolverCalls = 0;- const opts: CrossBrainQueryOpts = {- holder: 'garry',- localBrainId: 'garry-personal',- canReadMounts: true,- mountResolver: async () => {- mountResolverCalls++;- return [];- },- };- await queryAcrossBrains(localEngine, opts);- expect(mountResolverCalls).toBe(0);- });-- test('local empty + mount populated → mountResolver IS called', async () => {- const localEngine = buildEngine(null);- const mountEngine = buildEngine(buildProfile({ published: true }));- let mountResolverCalls = 0;- await queryAcrossBrains(localEngine, {- holder: 'garry',- localBrainId: 'garry-personal',- canReadMounts: true,- mountResolver: async () => {- mountResolverCalls++;- return [{ brainId: 'team', engine: mountEngine }];- },- });- expect(mountResolverCalls).toBe(1);- });-});--// ─── Mount priority order: first match wins ────────────────────────--describe('mount priority order', () => {- test('first published=true mount in the list wins', async () => {- const localEngine = buildEngine(null);- const mountA = buildEngine(buildProfile({ published: false, source_id: 'a' }));- const mountB = buildEngine(buildProfile({ published: true, source_id: 'b' }));- const mountC = buildEngine(buildProfile({ published: true, source_id: 'c' }));- const out = await queryAcrossBrains(localEngine, {- holder: 'garry',- localBrainId: 'garry-personal',- canReadMounts: true,- mountResolver: async () => [- { brainId: 'mount-a', engine: mountA },- { brainId: 'mount-b', engine: mountB },- { brainId: 'mount-c', engine: mountC },- ],- });- // mount-a has published=false, skipped; mount-b is first published=true.- expect(out!.source_brain_id).toBe('mount-b');- });-- test('all mounts have published=false → returns null', async () => {- const localEngine = buildEngine(null);- const mountA = buildEngine(buildProfile({ published: false }));- const mountB = buildEngine(buildProfile({ published: false }));- const out = await queryAcrossBrains(localEngine, {- holder: 'garry',- localBrainId: 'garry-personal',- canReadMounts: true,- mountResolver: async () => [- { brainId: 'a', engine: mountA },- { brainId: 'b', engine: mountB },- ],- });- expect(out).toBeNull();- });-- test('no mounts configured + local empty → null without throwing', async () => {- const localEngine = buildEngine(null);- const out = await queryAcrossBrains(localEngine, {- holder: 'garry',- localBrainId: 'garry-personal',- canReadMounts: true,- });- expect(out).toBeNull();- });-});--// ─── canReadMountsForCtx classifier ────────────────────────────────--describe('canReadMountsForCtx classifier', () => {- test('local CLI (remote=false) → true', () => {- expect(canReadMountsForCtx({ remote: false })).toBe(true);- });-- test('MCP non-subagent (remote=true, viaSubagent=undefined) → true', () => {- expect(canReadMountsForCtx({ remote: true })).toBe(true);- });-- test('subagent without trusted-workspace prefixes → false (D18 rule 4)', () => {- expect(- canReadMountsForCtx({ remote: true, viaSubagent: true, allowedSlugPrefixes: [] }),- ).toBe(false);- });-- test('subagent with trusted-workspace prefixes (cycle synthesize/patterns) → true', () => {- expect(- canReadMountsForCtx({- remote: true,- viaSubagent: true,- allowedSlugPrefixes: ['wiki/agents/synthesize/*'],- }),- ).toBe(true);- });-});diff --git a/test/cycle-abort.test.ts b/test/cycle-abort.test.tsindex 8393673dfd..e51141361f 100644--- a/test/cycle-abort.test.ts+++ b/test/cycle-abort.test.ts@@ -20,12 +20,6 @@ import { describe, test, expect } from 'bun:test';// but we CAN test the checkAborted pattern and CycleOpts contract.describe('CycleOpts.signal contract (v0.20.5)', () => {- test('signal field exists on CycleOpts interface', async () => {- // Type-level test: importing the type should work- const mod = await import('../src/core/cycle.ts');- // runCycle exists and is callable- expect(typeof mod.runCycle).toBe('function');- });test('runCycle accepts signal in opts without error', async () => {// Verify runCycle doesn't crash when signal is passed but no enginediff --git a/test/cycle-pack-gating.test.ts b/test/cycle-pack-gating.test.tsindex e5a1af08df..8d6b1d804f 100644--- a/test/cycle-pack-gating.test.ts+++ b/test/cycle-pack-gating.test.ts@@ -1,207 +1,133 @@// v0.41 T9 R-GATE — orchestrator-level pack gate for lens-pack phases.//-// IRON-RULE regression pinning:-// 1. ALL_PHASES includes 'extract_atoms' (after extract_facts) and-// 'synthesize_concepts' (after patterns).-// 2. PHASE_SCOPE declares extract_atoms='source', synthesize_concepts='global'.-// 3. NEEDS_LOCK_PHASES includes both (they mutate DB via put_page).-// 4. cycle.ts dispatch contains the packDeclaresPhase gate for both-// new phases (source-shape assertion — pins the not_in_active_pack-// semantics against future drift).-// 5. Pre-existing 17 core phases ALWAYS run regardless of active pack —-// only the 2 new lens-pack phases are gated (source-shape regression).-// 6. borrow_from does NOT borrow phases — gbrain-everything explicitly-// re-declares creator's phases per D4-B (verified in T4 test;-// cross-referenced here as a pinning hint via source grep).-//-// Why static-source assertions in addition to runtime tests: cycle.ts is a-// ~1700-line orchestrator and the dispatch logic for these new phases-// follows a load-bearing pattern (`if (phases.includes(X)) { ... if-// (!await packDeclaresPhase(engine, X)) skipped else dispatch }`). Static-// source pinning catches refactors that accidentally drop the gate while-// still passing happy-path runtime tests.--import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'fs';-import { join, dirname } from 'path';-import { fileURLToPath } from 'url';-import { ALL_PHASES, PHASE_SCOPE, type CyclePhase } from '../src/core/cycle.ts';+// Contracts, all asserted through runCycle on an in-memory PGLite brain:+// 1. ALL_PHASES orders extract_atoms after extract_facts and+// synthesize_concepts after patterns; PHASE_SCOPE covers every phase.+// 2. Under a pack that does not declare them, extract_atoms and+// synthesize_concepts report status 'skipped', reason+// 'not_in_active_pack', with an actionable summary (#2117).+// 3. Under a pack that declares them (gbrain-creator), the gate opens:+// the phase is dispatched instead of pack-skipped.+// 3b. Phases are local to the declaring manifest (D4-B): a user pack+// that extends gbrain-creator without re-declaring them stays gated.+// 4. Pack gating is additive: across a full cycle on the default pack,+// ONLY those two phases are pack-skipped.+// 5. Both phases take the cycle lock (they write pages), so a live+// holder turns the cycle into cycle_already_running.++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { ALL_PHASES, PHASE_SCOPE, runCycle, type CyclePhase } from '../src/core/cycle.ts';+import { withEnv, emptyHome } from './helpers/with-env.ts';++const PACK_GATED: ReadonlyArray<CyclePhase> = ['extract_atoms', 'synthesize_concepts'];++let engine: PGLiteEngine;+let brainDir: string;+let gbrainHome: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ brainDir = mkdtempSync(join(tmpdir(), 'gbrain-pack-gate-'));+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(brainDir, { recursive: true, force: true });+});-const here = dirname(fileURLToPath(import.meta.url));-const cycleTsSrc = readFileSync(- join(here, '..', 'src', 'core', 'cycle.ts'),- 'utf-8',-);+beforeEach(async () => {+ gbrainHome = emptyHome();+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks');+});-const NEW_PHASES: ReadonlyArray<CyclePhase> = ['extract_atoms', 'synthesize_concepts'];+function cycleUnderPack(pack: string | undefined, opts: Parameters<typeof runCycle>[1]) {+ return withEnv(+ { GBRAIN_HOME: gbrainHome, GBRAIN_SCHEMA_PACK: pack, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined },+ () => runCycle(engine, opts),+ );+}describe('v0.41 T9 R-GATE: ALL_PHASES + PHASE_SCOPE contract', () => {- test('ALL_PHASES contains extract_atoms', () => {- expect(ALL_PHASES).toContain('extract_atoms');- });-- test('ALL_PHASES contains synthesize_concepts', () => {- expect(ALL_PHASES).toContain('synthesize_concepts');+ test('extract_atoms runs after extract_facts; synthesize_concepts after patterns', () => {+ expect(ALL_PHASES.indexOf('extract_facts')).toBeGreaterThan(-1);+ expect(ALL_PHASES.indexOf('extract_atoms')).toBeGreaterThan(ALL_PHASES.indexOf('extract_facts'));+ expect(ALL_PHASES.indexOf('patterns')).toBeGreaterThan(-1);+ expect(ALL_PHASES.indexOf('synthesize_concepts')).toBeGreaterThan(ALL_PHASES.indexOf('patterns'));});- test('extract_atoms is positioned AFTER extract_facts (semantic ordering)', () => {- const extractFactsIdx = ALL_PHASES.indexOf('extract_facts');- const extractAtomsIdx = ALL_PHASES.indexOf('extract_atoms');- expect(extractFactsIdx).toBeGreaterThan(-1);- expect(extractAtomsIdx).toBeGreaterThan(extractFactsIdx);- });-- test('synthesize_concepts is positioned AFTER patterns (graph-fresh semantics)', () => {- const patternsIdx = ALL_PHASES.indexOf('patterns');- const synthIdx = ALL_PHASES.indexOf('synthesize_concepts');- expect(patternsIdx).toBeGreaterThan(-1);- expect(synthIdx).toBeGreaterThan(patternsIdx);- });-- test('PHASE_SCOPE declares extract_atoms as source-scoped', () => {+ test('PHASE_SCOPE: extract_atoms is source-scoped, synthesize_concepts global, every phase mapped', () => {expect(PHASE_SCOPE.extract_atoms).toBe('source');- });-- test('PHASE_SCOPE declares synthesize_concepts as global-scoped', () => {expect(PHASE_SCOPE.synthesize_concepts).toBe('global');- });-- test('every ALL_PHASES entry has a PHASE_SCOPE entry (exhaustive map)', () => {- for (const p of ALL_PHASES) {- expect(PHASE_SCOPE[p]).toBeDefined();- }- });-});--describe('v0.41 T9 R-GATE: NEEDS_LOCK_PHASES contract (source-shape)', () => {- // NEEDS_LOCK_PHASES isn't exported; static-source assertion pins the- // contract that both new phases acquire the cycle lock since they- // mutate DB state (put_page atom/concept pages).- test('cycle.ts source includes extract_atoms in NEEDS_LOCK_PHASES', () => {- // Find the NEEDS_LOCK_PHASES block and assert both phases appear in it.- const blockStart = cycleTsSrc.indexOf('NEEDS_LOCK_PHASES');- expect(blockStart).toBeGreaterThan(-1);- const blockEnd = cycleTsSrc.indexOf(']);', blockStart);- expect(blockEnd).toBeGreaterThan(blockStart);- const block = cycleTsSrc.slice(blockStart, blockEnd);- expect(block).toContain("'extract_atoms'");- });-- test('cycle.ts source includes synthesize_concepts in NEEDS_LOCK_PHASES', () => {- const blockStart = cycleTsSrc.indexOf('NEEDS_LOCK_PHASES');- const blockEnd = cycleTsSrc.indexOf(']);', blockStart);- const block = cycleTsSrc.slice(blockStart, blockEnd);- expect(block).toContain("'synthesize_concepts'");+ for (const p of ALL_PHASES) expect(PHASE_SCOPE[p]).toBeDefined();});});-describe('v0.41 T9 R-GATE: orchestrator dispatch wires the pack-gate', () => {- // Source-shape regression: the dispatch for each new phase MUST- // consult packDeclaresPhase(engine, '<phase>') before invoking the- // phase. Future refactors that accidentally drop the gate would still- // pass happy-path runtime tests; this assertion catches the drop.- test('cycle.ts dispatch for extract_atoms calls packDeclaresPhase', () => {- expect(cycleTsSrc).toContain("packDeclaresPhase(engine, 'extract_atoms')");- });-- test('cycle.ts dispatch for synthesize_concepts calls packDeclaresPhase', () => {- expect(cycleTsSrc).toContain("packDeclaresPhase(engine, 'synthesize_concepts')");- });-- test('packDeclaresPhase helper function exists in cycle.ts', () => {- expect(cycleTsSrc).toContain('async function packDeclaresPhase(');- });-- test('packDeclaresPhase reads phases from active pack manifest (NOT extends chain)', () => {- // Source-pin: the helper reads `resolved.manifest.phases` — D4-B- // says phases are local to the declaring manifest. Future drift- // that adds extends-chain merging would silently change semantics- // for users who extend gbrain-creator expecting inheritance; this- // assertion catches it.- expect(cycleTsSrc).toContain('resolved.manifest.phases');- });-- test('packDeclaresPhase fail-open: returns false on catch (no thrown exceptions)', () => {- // Source-pin: the helper's try/catch returns false on any error- // (registry not initialized, pack not found, malformed manifest).- // Skipping > crashing for an orchestrator gate.- const helperStart = cycleTsSrc.indexOf('async function packDeclaresPhase(');- expect(helperStart).toBeGreaterThan(-1);- const helperEnd = cycleTsSrc.indexOf('\n}\n', helperStart);- const helperBody = cycleTsSrc.slice(helperStart, helperEnd);- expect(helperBody).toContain('catch');- expect(helperBody).toContain('return false');- });-});--describe('v0.41 T9 R-GATE: pre-existing 17 core phases always run', () => {- // The IRON RULE that the wave depends on: pack-gating is ADDITIVE,- // not subtractive. A user on gbrain-base (which declares phases:[])- // must still see all 17 pre-existing phases run as before. The static- // assertion: only the 2 new lens-pack phases reference packDeclaresPhase- // in the dispatch.- test('only extract_atoms + synthesize_concepts dispatch sites reference packDeclaresPhase', () => {- const matches = cycleTsSrc.match(/packDeclaresPhase\(engine, '[^']+'\)/g) ?? [];- const phaseNames = matches.map((m) => {- const inner = /packDeclaresPhase\(engine, '([^']+)'\)/.exec(m);- return inner ? inner[1] : '';- });- // Should be EXACTLY two phases gated.- expect(phaseNames.sort()).toEqual(['extract_atoms', 'synthesize_concepts']);- });-- test('extract_facts dispatch does NOT consult packDeclaresPhase', () => {- // Pre-existing phase; must always run on every pack. Window scoped- // to the SINGLE dispatch block — find the next `// ──` comment- // marker (the next phase dispatch header) and stop there.- const blockStart = cycleTsSrc.indexOf("if (phases.includes('extract_facts'))");- expect(blockStart).toBeGreaterThan(-1);- const blockEnd = cycleTsSrc.indexOf('// ──', blockStart + 10);- expect(blockEnd).toBeGreaterThan(blockStart);- const block = cycleTsSrc.slice(blockStart, blockEnd);- expect(block).not.toContain('packDeclaresPhase');- });-- test('calibration_profile dispatch does NOT consult packDeclaresPhase', () => {- // Pre-existing v0.36.1.0 phase; always-on.- const cpBlockStart = cycleTsSrc.indexOf("phases.includes('calibration_profile')");- expect(cpBlockStart).toBeGreaterThan(-1);- // Window of 1500 chars covers the dispatch.- const block = cycleTsSrc.slice(cpBlockStart, cpBlockStart + 1500);- expect(block).not.toContain('packDeclaresPhase');- });-});--describe('v0.41 T9 R-GATE: dispatch result envelope', () => {- test('extract_atoms not_in_active_pack skip carries the correct reason marker', () => {- expect(cycleTsSrc).toContain("reason: 'not_in_active_pack'");- });-- test('synthesize_concepts not_in_active_pack uses the same marker (semantic consistency)', () => {- // Both phases should use identical reason marker — doctor can match- // a single string across both pack-gated skip events.- const occurrences = (cycleTsSrc.match(/reason: 'not_in_active_pack'/g) ?? []).length;- expect(occurrences).toBe(2);- });-});--// #2117 — the pack-gated skip summaries must tell the operator HOW to opt-// in: declare the phase in the active pack's `phases:` list or activate a-// lens pack that ships it (gbrain-creator / gbrain-everything). Source-shape-// pin, matching this file's style.-describe('#2117: pack-gated skip summaries are actionable', () => {- test('both skip summaries name the phases: key and a lens pack', () => {- const summaries = cycleTsSrc.match(- /summary: '(?:extract_atoms|synthesize_concepts): active pack[^']*'/g,- ) ?? [];- expect(summaries.length).toBe(2);- for (const s of summaries) {- expect(s).toContain('phases:');- expect(s).toContain('gbrain-creator');+describe('v0.41 T9 R-GATE: dispatch consults the active pack', () => {+ test('a pack without the phases skips both with an actionable not_in_active_pack summary', async () => {+ const report = await cycleUnderPack('gbrain-base', { brainDir, phases: [...PACK_GATED], dryRun: true });+ for (const phase of PACK_GATED) {+ const r = report.phases.find(p => p.phase === phase);+ expect(r?.status).toBe('skipped');+ expect(r?.details?.reason).toBe('not_in_active_pack');+ expect(r?.summary).toContain('phases:');+ expect(r?.summary).toContain('gbrain-creator');}- });+ const atoms = report.phases.find(p => p.phase === 'extract_atoms');+ expect(atoms?.summary).toContain('gbrain dream --phase extract_atoms --drain');+ }, 60_000);++ test('a pack that declares the phases (gbrain-creator) opens the gate', async () => {+ const report = await cycleUnderPack('gbrain-creator', { brainDir, phases: [...PACK_GATED], dryRun: true });+ for (const phase of PACK_GATED) {+ const r = report.phases.find(p => p.phase === phase);+ expect(r).toBeDefined();+ expect(r?.details?.reason).not.toBe('not_in_active_pack');+ }+ }, 60_000);++ test('phases are not inherited through extends (D4-B): a child of gbrain-creator stays gated', async () => {+ const packDir = join(gbrainHome, '.gbrain', 'schema-packs', 'creator-child-example');+ mkdirSync(packDir, { recursive: true });+ writeFileSync(join(packDir, 'pack.yaml'), [+ 'api_version: gbrain-schema-pack-v1',+ 'name: creator-child-example',+ 'version: 1.0.0',+ 'description: test pack extending gbrain-creator without declaring phases',+ 'gbrain_min_version: 0.41.0',+ 'extends: gbrain-creator',+ 'page_types: []',+ '',+ ].join('\n'));+ const report = await cycleUnderPack('creator-child-example', { brainDir, phases: ['extract_atoms'], dryRun: true });+ expect(report.phases.find(p => p.phase === 'extract_atoms')?.details?.reason).toBe('not_in_active_pack');+ }, 60_000);++ test('pack gating is additive: a full default-pack cycle pack-skips only the two lens phases', async () => {+ const report = await cycleUnderPack(undefined, { brainDir, dryRun: true });+ const packSkipped = report.phases+ .filter(p => p.details?.reason === 'not_in_active_pack')+ .map(p => p.phase)+ .sort();+ expect(packSkipped).toEqual([...PACK_GATED].sort());+ }, 120_000);+});- test('extract_atoms skip summary keeps the drain hint', () => {- expect(cycleTsSrc).toContain('gbrain dream --phase extract_atoms --drain');- });+describe('v0.41 T9 R-GATE: lens phases take the cycle lock', () => {+ for (const phase of PACK_GATED) {+ test(`${phase} alone waits behind a live cycle-lock holder`, async () => {+ await engine.executeRaw(+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at)+ VALUES ('gbrain-cycle', 99999, 'other-host', NOW(), NOW() + INTERVAL '1 hour')`,+ );+ const report = await cycleUnderPack('gbrain-base', { brainDir, phases: [phase], dryRun: true });+ expect(report.status).toBe('skipped');+ expect(report.reason).toBe('cycle_already_running');+ }, 60_000);+ }});diff --git a/test/cycle-patterns.test.ts b/test/cycle-patterns.test.tsindex 20573254fb..69bef2e5a3 100644--- a/test/cycle-patterns.test.ts+++ b/test/cycle-patterns.test.ts@@ -1,90 +1,69 @@/*** Unit tests for the patterns phase (v0.21).*- * The phase invokes a subagent and queues real Minions work, so this- * file leans on structural assertions over the source + a single- * end-to-end driver run that exercises the skip-paths.- *- * Full LLM behavior is exercised by E2E tests in test/e2e/.+ * Driven through `runPhasePatterns` and its `__testing` helpers on one+ * in-memory PGLite brain. Paths that would reach a real subagent stop at a+ * cheap gate instead: `dryRun`, the provider probe (`no_provider`), or a+ * near deadline (`insufficient_cycle_budget`, checked after the probe and+ * the allow-list load). Child outcomes, the evidence watermark, source+ * scoping and the budget clamp have their own files+ * (test/cycle-patterns-*.test.ts).*/-import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'fs';+import { describe, test, expect, beforeAll, afterAll, beforeEach, spyOn } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';import type { BrainEngine } from '../src/core/engine.ts';-import { __testing } from '../src/core/cycle/patterns.ts';--const patternsSrc = readFileSync(- new URL('../src/core/cycle/patterns.ts', import.meta.url),- 'utf-8',-);--describe('patterns phase wiring', () => {- test('imports queue + waitForCompletion + types', () => {- expect(patternsSrc).toContain("import { DEFAULT_PRIVATE_QUEUE_LEASE_MS, MinionQueue }");- // The post-drain wait must be the lease-renewing variant — a plain- // waitForCompletion would let the private-queue lease lapse mid-wait.- expect(patternsSrc).toContain('waitForCompletionRenewing');- // The keepalive must come from the shared throttled factory (T0- // extraction) — an inline closure here and in synthesize drifts.- expect(patternsSrc).toContain('makeThrottledLeaseRenewer');- expect(patternsSrc).toContain('SubagentHandlerData');- });-- test('threads allowed_slug_prefixes from filing-rules JSON', () => {- expect(patternsSrc).toContain('allowed_slug_prefixes');- expect(patternsSrc).toContain('_brain-filing-rules.json');- expect(patternsSrc).toContain('dream_synthesize_paths');- });-- test('reads min_evidence + lookback_days config', () => {- expect(patternsSrc).toContain('dream.patterns.min_evidence');- expect(patternsSrc).toContain('dream.patterns.lookback_days');- });-- test('uses subagent_tool_executions for slug provenance (Codex #2 fix)', () => {- expect(patternsSrc).toContain('subagent_tool_executions');- expect(patternsSrc).toContain("tool_name = 'brain_put_page'");- });-- test('gates on gateway provider reachability, not ANTHROPIC_API_KEY (PR #2279)', () => {- // The gate must probe the RESOLVED patterns model through the gateway- // (any configured provider can run patterns), not hardcode the Anthropic- // env var — that misclassified non-Anthropic stacks as "no upstream".- expect(patternsSrc).toContain('probeChatModel');- expect(patternsSrc).toContain('normalizeModelId');- expect(patternsSrc).toContain('no_provider');- expect(patternsSrc).not.toContain('process.env.ANTHROPIC_API_KEY');- });+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { parseMarkdown } from '../src/core/markdown.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { __testing, runPhasePatterns } from '../src/core/cycle/patterns.ts';++let engine: PGLiteEngine;+let schemaVersion: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ // resetPgliteState truncates `config`, including the `version` row that+ // MinionQueue.ensureSchema checks before a submission.+ schemaVersion = (await engine.getConfig('version')) ?? '7';+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});- test('skips when reflections below min_evidence', () => {- expect(patternsSrc).toContain('insufficient_evidence');- });+beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', schemaVersion);+});- test('reverse-writes pages to disk via serializeMarkdown', () => {- expect(patternsSrc).toContain('serializeMarkdown');- expect(patternsSrc).toContain('writeFileSync');- });+async function seed(slugs: string[], ageMinutes = 0): Promise<void> {+ for (const slug of slugs) {+ await engine.executeRaw(+ `INSERT INTO pages (slug, type, title, compiled_truth, updated_at)+ VALUES ($1, 'note', $1, 'reflection body', NOW() - ($2 || ' minutes')::interval)`,+ [slug, String(ageMinutes)],+ );+ }+}- test('runs after extract — queries fresh graph', () => {- // Documented invariant: pattern phase MUST run after extract.- // The cycle.ts dispatcher enforces order; this just confirms the- // patterns module doesn't try to compute its own auto-link layer- // (which would be a subtle regression).- expect(patternsSrc).not.toContain('runAutoLink');- expect(patternsSrc).not.toContain('extractPageLinks(');- });+const reflections = (n: number, prefix = 'wiki/personal/reflections') =>+ Array.from({ length: n }, (_, i) => `${prefix}/r-${i}`);- test('does NOT use raw_data table (Codex #3 fix)', () => {- expect(patternsSrc).not.toContain('putRawData');- expect(patternsSrc).not.toContain('getRawData');- });-});+function noKeys<T>(fn: () => Promise<T>, extra: Record<string, string | undefined> = {}) {+ return withEnv({ ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: undefined, ...extra }, fn);+}-describe('patterns scope filter', () => {+describe('patterns reflection gathering', () => {test('reflection excerpts never split a UTF-16 surrogate pair', async () => {const rocket = '\uD83D\uDE80';const compiledTruth = `${'a'.repeat(599)}${rocket}tail`;- const engine = {+ const fake = {executeRaw: async () => [{slug: 'wiki/personal/reflections/example',title: 'Example',@@ -92,50 +71,162 @@ describe('patterns scope filter', () => {}],} as unknown as BrainEngine;- const [reflection] = await __testing.gatherReflections(engine, 30);+ const [reflection] = await __testing.gatherReflections(fake, 30);expect(reflection.excerpt.isWellFormed()).toBe(true);expect(reflection.excerpt.endsWith(rocket)).toBe(false);expect(reflection.excerpt.length).toBe(599);});- test('filters reflections by slug LIKE <source_slug_prefix>/%', () => {- // #2415 made the top-level namespace root configurable- // (dream.synthesize.output_root, default 'wiki'). A later patch made the- // full `personal/reflections` sub-path configurable too- // (dream.patterns.source_slug_prefix, defaults to- // `<output_root>/personal/reflections` so existing behavior is- // unchanged) — schemas with no `personal/` nesting (e.g. a flat- // `meetings/` tree) can point the phase at their own compiled_truth- // source instead.- expect(patternsSrc).toContain('slug LIKE $2');- expect(patternsSrc).toContain('${sourceSlugPrefix}/%');- expect(patternsSrc).toContain('dream.patterns.source_slug_prefix');- });+ test('scoped to <prefix>/, newest first, capped at 100, bounded by lookback', async () => {+ await engine.executeRaw(+ `INSERT INTO pages (slug, type, title, compiled_truth, updated_at)+ SELECT 'wiki/personal/reflections/r-' || lpad(g::text, 3, '0'), 'note', 'R', 'body',+ NOW() - (g || ' minutes')::interval+ FROM generate_series(0, 100) g`,+ );+ await seed(['wiki/personal/reflections-archive/newest', 'wiki/personal/other/newest']);++ const rows = await __testing.gatherReflections(engine, 30, 'wiki/personal/reflections', 'default');+ expect(rows).toHaveLength(100);+ expect(rows[0]!.slug).toBe('wiki/personal/reflections/r-000');+ expect(rows[99]!.slug).toBe('wiki/personal/reflections/r-099');+ expect(rows.every(r => r.slug.startsWith('wiki/personal/reflections/'))).toBe(true);+- test('orders by updated_at DESC for recency-bias', () => {- expect(patternsSrc).toContain('ORDER BY updated_at DESC');+ await seed(['journal/old/x'], 40 * 24 * 60);+ expect(await __testing.gatherReflections(engine, 30, 'journal/old', 'default')).toHaveLength(0);+ expect(await __testing.gatherReflections(engine, 60, 'journal/old', 'default')).toHaveLength(1);});+});- test('caps gather to 100 reflections (cost control)', () => {- expect(patternsSrc).toContain('LIMIT 100');+describe('patterns config knobs (dry-run)', () => {+ test('min_evidence: 2 reflections skip by default (needs 3) and run at min_evidence=2', async () => {+ await seed(reflections(2));+ const skipped = await runPhasePatterns(engine, { brainDir: '/tmp', dryRun: true });+ expect(skipped.status).toBe('skipped');+ expect(skipped.details.reason).toBe('insufficient_evidence');++ await engine.setConfig('dream.patterns.min_evidence', '2');+ const ran = await runPhasePatterns(engine, { brainDir: '/tmp', dryRun: true });+ expect(ran.status).toBe('ok');+ expect(ran.details.reflections_considered).toBe(2);+ });++ test('lookback_days narrows the window', async () => {+ await seed(reflections(3), 5 * 24 * 60);+ const wide = await runPhasePatterns(engine, { brainDir: '/tmp', dryRun: true });+ expect(wide.details.reflections_considered).toBe(3);+ await engine.setConfig('dream.patterns.lookback_days', '1');+ const narrow = await runPhasePatterns(engine, { brainDir: '/tmp', dryRun: true });+ expect(narrow.details.reason).toBe('insufficient_evidence');+ });++ test('source_slug_prefix points the phase at another reflection tree', async () => {+ await seed(reflections(3, 'journal/entries'));+ const def = await runPhasePatterns(engine, { brainDir: '/tmp', dryRun: true });+ expect(def.details.reason).toBe('insufficient_evidence');+ await engine.setConfig('dream.patterns.source_slug_prefix', 'journal/entries');+ const custom = await runPhasePatterns(engine, { brainDir: '/tmp', dryRun: true });+ expect(custom.status).toBe('ok');+ expect(custom.details.reflections_considered).toBe(3);});+});- test('output slug prefix is config-driven, defaulting to <output_root>/personal/patterns', () => {- expect(patternsSrc).toContain('dream.patterns.output_slug_prefix');- expect(patternsSrc).toContain('${outputRoot}/personal/patterns');+describe('patterns provider gate (PR #2279)', () => {+ // A near deadline makes a probe-passing run stop at insufficient_cycle_budget+ // before any subagent is submitted.+ const nearDeadline = () => Date.now() + 1_000;++ test('the default Anthropic model with no key skips as no_provider', async () => {+ await seed(reflections(3));+ const r = await noKeys(() => runPhasePatterns(engine, { brainDir: '/tmp', dryRun: false, deadlineAtMs: nearDeadline() }));+ expect(r.status).toBe('skipped');+ expect(r.details.reason).toBe('no_provider');+ });++ test('a non-Anthropic model passes the gate with no ANTHROPIC_API_KEY', async () => {+ await seed(reflections(3));+ await engine.setConfig('models.dream.patterns', 'openai:gpt-5.4');+ const r = await noKeys(+ () => runPhasePatterns(engine, { brainDir: '/tmp', dryRun: false, deadlineAtMs: nearDeadline() }),+ { OPENAI_API_KEY: 'sk-test' },+ );+ expect(r.details.reason).toBe('insufficient_cycle_budget');+ });++ test('a bare model id is normalized to its provider before probing', async () => {+ await seed(reflections(3));+ await engine.setConfig('models.dream.patterns', 'claude-sonnet-4-6');+ const r = await noKeys(+ () => runPhasePatterns(engine, { brainDir: '/tmp', dryRun: false, deadlineAtMs: nearDeadline() }),+ { ANTHROPIC_API_KEY: 'sk-ant-test' },+ );+ expect(r.details.reason).toBe('insufficient_cycle_budget');});+});- test('source slug prefix defaults to <output_root>/personal/reflections', () => {- expect(patternsSrc).toContain('${outputRoot}/personal/reflections');+describe('patterns subagent submission', () => {+ test('job carries filing-rule + configured output allow-list and prompt prefixes; no raw_data', async () => {+ const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-patterns-submit-'));+ try {+ await seed(reflections(3));+ await engine.setConfig('dream.patterns.output_slug_prefix', 'journal/themes');+ // Fake key with fetch stubbed offline: the inline drain's provider call+ // fails at once and the child dead-letters, with no network access.+ const offline = spyOn(globalThis, 'fetch').mockImplementation((async () => { throw new Error('offline'); }) as never);+ let result;+ try {+ result = await noKeys(+ () => runPhasePatterns(engine, { brainDir, dryRun: false }),+ { ANTHROPIC_API_KEY: 'sk-ant-test' },+ );+ } finally {+ offline.mockRestore();+ }+ expect(result.details.child_outcome).toBeDefined();+ const [job] = await engine.executeRaw<{ data: any }>(+ `SELECT data FROM minion_jobs WHERE name = 'subagent' ORDER BY id DESC LIMIT 1`,+ );+ const data = typeof job!.data === 'string' ? JSON.parse(job!.data) : job!.data;+ expect(data.allowed_slug_prefixes).toContain('wiki/personal/patterns/*');+ expect(data.allowed_slug_prefixes).toContain('journal/themes/*');+ expect(data.prompt).toContain('journal/themes/<topic-slug>');+ expect(data.prompt).toContain('[[wiki/personal/reflections/r-0]]');+ const [raw] = await engine.executeRaw<{ n: number }>('SELECT COUNT(*)::int AS n FROM raw_data');+ expect(raw!.n).toBe(0);+ } finally {+ rmSync(brainDir, { recursive: true, force: true });+ }+ }, 60_000);+});++describe('patterns private-queue keepalive wiring', () => {+ test('the post-drain wait renews the private-queue lease through the shared throttled factory', () => {+ // test-reads-source-ok[structural]: the lease only lapses after a >10-minute post-drain wait with a live child, which no unit harness reaches; the invariant is that patterns reuses queue.makeThrottledLeaseRenewer + waitForCompletionRenewing instead of an inline closure that drifts from synthesize's (library behavior: test/wait-for-completion.test.ts, test/queue-child-done.test.ts).+ const src = readFileSync(new URL('../src/core/cycle/patterns.ts', import.meta.url), 'utf8');+ expect(src).toContain('queue.makeThrottledLeaseRenewer(');+ expect(src).toMatch(/waitForCompletionRenewing\(queue, job\.id, \{[\s\S]*?renew: renewPrivateQueueLease/);});+});- test('adds a configured output_slug_prefix to the subagent write allow-list', () => {- // A custom dream.patterns.output_slug_prefix (e.g. a flat schema with no- // personal/ nesting) is not covered by the filing-rules globs, which only- // remap the `wiki/personal/patterns/*` literal by output_root. The phase- // must add it explicitly so put_page actually grants write access there.- expect(patternsSrc).toContain('outputGlob');- expect(patternsSrc).toContain('allowedSlugPrefixes.push(outputGlob)');+describe('patterns reverse-write', () => {+ test('writes the page back as markdown that round-trips title, type, tags and body', async () => {+ const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-patterns-rw-'));+ try {+ await engine.putPage('wiki/personal/patterns/focus', {+ type: 'note', title: 'Focus', compiled_truth: 'Recurring focus theme.', timeline: '', frontmatter: {},+ });+ await engine.addTag('wiki/personal/patterns/focus', 'theme');+ const n = await __testing.reverseWriteRefs(engine, brainDir, [{ slug: 'wiki/personal/patterns/focus', source_id: 'default' }]);+ expect(n).toBe(1);+ const parsed = parseMarkdown(readFileSync(join(brainDir, 'wiki/personal/patterns/focus.md'), 'utf8'));+ expect(parsed.title).toBe('Focus');+ expect(parsed.type).toBe('note');+ expect(parsed.tags).toEqual(['theme']);+ expect(parsed.compiled_truth.trim()).toBe('Recurring focus theme.');+ } finally {+ rmSync(brainDir, { recursive: true, force: true });+ }});});diff --git a/test/cycle/cycle-lock-ttl.test.ts b/test/cycle/cycle-lock-ttl.test.tsdeleted file mode 100644index a3da3138a5..0000000000--- a/test/cycle/cycle-lock-ttl.test.ts+++ /dev/null@@ -1,29 +0,0 @@-// v0.41.19.0 — T2 of ops-fix-wave.-//-// Regression pin: the cycle DB lock TTL was dropped from 30 min to 5 min-// in v0.41.19.0 (T2). Combined with active in-phase refresh via-// buildYieldDuringPhase (T3) this makes crash recovery 6× faster-// (≤5min vs ≤30min before).-//-// This test pins the constant via the migration query observable. If-// the TTL ever climbs back above 5 min, the ops pain comes back.--import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'fs';-import { join } from 'path';--describe('cycle lock TTL (T2 regression pin)', () => {- test('LOCK_TTL_MINUTES === 5 in src/core/cycle.ts', () => {- const src = readFileSync(- join(__dirname, '..', '..', 'src', 'core', 'cycle.ts'),- 'utf-8',- );- // Pin the literal constant value. Two patterns guarded:- // - LOCK_TTL_MINUTES = 5- // - LOCK_TTL_MS = 5 * 60 * 1000- expect(src).toMatch(/LOCK_TTL_MINUTES\s*=\s*5\b/);- expect(src).toMatch(/LOCK_TTL_MS\s*=\s*5\s*\*\s*60\s*\*\s*1000/);- // And explicitly disallow the prior 30-minute value re-creeping back.- expect(src).not.toMatch(/LOCK_TTL_MINUTES\s*=\s*30\b/);- });-});diff --git a/test/data-research.test.ts b/test/data-research.test.tsdeleted file mode 100644index 46c6b61455..0000000000--- a/test/data-research.test.ts+++ /dev/null@@ -1,343 +0,0 @@-import { describe, test, expect } from 'bun:test';-import {- validateRecipe,- extractFields,- verifyExtraction,- isDuplicate,- parseTrackerPage,- appendToTracker,- computeTotals,- buildDateWindows,- stripEmailHtml,-} from '../src/core/data-research.ts';--describe('data-research', () => {- describe('validateRecipe', () => {- test('valid recipe passes', () => {- const result = validateRecipe({- name: 'test',- source_queries: { gmail: ['subject:test'] },- extraction_schema: { amount: 'currency' },- tracker_page: 'trackers/test',- tracker_format: { group_by: 'year', columns: ['date', 'amount'] },- });- expect(result.valid).toBe(true);- expect(result.errors.length).toBe(0);- });-- test('missing name fails', () => {- const result = validateRecipe({- source_queries: { gmail: ['test'] },- extraction_schema: { a: 'string' },- tracker_page: 't',- tracker_format: { group_by: 'y', columns: ['a'] },- });- expect(result.valid).toBe(false);- expect(result.errors).toContain('Missing required field: name');- });-- test('empty source_queries fails', () => {- const result = validateRecipe({- name: 'test',- source_queries: {},- extraction_schema: { a: 'string' },- tracker_page: 't',- tracker_format: { group_by: 'y', columns: ['a'] },- });- expect(result.valid).toBe(false);- });-- test('missing tracker_format columns fails', () => {- const result = validateRecipe({- name: 'test',- source_queries: { gmail: ['test'] },- extraction_schema: { a: 'string' },- tracker_page: 't',- tracker_format: { group_by: 'y', columns: [] },- });- expect(result.valid).toBe(false);- });- });-- describe('extractFields', () => {- test('extracts MRR from text', () => {- const result = extractFields('Our MRR hit $188K this month', { mrr: 'currency' });- expect(result.mrr).toBe('188K');- });-- test('extracts ARR from text', () => {- const result = extractFields('ARR: $2.3M', { arr: 'currency' });- expect(result.arr).toBe('2.3M');- });-- test('extracts growth rate', () => {- const result = extractFields('We grew +14.7% MoM', { growth_mom: 'percentage' });- expect(result.growth_mom).toBe('+14.7%');- });-- test('extracts runway months', () => {- const result = extractFields('We have 16 months of runway', { runway_months: 'number' });- expect(result.runway_months).toBe('16');- });-- test('extracts headcount', () => {- const result = extractFields('Team of 23 employees', { headcount: 'number' });- expect(result.headcount).toBe('23');- });-- test('extracts dollar amounts', () => {- const result = extractFields('Total Charged\n$5,900.00', { amount: 'currency' });- expect(result.amount).toBe('5,900.00');- });-- test('returns null for unmatched fields', () => {- const result = extractFields('no metrics here', { mrr: 'currency', arr: 'currency' });- expect(result.mrr).toBeNull();- expect(result.arr).toBeNull();- });-- test('extracts dates', () => {- const result = extractFields('Updated on 2026-04-15', { date: 'date' });- expect(result.date).toBe('2026-04-15');- });- });-- describe('verifyExtraction', () => {- test('matching fields verify OK', () => {- const result = verifyExtraction(- { mrr: '188K', arr: '2.3M' },- { mrr: '188K', arr: '2.3M' },- );- expect(result.verified).toBe(true);- expect(result.mismatches.length).toBe(0);- });-- test('mismatched fields are flagged', () => {- const result = verifyExtraction(- { mrr: '188K', arr: '2.3M' },- { mrr: '200K', arr: '2.3M' },- );- expect(result.verified).toBe(false);- expect(result.mismatches.length).toBe(1);- expect(result.mismatches[0]).toContain('mrr');- });- });-- describe('isDuplicate', () => {- const existing = [- { date: '2026-04-01', recipient: 'Alice', amount: '$100.00' },- { date: '2026-04-01', recipient: 'Bob', amount: '$200.00' },- ];-- test('exact match is duplicate', () => {- const result = isDuplicate(existing, { date: '2026-04-01', recipient: 'Alice', amount: '$100.00' }, ['date', 'recipient', 'amount']);- expect(result.isDuplicate).toBe(true);- expect(result.type).toBe('exact');- });-- test('new entry is not duplicate', () => {- const result = isDuplicate(existing, { date: '2026-04-02', recipient: 'Charlie', amount: '$300.00' }, ['date', 'recipient', 'amount']);- expect(result.isDuplicate).toBe(false);- expect(result.type).toBe('new');- });-- test('different amount same entity+date flagged', () => {- const result = isDuplicate(- existing,- { date: '2026-04-01', recipient: 'Alice', amount: '$150.00' },- ['date', 'recipient', 'amount'],- );- expect(result.type).toBe('different_amount');- });-- test('fuzzy entity matching', () => {- const result = isDuplicate(- existing,- { date: '2026-04-01', recipient: 'Alice Smith', amount: '$100.00' },- ['date', 'recipient', 'amount'],- { entityFuzzy: true },- );- // "Alice" and "Alice Smith" share first 5 chars but fuzzy is first 15- // They won't fuzzy-match since "Alice" is only 5 chars- expect(result.type).toBe('new');- });- });-- describe('parseTrackerPage', () => {- test('parses markdown table into entries', () => {- const md = `| Date | Amount | Status |-|------|--------|--------|-| 2026-04-01 | $100 | Done |-| 2026-04-02 | $200 | Pending |`;- const entries = parseTrackerPage(md, ['Date', 'Amount', 'Status']);- expect(entries.length).toBe(2);- expect(entries[0]['Date']).toBe('2026-04-01');- expect(entries[1]['Amount']).toBe('$200');- });-- test('handles empty table', () => {- const entries = parseTrackerPage('No table here', ['a', 'b']);- expect(entries.length).toBe(0);- });- });-- describe('appendToTracker', () => {- test('appends rows to markdown', () => {- const md = '### 2026\n\n| Date | Amount |\n|------|--------|\n| 2026-01-01 | $50 |\n';- const result = appendToTracker(md, [{ Date: '2026-04-01', Amount: '$100' }], ['Date', 'Amount']);- expect(result).toContain('2026-04-01');- expect(result).toContain('$100');- });- });-- describe('computeTotals', () => {- test('sums numeric columns', () => {- const entries = [- { amount: '$100.00', count: '5' },- { amount: '$200.50', count: '3' },- ];- const totals = computeTotals(entries, ['amount', 'count']);- expect(totals.amount).toBeCloseTo(300.50, 2);- expect(totals.count).toBe(8);- });-- test('handles non-numeric values', () => {- const entries = [{ amount: 'N/A' }];- const totals = computeTotals(entries, ['amount']);- expect(totals.amount).toBe(0);- });- });-- describe('buildDateWindows', () => {- test('quarterly windows for one year', () => {- const windows = buildDateWindows(2026, 2026, 'quarterly');- expect(windows.length).toBe(4);- expect(windows[0].label).toBe('Q1 2026');- expect(windows[3].label).toBe('Q4 2026');- });-- test('monthly windows for one year', () => {- const windows = buildDateWindows(2026, 2026, 'monthly');- expect(windows.length).toBe(12);- expect(windows[0].label).toBe('2026-01');- expect(windows[11].label).toBe('2026-12');- });-- test('multi-year quarterly windows', () => {- const windows = buildDateWindows(2024, 2026, 'quarterly');- expect(windows.length).toBe(12); // 3 years * 4 quarters- });-- test('endYear < startYear throws', () => {- expect(() => buildDateWindows(2026, 2024)).toThrow('endYear');- });- });-- describe('stripEmailHtml', () => {- test('strips HTML tags', () => {- const result = stripEmailHtml('<p>Hello <b>World</b></p>');- expect(result).toContain('Hello');- expect(result).toContain('World');- expect(result).not.toContain('<p>');- expect(result).not.toContain('<b>');- });-- test('removes style blocks', () => {- const result = stripEmailHtml('<style>.foo { color: red; }</style><p>Content</p>');- expect(result).toContain('Content');- expect(result).not.toContain('color');- });-- test('removes script blocks', () => {- const result = stripEmailHtml('<script>alert("xss")</script><p>Safe</p>');- expect(result).toContain('Safe');- expect(result).not.toContain('alert');- });-- test('decodes HTML entities', () => {- const result = stripEmailHtml('& < > ');- expect(result).toContain('&');- expect(result).toContain('<');- expect(result).toContain('>');- });-- test.each([- '<style>.hidden { color: red; }</style><script>hidden()</script><!-- hidden --><p>Hello</p><p>World<br>Again</p>',- '<style>.hidden { color: red; }</style><script>hidden()</script><!-- hidden --><p>Hello</p><p>World<br>Again</p>',- '<style>.hidden { color: red; }</style><script>hidden()</script><!-- hidden --><p>Hello</p><p>World<br>Again</p>',- '&lt;style&gt;.hidden { color: red; }&lt;/style&gt;&lt;script&gt;hidden()&lt;/script&gt;&lt;!-- hidden --&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;World&lt;br&gt;Again&lt;/p&gt;',- ])('strips raw or decoded email markup without joining paragraphs: %s', (html) => {- expect(stripEmailHtml(html)).toBe('Hello\nWorld\nAgain');- });-- test('removes mixed-case blocks with attributes and comment contents', () => {- expect(stripEmailHtml('<STYLE type="text/css">hidden css</STYLE><SCRIPT defer>hidden script</SCRIPT><!-- <p>hidden comment</p> --><DIV>Visible</DIV>')).toBe('Visible');- });-- test.each([- ['1 < 2 and 3 > 1; R&D says "yes".', '1 < 2 and 3 > 1; R&D says "yes".'],- ['1 < 2 and 3 > 1; R&D says "yes".', '1 < 2 and 3 > 1; R&D says "yes".'],- ['中文 café 😀 & 😀 'fine'', "中文 café 😀 & 😀 'fine'"],- ['© 😀 &#-1; � � � �', '© 😀 &#-1; � � � �'],- ['퟿  ', '\uD7FF \uE000 \u{10FFFF}'],- ['&amp;lt;p&amp;gt;Deep&amp;lt;/p&amp;gt;', '<p>Deep</p>'],- ['Hello &amp; goodbye', 'Hello & goodbye'],- ['', ''],- ['<p>Visible</p><broken', 'Visible\n<broken'],- ])('preserves text and bounded entity decoding: %s', (html, expected) => {- expect(stripEmailHtml(html)).toBe(expected);- });-- test('leaves overflowing decimal entities literal', () => {- const entity = `&#${'9'.repeat(400)};`;- expect(stripEmailHtml(entity)).toBe(entity);- });-- test.each([- ['<p>Contact <[email protected]> to confirm.</p>', 'Contact <[email protected]> to confirm.'],- ['<p>Contact <[email protected]> to confirm.</p>', 'Contact <[email protected]> to confirm.'],- ['Constraint: x<y and z>0.', 'Constraint: x<y and z>0.'],- ['Constraint: x<y and z>0.', 'Constraint: x<y and z>0.'],- ['<span class="note">R&D</span> <a href="https://example.com">Link</a>', 'R&D Link'],- ['<font color="red">Legacy</font> <custom-placeholder>literal</custom-placeholder>', 'Legacy <custom-placeholder>literal</custom-placeholder>'],- ])('distinguishes recognized HTML from visible angle-bracket text: %s', (html, expected) => {- expect(stripEmailHtml(html)).toBe(expected);- });-- test.each([- '<span title="x<y">Visible</span>',- '<a href="https://example.com" title="1 < 2">Visible</a>',- '<span title="x>y">Visible</span>',- '<span title="x>y and x<z">Visible</span>',- '<span title="say "hi"">Visible</span>',- '<span title="x&lt;y">Visible</span>',- '<span title="say &quot;hi&quot;">Visible</span>',- "<span title='x<y and x>z'>Visible</span>",- ])('discards attributes without decoding their contents into markup: %s', (html) => {- expect(stripEmailHtml(html)).toBe('Visible');- });-- test('caps encoded input before decoding or removing hidden blocks', () => {- const prefix = '<style>hidden</style><p>';- const html = prefix + 'x'.repeat(500 * 1024 - prefix.length) + 'outside-the-cap';- expect(stripEmailHtml(html)).toBe('x'.repeat(500 * 1024 - prefix.length) + '\n...[truncated]');- });-- test('truncates >500KB input (ReDoS prevention)', () => {- // Use a string just over 500KB to trigger truncation- const huge = '<p>' + 'x'.repeat(510 * 1024) + '</p>';- const result = stripEmailHtml(huge);- // After truncation, length should be around 500KB + "[truncated]"- expect(result).toContain('[truncated]');- });-- test('completes quickly on large nested HTML', () => {- // Generate HTML that could cause ReDoS without the size cap- const nested = '<div>'.repeat(100) + 'content' + '</div>'.repeat(100);- const start = performance.now();- stripEmailHtml(nested);- const elapsed = performance.now() - start;- expect(elapsed).toBeLessThan(100); // should be well under 100ms- });- });-});diff --git a/test/distribution-import-boundary.test.ts b/test/distribution-import-boundary.test.tsdeleted file mode 100644index f6f8d2efc3..0000000000--- a/test/distribution-import-boundary.test.ts+++ /dev/null@@ -1,93 +0,0 @@-// T26: `src/core/distribution/` import boundary regression guard.-//-// E2 + Codex F6: the distribution module is shared infrastructure-// (tarball, trust-prompt, registry, remote-source). It MUST NOT-// import from:-// - src/commands/ (command-layer code; would create a layering inversion)-// - src/core/schema-pack/ (downstream consumer)-// - src/core/postgres-engine.ts / pglite-engine.ts (engines should-// not be referenced from distribution)-// - src/core/config.ts (config resolution shouldn't reach into-// distribution; the reverse is fine on a case-by-case basis but-// stays controlled)-//-// This test reads the distribution module's source files via fs and-// asserts that the import statements match an allowlist. If a future-// commit accidentally adds a forbidden import, this test fails loud-// before the bad module shape lands in `bun run verify`.-//-// Per Codex F25 we use a simple source-text grep rather than-// dependency-cruiser to avoid the extra tooling dep. The check is-// narrow (imports only) and lives next to the actual module shape.--import { describe, expect, test } from 'bun:test';-import { readFileSync, readdirSync } from 'node:fs';-import { join } from 'node:path';--const DIST_DIR = join(import.meta.dir, '../src/core/distribution');--// Allowlist of paths the distribution module MAY import FROM.-// Currently empty + only re-exports from skillpack/; if a real-// implementation lands in distribution/ later, this allowlist-// expands carefully.-const ALLOWED_IMPORT_PREFIXES: readonly string[] = [- '../skillpack/', // permitted re-export source (Option B)- 'node:', // node built-ins-];--// Hard-forbidden imports — any of these on a `from` line is a fail.-const FORBIDDEN_PATTERNS: readonly RegExp[] = [- /from\s+['"][^'"]*\/commands\//,- /from\s+['"]\.\.\/schema-pack\//,- /from\s+['"][^'"]*postgres-engine/,- /from\s+['"][^'"]*pglite-engine/,- /from\s+['"]\.\.\/config\.ts['"]/,- /from\s+['"]\.\.\/config\/['"]/,-];--describe('distribution module import boundary (E2 + Codex F6)', () => {- test('every src/core/distribution/*.ts file passes the import allowlist', () => {- const files = readdirSync(DIST_DIR).filter(f => f.endsWith('.ts'));- expect(files.length).toBeGreaterThan(0);- for (const file of files) {- const path = join(DIST_DIR, file);- const content = readFileSync(path, 'utf-8');- // Match `from '<path>'` and `from "<path>"`- const importMatches = content.matchAll(/from\s+['"]([^'"]+)['"]/g);- for (const match of importMatches) {- const importPath = match[1];- const allowed = ALLOWED_IMPORT_PREFIXES.some(prefix => importPath.startsWith(prefix));- if (!allowed) {- throw new Error(- `forbidden import in ${file}: "${importPath}"\n` +- `distribution/ may only import from: ${ALLOWED_IMPORT_PREFIXES.join(', ')}\n` +- `if this is intentional, update ALLOWED_IMPORT_PREFIXES in this test`,- );- }- for (const pat of FORBIDDEN_PATTERNS) {- if (pat.test(match[0])) {- throw new Error(- `forbidden import pattern in ${file}: "${importPath}" matches ${pat}`,- );- }- }- }- }- });-- test('distribution/index.ts re-exports cover the v0.37 helper surface', async () => {- // Ensure the v0.37 helpers we promised are accessible via the- // distribution barrel. Schema-pack consumers depend on these names.- const dist = await import('../src/core/distribution/index.ts');- expect(typeof dist.extractTarball).toBe('function');- expect(typeof dist.packTarball).toBe('function');- expect(typeof dist.askTrust).toBe('function');- expect(typeof dist.loadRegistry).toBe('function');- expect(typeof dist.resolveSource).toBe('function');- expect(typeof dist.classifySpec).toBe('function');- expect(typeof dist.effectiveTier).toBe('function');- expect(typeof dist.validateRegistryCatalog).toBe('function');- expect(typeof dist.runScaffoldThirdParty).toBe('function');- expect(dist.REGISTRY_SCHEMA_VERSION).toBe('gbrain-registry-v1');- });-});diff --git a/test/doc-claims.test.ts b/test/doc-claims.test.tsnew file mode 100644index 0000000000..8389692b28--- /dev/null+++ b/test/doc-claims.test.ts@@ -0,0 +1,66 @@+/**+ * Retracted doc claims stay retracted.+ *+ * Each row is an honesty or privacy promise that shipped docs once made, the+ * product does not keep, and a fix removed. The check is negative only: no+ * shipped Markdown file (README, agent instructions, docs, skills, templates,+ * recipes and the generated plugin trees) may state it again. CHANGELOG.md is+ * history and docs/test-audit/ quotes the claims as evidence, so both are+ * excluded. Text is whitespace-flattened so a re-wrapped paragraph still+ * matches.+ *+ * Positive wording pins were dropped on purpose (docs/TESTING.md "Retiring a+ * test"): they fail on a meaning-preserving reword and pass when the behavior+ * they describe breaks. Behavior owners are named per row.+ */++import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { readFileSync } from 'node:fs';+import { join, resolve } from 'node:path';++const ROOT = resolve(import.meta.dir, '..');+const SHIPPED = /^(?:README\.md|AGENTS\.md|CLAUDE\.md|INSTALL_FOR_AGENTS\.md|(?:docs|skills|templates|recipes|plugin|plugin-variants)\/.+\.md)$/;+const EXCLUDED = /^docs\/test-audit\//;++interface Claim {+ claim: string | RegExp;+ why: string;+}++const RETRACTED: Claim[] = [+ { claim: '~/.openclaw/config.json', why: '#4842: OpenClaw reads ~/.openclaw/openclaw.json `mcp.servers`; registration goes through `openclaw mcp add`' },+ { claim: "Don't store user preferences in GBrain", why: 'durable preferences belong in shared memory (docs/guides/brain-vs-memory.md)' },+ { claim: 'it should return nothing', why: 'recall of a stored preference is expected to return it (brain-vs-memory guidance)' },+ { claim: /Every (?:future )?`put_page` (?:auto-creates|extracts)/, why: '#4679: remote put_page skips inline graph extraction (owner: test/put-page-remote-autolink-hint.test.ts)' },+ { claim: 'auto-linking on every write', why: '#4679: remote writes return `skipped: "remote"` and rely on a sweep' },+ { claim: 'MCP response includes `auto_links: { created', why: '#4679: MCP put_page responses carry no inline auto_links result' },+ { claim: 'Verify via the `auto_links` field in the put_page response (`{ created', why: '#4679: same retracted inline auto_links promise' },+ { claim: 'No manual `add_link` calls needed for ordinary page writes', why: '#4679: HTTP writers need a host sweep or explicit add_link' },+ { claim: 'nobody else ships together', why: 'exclusivity claim retracted from the primary docs' },+ { claim: 'keychain and survives', why: '#4741: the empty-dir hermetic config does not keep the macOS keychain login across logout' },+];++const files = execFileSync('git', ['ls-files', '-z', '*.md'], { cwd: ROOT, encoding: 'utf8' })+ .split('\0')+ .filter(path => SHIPPED.test(path) && !EXCLUDED.test(path));++describe('retracted doc claims', () => {+ test('the scan covers the shipped doc surfaces', () => {+ for (const path of ['README.md', 'docs/guides/brain-vs-memory.md', 'docs/mcp/OPENCLAW.md', 'docs/UPGRADING_DOWNSTREAM_AGENTS.md', 'skills/brain-ops/SKILL.md', 'skills/enrich/SKILL.md']) {+ expect(files).toContain(path);+ }+ });++ test('no shipped Markdown file restates a retracted claim', () => {+ const hits: string[] = [];+ for (const path of files) {+ const flat = readFileSync(join(ROOT, path), 'utf8').replace(/\s+/g, ' ');+ for (const { claim, why } of RETRACTED) {+ const found = typeof claim === 'string' ? flat.includes(claim) : claim.test(flat);+ if (found) hits.push(`${path}: restates "${claim}" — retracted: ${why}`);+ }+ }+ expect(hits, 'fix the doc (the claim is false), rerun: bun test test/doc-claims.test.ts').toEqual([]);+ });+});diff --git a/test/docs-bootstrap-persistence-table.test.ts b/test/docs-bootstrap-persistence-table.test.tsdeleted file mode 100644index 081dc30d5d..0000000000--- a/test/docs-bootstrap-persistence-table.test.ts+++ /dev/null@@ -1,26 +0,0 @@-import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'node:fs';-import { join } from 'node:path';--// #4986: three code paths in src/commands/hook.ts spawn the workspace push —-// stopPushIfDue (Stop), hookSessionEnd (SessionEnd) and dirtyTreePush (the-// SessionStart crash-recovery push). Only the Stop path reads GBRAIN_STOP_PUSH-// and hooks.stop_push_debounce_min. The operator-facing table must say so and-// list the recovery push, or an operator tuning the debounce expects it to slow-// commits that the other two paths keep landing.-const rows = readFileSync(join(import.meta.dir, '..', 'docs/guides/bootstrap.md'), 'utf8').split('\n');--describe('#4986 bootstrap.md scopes the Stop-push knobs and lists every push path', () => {- test('per-turn row says the switch + debounce govern the Stop path only', () => {- const row = rows.find((l) => l.startsWith('| Per-turn persistence'));- expect(row).toBeDefined();- expect(row).toMatch(/Stop path only/);- });-- test('session-end row names no switch/debounce; crash-recovery push has its own row', () => {- const sessionEnd = rows.find((l) => l.startsWith('| Session persistence'));- expect(sessionEnd).toBeDefined();- expect(sessionEnd).toMatch(/no per-path switch or debounce/);- expect(rows.some((l) => l.startsWith('| Crash recovery'))).toBe(true);- });-});diff --git a/test/docs-cli-commands.test.ts b/test/docs-cli-commands.test.tsindex 7f6028c80a..0768395f3c 100644--- a/test/docs-cli-commands.test.ts+++ b/test/docs-cli-commands.test.ts@@ -1,5 +1,5 @@/**- * #3502: docs must not reference nonexistent gbrain commands.+ * #3502: docs must not reference nonexistent gbrain commands or flags.** `docs/tutorials/personal-brain.md` shipped a `gbrain install` step for two* months after the command it replaced was retired — every reader hit@@ -8,50 +8,71 @@* and checks each verb against the live CLI surface: CLI_ONLY, operation* cliHints names (non-hidden), and aliases.*+ * Docs-CLI truth check: in docs/guides/, docs/migrations/ and skills/ each+ * invocation's flags must also pass the production argument pipeline+ * (parseGlobalFlags + validateCommandFlags, see test/helpers/+ * cli-command-surface.ts), so a documented flag the CLI rejects fails here.+ *+ * Escape hatches, in order of preference:+ * 1. Fix the doc to the current command.+ * 2. `<!-- gbrain-cli: historical -->` on the line above a code fence (or+ * on/above a line with inline code) for examples that document an older+ * release's CLI.+ * 3. ALLOWLIST below — shrink-only, every entry carries a reason, and an+ * entry that no longer matches a violation fails the stale-entry test.+ ** Deliberately excluded (historical or speculative by design, per CLAUDE.md's* "historical docs are never rewritten" rule):* - docs/GBRAIN_V0.md — the v0 spec; documents v0's CLI* - docs/designs/, docs/plans/ — future/speculative design docs- * - docs/migrations/, skills/migrations/ — per-release migration notes,- * written against that release's CLI* - docs/UPGRADING_DOWNSTREAM_AGENTS.md — per-release upgrade chronicle- *- * Heuristics keep prose out: only fenced code + inline spans are scanned,- * comment lines and diagram lines are skipped, and the verb must sit in- * command position (start of command text, or after a shell operator).+ * - docs/test-audit/ — dated audit evidence that quotes the+ * tests and docs it examined, including the dead commands they pinned*/import { describe, expect, test } from 'bun:test';import { readdirSync, readFileSync, statSync } from 'fs';import { dirname, join, relative } from 'path';-import { CLI_ONLY, cliAliases } from '../src/cli.ts';-import { operations } from '../src/core/operations.ts';+import { CLI_ONLY } from '../src/cli.ts';+import {+ codeRegions, flagRejection, gbrainInvocations, HISTORICAL_MARKER, liveCliVerbs,+} from './helpers/cli-command-surface.ts';const ROOT = dirname(import.meta.dir);+const RERUN = 'bun test test/docs-cli-commands.test.ts';const EXCLUDED = ['docs/GBRAIN_V0.md','docs/UPGRADING_DOWNSTREAM_AGENTS.md','docs/designs/','docs/plans/',- 'docs/migrations/',- 'skills/migrations/',+ 'docs/test-audit/',];-/** Known-intentional references to commands that deliberately don't exist. */-const ALLOWLIST: Record<string, string[]> = {- // The doc explains that gbrain does NOT ship this command, on purpose.- 'docs/guides/rls-and-you.md': ['rls-exempt'],+/** Trees whose invocations are checked for flags as well as verbs. */+const FLAG_CHECKED = ['docs/guides/', 'docs/migrations/', 'skills/'];++/**+ * Shrink-only: file → the offending verbs/flags it may carry, with why.+ * Never add an entry for a doc that is simply out of date — fix the doc.+ */+const ALLOWLIST: Record<string, { tokens: string[]; reason: string }> = {+ 'docs/guides/rls-and-you.md': {+ tokens: ['rls-exempt'],+ reason: 'explains that gbrain deliberately does NOT ship this command',+ },+ 'docs/guides/concurrent-writes.md': {+ tokens: ['--dry-run'],+ reason: 'CLI bug: `auth rescope-client` / `auth local-writer` parse --dry-run '+ + '(src/core/grants/cli.ts, src/commands/persistence-admin.ts) but '+ + "CLI_FLAG_REGISTRY['auth'] omits it, so the validator rejects it. Remove once the registry accepts it.",+ },+ 'docs/guides/shared-brain-skills.md': {+ tokens: ['--dry-run'],+ reason: 'same auth --dry-run registry bug as docs/guides/concurrent-writes.md',+ },};-function validCommands(): Set<string> {- const valid = new Set<string>(CLI_ONLY);- for (const op of operations) {- const name = op.cliHints?.name;- if (name && !op.cliHints?.hidden) valid.add(name);- }- for (const alias of cliAliases.keys()) valid.add(alias);- return valid;-}+interface Violation { file: string; line: number; token: string; message: string }function* mdFiles(dir: string): Generator<string> {for (const entry of readdirSync(dir)) {@@ -61,68 +82,76 @@ function* mdFiles(dir: string): Generator<string> {}}-interface CodeLine { code: string; line: number }--/** Fenced-block lines + inline code spans that START with `gbrain `. */-function codeRegions(text: string): CodeLine[] {- const out: CodeLine[] = [];- const lines = text.split('\n');- let inFence = false;- for (let i = 0; i < lines.length; i++) {- const l = lines[i];- if (/^\s*(```|~~~)/.test(l)) { inFence = !inFence; continue; }- if (inFence) {- const t = l.trim();- if (/^(#|\/\/|--|\*)/.test(t)) continue; // comment lines- if (/[│┌┐└┘├┤─═╔╗╚╝]/.test(l)) continue; // ASCII-art diagrams- out.push({ code: l, line: i + 1 });- continue;+function scanText(rel: string, text: string, valid: Set<string>): Violation[] {+ const checkFlags = FLAG_CHECKED.some((t) => rel.startsWith(t));+ const out: Violation[] = [];+ for (const { code, line, historical } of codeRegions(text)) {+ if (historical) continue;+ for (const inv of gbrainInvocations(code)) {+ const snippet = code.trim().slice(0, 100);+ if (!valid.has(inv.verb)) {+ out.push({ file: rel, line, token: inv.verb, message: `\`gbrain ${inv.verb}\` — unknown verb (not a registered command) — ${snippet}` });+ continue;+ }+ const why = checkFlags ? flagRejection(inv) : null;+ const flag = why?.match(/(--[\w-]+)/)?.[1];+ if (why) out.push({ file: rel, line, token: flag ?? inv.verb, message: `\`gbrain ${inv.verb}\` — ${why} — ${snippet}` });}- for (const m of l.matchAll(/`(gbrain [^`]+)`/g)) out.push({ code: m[1], line: i + 1 });}return out;}-/** True when `gbrain` sits at command position (not mid-prose). */-function commandPosition(prefix: string): boolean {- const p = prefix.trimEnd();- return p === '' || /[|;&`(={[]$/.test(p) || /\$$/.test(p);-}--function scan(): string[] {- const valid = validCommands();- const violations: string[] = [];- const files = [- join(ROOT, 'README.md'),- ...mdFiles(join(ROOT, 'docs')),- ...mdFiles(join(ROOT, 'skills')),- ];+function scan(): Violation[] {+ const valid = liveCliVerbs();+ const files = [join(ROOT, 'README.md'), ...mdFiles(join(ROOT, 'docs')), ...mdFiles(join(ROOT, 'skills'))];+ const out: Violation[] = [];for (const file of files) {const rel = relative(ROOT, file);if (EXCLUDED.some((e) => rel === e || rel.startsWith(e))) continue;- const text = readFileSync(file, 'utf-8');- for (const { code, line } of codeRegions(text)) {- for (const m of code.matchAll(/\bgbrain\s+([A-Za-z][\w-]*)/g)) {- const verb = m[1];- if (!/^[a-z][a-z0-9_-]{2,}$/.test(verb)) continue; // flags, <slots>, v0.x- if (!commandPosition(code.slice(0, m.index))) continue;- if (valid.has(verb)) continue;- if (ALLOWLIST[rel]?.includes(verb)) continue;- violations.push(`${rel}:${line}: \`gbrain ${verb}\` is not a real command — ${code.trim().slice(0, 90)}`);- }- }+ out.push(...scanText(rel, readFileSync(file, 'utf-8'), valid));}- return violations;+ return out;}-describe('#3502 — docs reference only real gbrain commands', () => {- test('every `gbrain <verb>` in README/docs/skills resolves to a live command', () => {- const violations = scan();- expect(violations).toEqual([]);+const allowed = (v: Violation) => ALLOWLIST[v.file]?.tokens.includes(v.token) ?? false;++describe('#3502 — docs reference only real gbrain commands and flags', () => {+ const violations = scan();++ test('every `gbrain <verb> [--flag]` in README/docs/skills resolves against the live CLI', () => {+ const open = violations.filter((v) => !allowed(v)).map((v) => `${v.file}:${v.line}: ${v.message}`);+ expect(+ open,+ `Docs name gbrain commands/flags the CLI rejects:\n${open.join('\n')}\n\n`+ + 'Fix the doc to the current command (check `gbrain <verb> --help`), or delete the claim if the '+ + `feature is gone. If the example documents an older release, put ${HISTORICAL_MARKER} on the line `+ + `above its code fence (or on the inline-code line).\nRerun: ${RERUN}`,+ ).toEqual([]);+ });++ test('ALLOWLIST has no stale entries', () => {+ const stale = Object.entries(ALLOWLIST).flatMap(([file, { tokens }]) =>+ tokens.filter((t) => !violations.some((v) => v.file === file && v.token === t)).map((t) => `${file}: ${t}`));+ expect(+ stale,+ `These ALLOWLIST entries no longer match a violation — remove them from test/docs-cli-commands.test.ts:\n`+ + `${stale.join('\n')}\nRerun: ${RERUN}`,+ ).toEqual([]);+ });++ test('scanner self-check: unknown verb and unknown flag are caught; the historical marker suppresses', () => {+ const valid = liveCliVerbs();+ const doc = [+ '```bash', 'gbrain notacommand --x', 'gbrain search "q" --no-such-flag', 'gbrain search "q" --limit 5', '```',+ HISTORICAL_MARKER, '```bash', 'gbrain notacommand', '```',+ `Run \`gbrain sync --no-such-flag\`. ${HISTORICAL_MARKER}`,+ ].join('\n');+ const found = scanText('docs/guides/x.md', doc, valid).map((v) => `${v.line}:${v.token}`);+ expect(found).toEqual(['2:notacommand', '3:--no-such-flag']);});test('the sanity anchors: install is dead, init/put/skillpack are live', () => {- const valid = validCommands();+ const valid = liveCliVerbs();expect(valid.has('install')).toBe(false); // retired v0.36.0.0 — the #3502 bugexpect(valid.has('init')).toBe(true);expect(valid.has('put')).toBe(true);diff --git a/test/docs-mcp-deploy.test.ts b/test/docs-mcp-deploy.test.tsindex 520b3ab08c..ea39ec7ea1 100644--- a/test/docs-mcp-deploy.test.ts+++ b/test/docs-mcp-deploy.test.ts@@ -1,11 +1,8 @@/**- * #4500: docs/mcp/DEPLOY.md + ALTERNATIVES.md must document the tailnet/LAN-only- * `serve --http` shape and the MCP SDK's "Issuer URL must be HTTPS" exit.- *- * The HTTPS-issuer check lives in @modelcontextprotocol/sdk (checkIssuerUrl), so- * gbrain cannot soften it; the only fix is telling operators which shapes work- * (Tailscale Serve, plain-HTTP bearer-only without --public-url) and naming the- * SDK's own opt-in. Doc-text pins, same precedent as docs-cli-commands.test.ts.+ * #5007: docs/mcp/DEPLOY.md names the owner login-link request and the existing+ * mint endpoint, anchored to the real route registration. The `gbrain auth --help`+ * half of this contract is asserted on spawned output in+ * test/cli-help-discoverability.test.ts.*/import { describe, expect, test } from 'bun:test';import { readFileSync } from 'fs';@@ -13,45 +10,9 @@ import { dirname, join } from 'path';const ROOT = dirname(import.meta.dir);const deploy = readFileSync(join(ROOT, 'docs/mcp/DEPLOY.md'), 'utf8');-const alternatives = readFileSync(join(ROOT, 'docs/mcp/ALTERNATIVES.md'), 'utf8');--describe('DEPLOY.md documents the tailnet/LAN-only serve --http shape (#4500)', () => {- test('troubleshooting names the SDK issuer error and its opt-in', () => {- const troubleshooting = deploy.slice(deploy.indexOf('## Troubleshooting'));- expect(troubleshooting).toContain('Issuer URL must be HTTPS');- expect(troubleshooting).toContain('MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL');- });-- test('HTTP section states --source-guard is stdio-only and points at the CORS allowlist', () => {- expect(deploy).toContain('--source-guard');- expect(deploy).toContain('GBRAIN_HTTP_CORS_ORIGIN');- });-- test('ALTERNATIVES.md distinguishes tailnet-only Serve from public Funnel', () => {- expect(alternatives).toContain('tailscale serve');- expect(alternatives).toContain('tailscale funnel');- });-});--describe('DEPLOY.md documents dual-mode /mcp auth (#4893)', () => {- // The anonymous 401 + resource_metadata challenge is spec discovery, not- // proof the configured bearer failed; client status probes that omit the- // header report needsAuth while authenticated tool calls succeed.- test('troubleshooting covers "needsAuth while tool calls succeed"', () => {- const troubleshooting = deploy.slice(deploy.indexOf('## Troubleshooting'));- expect(troubleshooting).toContain('needsAuth');- expect(troubleshooting).toContain('whoami');- });-});describe('DEPLOY.md documents the owner magic-link flow (#5007)', () => {- // The admin login page tells owners to ask their agent for a login link; the- // mint endpoint already exists, so the only fix is documenting it where the- // agent looks (DEPLOY.md + `gbrain auth --help`). Source reads below pin the- // help text and anchor the documented route to the real registration.- // test-reads-source-ok: AUTH_USAGE is a help-text template literal; pinning its spelling IS the contract- const auth = readFileSync(join(ROOT, 'src/commands/auth.ts'), 'utf8');- // test-reads-source-ok: anchors the documented route to the existing app.post registration+ // test-reads-source-ok[structural]: anchors the documented route to the existing app.post registrationconst server = readFileSync(join(ROOT, 'src/commands/serve-http.ts'), 'utf8');test('documents the owner request and the existing mint endpoint', () => {@@ -59,30 +20,4 @@ describe('DEPLOY.md documents the owner magic-link flow (#5007)', () => {expect(deploy).toContain('POST /admin/api/issue-magic-link');expect(server).toContain("app.post('/admin/api/issue-magic-link'");});-- test('auth help points at the owner login flow without inventing a CLI command', () => {- expect(auth).toContain('Admin dashboard login (running HTTP server):');- expect(auth).toContain('POST /admin/api/issue-magic-link');- expect(auth).toContain('See docs/mcp/DEPLOY.md.');- });-- test('warns against consuming the single-use nonce during verification', () => {- expect(deploy).toContain('Do not GET or fetch the generated login URL');- expect(auth).toContain('do not GET the generated link');- });-- test('preserves private delivery and protected-bootstrap requirements', () => {- expect(deploy).toContain('GBRAIN_ADMIN_BOOTSTRAP_TOKEN');- expect(deploy).toContain('only to the requesting owner in');- expect(deploy).toContain('Never expose its value in chat, logs, shell arguments,');- expect(deploy).toContain('An MCP client bearer token or client secret is not the');- });-- test('distinguishes login from client creation and states lifecycle limits', () => {- expect(deploy).toContain('does not create, reveal, or rotate');- expect(deploy).toContain('expires after five minutes');- expect(deploy).toContain('cannot be replayed');- expect(deploy).toContain('invalidated by a server restart');- expect(deploy).toContain("server's configured `--public-url`");- });});diff --git a/test/docs-navigation.test.ts b/test/docs-navigation.test.tsindex 4803f0c679..8ba8dbf544 100644--- a/test/docs-navigation.test.ts+++ b/test/docs-navigation.test.ts@@ -77,27 +77,4 @@ describe('primary documentation navigation', () => {});expect(failures).toEqual([]);});-- test('active memory guidance keeps durable preferences separate from configuration', () => {- const guide = readFileSync(join(root, 'docs/guides/brain-vs-memory.md'), 'utf8');- expect(guide).toContain('Durable facts, preferences');- expect(guide).toContain('Tool configuration, credentials');- expect(guide).not.toContain("Don't store user preferences in GBrain");- expect(guide).not.toContain('it should return nothing');- });-- test('primary docs do not reinstate blanket graph or exclusivity promises', () => {- for (const document of documents.filter(path => !path.startsWith(subsystemDir))) {- const text = readFileSync(join(root, document), 'utf8');- expect(text).not.toMatch(/Every (?:future )?`put_page` (?:auto-creates|extracts)/);- expect(text).not.toContain('auto-linking on every write');- expect(text).not.toContain('nobody else ships together');- }- const boundaries = readFileSync(join(root, 'docs/guides/memory-boundaries.md'), 'utf8');- expect(boundaries).toContain('no inline graph extraction');- expect(boundaries).toContain('Does not self-sweep');- expect(boundaries).toContain('embeddings receive the text');- expect(boundaries).toContain('rerankers receive the query');- expect(boundaries).toContain('not a full database backup');- });});diff --git a/test/docs-timeline-extraction-guide.test.ts b/test/docs-timeline-extraction-guide.test.tsdeleted file mode 100644index 3b17bfbcbb..0000000000--- a/test/docs-timeline-extraction-guide.test.ts+++ /dev/null@@ -1,27 +0,0 @@-import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'node:fs';-import { join } from 'node:path';--// #4987: timeline extraction scans the WHOLE page (parseTimelineEntries +-// parseInlineCitationTimelineEntries — behavior pinned in test/extract.test.ts);-// the `<!-- timeline -->` sentinel only splits compiled_truth from timeline for-// storage. The docs must not tell operators the sentinel scopes extraction,-// because a `[Source: ..., YYYY-MM-DD]` citation under a compiled-truth bullet-// mints a permanent timeline row and no removal op exists.-const repoRoot = join(import.meta.dir, '..');--describe('#4987 timeline extraction docs describe the real trigger', () => {- test('system-of-record.md Timeline row names dated markers anywhere in the page', () => {- const doc = readFileSync(join(repoRoot, 'docs/architecture/system-of-record.md'), 'utf8');- const row = doc.split('\n').find((l) => l.startsWith('| **Timeline**'));- expect(row).toBeDefined();- expect(row).not.toMatch(/section after/);- expect(row).toContain('[Source:');- });-- test('compiled-truth.md warns that compiled-truth citations mint timeline rows', () => {- const doc = readFileSync(join(repoRoot, 'docs/guides/compiled-truth.md'), 'utf8');- expect(doc).toContain('auto_timeline');- expect(doc).toMatch(/blank line above and\s+below/);- });-});diff --git a/test/doctor.test.ts b/test/doctor.test.tsindex 6f556b59c3..906d2b0c70 100644--- a/test/doctor.test.ts+++ b/test/doctor.test.ts@@ -29,16 +29,6 @@ describe('doctor command', () => {expect(source).not.toContain('manual ALTER recipe');});- test('doctor module exports runDoctor', async () => {- const { runDoctor } = await import('../src/commands/doctor.ts');- expect(typeof runDoctor).toBe('function');- });-- test('LATEST_VERSION is importable from migrate', async () => {- const { LATEST_VERSION } = await import('../src/core/migrate.ts');- expect(typeof LATEST_VERSION).toBe('number');- });-test('CLI registers doctor command', async () => {const result = Bun.spawnSync({cmd: ['bun', 'run', 'src/cli.ts', '--help'],@@ -616,16 +606,8 @@ describe('doctor command', () => {expect(src).not.toContain('gbrain timeline-extract');});- // v0.32 — takes_weight_grid pure-helper export.- // Codex review #7 demanded the check be extracted as a pure function so- // tests target it directly with stubbed engines instead of running the- // full runDoctor pipeline. This block validates the export shape and the- // 4 branches (no-takes / fail / warn / ok) behaviorally against PGLite.- test('takesWeightGridCheck is exported as a pure function', async () => {- const mod = await import('../src/commands/doctor.ts');- expect(typeof mod.takesWeightGridCheck).toBe('function');- });-+ // takes_weight_grid pure helper: the 4 branches (no-takes / fail / warn / ok)+ // run behaviorally against PGLite.test('takes_weight_grid: 0 takes → ok with "No takes yet"', async () => {const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');const { takesWeightGridCheck } = await import('../src/commands/doctor.ts');diff --git a/test/dream-cli-flags.test.ts b/test/dream-cli-flags.test.tsdeleted file mode 100644index a718b22c5e..0000000000--- a/test/dream-cli-flags.test.ts+++ /dev/null@@ -1,198 +0,0 @@-/**- * Structural tests for `gbrain dream` argv parsing (v0.21).- *- * Verifies the help text + parser source contains the new flags- * (--input, --date, --from, --to) and that conflict detection is wired.- * The actual parseArgs is internal; we exercise it via the source file- * structure to avoid spinning up a process per test.- */--import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'fs';--const dreamSrc = readFileSync(new URL('../src/commands/dream.ts', import.meta.url), 'utf-8');--describe('dream CLI flag wiring', () => {- test('declares --input flag with file argument', () => {- expect(dreamSrc).toContain("'--input'");- expect(dreamSrc).toContain('inputFile');- });-- test('declares --date / --from / --to flags', () => {- expect(dreamSrc).toContain("'--date'");- expect(dreamSrc).toContain("'--from'");- expect(dreamSrc).toContain("'--to'");- });-- test('validates ISO date format', () => {- expect(dreamSrc).toMatch(/ISO_DATE_RE/);- expect(dreamSrc).toContain('YYYY-MM-DD');- });-- test('--input + --date conflict detection', () => {- expect(dreamSrc).toContain('--input cannot be combined with --date');- });-- test('--input implies --phase synthesize', () => {- // #4493: phase became the phases[] array (repeated --phase flags all run).- expect(dreamSrc).toContain("phases = ['synthesize']");- });-- test('--from > --to range validation', () => {- expect(dreamSrc).toContain('empty range');- });-- test('forwards synth fields to runCycle', () => {- expect(dreamSrc).toContain('synthInputFile');- expect(dreamSrc).toContain('synthDate');- expect(dreamSrc).toContain('synthFrom');- expect(dreamSrc).toContain('synthTo');- });-- test('totals line includes synth + patterns counters', () => {- expect(dreamSrc).toContain('synth_transcripts');- expect(dreamSrc).toContain('synth_pages');- expect(dreamSrc).toContain('patterns=');- });-- test('help text documents dry-run synthesis semantics (Codex finding #8)', () => {- expect(dreamSrc).toContain('skips the synthesis subagents');- expect(dreamSrc.toLowerCase()).toContain('zero llm calls');- });-- test('help text documents local-day cycle timezone configuration (#4348)', () => {- expect(dreamSrc).toContain('gbrain config set cycle.timezone Asia/Kolkata');- expect(dreamSrc).toContain('host timezone');- });-- // v0.41.13: --source / --source-id flag wiring (supersedes PR #1559).- // Structural-only tests; behavioral tests live in test/dream.test.ts.- describe('--source / --source-id wiring (v0.41.13)', () => {- test('declares --source flag in argv parsing', () => {- expect(dreamSrc).toContain("'--source'");- });-- test('declares --source-id alias in argv parsing', () => {- expect(dreamSrc).toContain("'--source-id'");- });-- test('forwards resolved sourceId to runCycle', () => {- // The runCycle call must pass sourceId; gate name "sourceId"- // not "source" because CycleOpts.sourceId is the contract.- expect(dreamSrc).toMatch(/sourceId:\s*resolvedSourceId/);- });-- test('imports resolveSourceId from canonical source-resolver helper', () => {- expect(dreamSrc).toContain("from '../core/source-resolver.ts'");- expect(dreamSrc).toContain('resolveSourceId');- });-- test('uses the shared isResolverUserError predicate for the typed-error catch (T3 from eng review)', () => {- // One predicate, exported from source-resolver.ts next to the messages- // it matches — never a local copy that can drift from the wording.- expect(dreamSrc).not.toContain('function isResolverUserError');- expect(dreamSrc).toMatch(/import \{[^}]*\bisResolverUserError\b[^}]*\} from '\.\.\/core\/source-resolver\.ts'/);- expect(dreamSrc).toContain('if (isResolverUserError(e))');- });-- test('documents --source in --help output', () => {- expect(dreamSrc).toContain('--source <id>');- expect(dreamSrc).toContain('--source-id <id>');- });-- test('preserves --help short-circuit ordering comment (IRON RULE)', () => {- // The comment lives in runDream BEFORE the engine-null gate.- // Future refactors that reorder these blocks will trip this guard.- expect(dreamSrc).toContain('IRON RULE: --help short-circuits BEFORE');- });-- test('declares engine-null guard for --source', () => {- expect(dreamSrc).toContain('requires a connected brain');- });-- test('declares archived-source guard', () => {- expect(dreamSrc).toMatch(/source.*is archived/);- expect(dreamSrc).toContain('gbrain sources restore');- });- });-- // issue #1678 — --drain bounded backlog drain wiring (structural).- describe('--drain wiring', () => {- test('declares --drain and --window flags', () => {- expect(dreamSrc).toContain("'--drain'");- expect(dreamSrc).toContain("'--window'");- expect(dreamSrc).toContain('windowSeconds');- });-- test('--drain defaults to extract_atoms and rejects other phases', () => {- // #4493: phase became the phases[] array (repeated --phase flags all run).- expect(dreamSrc).toContain("phases = ['extract_atoms']");- expect(dreamSrc).toContain('--drain currently supports only --phase extract_atoms');- });-- test('drain routes through the shared helper with the resolved source (5A)', () => {- // v0.42.10.0 (#1685 GAP D / 5A): the lock+batch+count wiring moved into- // runExtractAtomsDrainForSource so the CLI, the Minion handler, and- // autopilot share ONE drain path. dream threads resolvedSourceId so the- // helper picks cycleLockIdFor(resolvedSourceId) — the same lock the routine- // cycle holds for that source. The lock-id contract is now pinned in- // test/extract-atoms-drain.test.ts ("shared wiring helper holds the cycle lock").- expect(dreamSrc).toContain('runExtractAtomsDrainForSource');- expect(dreamSrc).toContain('sourceId: resolvedSourceId');- });-- test('drain reports remaining + exits non-zero when incomplete', () => {- expect(dreamSrc).toContain('EXIT_DRAIN_INCOMPLETE');- expect(dreamSrc).toContain('cycle_already_running');- });- });-- // issue #2860 — --once one-shot phase-enabled-gate bypass (structural).- // Behavioral coverage: test/e2e/dream-patterns-pglite.test.ts (bypass +- // config-untouched) and test/core/cycle.serial.test.ts (non-leak across- // phases via CycleOpts.onceForPhase).- describe('--once wiring (issue #2860)', () => {- test('declares --once flag', () => {- expect(dreamSrc).toContain("'--once'");- });-- test('rejects bare --once with no --phase (exit 2)', () => {- expect(dreamSrc).toContain('--once requires an explicit --phase <name>');- // --help must short-circuit this validation (Codex review finding) —- // see the "--help --once" test in test/dream.test.ts for the- // behavioral pin of this exact ordering.- expect(dreamSrc).toContain('if (once && !phaseWasExplicit && !wantsHelp)');- });-- // Codex P3 finding: the derived phase value gets populated by- // --input/--drain BEFORE this validation used to run, so those two- // silently slipped past an emptiness-based check. The fix validates- // against `phaseWasExplicit` (captured from the raw flag occurrences,- // before any implicit defaulting) instead. Behavioral pins live in- // test/dream.test.ts. (#4493: the capture source moved from- // `phaseIdx !== -1` to `phaseValues.length > 0` when --phase became- // repeatable — same before-defaulting ordering contract.)- test('validates against phaseWasExplicit, captured before --input/--drain defaulting', () => {- expect(dreamSrc).toContain('const phaseWasExplicit = phaseValues.length > 0;');- // Must be declared before the --input-implies-synthesize and- // --drain-implies-extract_atoms defaulting blocks so it captures- // presence prior to any implicit phase assignment.- const explicitIdx = dreamSrc.indexOf('const phaseWasExplicit = phaseValues.length > 0;');- const inputImpliesIdx = dreamSrc.indexOf("phases = ['synthesize']");- const drainImpliesIdx = dreamSrc.indexOf("phases = ['extract_atoms']");- expect(explicitIdx).toBeGreaterThan(-1);- expect(explicitIdx).toBeLessThan(inputImpliesIdx);- expect(explicitIdx).toBeLessThan(drainImpliesIdx);- });-- test('threads onceForPhase to runCycle, gated on opts.once', () => {- // #4493: opts.phases[0] — parseArgs guarantees exactly one when --once.- expect(dreamSrc).toMatch(/onceForPhase:\s*opts\.once\s*\?\s*opts\.phases\[0\]!\s*:\s*undefined/);- });-- test('documents --once in --help output', () => {- expect(dreamSrc).toContain('--once');- expect(dreamSrc).toContain('Never reads or writes config');- });- });-});diff --git a/test/dream-drain-failure-summary.serial.test.ts b/test/dream-drain-failure-summary.serial.test.tsindex 163dc66ce0..b904efe85f 100644--- a/test/dream-drain-failure-summary.serial.test.ts+++ b/test/dream-drain-failure-summary.serial.test.ts@@ -7,23 +7,25 @@** The drain loop itself (capping, sanitizing, reconciling failure_count) is* pinned in test/extract-atoms-drain*.test.ts. This file pins dream.ts's- * rendering of the drain RESULT, so the shared drain helper is replaced by a+ * rendering of the drain RESULT and its argv/exit-code wiring (#1678), so the shared drain helper is replaced by a* stub that returns a hand-built result. Serial: a top-level mock.module.*/import { afterAll, beforeAll, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';import type { ExtractAtomsDrainResult } from '../src/core/cycle/extract-atoms-drain.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { LockUnavailableError } from '../src/core/db-lock.ts';-let nextResult: ExtractAtomsDrainResult;-let drainCalls: Array<{ sourceId: string | undefined }> = [];+let nextResult: ExtractAtomsDrainResult | Error;+let drainCalls: Array<{ sourceId: string | undefined; windowSeconds: number }> = [];mock.module('../src/core/cycle/extract-atoms-drain.ts', () => ({MAX_DRAIN_FAILURE_RECORDS: 25,MAX_DRAIN_FAILURE_SOURCE_CHARS: 256,MAX_DRAIN_FAILURE_REASON_CHARS: 200,- runExtractAtomsDrainForSource: async (_engine: unknown, opts: { sourceId: string | undefined }) => {- drainCalls.push({ sourceId: opts.sourceId });+ runExtractAtomsDrainForSource: async (_engine: unknown, opts: { sourceId: string | undefined; windowSeconds: number }) => {+ drainCalls.push({ sourceId: opts.sourceId, windowSeconds: opts.windowSeconds });+ if (nextResult instanceof Error) throw nextResult;return nextResult;},}));@@ -158,3 +160,38 @@ describe('dream --drain failure summary (#4730)', () => {expect(r.stdout.join('\n')).not.toContain('beyond the record cap');});});++describe('dream --drain wiring and exit codes (#1678)', () => {+ test('exits 3 while backlog remains or the final count is unknown', async () => {+ for (const remaining of [4, null]) {+ nextResult = baseResult({ remaining });+ expect((await runDrainCaptured([])).exitCode, String(remaining)).toBe(3);+ }+ });++ test('a held cycle lock reports cycle_already_running and exits 3', async () => {+ nextResult = new LockUnavailableError('gbrain-cycle');+ const r = await runDrainCaptured(['--json']);+ expect(JSON.parse(r.stdout.join('\n'))).toEqual({ phase: 'extract_atoms', status: 'skipped', reason: 'cycle_already_running' });+ expect(r.exitCode).toBe(3);+ });++ test('--window sets the drain budget (default 300 s) and --source reaches the shared helper', async () => {+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('drain-fixture','drain-fixture') ON CONFLICT DO NOTHING");+ nextResult = baseResult({});+ await runDrainCaptured([]);+ await runDrainCaptured(['--window', '42', '--source', 'drain-fixture']);+ expect(drainCalls.map(c => c.windowSeconds)).toEqual([300, 42]);+ expect(drainCalls[1].sourceId).toBe('drain-fixture');+ });++ test('rejects a bad --window and a non-drainable --phase with exit 2 before draining', async () => {+ const window = await runDrainCaptured(['--window', '0']);+ expect(window.exitCode).toBe(2);+ expect(window.stderr).toContain('--window must be a positive integer (seconds); got "0"');+ const phase = await runDrainCaptured(['--phase', 'lint']);+ expect(phase.exitCode).toBe(2);+ expect(phase.stderr).toContain('--drain currently supports only --phase extract_atoms (got "lint")');+ expect(drainCalls).toEqual([]);+ });+});diff --git a/test/e2e/dream-synthesize-chunking.test.ts b/test/dream-synthesize-chunking.serial.test.tssimilarity index 98%rename from test/e2e/dream-synthesize-chunking.test.tsrename to test/dream-synthesize-chunking.serial.test.tsindex 96946606d6..f9bcc67037 100644--- a/test/e2e/dream-synthesize-chunking.test.ts+++ b/test/dream-synthesize-chunking.serial.test.ts@@ -15,17 +15,21 @@* - Chunked path: fat transcript spawns N children with chunk-suffixed* path-independent idempotency keys; single-chunk omits the suffix.*- * Run: bun test test/e2e/dream-synthesize-chunking.test.ts+ * Run: bun test test/dream-synthesize-chunking.serial.test.ts+ *+ * Lane: serial. Run: `bash scripts/run-serial-tests.sh test/dream-synthesize-chunking.serial.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, expect } from 'bun:test';-import { keylessDreamTest as test } from '../helpers/keyless-dream-test.ts';+import { keylessDreamTest as test } from './helpers/keyless-dream-test.ts';import { mkdtempSync, rmSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { runPhaseSynthesize, TRIAGE_VERSION } from '../../src/core/cycle/synthesize.ts';-import { TIER_DEFAULTS } from '../../src/core/model-config.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runPhaseSynthesize, TRIAGE_VERSION } from '../src/core/cycle/synthesize.ts';+import { TIER_DEFAULTS } from '../src/core/model-config.ts';interface TestRig {engine: PGLiteEngine;diff --git a/test/dream.test.ts b/test/dream.test.tsindex 87ec0a4a42..78ce15a164 100644--- a/test/dream.test.ts+++ b/test/dream.test.ts@@ -824,6 +824,108 @@ describe('runDream — --drain --dry-run --json payload (#4730)', () => {}, 300_000);});+// ─── synthesize targeting flags (--input / --date / --from / --to) ──++async function dreamExit(args: string[]): Promise<{ code: number | undefined; stderr: string }> {+ let code: number | undefined;+ const exitSpy = spyOn(process, 'exit').mockImplementation(((c?: number) => { code = c; throw new Error('EXIT'); }) as never);+ const errSpy = spyOn(console, 'error').mockImplementation(() => {});+ try {+ await runDream(engine, ['--dir', repo, ...args]);+ } catch (e: any) {+ if (e.message !== 'EXIT') throw e;+ } finally {+ exitSpy.mockRestore();+ }+ const stderr = errSpy.mock.calls.flat().join(' ');+ errSpy.mockRestore();+ return { code, stderr };+}++async function dreamJson(args: string[]) {+ const lines: string[] = [];+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });+ const exitSpy = spyOn(process, 'exit').mockImplementation(((c?: number) => { throw new Error(`EXIT ${c}`); }) as never);+ try {+ await runDream(engine, ['--dir', repo, ...args, '--dry-run', '--json']);+ } catch (e: any) {+ if (!String(e.message).startsWith('EXIT')) throw e;+ } finally {+ logSpy.mockRestore();+ exitSpy.mockRestore();+ }+ return JSON.parse(lines.join('\n')) as { phases: Array<{ phase: string; status: string; summary: string; details?: Record<string, unknown> }> };+}++describe('runDream — synthesize targeting flags', () => {+ test('malformed dates, an inverted range and --input with a date filter exit 2 with the reason', async () => {+ const cases: Array<[string[], string]> = [+ [['--date', '2026-4-1'], '--date must be YYYY-MM-DD; got "2026-4-1"'],+ [['--from', '04/01/2026'], '--from must be YYYY-MM-DD'],+ [['--to', 'tomorrow'], '--to must be YYYY-MM-DD'],+ [['--from', '2026-04-25', '--to', '2026-04-01'], '--from (2026-04-25) is after --to (2026-04-01); empty range'],+ [['--input', '/tmp/gbrain-dream-fixture.txt', '--from', '2026-04-01'], '--input cannot be combined with --date / --from / --to'],+ ];+ for (const [args, message] of cases) {+ const r = await dreamExit(args);+ expect(r.code, args.join(' ')).toBe(2);+ expect(r.stderr, args.join(' ')).toContain(message);+ }+ });++ test('--input implies --phase synthesize and reaches the phase even with no corpus dir configured', async () => {+ const missing = join(repo, '..', 'gbrain-dream-missing-transcript.txt');+ const report = await dreamJson(['--input', missing]);+ expect(report.phases.map(p => p.phase)).toEqual(['synthesize']);+ expect(JSON.stringify(report.phases[0])).toContain(`could not read transcript at ${missing}`);+ const unscoped = await dreamJson(['--phase', 'synthesize']);+ expect(unscoped.phases[0].details).toMatchObject({ reason: 'not_configured' });+ });++ test('--date, --from and --to reach the synthesize phase as explicit targets (they bypass the cooldown)', async () => {+ const corpus = mkdtempSync(join(tmpdir(), 'gbrain-dream-corpus-'));+ try {+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);+ await engine.setConfig('dream.synthesize.last_completion_ts', new Date().toISOString());+ const cooled = await dreamJson(['--phase', 'synthesize']);+ expect(cooled.phases[0].details).toMatchObject({ reason: 'cooldown_active' });+ for (const target of [['--date', '2026-04-01'], ['--from', '2026-04-01'], ['--to', '2026-04-25']]) {+ const report = await dreamJson(['--phase', 'synthesize', ...target]);+ expect(report.phases[0], target.join(' ')).toMatchObject({ status: 'ok', summary: 'no transcripts to process' });+ }+ } finally {+ rmSync(corpus, { recursive: true, force: true });+ }+ });+});++describe('runDream — help and human totals', () => {+ test('--help documents dry-run synthesis cost and the cycle timezone setting', async () => {+ const logSpy = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await runDream(engine, ['--help']);+ const help = logSpy.mock.calls.flat().join('\n');+ expect(help).toContain('skips the synthesis subagents');+ expect(help.toLowerCase()).toContain('zero llm calls');+ expect(help).toContain('gbrain config set cycle.timezone');+ } finally {+ logSpy.mockRestore();+ }+ });++ test('a cycle with work prints the totals line including the synth and patterns counters', async () => {+ await engine.putPage('notes/lonely-example', { type: 'note', title: 'Lonely', compiled_truth: 'No links here.', timeline: '' });+ const logSpy = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await runDream(engine, ['--dir', repo, '--phase', 'orphans']);+ const totals = logSpy.mock.calls.flat().map(String).find(l => l.includes('totals:'));+ expect(totals).toMatch(/orphans=[1-9]\d* synth_transcripts=0 synth_pages=0 patterns=0$/);+ } finally {+ logSpy.mockRestore();+ }+ });+});+// ─── v0.41.13 D5: end-to-end dream → checkCycleFreshness parity ───────//// Closes the column-rename drift class: if a future PR renamesdiff --git a/test/e2e/attendance-repair-postgres.test.ts b/test/e2e/attendance-repair-postgres.test.tsindex 2ff1369aed..72e77a0e69 100644--- a/test/e2e/attendance-repair-postgres.test.ts+++ b/test/e2e/attendance-repair-postgres.test.ts@@ -1 +1,3 @@-import '../attendance-repair.test.ts';+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../attendance-repair.test.ts'));diff --git a/test/e2e/attendance-retrieval-postgres.test.ts b/test/e2e/attendance-retrieval-postgres.test.tsindex 2f7655d07d..7151afd0f7 100644--- a/test/e2e/attendance-retrieval-postgres.test.ts+++ b/test/e2e/attendance-retrieval-postgres.test.ts@@ -1 +1,3 @@-import '../attendance-retrieval.test.ts';+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../attendance-retrieval.test.ts'));diff --git a/test/e2e/cjk-roundtrip.test.ts b/test/e2e/cjk-roundtrip.test.tsindex 96b920b0c5..cc9accb09d 100644--- a/test/e2e/cjk-roundtrip.test.ts+++ b/test/e2e/cjk-roundtrip.test.ts@@ -7,7 +7,7 @@* 3. Search via the PGLite CJK keyword fallback (ILIKE + bigram count).* 4. Assert the page is findable by a CJK substring.*- * Vector path requires OPENAI_API_KEY; skipped gracefully when absent.+ * The vector path is not exercised here (keyword-only, keyless).*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';@@ -106,14 +106,4 @@ The system uses 测试 framework for validation.`, { noEmbed: true });const hits = await engine.searchKeyword('测试');expect(hits.some(h => h.slug === 'originals/mixed-roundtrip')).toBe(true);});-- test('vector path skip-gracefully without OPENAI_API_KEY', () => {- if (!process.env.OPENAI_API_KEY) {- // Documented behavior — surface to the CI log so reviewers know the- // vector path didn't run. Test still passes.- // eslint-disable-next-line no-console- console.log('[skip] vector path — set OPENAI_API_KEY to exercise');- }- expect(true).toBe(true);- });});diff --git a/test/e2e/extract-timeline-attendance-postgres.test.ts b/test/e2e/extract-timeline-attendance-postgres.test.tsindex af5c0a3efd..344c886502 100644--- a/test/e2e/extract-timeline-attendance-postgres.test.ts+++ b/test/e2e/extract-timeline-attendance-postgres.test.ts@@ -1 +1,3 @@-import '../extract-timeline-attendance.test.ts';+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../extract-timeline-attendance.test.ts'));diff --git a/test/e2e/helpers.ts b/test/e2e/helpers.tsindex 427b552c45..b0142f0dd9 100644--- a/test/e2e/helpers.ts+++ b/test/e2e/helpers.ts@@ -1,8 +1,8 @@/**- * E2E test helpers: DB lifecycle, fixture import, timing, and diagnostics.+ * E2E test helpers: DB lifecycle, fixture import, and diagnostics.** Usage in test files:- * import { setupDB, teardownDB, importFixtures, time } from './helpers.ts';+ * import { setupDB, teardownDB, importFixtures } from './helpers.ts';* beforeAll(async () => { await setupDB(); await importFixtures(); });* afterAll(async () => { await teardownDB(); });*/@@ -269,16 +269,6 @@ function findMarkdownFiles(dir: string): string[] {return results.sort();}-/**- * Time a function and return [result, durationMs].- */-export async function time<T>(fn: () => Promise<T>): Promise<[T, number]> {- const start = performance.now();- const result = await fn();- const dur = performance.now() - start;- return [result, dur];-}-/*** Dump DB state for debugging on test failure.*/diff --git a/test/e2e/jobs-watch-readsnapshot.test.ts b/test/e2e/jobs-watch-readsnapshot.test.tsindex 1cef03c3d8..d9aa45096b 100644--- a/test/e2e/jobs-watch-readsnapshot.test.ts+++ b/test/e2e/jobs-watch-readsnapshot.test.ts@@ -12,7 +12,6 @@ import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { MinionQueue } from '../../src/core/minions/queue.ts';import { readSnapshot } from '../../src/commands/jobs-watch.ts';import { logLeasePressure } from '../../src/core/minions/lease-pressure-audit.ts';-import { setOwnerBudget } from '../../src/core/minions/budget-tracker.ts';let engine: PGLiteEngine;let queue: MinionQueue;@@ -65,7 +64,12 @@ describe('v0.41 jobs-watch readSnapshot E2E', () => {);// One budget-bearing owner with cents.const budgetOwner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, budgetOwner.id, 5.0);+ await engine.executeRaw(+ `UPDATE minion_jobs+ SET budget_remaining_cents = 500, budget_owner_job_id = $1, budget_root_owner_id = $1+ WHERE id = $1`,+ [budgetOwner.id],+ );const s = await readSnapshot(engine);// Queue health: 4 waiting from queue.add, +1 budget owner = 5 waiting.diff --git a/test/e2e/mcp.test.ts b/test/e2e/mcp.test.tsdeleted file mode 100644index c2faecd76a..0000000000--- a/test/e2e/mcp.test.ts+++ /dev/null@@ -1,70 +0,0 @@-/**- * E2E MCP Protocol Test — Tier 1- *- * Verifies the MCP server can start and that the tools/list- * from operations.ts generates correct tool definitions.- *- * Note: The full stdio MCP protocol test (spawn server, send JSON-RPC)- * is complex because the MCP SDK uses its own transport layer. This test- * verifies the tool generation logic directly, which is what matters for- * agent compatibility.- */--import { describe, test, expect } from 'bun:test';-import { operations } from '../../src/core/operations.ts';--describe('E2E: MCP Tool Generation', () => {- test('operations generate valid MCP tool definitions', () => {- // This replicates server.ts's tool-def mapping over the FULL op list.- // (The live tools/list additionally subtracts gate-off publish-gated ops- // per request — stdioVisibleTools, pinned by test/mcp-stdio-gate-list.)- const tools = operations.map(op => ({- name: op.name,- description: op.description,- inputSchema: {- type: 'object' as const,- properties: Object.fromEntries(- Object.entries(op.params).map(([k, v]) => [k, {- type: v.type === 'array' ? 'array' : v.type,- ...(v.description ? { description: v.description } : {}),- ...(v.enum ? { enum: v.enum } : {}),- ...(v.items ? { items: { type: v.items.type } } : {}),- }]),- ),- required: Object.entries(op.params)- .filter(([, v]) => v.required)- .map(([k]) => k),- },- }));-- expect(tools.length).toBe(operations.length);- expect(tools.length).toBeGreaterThanOrEqual(30);-- for (const tool of tools) {- expect(tool.name).toBeTruthy();- expect(tool.description).toBeTruthy();- expect(tool.inputSchema.type).toBe('object');- expect(typeof tool.inputSchema.properties).toBe('object');- expect(Array.isArray(tool.inputSchema.required)).toBe(true);- }-- // Verify specific tools exist- const names = tools.map(t => t.name);- expect(names).toContain('get_page');- expect(names).toContain('put_page');- expect(names).toContain('search');- expect(names).toContain('query');- expect(names).toContain('add_link');- expect(names).toContain('get_health');- expect(names).toContain('sync_brain');- expect(names).toContain('file_upload');- expect(names).toContain('find_orphans');- });-- test('MCP server module can be imported', async () => {- // Verify the server module loads without errors- const mod = await import('../../src/mcp/server.ts');- expect(typeof mod.startMcpServer).toBe('function');- expect(typeof mod.handleToolCall).toBe('function');- });-});diff --git a/test/e2e/mechanical.test.ts b/test/e2e/mechanical.test.tsindex 4e85265b2d..96091985d3 100644--- a/test/e2e/mechanical.test.ts+++ b/test/e2e/mechanical.test.ts@@ -14,7 +14,7 @@ import { execSync } from 'child_process';import { tmpdir } from 'os';import {hasDatabase, setupDB, setupLegacyEmbeddingDB, teardownDB, getEngine, getConn,- importFixtures, importFixture, time, dumpDBState, FIXTURES_PATH,+ importFixtures, importFixture, dumpDBState, FIXTURES_PATH,} from './helpers.ts';import { operationsByName, operations } from '../../src/core/operations.ts';import type { OperationContext } from '../../src/core/operations.ts';@@ -1562,39 +1562,3 @@ describeE2E('E2E: Parallel Import', () => {expect(stats.chunk_count).toBe(seqChunkCount);}, 60_000);});--// ─────────────────────────────────────────────────────────────────-// Performance Baselines-// ─────────────────────────────────────────────────────────────────--describeE2E('E2E: Performance Baselines', () => {- beforeAll(async () => {- await setupDB();- }, 30_000);- afterAll(teardownDB);-- test('import + search + link performance', async () => {- const [_, importMs] = await time(importFixtures);-- const searchTimes: number[] = [];- for (const q of ['NovaMind', 'hybrid search', 'Stanford', 'investor', 'compiled truth']) {- const [__, ms] = await time(() => callOp('search', { query: q }));- searchTimes.push(ms);- }-- const [___, linkMs] = await time(async () => {- await callOp('add_link', { from: 'people/sarah-chen', to: 'companies/novamind' });- await callOp('get_backlinks', { slug: 'companies/novamind' });- });-- searchTimes.sort((a, b) => a - b);- const p50 = searchTimes[Math.floor(searchTimes.length * 0.5)];- const p99 = searchTimes[searchTimes.length - 1];-- console.log('\n Performance Baselines:');- console.log(` Import 13 fixtures: ${importMs.toFixed(0)}ms`);- console.log(` Search p50: ${p50.toFixed(0)}ms`);- console.log(` Search p99: ${p99.toFixed(0)}ms`);- console.log(` Link + backlink: ${linkMs.toFixed(0)}ms`);- }, 30_000);-});diff --git a/test/e2e/minions-budget-cathedral.test.ts b/test/e2e/minions-budget-cathedral.test.tsdeleted file mode 100644index f41c4075fc..0000000000--- a/test/e2e/minions-budget-cathedral.test.ts+++ /dev/null@@ -1,126 +0,0 @@-/**- * v0.41 E2E — budget cathedral (D4 projection + D5 enforcement + Eng D7 reservation).- *- * Two end-to-end scenarios:- *- * 1. Mid-batch budget exhaustion halts the subtree cleanly (Eng D7- * recursive halt). 10 children of one budget-bearing parent;- * reservations drain the cap; remaining children get halted via- * `haltBudgetSubtree`.- *- * 2. Parallel-children reservation prevents overspend (the failure mode- * CAS-only would NOT bound). 8 concurrent reserves at the limit- * cannot exceed the budget.- */--import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { MinionQueue } from '../../src/core/minions/queue.ts';-import {- setOwnerBudget,- inheritBudgetOwner,- reserveBudget,- haltBudgetSubtree,- getBudgetOwner,-} from '../../src/core/minions/budget-tracker.ts';--let engine: PGLiteEngine;-let queue: MinionQueue;--beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({});- await engine.initSchema();- queue = new MinionQueue(engine);-}, 60_000);--afterAll(async () => {- await engine.disconnect();-});--beforeEach(async () => {- await engine.executeRaw('DELETE FROM minion_budget_log');- await engine.executeRaw('DELETE FROM minion_jobs');-}, 30_000);--describe('v0.41 budget cathedral E2E', () => {- test('mid-batch budget exhaustion halts subtree; surviving children = dead', async () => {- const owner = await queue.add('subagent', { prompt: 'parent' }, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, owner.id, 0.50); // 50¢ — small budget-- // Spawn 10 children inheriting the owner.- const children: number[] = [];- for (let i = 0; i < 10; i++) {- const c = await queue.add(- 'subagent',- { prompt: `child ${i}` },- { parent_job_id: owner.id },- { allowProtectedSubmit: true },- );- await inheritBudgetOwner(engine, c.id, owner.id);- children.push(c.id);- }-- // Reserve 10¢ per child, in serial. After 5 children consume- // 5 × 10¢ = 50¢, the budget is exhausted.- const outcomes: string[] = [];- for (const id of children) {- const r = await reserveBudget(engine, id, 10);- outcomes.push(r.kind);- }- // First 5 succeed; remaining 5 see CAS miss.- expect(outcomes.filter(o => o === 'reserved').length).toBe(5);- expect(outcomes.filter(o => o === 'exhausted').length).toBe(5);-- // Now haltBudgetSubtree → all remaining waiting children flip to dead.- const halted = await haltBudgetSubtree(engine, owner.id, 'budget_exhausted');- expect(halted).toBe(10); // every CHILD (not the owner) gets halted- // Owner stays in its own status.- const ownerAfter = await queue.getJob(owner.id);- expect(ownerAfter!.status).not.toBe('dead');-- // Owner balance is 0.- const ownerInfo = await getBudgetOwner(engine, owner.id);- expect(ownerInfo!.budget_remaining_cents).toBe(0);-- // Audit rows: 5 reserved + 5 halted + N owner_deleted (0) + final halt rows.- // We just check that audit rows were written for each reservation event.- const auditCount = await engine.executeRaw<{ count: string }>(- `SELECT count(*)::text AS count FROM minion_budget_log WHERE event_type IN ('reserved', 'halted')`,- );- expect(parseInt(auditCount[0]!.count, 10)).toBeGreaterThanOrEqual(10);- });-- test('parallel reservations cannot exceed budget (CAS bounds N concurrent children)', async () => {- const owner = await queue.add('subagent', { prompt: 'parent' }, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, owner.id, 0.30); // 30¢-- // 8 concurrent children all trying to reserve 10¢ each — total- // would-spend = 80¢ if unbounded. CAS prevents the 30¢ owner- // balance from going negative.- const childIds: number[] = [];- for (let i = 0; i < 8; i++) {- const c = await queue.add(- 'subagent',- { prompt: `c${i}` },- { parent_job_id: owner.id },- { allowProtectedSubmit: true },- );- await inheritBudgetOwner(engine, c.id, owner.id);- childIds.push(c.id);- }-- // Fire all 8 reservations in parallel.- const outcomes = await Promise.all(childIds.map(id => reserveBudget(engine, id, 10)));- const reserved = outcomes.filter(o => o.kind === 'reserved').length;- const exhausted = outcomes.filter(o => o.kind === 'exhausted').length;-- // Exactly 3 should succeed (30¢ / 10¢ = 3); 5 should hit exhausted.- expect(reserved).toBe(3);- expect(exhausted).toBe(5);-- // Owner balance is 0 (not negative — that's the CAS guarantee).- const ownerInfo = await getBudgetOwner(engine, owner.id);- expect(ownerInfo!.budget_remaining_cents).toBe(0);- });-});diff --git a/test/e2e/minions-controller-bounce-only.test.ts b/test/e2e/minions-controller-bounce-only.test.tsdeleted file mode 100644index 5670b2d4c1..0000000000--- a/test/e2e/minions-controller-bounce-only.test.ts+++ /dev/null@@ -1,98 +0,0 @@-/**- * v0.41 E2E IRON-RULE — Eng D6 controller sign correction.- *- * Pins the load-bearing post-codex-pass-2-#9 correction at the- * integration boundary: bounces without 429s = workers starving = cap- * goes UP, NOT down. Pre-correction, the controller would crater the- * cap during a healthy 100-job burst (the field-report scenario).- *- * This test simulates 100 bounce events in the audit table (no real- * worker pressure needed — just write rows) and runs the controller- * tick. Asserts cap moved UP.- *- * REGRESSION GUARD — if a future "simplify the controller rule" PR ever- * inverts this sign, this test screams.- */--import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { controllerTick, writeLeaseCap, readCurrentLeaseCap } from '../../src/core/minions/lease-cap-controller.ts';-import { logLeasePressure } from '../../src/core/minions/lease-pressure-audit.ts';-import { MinionQueue } from '../../src/core/minions/queue.ts';--let engine: PGLiteEngine;-let queue: MinionQueue;--beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({});- await engine.initSchema();- queue = new MinionQueue(engine);-}, 60_000);--afterAll(async () => {- await engine.disconnect();-});--beforeEach(async () => {- await engine.executeRaw('DELETE FROM minion_lease_pressure_log');- await engine.executeRaw('DELETE FROM minion_jobs');- await engine.executeRaw(`DELETE FROM gbrain_cycle_locks WHERE id = 'minions-lease-cap-controller'`);- await engine.executeRaw(`DELETE FROM config WHERE key = 'minions.lease_cap_current'`);-}, 30_000);--describe('v0.41 lease-cap controller E2E (Eng D6 corrected sign)', () => {- test('IRON-RULE: bounces without 429s ramp cap UP (not DOWN)', async () => {- await writeLeaseCap(engine, 8); // start with the legacy default- // Seed an owner job (not strictly required, but matches realistic state).- const owner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- // Simulate 100 bounce events in the audit table. No 429s. No completed- // subagent jobs (so the bounce-rate signal dominates).- for (let i = 0; i < 100; i++) {- await logLeasePressure(engine, {- job_id: owner.id,- lease_key: 'anthropic:messages',- active_at_bounce: 8,- max_concurrent: 8,- });- }-- // Run the controller tick.- const r = await controllerTick(engine);- expect(r).not.toBeNull();- expect(r!.changed).toBe(true);- // CRITICAL: cap MUST have gone UP. The pre-correction draft would- // have done r!.next < 8 here.- expect(r!.next).toBeGreaterThan(8);-- const stored = await readCurrentLeaseCap(engine);- expect(stored).toBeGreaterThan(8);- });-- test('upstream 429s ramp cap DOWN even with bounces present', async () => {- await writeLeaseCap(engine, 64);- const owner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });- // Bounces + REAL upstream rate-limit failures.- for (let i = 0; i < 50; i++) {- await logLeasePressure(engine, {- job_id: owner.id,- lease_key: 'anthropic:messages',- active_at_bounce: 64,- max_concurrent: 64,- });- }- // Insert dead jobs whose error_text matches the 429 classifier path.- for (let i = 0; i < 10; i++) {- await engine.executeRaw(- `INSERT INTO minion_jobs (submission_authority, name, queue, status, attempts_made, attempts_started, max_attempts, error_text, finished_at)- VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent-test', 'default', 'failed', 1, 1, 1, '429 Too Many Requests', now())`,- );- }-- const r = await controllerTick(engine);- expect(r).not.toBeNull();- expect(r!.changed).toBe(true);- // Upstream 429s = cap must go DOWN.- expect(r!.next).toBeLessThan(64);- });-});diff --git a/test/e2e/minions-self-fix-flow.test.ts b/test/e2e/minions-self-fix-flow.test.tsdeleted file mode 100644index 3851f45a5c..0000000000--- a/test/e2e/minions-self-fix-flow.test.ts+++ /dev/null@@ -1,144 +0,0 @@-/**- * v0.41 E2E — self-fix flow (E6 with narrowed classifier per codex pass-2 #4).- *- * End-to-end: parent fails with each recoverable cluster + non-recoverable- * cluster + opt-out flag. Verifies the decision-then-submission chain- * works against a real PGLite + the v93 audit table.- *- * Three scenarios per the eng plan:- * 1. prompt_too_long → self-fix child submitted; chain depth=1- * 2. tool_crash → NOT recoverable; NO child submitted; parent stays dead- * 3. no_self_fix flag on parent → bypass even for recoverable cluster- */--import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { MinionQueue } from '../../src/core/minions/queue.ts';-import {- decideSelfFix,- submitSelfFixChild,-} from '../../src/core/minions/self-fix.ts';--let engine: PGLiteEngine;-let queue: MinionQueue;--beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({});- await engine.initSchema();- queue = new MinionQueue(engine);-}, 60_000);--afterAll(async () => {- await engine.disconnect();-});--beforeEach(async () => {- await engine.executeRaw('DELETE FROM minion_self_fix_log');- await engine.executeRaw('DELETE FROM minion_budget_log');- await engine.executeRaw('DELETE FROM minion_jobs');-}, 30_000);--describe('v0.41 self-fix E2E', () => {- test('prompt_too_long: parent fails → child submitted → chain depth=1 + audit row', async () => {- const parent = await queue.add(- 'subagent',- { prompt: 'massive prompt that exceeded context' },- {},- { allowProtectedSubmit: true },- );- const decision = await decideSelfFix(- engine,- parent.id,- { prompt: 'massive prompt that exceeded context' },- 'prompt is too long: 1.8M tokens > 1M maximum',- );- expect(decision.should_fix).toBe(true);- expect(decision.cluster).toBe('prompt_too_long');-- const result = await submitSelfFixChild(- engine,- queue,- {- id: parent.id,- data: { prompt: 'massive prompt that exceeded context' },- last_error: 'prompt is too long: 1.8M tokens > 1M maximum',- },- 'prompt_too_long',- );- expect(result).not.toBeNull();-- const child = await queue.getJob(result!.child_id);- expect(child).not.toBeNull();- expect(child!.parent_job_id).toBe(parent.id);- const data = child!.data as Record<string, unknown>;- expect(data.is_self_fix_child).toBe(true);- expect(data.self_fix_cluster).toBe('prompt_too_long');- expect(String(data.prompt)).toContain('self-fix retry');- expect(String(data.prompt)).toContain('prompt was too long');-- // Audit row.- const audit = await engine.executeRaw<{ outcome: string }>(- `SELECT outcome FROM minion_self_fix_log WHERE parent_id = $1`,- [parent.id],- );- expect(audit.length).toBe(1);- expect(audit[0]!.outcome).toBe('submitted');- });-- test('tool_crash: NOT recoverable → no child submitted, parent stays dead-letter path', async () => {- const parent = await queue.add(- 'subagent', { prompt: 'do thing with broken tool' },- {}, { allowProtectedSubmit: true },- );- const decision = await decideSelfFix(- engine,- parent.id,- { prompt: 'do thing with broken tool' },- 'tool "git_commit" failed: ENOENT spawn git',- );- expect(decision.should_fix).toBe(false);- expect(decision.cluster).toBe('tool_crash');- expect(decision.reason).toContain('cluster_not_recoverable');-- // No child should exist (decision short-circuits before submission).- const childCount = await engine.executeRaw<{ count: string }>(- `SELECT count(*)::text AS count FROM minion_jobs WHERE parent_job_id = $1`,- [parent.id],- );- expect(parseInt(childCount[0]!.count, 10)).toBe(0);- });-- test('no_self_fix opt-out: even prompt_too_long bypasses', async () => {- const parent = await queue.add(- 'subagent', { prompt: 'long', no_self_fix: true },- {}, { allowProtectedSubmit: true },- );- const decision = await decideSelfFix(- engine,- parent.id,- { prompt: 'long', no_self_fix: true },- 'prompt is too long: 1.8M tokens',- );- expect(decision.should_fix).toBe(false);- expect(decision.reason).toBe('no_self_fix_flag_on_job');- });-- test('chain depth cap (default=2): grandchild self-fix refused', async () => {- // root -> sf-child-1 -> sf-child-2 → next attempt blocked- const root = await queue.add('subagent', { prompt: 'r' }, {}, { allowProtectedSubmit: true });- const c1 = await queue.add(- 'subagent', { prompt: 'c1', is_self_fix_child: true },- { parent_job_id: root.id }, { allowProtectedSubmit: true },- );- const c2 = await queue.add(- 'subagent', { prompt: 'c2', is_self_fix_child: true },- { parent_job_id: c1.id }, { allowProtectedSubmit: true },- );- const decision = await decideSelfFix(- engine, c2.id, { prompt: 'c2', is_self_fix_child: true }, 'prompt is too long',- );- expect(decision.should_fix).toBe(false);- expect(decision.reason).toContain('max_depth_reached');- });-});diff --git a/test/e2e/openrouter-anthropic-subagent-replay.live.test.ts b/test/e2e/openrouter-anthropic-subagent-replay.live.test.tsindex 1e8c61bbe8..cdc2d7840d 100644--- a/test/e2e/openrouter-anthropic-subagent-replay.live.test.ts+++ b/test/e2e/openrouter-anthropic-subagent-replay.live.test.ts@@ -10,9 +10,9 @@* isError blocks). Abort is therefore the job AbortSignal after the first* successful observation — not a throw from execute.*- * Run (keep-keys required — unit preload strips OPENROUTER_API_KEY):- * GBRAIN_TEST_KEEP_PROVIDER_KEYS=1 OPENROUTER_API_KEY=... \- * bun test test/e2e/openrouter-anthropic-subagent-replay.live.test.ts+ * No CI job provides OPENROUTER_API_KEY, so scripts/run-e2e.sh leaves this+ * file out of its default glob. Run it by name (the runner keeps provider keys):+ * OPENROUTER_API_KEY=... bash scripts/run-e2e.sh test/e2e/openrouter-anthropic-subagent-replay.live.test.ts*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';diff --git a/test/e2e/openrouter-deepseek-subagent-replay.live.test.ts b/test/e2e/openrouter-deepseek-subagent-replay.live.test.tsindex 132e8ea8c4..ae654893e0 100644--- a/test/e2e/openrouter-deepseek-subagent-replay.live.test.ts+++ b/test/e2e/openrouter-deepseek-subagent-replay.live.test.ts@@ -10,9 +10,9 @@* isError blocks). Abort is therefore the job AbortSignal after the first* successful observation — not a throw from execute.*- * Run (keep-keys required — unit preload strips OPENROUTER_API_KEY):- * GBRAIN_TEST_KEEP_PROVIDER_KEYS=1 OPENROUTER_API_KEY=... \- * bun test test/e2e/openrouter-deepseek-subagent-replay.live.test.ts+ * No CI job provides OPENROUTER_API_KEY, so scripts/run-e2e.sh leaves this+ * file out of its default glob. Run it by name (the runner keeps provider keys):+ * OPENROUTER_API_KEY=... bash scripts/run-e2e.sh test/e2e/openrouter-deepseek-subagent-replay.live.test.ts*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';diff --git a/test/e2e/schema-cathedral.test.ts b/test/e2e/schema-cathedral.test.tsindex 7645ef16f8..1306eb84ea 100644--- a/test/e2e/schema-cathedral.test.ts+++ b/test/e2e/schema-cathedral.test.ts@@ -15,7 +15,6 @@ import { parseMarkdown } from '../../src/core/markdown.ts';import { runDetect } from '../../src/core/schema-pack/detect.ts';import { runReviewCandidates, runReviewOrphans } from '../../src/core/schema-pack/review.ts';import { knobsHash } from '../../src/core/search/mode.ts';-import { detectArtifactKind, validateManifestByKind } from '../../src/core/artifact/index.ts';// Cold-path opt-out (conservative): umbrella schema-invariant suite whose// point is proving the cathedral end-to-end through a genuinely cold-built@@ -126,19 +125,6 @@ describe('v0.39 T22c — T18-replacement: schema show --as-filing-rules', () =>});});-describe('v0.39 T22d — artifact-type routing', () => {- test('detectArtifactKind dispatches by extension', () => {- expect(detectArtifactKind('/tmp/foo.gbrain-schema')).toBe('schemapack');- expect(detectArtifactKind('/tmp/foo.gbrain-skillpack')).toBe('skillpack');- expect(detectArtifactKind('/tmp/foo.tar.gz')).toBe(null);- });-- test('validateManifestByKind rejects cross-kind manifests', () => {- expect(() => validateManifestByKind('schemapack', { api_version: 'gbrain-skillpack-v1' })).toThrow();- expect(() => validateManifestByKind('skillpack', { api_version: 'gbrain-schema-pack-v1' })).toThrow();- });-});-describe('v0.39 T21 — cache pack isolation in knobsHash', () => {test('hash differs when schema_pack name differs', () => {// Minimal ResolvedSearchKnobs - just the fields knobsHash reads.diff --git a/test/e2e/serve-http-oauth.test.ts b/test/e2e/serve-http-oauth.test.tsindex 04c76bd9f3..1d2c53251a 100644--- a/test/e2e/serve-http-oauth.test.ts+++ b/test/e2e/serve-http-oauth.test.ts@@ -16,7 +16,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { createHash } from 'crypto';import { auth, extractWWWAuthenticateParams, type OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';import type { OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';-import { hasDatabase, setupDB, teardownDB } from './helpers.ts';+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';const skip = !hasDatabase();@@ -578,12 +578,21 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {test('admin source access APIs enumerate sources and rescope an OAuth client', async () => {const cookie = await adminCookie();+ const webhookSecret = `whsec-sentinel-${crypto.randomUUID()}`;+ await getEngine().executeRaw(+ `INSERT INTO sources (id, name, config) VALUES ('admin-hooked', 'admin-hooked', $1::text::jsonb)+ ON CONFLICT (id) DO UPDATE SET config = EXCLUDED.config`,+ [JSON.stringify({ federated: true, github_repo: 'acme-example/brain', webhook_secret: webhookSecret })],+ );const sourcesRes = await fetch(`${BASE}/admin/api/sources`, {headers: { Cookie: cookie },});expect(sourcesRes.ok).toBe(true);- const sources = await sourcesRes.json() as Array<{ id: string; name: string; federated: boolean }>;+ const sourcesBody = await sourcesRes.text();+ const sources = JSON.parse(sourcesBody) as Array<{ id: string; name: string; federated: boolean }>;expect(sources.some(source => source.id === 'default')).toBe(true);+ expect(sources.some(source => source.id === 'admin-hooked')).toBe(true);+ expect(sourcesBody).not.toContain(webhookSecret);const rescopeRes = await fetch(`${BASE}/admin/api/rescope-client`, {method: 'POST',diff --git a/test/e2e/sync-lock-recovery.test.ts b/test/e2e/sync-lock-recovery.test.tsindex 75c4b904a4..e34519cc7e 100644--- a/test/e2e/sync-lock-recovery.test.ts+++ b/test/e2e/sync-lock-recovery.test.ts@@ -8,11 +8,11 @@* Scenarios:* 1. Concurrent sync: second exits with PID + age + --break-lock hint* (per eng-review D10).- * 2. SIGTERM during sync: lock row deleted within 3s- * (per process-cleanup registry contract).- * 3. SIGPIPE via real `head -5` pipe: clean exit, next sync runs- * without "Another sync is in progress" (per outside-voice F14 /- * eng-review D19).+ * 2. SIGTERM during sync (lock observed held first): exit 143, lock row+ * deleted (per process-cleanup registry contract).+ * 3. Output pipe closed mid-sync (lock observed held first): the+ * broken-pipe cleanup route exits early, deletes the lock row, and the+ * next sync runs without "Another sync is in progress".* 4. --break-lock with dead local PID: clears the row.* 5. --break-lock with alive local PID: refuses with --force-break-lock hint.* 6. --force-break-lock with alive PID: clears (with warning).@@ -179,83 +179,117 @@ describeE2E('v0.41.6.0 — sync lock recovery scenarios', () => {expect(snap).toBeNull();});- test('SIGTERM during sync releases the lock within 3s', async () => {- // Start a sync subprocess that will hold the lock briefly.- // We'd ideally watch for the lock row to appear, then SIGTERM. Since- // sync is fast on a 5-file repo, we use a tight polling loop with- // an early-exit if we see the row.+ // Both abnormal-termination cases below observe the boundary before acting:+ // the lock row carries the child's PID AND the child has printed import+ // progress (so the lock's cleanup callback is registered). A run that never+ // reaches that point fails instead of passing vacuously. The bulk repo keeps+ // the sync busy long enough that "exited early" is observable: a child that+ // finished the whole import did not take the abnormal-exit path.+ const BULK_FILES = 1000;++ function makeBulkRepo(dirName: string): string {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-lock-recovery-bulk-'));+ mkdirSync(join(dir, dirName), { recursive: true });+ for (let i = 0; i < BULK_FILES; i++) {+ writeFileSync(join(dir, dirName, `note-${i}.md`), `---\ntype: note\ntitle: Bulk note ${i}\n---\n\nPlaceholder note ${i}.\n`);+ }+ execFileSync('git', ['init', '-q'], { cwd: dir });+ execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: dir });+ execFileSync('git', ['config', 'user.name', 'Test'], { cwd: dir });+ execFileSync('git', ['add', '.'], { cwd: dir });+ execFileSync('git', ['commit', '-q', '-m', 'bulk'], { cwd: dir });+ return dir;+ }++ async function startSyncAtLockBoundary(dir: string, opts: { importStarted: boolean } = { importStarted: true }) {const eng = getEngine();- const sigtermProc = spawn(CLI[0], [...CLI.slice(1), 'sync', '--repo', repoDir, '--full', '--yes', '--no-embed'], {- env: {- ...process.env,- GBRAIN_HOME: tmpHome,- DATABASE_URL: process.env.DATABASE_URL!,- } as Record<string, string>,+ const child = spawn(CLI[0], [...CLI.slice(1), 'sync', '--repo', dir, '--full', '--yes', '--no-embed'], {+ env: { ...process.env, GBRAIN_HOME: tmpHome, DATABASE_URL: process.env.DATABASE_URL! } as Record<string, string>,stdio: ['ignore', 'pipe', 'pipe'],});-- // Wait up to 5s for the lock row to appear, then SIGTERM.- let lockSeen = false;- for (let i = 0; i < 50; i++) {- const snap = await inspectLock(eng, 'gbrain-sync:default');- if (snap && snap.holder_pid === sigtermProc.pid) { lockSeen = true; break; }- await new Promise(r => setTimeout(r, 100));+ let stderr = '';+ child.stderr!.on('data', d => { stderr += d; });+ child.stdout!.on('data', () => {});+ let exit: { code: number | null; signal: NodeJS.Signals | null } | null = null;+ const exited = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(resolve => {+ child.on('exit', (code, signal) => { exit = { code, signal }; resolve(exit); });+ });+ const deadline = Date.now() + 30_000;+ let lockHeld = false;+ const atBoundary = () => lockHeld && (!opts.importStarted || /\[import\.files\] \d+\//.test(stderr));+ while (!exit && Date.now() < deadline && !atBoundary()) {+ if (!lockHeld) {+ const snap = await inspectLock(eng, 'gbrain-sync:default');+ lockHeld = !!snap && snap.holder_pid === child.pid;+ }+ await new Promise(r => setTimeout(r, 20));}- if (!lockSeen) {- // Sync may have completed before we caught the lock. That's also fine.- sigtermProc.kill('SIGTERM');- await new Promise(r => sigtermProc.on('exit', r));- // Skip the rest of the assertion.- return;+ if (exit || !atBoundary()) {+ child.kill('SIGKILL');+ await exited;+ throw new Error(`sync never reached the held-lock boundary (lockHeld=${lockHeld}, exit=${JSON.stringify(exit)}):\n${stderr.slice(-2000)}`);}+ return { child, exited, stderr: () => stderr };+ }++ async function importedCount(dirName: string): Promise<number> {+ const rows = await (getEngine() as any).sql`SELECT count(*)::int AS n FROM pages WHERE slug LIKE ${dirName + '/%'}`;+ return rows[0].n;+ }- sigtermProc.kill('SIGTERM');- await new Promise(r => sigtermProc.on('exit', r));+ test('SIGTERM during sync releases the lock', async () => {+ const dir = makeBulkRepo('sigterm-bulk');+ try {+ const run = await startSyncAtLockBoundary(dir);+ run.child.kill('SIGTERM');+ const exit = await run.exited;- // Within 3s of exit, lock should be gone.- let lockGone = false;- for (let i = 0; i < 30; i++) {- const snap = await inspectLock(eng, 'gbrain-sync:default');- if (!snap || snap.holder_pid !== sigtermProc.pid) { lockGone = true; break; }- await new Promise(r => setTimeout(r, 100));+ expect(exit.code, run.stderr().slice(-2000)).toBe(143);+ expect(await inspectLock(getEngine(), 'gbrain-sync:default')).toBeNull();+ expect(await importedCount('sigterm-bulk')).toBeLessThan(BULK_FILES);+ } finally {+ rmSync(dir, { recursive: true, force: true });}- expect(lockGone).toBe(true);- });+ }, 60_000);- // v0.41.7+ follow-up: this test's timing is brittle on slow CI.- // The SIGPIPE cleanup-registry codepath IS exercised structurally by- // unit test/process-cleanup.test.ts. The SIGTERM-during-sync E2E above- // verifies the lock-release on abnormal termination. Re-enable once- // the head-pipe scenario can be made deterministic across CI runners.- test.skip('pipe through `head -5` exits cleanly, next sync runs without lock-busy', async () => {- // Run `gbrain sync ... | head -5` via shell.- const cmd = `${CLI.join(' ')} sync --repo ${repoDir} --full --yes --no-embed 2>&1 | head -5`;- const result = spawnSync('sh', ['-c', cmd], {- env: {- ...process.env,- GBRAIN_HOME: tmpHome,- DATABASE_URL: process.env.DATABASE_URL!,- } as Record<string, string>,- stdio: ['ignore', 'pipe', 'pipe'],- encoding: 'utf8',- timeout: 30_000,- });- // head closes the pipe → SIGPIPE → cleanup → exit. Exit code from `sh` is- // last command (head) which exited 0 since it read its 5 lines.- expect(result.status).toBe(0);-- // Next sync should NOT report "Another sync is in progress" — give the- // cleanup pass up to 5s to clear the lock.- let nextResult: ReturnType<typeof runCli>;- let nextOk = false;- for (let i = 0; i < 5; i++) {- nextResult = runCli(['sync', '--repo', repoDir, '--full', '--yes', '--no-embed']);- if (!/Another sync is in progress/.test(nextResult.stderr + nextResult.stdout)) {- nextOk = true;- break;- }- await new Promise(r => setTimeout(r, 1000));+ test('closing the output pipe as soon as the lock row appears still releases the lock', async () => {+ // The early close delivers a second broken-pipe signal while the first+ // cleanup pass is still deleting the lock row; that signal must wait for+ // the pass instead of exiting ahead of the DELETE.+ const dir = makeBulkRepo('lock-row-pipe-bulk');+ try {+ const run = await startSyncAtLockBoundary(dir, { importStarted: false });+ run.child.stdout!.destroy();+ run.child.stderr!.destroy();+ const exit = await run.exited;++ expect([0, 141] as Array<number | null>).toContain(exit.code);+ expect(await inspectLock(getEngine(), 'gbrain-sync:default')).toBeNull();+ } finally {+ rmSync(dir, { recursive: true, force: true });}- expect(nextOk).toBe(true);}, 60_000);++ test('closing the output pipe mid-sync routes through cleanup and releases the lock', async () => {+ const dir = makeBulkRepo('sigpipe-bulk');+ try {+ const run = await startSyncAtLockBoundary(dir);+ run.child.stdout!.destroy();+ run.child.stderr!.destroy();+ const exit = await run.exited;++ // Bun raises SIGPIPE (handler exits 141); runtimes that surface EPIPE+ // on the stream instead take triggerCleanupAndExit(0). Either way the+ // child must stop early and leave no lock row behind.+ expect([0, 141] as Array<number | null>).toContain(exit.code);+ expect(await importedCount('sigpipe-bulk')).toBeLessThan(BULK_FILES);+ expect(await inspectLock(getEngine(), 'gbrain-sync:default')).toBeNull();++ const next = runCli(['sync', '--repo', repoDir, '--full', '--yes', '--no-embed']);+ expect(next.stdout + next.stderr).not.toMatch(/Another sync is in progress/);+ expect(next.code).toBe(0);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ }, 90_000);});diff --git a/test/e2e/v030_1-integration-pglite.test.ts b/test/e2e/v030_1-integration-pglite.test.tsdeleted file mode 100644index 8e7d4fa4ff..0000000000--- a/test/e2e/v030_1-integration-pglite.test.ts+++ /dev/null@@ -1,222 +0,0 @@-/**- * v0.30.1 integration smoke test — PGLite path.- *- * Exercises the Lane A-E surfaces together against an in-memory PGLite- * brain to prove the new modules integrate. No DATABASE_URL required.- *- * What this proves:- * Lane A: ConnectionManager constructed; doctor diagnostic shape- * (single-mode for non-Supabase URL).- * Lane B: Migration runner applies pending migrations cleanly via the- * new retry wrapper. v44 (emotional_weight_recomputed_at)- * lands on PGLite.- * Lane C: Backfill registry resolves all 3 entries; running- * emotional_weight backfill on an empty brain returns- * examined=0 (no work).- * Lane D: dropZombieIndexes on PGLite returns dropped=[] (no-op).- * Lane E: upgrade-checkpoint round-trips with a brain_id derived from- * the engine config.- *- * Postgres-only e2es (connection-routing, hnsw-lifecycle, migrate-supabase- * timeout/wedge recovery) live in their own DATABASE_URL-gated files;- * those verify behaviors that PGLite can't exercise (pooler timeout,- * CONCURRENTLY index, multi-tenant lock, etc.).- */--import { describe, expect, test, beforeEach, afterEach } from 'bun:test';-import { mkdtempSync, rmSync, existsSync } from 'node:fs';-import { join } from 'node:path';-import { tmpdir } from 'node:os';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { listBackfills, getBackfill } from '../../src/core/backfill-registry.ts';--import { runBackfill } from '../../src/core/backfill-base.ts';-import { dropZombieIndexes, checkActiveBuild } from '../../src/core/vector-index.ts';-import {- computeBrainId,- writeCheckpoint,- loadCheckpoint,- validateCheckpoint,- markStepComplete,- type UpgradeCheckpoint,-} from '../../src/core/upgrade-checkpoint.ts';-import { LATEST_VERSION } from '../../src/core/migrate.ts';--// Cold-path opt-out: asserts config.version === LATEST_VERSION *because of*-// initSchema's migration chain — under a snapshot the version comes from the-// fixture and the assertion proves nothing.-delete process.env.GBRAIN_PGLITE_SNAPSHOT;--let tmpHome: string;-let originalHome: string | undefined;-let engine: PGLiteEngine;--beforeEach(async () => {- tmpHome = mkdtempSync(join(tmpdir(), 'v030_1-int-'));- originalHome = process.env.GBRAIN_HOME;- process.env.GBRAIN_HOME = tmpHome;- engine = new PGLiteEngine();- await engine.connect({});- await engine.initSchema();-});--afterEach(async () => {- await engine.disconnect();- if (originalHome === undefined) delete process.env.GBRAIN_HOME;- else process.env.GBRAIN_HOME = originalHome;- if (existsSync(tmpHome)) rmSync(tmpHome, { recursive: true, force: true });-});--describe('Lane B — migration runner applies cleanly through retry wrapper', () => {- test('after initSchema, config.version is at LATEST_VERSION', async () => {- const ver = await engine.getConfig('version');- expect(parseInt(ver || '1', 10)).toBe(LATEST_VERSION);- });-- test('v44 emotional_weight_recomputed_at column exists on pages', async () => {- // PGLite supports information_schema.columns. ALTER TABLE ADD COLUMN- // is idempotent, so v44 should have applied even on a freshly-created- // PGLite brain.- const rows = await engine.executeRaw<{ column_name: string }>(- `SELECT column_name FROM information_schema.columns- WHERE table_name = 'pages' AND column_name = 'emotional_weight_recomputed_at'`,- );- expect(rows.length).toBe(1);- });-});--describe('Lane C — backfill registry on empty brain', () => {- test('listBackfills returns the canonical registry entries', () => {- // v0.30.1 shipped 3 entries (effective_date, embedding_voyage,- // emotional_weight). v0.36 cross-modal wave adds `modality` for- // historical image-asset chunks. Extend this assertion as new- // backfills land.- const list = listBackfills();- const names = list.map(e => e.spec.name).sort();- expect(names).toEqual(['effective_date', 'embedding_voyage', 'emotional_weight', 'modality']);- });-- test('embedding_voyage is declared-only in v0.30.1', () => {- const reg = getBackfill('embedding_voyage');- expect(reg).toBeDefined();- expect(reg!.v030_1_status).toBe('declared-only');- });-- test('emotional_weight backfill on empty brain: examined=0', async () => {- const reg = getBackfill('emotional_weight');- expect(reg).toBeDefined();- const result = await runBackfill(engine, reg!.spec, { batchSize: 100 });- expect(result.examined).toBe(0);- expect(result.errors).toBe(0);- });-- test('effective_date backfill on empty brain: examined=0', async () => {- const reg = getBackfill('effective_date');- expect(reg).toBeDefined();- const result = await runBackfill(engine, reg!.spec, { batchSize: 100 });- expect(result.examined).toBe(0);- });-});--describe('Lane D — vector-index lifecycle on PGLite', () => {- test('dropZombieIndexes on PGLite is a no-op', async () => {- const r = await dropZombieIndexes(engine);- expect(r.dropped).toEqual([]);- });-- test('checkActiveBuild on PGLite returns active: false', async () => {- const r = await checkActiveBuild(engine, 'idx_chunks_embedding');- expect(r.active).toBe(false);- });-});--describe('Lane E — upgrade-checkpoint with brain identity', () => {- test('round-trips a checkpoint with brain_id', async () => {- const brainId = computeBrainId(undefined); // PGLite path- const cp: UpgradeCheckpoint = {- brain_id: brainId,- started_at: new Date().toISOString(),- from_version: '0.30.0',- to_version: '0.30.1',- completed_steps: ['pull', 'install'],- };- writeCheckpoint(cp);- const loaded = loadCheckpoint();- expect(loaded?.brain_id).toBe(brainId);- expect(loaded?.completed_steps).toEqual(['pull', 'install']);- });-- test('validateCheckpoint detects partial completion → resumeAt', async () => {- const brainId = computeBrainId(undefined);- const cp: UpgradeCheckpoint = {- brain_id: brainId,- started_at: new Date().toISOString(),- from_version: '0.30.0',- to_version: '0.30.1',- completed_steps: ['pull', 'install', 'schema'],- };- writeCheckpoint(cp);- const r = validateCheckpoint(brainId);- expect(r.valid).toBe(true);- expect(r.resumeAt).toBe('features');- });-- test('cross-brain checkpoint mismatch (X2) refuses', async () => {- const brainA = computeBrainId('postgresql://u:p@host:5432/db_a');- const brainB = computeBrainId('postgresql://u:p@host:5432/db_b');- const cp: UpgradeCheckpoint = {- brain_id: brainA,- started_at: new Date().toISOString(),- from_version: '0.30.0',- to_version: '0.30.1',- completed_steps: ['pull'],- };- writeCheckpoint(cp);- const r = validateCheckpoint(brainB);- expect(r.valid).toBe(false);- expect(r.reason).toBe('brain_mismatch');- });-- test('full step progression: pull → install → schema → features → backfills → verify', async () => {- const brainId = computeBrainId(undefined);- let cp: UpgradeCheckpoint = {- brain_id: brainId,- started_at: new Date().toISOString(),- from_version: '0.30.0',- to_version: '0.30.1',- completed_steps: [],- };- writeCheckpoint(cp);-- const steps = ['pull', 'install', 'schema', 'features', 'backfills'] as const;- for (const s of steps) {- cp = markStepComplete(cp, s);- writeCheckpoint(cp);- const v = validateCheckpoint(brainId);- expect(v.valid).toBe(true);- }- cp = markStepComplete(cp, 'verify');- writeCheckpoint(cp);- const final = validateCheckpoint(brainId);- expect(final.valid).toBe(false);- expect(final.reason).toBe('all_complete');- });-});--describe('Cross-lane integration', () => {- test('PostgresEngine.connectionManager is null on PGLite (engine kind branch)', () => {- // PGLite engines don't get a ConnectionManager — that's a Postgres-only- // concern. PGLiteEngine doesn't have the property at all.- const hasManager = 'connectionManager' in engine;- expect(hasManager).toBe(false);- });-- test('schema_version on BrainHealth is the optional v0.30.1 marker', async () => {- // Engines don't yet populate this field; it's an optional contract.- // The SHAPE compiles, the runtime read returns undefined.- const health = await engine.getHealth();- // schema_version is OPTIONAL (v0.30.1 declares the contract; engines- // populate in v0.30.2). undefined is a valid v0.30.1 state.- expect(health.schema_version === undefined || health.schema_version === '1').toBe(true);- });-});diff --git a/test/e2e/v0_30_3-fix-wave.test.ts b/test/e2e/v0_30_3-fix-wave.test.tsdeleted file mode 100644index 4a37b42b86..0000000000--- a/test/e2e/v0_30_3-fix-wave.test.ts+++ /dev/null@@ -1,201 +0,0 @@-/**- * E2E coverage for the v0.30.3 fix wave.- *- * Codex-mandated test gate C3 (from /codex review of v0.30.3 plan): pin- * that brains rewound to pre-v39 (PGLite < 41) shapes upgrade cleanly- * through the assembled wave. Three regression scenarios:- *- * 1. Pre-v39 brain (missing modality + embedding_image columns) survives- * `initSchema` because pr-741 added these columns to- * `applyForwardReferenceBootstrap`. Pre-#741, the schema replay- * crashed with `column "modality" does not exist`.- *- * 2. Pre-v40 brain (missing emotional_weight + effective_date +- * effective_date_source) survives `initSchema`. Pre-#741, replay- * crashed with `column "effective_date" does not exist`.- *- * 3. Pre-v41 PGLite brain (missing import_filename + salience_touched_at)- * survives `initSchema`. Pre-#741, replay crashed on the same- * `column "..." does not exist` class.- *- * Pattern follows test/e2e/v0_28_5-fix-wave.test.ts: spin up a fresh- * LATEST brain, surgically drop the columns the bootstrap is supposed to- * restore, reset config.version, then re-call initSchema and assert the- * brain advances to LATEST_VERSION with no crash. PGLite-only.- */--import { describe, test, expect } from 'bun:test';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { LATEST_VERSION } from '../../src/core/migrate.ts';--// Cold-path opt-out: the rewind-to-v38 → re-initSchema → LATEST arc needs its-// seeding initSchema to be a genuine cold build, not a snapshot restore.-delete process.env.GBRAIN_PGLITE_SNAPSHOT;--describe('v0.30.3 wave — pre-v39/v40/v41 forward-reference bootstrap (#741)', () => {- test('pre-v39 brain (missing modality + embedding_image) re-runs initSchema cleanly', async () => {- const engine = new PGLiteEngine();- await engine.connect({});- try {- await engine.initSchema();- const db = (engine as any).db;-- // Rewind to a pre-v39 shape — drop columns the bootstrap claims to- // restore (modality + embedding_image). v39 = multimodal_dual_column_v0_27_1.- await db.exec(`- DROP INDEX IF EXISTS idx_chunks_embedding_image;- ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding_image CASCADE;- ALTER TABLE content_chunks DROP COLUMN IF EXISTS modality CASCADE;- UPDATE config SET value = '38' WHERE key = 'version';- `);-- // Re-run initSchema. Pre-#741 this crashed with- // `column "modality" does not exist` during schema replay.- await engine.initSchema();-- const versionRow = await db.query(`SELECT value FROM config WHERE key = 'version'`);- expect(Number(versionRow.rows[0].value)).toBe(LATEST_VERSION);-- // Confirm the rewound columns are restored.- const modality = await db.query(- `SELECT column_name FROM information_schema.columns- WHERE table_schema='public' AND table_name='content_chunks' AND column_name='modality'`,- );- expect(modality.rows.length).toBeGreaterThan(0);-- const embeddingImage = await db.query(- `SELECT column_name FROM information_schema.columns- WHERE table_schema='public' AND table_name='content_chunks' AND column_name='embedding_image'`,- );- expect(embeddingImage.rows.length).toBeGreaterThan(0);- } finally {- await engine.disconnect();- }- });-- test('pre-v40 brain (missing emotional_weight + effective_date) re-runs initSchema cleanly', async () => {- const engine = new PGLiteEngine();- await engine.connect({});- try {- await engine.initSchema();- const db = (engine as any).db;-- // Rewind to a pre-v40 shape — drop emotional_weight + effective_date +- // effective_date_source. v40 = pages_emotional_weight + effective_date.- await db.exec(`- ALTER TABLE pages DROP COLUMN IF EXISTS emotional_weight CASCADE;- ALTER TABLE pages DROP COLUMN IF EXISTS effective_date CASCADE;- ALTER TABLE pages DROP COLUMN IF EXISTS effective_date_source CASCADE;- UPDATE config SET value = '39' WHERE key = 'version';- `);-- await engine.initSchema();-- const versionRow = await db.query(`SELECT value FROM config WHERE key = 'version'`);- expect(Number(versionRow.rows[0].value)).toBe(LATEST_VERSION);-- const emotional = await db.query(- `SELECT column_name FROM information_schema.columns- WHERE table_schema='public' AND table_name='pages' AND column_name='emotional_weight'`,- );- expect(emotional.rows.length).toBeGreaterThan(0);-- const effective = await db.query(- `SELECT column_name FROM information_schema.columns- WHERE table_schema='public' AND table_name='pages' AND column_name='effective_date'`,- );- expect(effective.rows.length).toBeGreaterThan(0);- } finally {- await engine.disconnect();- }- });-- test('pre-v41 PGLite brain (missing import_filename + salience_touched_at) re-runs initSchema cleanly', async () => {- const engine = new PGLiteEngine();- await engine.connect({});- try {- await engine.initSchema();- const db = (engine as any).db;-- // Rewind to pre-v41 — drop import_filename + salience_touched_at.- await db.exec(`- ALTER TABLE pages DROP COLUMN IF EXISTS import_filename CASCADE;- ALTER TABLE pages DROP COLUMN IF EXISTS salience_touched_at CASCADE;- UPDATE config SET value = '40' WHERE key = 'version';- `);-- await engine.initSchema();-- const versionRow = await db.query(`SELECT value FROM config WHERE key = 'version'`);- expect(Number(versionRow.rows[0].value)).toBe(LATEST_VERSION);-- const importFn = await db.query(- `SELECT column_name FROM information_schema.columns- WHERE table_schema='public' AND table_name='pages' AND column_name='import_filename'`,- );- expect(importFn.rows.length).toBeGreaterThan(0);-- const salience = await db.query(- `SELECT column_name FROM information_schema.columns- WHERE table_schema='public' AND table_name='pages' AND column_name='salience_touched_at'`,- );- expect(salience.rows.length).toBeGreaterThan(0);- } finally {- await engine.disconnect();- }- });-- test('pre-v34 brain (compounded v0.20 + v0.26.3 + v39-v41 wedge) walks forward cleanly', async () => {- // The "user stuck on v0.20-era PGLite brain hitting v0.30.0" scenario:- // multiple bootstrap forward-reference gaps compounded. This is the- // headline upgrade-path claim in the v0.30.3 release notes.- const engine = new PGLiteEngine();- await engine.connect({});- try {- await engine.initSchema();- const db = (engine as any).db;-- await db.exec(`- -- v0.20 surface (Cathedral II columns)- DROP INDEX IF EXISTS idx_chunks_search_vector;- DROP INDEX IF EXISTS idx_chunks_symbol_qualified;- DROP TRIGGER IF EXISTS chunk_search_vector_trigger ON content_chunks;- DROP FUNCTION IF EXISTS update_chunk_search_vector;- ALTER TABLE content_chunks DROP COLUMN IF EXISTS parent_symbol_path CASCADE;- ALTER TABLE content_chunks DROP COLUMN IF EXISTS doc_comment CASCADE;- ALTER TABLE content_chunks DROP COLUMN IF EXISTS symbol_name_qualified CASCADE;- ALTER TABLE content_chunks DROP COLUMN IF EXISTS search_vector CASCADE;-- -- v0.26.3 surface- DROP INDEX IF EXISTS idx_mcp_log_agent_time;- ALTER TABLE mcp_request_log DROP COLUMN IF EXISTS agent_name CASCADE;- ALTER TABLE mcp_request_log DROP COLUMN IF EXISTS params CASCADE;- ALTER TABLE mcp_request_log DROP COLUMN IF EXISTS error_message CASCADE;-- -- v0.27 surface- DROP INDEX IF EXISTS idx_subagent_messages_provider;- ALTER TABLE subagent_messages DROP COLUMN IF EXISTS provider_id CASCADE;-- -- v39-v41 surface (the wave's bootstrap fixes)- DROP INDEX IF EXISTS idx_chunks_embedding_image;- ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding_image CASCADE;- ALTER TABLE content_chunks DROP COLUMN IF EXISTS modality CASCADE;- ALTER TABLE pages DROP COLUMN IF EXISTS emotional_weight CASCADE;- ALTER TABLE pages DROP COLUMN IF EXISTS effective_date CASCADE;- ALTER TABLE pages DROP COLUMN IF EXISTS effective_date_source CASCADE;- ALTER TABLE pages DROP COLUMN IF EXISTS import_filename CASCADE;- ALTER TABLE pages DROP COLUMN IF EXISTS salience_touched_at CASCADE;-- UPDATE config SET value = '13' WHERE key = 'version';- `);-- // Walk all the way forward from a deeply-rewound state.- await engine.initSchema();-- const versionRow = await db.query(`SELECT value FROM config WHERE key = 'version'`);- expect(Number(versionRow.rows[0].value)).toBe(LATEST_VERSION);- } finally {- await engine.disconnect();- }- });-});diff --git a/test/e2e/voyage-multimodal.test.ts b/test/e2e/voyage-multimodal.test.tsindex 29a8554dd4..97533fc181 100644--- a/test/e2e/voyage-multimodal.test.ts+++ b/test/e2e/voyage-multimodal.test.ts@@ -5,6 +5,10 @@// Pairs with the Phase 1 bun --compile probe (which exercises decode but// not the network call) — this hits Voyage for real and asserts a// 1024-dim vector comes back with sane shape.+//+// No CI job provides VOYAGE_API_KEY, so scripts/run-e2e.sh leaves this file+// out of its default glob. Run it by name (the runner keeps provider keys):+// VOYAGE_API_KEY=... bash scripts/run-e2e.sh test/e2e/voyage-multimodal.test.tsimport { describe, expect, test, beforeAll, afterEach } from 'bun:test';import { configureGateway, embedMultimodal, resetGateway } from '../../src/core/ai/gateway.ts';diff --git a/test/e2e/voyage-rerank-live.test.ts b/test/e2e/voyage-rerank-live.test.tsindex 37dd3fe285..472f65788b 100644--- a/test/e2e/voyage-rerank-live.test.ts+++ b/test/e2e/voyage-rerank-live.test.ts@@ -8,7 +8,9 @@* accepts both data[] and the legacy results[] dialect). Also round-trips one* voyage-4 embed at the new-install width (1024).*- * Run: VOYAGE_API_KEY=... bun test test/e2e/voyage-rerank-live.test.ts+ * No CI job provides VOYAGE_API_KEY, so scripts/run-e2e.sh leaves this file+ * out of its default glob. Run it by name (the runner keeps provider keys):+ * VOYAGE_API_KEY=... bash scripts/run-e2e.sh test/e2e/voyage-rerank-live.test.ts*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';diff --git a/test/embed-default-concurrency.test.ts b/test/embed-default-concurrency.test.tsnew file mode 100644index 0000000000..43e5a4190b--- /dev/null+++ b/test/embed-default-concurrency.test.ts@@ -0,0 +1,99 @@+/**+ * `gbrain embed` runs 20 page workers when GBRAIN_EMBED_CONCURRENCY is unset,+ * on both the --all path (embedAll) and the --stale path (embedAllStale).+ * Drives the real embed -> embedBatch -> gateway path with a barrier embed+ * transport that holds every request until arrivals go quiet, so the peak+ * in-flight count equals the worker count.+ */++import { afterAll, afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { runEmbedCore } from '../src/commands/embed.ts';+import { mockEmbedProjectionEngine as mockEngine } from './helpers/embed-projection-mock.ts';+import { withEnv } from './helpers/with-env.ts';++const DIMS = 1536;+const PAGES = 30;+const QUIET_MS = 150;++let inFlight = 0;+let peak = 0;+let calls = 0;+let waiters: Array<() => void> = [];+let quietTimer: ReturnType<typeof setTimeout> | null = null;++function releaseWhenQuiet() {+ if (quietTimer) clearTimeout(quietTimer);+ quietTimer = setTimeout(() => {+ const release = waiters;+ waiters = [];+ for (const go of release) go();+ }, QUIET_MS);+}++const barrierTransport = (async ({ values }: { values: string[] }) => {+ calls++;+ inFlight++;+ peak = Math.max(peak, inFlight);+ await new Promise<void>(resolve => { waiters.push(resolve); releaseWhenQuiet(); });+ inFlight--;+ return {+ embeddings: values.map(() => Array.from({ length: DIMS }, (_, j) => (j === 0 ? 1 : 0))),+ usage: { tokens: values.length },+ };+}) as never;++beforeEach(() => {+ inFlight = 0;+ peak = 0;+ calls = 0;+ waiters = [];+ resetGateway();+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test' } });+ __setEmbedTransportForTests(barrierTransport);+});++afterEach(() => {+ if (quietTimer) clearTimeout(quietTimer);+ __setEmbedTransportForTests(null);+});++afterAll(() => resetGateway());++const slugs = Array.from({ length: PAGES }, (_, i) => `notes/concurrency-${i}`);+const staleChunk = (slug: string) => ({ chunk_index: 0, chunk_text: `Synthetic text for ${slug}.`, chunk_source: 'compiled_truth', embedded_at: null, token_count: 4 });++describe('embed default concurrency', () => {+ test('--all runs 20 page workers when GBRAIN_EMBED_CONCURRENCY is unset', async () => {+ const engine = mockEngine({+ listPages: async () => slugs.map(slug => ({ slug })),+ getChunks: async (slug: string) => [staleChunk(slug)],+ upsertChunks: async () => {},+ });++ const result = await withEnv({ GBRAIN_EMBED_CONCURRENCY: undefined }, () => runEmbedCore(engine, { all: true }));++ expect(calls).toBe(PAGES);+ expect(result.embedded).toBe(PAGES);+ expect(peak).toBe(20);+ });++ test('--stale runs 20 page workers when GBRAIN_EMBED_CONCURRENCY is unset', async () => {+ const stale = slugs.map((slug, i) => ({+ slug, chunk_index: 0, chunk_text: `Synthetic text for ${slug}.`, chunk_source: 'compiled_truth' as const,+ model: null, token_count: 4, source_id: 'default', page_id: i + 1,+ }));+ let served = false;+ const engine = mockEngine({+ countStaleChunks: async () => (served ? 0 : PAGES),+ listStaleChunks: async () => { if (served) return []; served = true; return stale; },+ getChunks: async (slug: string) => [staleChunk(slug)],+ upsertChunks: async () => {},+ });++ await withEnv({ GBRAIN_EMBED_CONCURRENCY: undefined }, () => runEmbedCore(engine, { stale: true }));++ expect(calls).toBe(PAGES);+ expect(peak).toBe(20);+ });+});diff --git a/test/embed-helper-migration.test.ts b/test/embed-helper-migration.test.tsdeleted file mode 100644index 8d13572e5b..0000000000--- a/test/embed-helper-migration.test.ts+++ /dev/null@@ -1,110 +0,0 @@-/**- * Structural regression test for the embed.ts → worker-pool migration- * (v0.41.15.0, T3, REGRESSION per IRON RULE).- *- * What this test asserts:- * 1. embed.ts imports `runSlidingPool` from `../core/worker-pool.ts`.- * 2. Both pre-migration sliding-pool sites are GONE:- * - the `let nextIdx = 0; async function worker() {}` shape- * - the `Promise.all(Array.from({ length: numWorkers }, () => worker()))`- * shape (which paired with the above).- * 3. Both migration sites call `runSlidingPool({ items: ..., workers: CONCURRENCY, ... })`.- * 4. The legacy `CONCURRENCY = parseInt(process.env.GBRAIN_EMBED_CONCURRENCY...)`- * default is preserved (codex finding #13 — embed's pre-existing default- * pre-dates autoConcurrency; the migration must NOT route it through- * resolveWorkersWithClamp). This is the load-bearing back-compat for- * every existing brain that relies on the 20-worker embed sweep.- *- * Why structural rather than end-to-end:- * Per codex finding #16/#17, embed.ts byte-equality via stubbed transport- * was overclaimed in the original plan — it can't prove provider retry- * behavior, SDK usage accounting, or progress event ordering preservation.- * The pre-migration sliding pool didn't have any of those guarantees either;- * it just had a small inline `while (nextIdx < pages.length)` loop. The- * honest contract is "the same pages still get embedded by the same workers- * reading from the same queue, just through a helper now." That's a- * structural property — easiest to pin by source grep.- *- * The helper's contracts (atomic claim, abort propagation, failures[]- * shape, BudgetExhausted bypass) are exhaustively tested in- * test/worker-pool.test.ts; embed inherits those by import.- */--import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'fs';-import { resolve } from 'path';--const REPO_ROOT = resolve(import.meta.dir, '..');-const EMBED_PATH = resolve(REPO_ROOT, 'src/commands/embed.ts');-const EMBED_SOURCE = readFileSync(EMBED_PATH, 'utf-8');--describe('embed.ts → worker-pool migration (T3)', () => {- test('imports runSlidingPool from worker-pool helper', () => {- expect(EMBED_SOURCE).toMatch(- /import\s*\{\s*runSlidingPool\s*\}\s*from\s*['"]\.\.\/core\/worker-pool\.ts['"]/,- );- });-- test('calls runSlidingPool at least twice (embedAll + embedAllStale paths)', () => {- const matches = EMBED_SOURCE.match(/runSlidingPool\(/g) ?? [];- expect(matches.length).toBeGreaterThanOrEqual(2);- });-- test('pre-migration `let nextIdx = 0; async function worker()` shape is gone', () => {- // The exact shape the migration replaced. Either token alone could- // legitimately appear in a comment or string literal; both together- // on adjacent lines indicates a regression to the inline pool.- const inlinePool =- /let\s+nextIdx\s*=\s*0\s*;\s*\n\s*async\s+function\s+worker\s*\(/;- expect(EMBED_SOURCE).not.toMatch(inlinePool);- });-- test('pre-migration `Promise.all(Array.from({ length: numWorkers }, () => worker()))` is gone', () => {- // Migration-specific shape from the original inline pool. The- // generic `Promise.all(...)` pattern is still allowed elsewhere- // (gateway, etc.); only the worker-pool-fanout shape is banned.- const fanout =- /Promise\.all\(Array\.from\(\{\s*length:\s*numWorkers\s*\}/;- expect(EMBED_SOURCE).not.toMatch(fanout);- });-- test('preserves GBRAIN_EMBED_CONCURRENCY default of 20 (codex #13)', () => {- // The pre-migration default must survive: env override or 20.- // Routing through resolveWorkersWithClamp would change this behavior- // (autoConcurrency returns 1 for small file counts even on Postgres),- // breaking every existing brain that relies on the 20-worker default.- expect(EMBED_SOURCE).toMatch(- /parseInt\(process\.env\.GBRAIN_EMBED_CONCURRENCY\s*\|\|\s*['"]20['"]/,- );- });-- test('runSlidingPool call sites pass `workers: CONCURRENCY`', () => {- // The migrated calls must thread the pre-existing CONCURRENCY value- // through, not invent a new default. Catches the regression where- // a future contributor swaps `workers: CONCURRENCY` for a literal.- // Allow optional commas/whitespace — match both call sites' shape.- const callSites = EMBED_SOURCE.match(- /runSlidingPool\(\s*\{[\s\S]*?workers:\s*CONCURRENCY/g,- );- expect(callSites?.length ?? 0).toBeGreaterThanOrEqual(2);- });-- test('embedAllStale path still threads the cancellation signal into pool', () => {- // The pre-migration code checked `!budgetSignal.aborted` in the worker- // loop. The migration moves that check into the helper via the `signal`- // option. #1737 then composed the wall-clock budget with the caller's- // abort into `effectiveSignal` (anySignal(budgetSignal, externalSignal)) so- // a killed job stops the pool too. If a future refactor drops the signal,- // both wall-clock budget AND cooperative abort cancellation regress.- expect(EMBED_SOURCE).toMatch(- /runSlidingPool\(\s*\{[\s\S]*?signal:\s*effectiveSignal[\s\S]*?\}\)/,- );- });-- test('failureLabel projector uses page.slug (memory bound on large brains)', () => {- // Per codex #10 + D7, failures[] must not store full Page objects.- // We can't test the runtime behavior without a full mock engine, but- // we CAN assert the call sites pass the projector explicitly.- expect(EMBED_SOURCE).toMatch(/failureLabel:\s*\(page\)\s*=>\s*page\.slug/);- });-});diff --git a/test/embed-pool-abort.test.ts b/test/embed-pool-abort.test.tsnew file mode 100644index 0000000000..7a33de0d60--- /dev/null+++ b/test/embed-pool-abort.test.ts@@ -0,0 +1,80 @@+/**+ * An aborted `gbrain embed` stops claiming pages: after the caller's signal+ * fires during one page's embed call, no later page is read or embedded, on+ * both the --stale path (embedAllStale) and the --all path (embedAll). Drives+ * the real embed -> gateway path with one worker and an embed transport that+ * aborts the run on its first call.+ */++import { afterAll, afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { runEmbedCore } from '../src/commands/embed.ts';+import { mockEmbedProjectionEngine as mockEngine } from './helpers/embed-projection-mock.ts';+import { withEnv } from './helpers/with-env.ts';++const DIMS = 1536;+const slugs = Array.from({ length: 5 }, (_, i) => `notes/abort-${i}`);++let controller: AbortController;+let embeddedTexts: string[][] = [];++beforeEach(() => {+ controller = new AbortController();+ embeddedTexts = [];+ resetGateway();+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ embeddedTexts.push(values);+ controller.abort();+ return {+ embeddings: values.map(() => Array.from({ length: DIMS }, (_, j) => (j === 0 ? 1 : 0))),+ usage: { tokens: values.length },+ };+ }) as never);+});++afterEach(() => __setEmbedTransportForTests(null));++afterAll(() => resetGateway());++const chunk = (slug: string) => ({ chunk_index: 0, chunk_text: `Synthetic text for ${slug}.`, chunk_source: 'compiled_truth', embedded_at: null, token_count: 4 });++const pagesRead = (engine: unknown) => [...new Set(+ (engine as { _calls: { method: string; args: unknown[] }[] })._calls+ .filter(call => call.method === 'readPageSnapshot')+ .map(call => call.args[0]),+)];++describe('embed abort stops the page pool', () => {+ test('--stale: no page after the aborting one is read or embedded', async () => {+ const stale = slugs.map((slug, i) => ({+ slug, chunk_index: 0, chunk_text: `Synthetic text for ${slug}.`, chunk_source: 'compiled_truth' as const,+ model: null, token_count: 4, source_id: 'default', page_id: i + 1,+ }));+ let served = false;+ const engine = mockEngine({+ countStaleChunks: async () => (served ? 0 : slugs.length),+ listStaleChunks: async () => { if (served) return []; served = true; return stale; },+ getChunks: async (slug: string) => [chunk(slug)],+ upsertChunks: async () => {},+ });++ await withEnv({ GBRAIN_EMBED_CONCURRENCY: '1' }, () => runEmbedCore(engine, { stale: true, signal: controller.signal }));++ expect(embeddedTexts).toHaveLength(1);+ expect(pagesRead(engine)).toEqual([slugs[0]]);+ });++ test('--all: no page after the aborting one is read or embedded', async () => {+ const engine = mockEngine({+ listPages: async () => slugs.map(slug => ({ slug })),+ getChunks: async (slug: string) => [chunk(slug)],+ upsertChunks: async () => {},+ });++ await withEnv({ GBRAIN_EMBED_CONCURRENCY: '1' }, () => runEmbedCore(engine, { all: true, signal: controller.signal }));++ expect(embeddedTexts).toHaveLength(1);+ expect(pagesRead(engine)).toEqual([slugs[0]]);+ });+});diff --git a/test/embedding-dim-check-facts.test.ts b/test/embedding-dim-check-facts.test.tsindex bdd60eb483..d661dff130 100644--- a/test/embedding-dim-check-facts.test.ts+++ b/test/embedding-dim-check-facts.test.ts@@ -251,7 +251,4 @@ describe('postgres-engine fact insert cast (T6, codex #20)', () => {expect(literalHits ?? []).toEqual([]);});- test('cached cast suffix has a test-only reset hook for unit cases', () => {- expect(PG_SRC).toMatch(/__resetFactsEmbeddingCastCacheForTest/);- });});diff --git a/test/enrichment-service.test.ts b/test/enrichment-service.test.tsindex d53e2f97ff..156d997e3e 100644--- a/test/enrichment-service.test.ts+++ b/test/enrichment-service.test.ts@@ -120,33 +120,4 @@ describe('enrichment-service', () => {expect(entities.some(e => e.name.includes('\f'))).toBe(false);});});-- describe('enrichEntity (mock)', () => {- test('module exports enrichEntity function', async () => {- const mod = await import('../src/core/enrichment-service.ts');- expect(typeof mod.enrichEntity).toBe('function');- });-- test('module exports enrichEntities for batch processing', async () => {- const mod = await import('../src/core/enrichment-service.ts');- expect(typeof mod.enrichEntities).toBe('function');- });-- test('module exports extractAndEnrich for text processing', async () => {- const mod = await import('../src/core/enrichment-service.ts');- expect(typeof mod.extractAndEnrich).toBe('function');- });- });-- describe('tier auto-escalation logic', () => {- // We test the tier suggestion indirectly through the public interface- // The actual suggestTier function is private, but its behavior is- // observable through enrichEntity's return value (needs engine mock for full test)- test('enrichment result includes tier fields', async () => {- const mod = await import('../src/core/enrichment-service.ts');- // Verify the EnrichmentResult type shape is correct by checking exports- expect(mod.enrichEntity).toBeDefined();- // Full tier escalation testing requires engine mock (covered in E2E)- });- });});diff --git a/test/enrichment.test.ts b/test/enrichment.test.tsdeleted file mode 100644index 89737d4dba..0000000000--- a/test/enrichment.test.ts+++ /dev/null@@ -1,357 +0,0 @@-/**- * BudgetLedger + CompletenessScorer tests.- *- * BudgetLedger runs against PGLite in-memory (needs real FOR UPDATE semantics- * and the v11 schema migration). CompletenessScorer is pure — no engine.- */--import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';-import { tmpdir } from 'os';-import { mkdtempSync, rmSync } from 'fs';-import { join } from 'path';--import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import type { BrainEngine } from '../src/core/engine.ts';--import { BudgetLedger, BudgetError } from '../src/core/enrichment/budget.ts';-import {- scorePage,- getRubric,- personRubric,- companyRubric,- projectRubric,- dealRubric,- conceptRubric,- sourceRubric,- mediaRubric,- defaultRubric,-} from '../src/core/enrichment/completeness.ts';-import type { Page } from '../src/core/types.ts';--// ----------------------------------------------------------------------------// Engine fixture (BudgetLedger only)-// -----------------------------------------------------------------------------let engine: BrainEngine;-let dbDir: string;--beforeAll(async () => {- dbDir = mkdtempSync(join(tmpdir(), 'enrichment-test-'));- engine = new PGLiteEngine();- await engine.connect({ engine: 'pglite', database_path: dbDir });- await engine.initSchema();-});--afterAll(async () => {- await engine.disconnect();- rmSync(dbDir, { recursive: true, force: true });-});--async function resetBudget(): Promise<void> {- await engine.executeRaw('TRUNCATE budget_ledger, budget_reservations');-}--// ----------------------------------------------------------------------------// BudgetLedger-// -----------------------------------------------------------------------------describe('BudgetLedger', () => {- beforeEach(async () => { await resetBudget(); });-- test('reserve under cap succeeds', async () => {- const ledger = new BudgetLedger(engine);- const r = await ledger.reserve({ resolverId: 'perplexity', estimateUsd: 0.5, capUsd: 1.0 });- expect(r.kind).toBe('held');- if (r.kind === 'held') {- expect(r.resolverId).toBe('perplexity');- expect(r.estimateUsd).toBe(0.5);- }- });-- test('reserve over cap returns exhausted', async () => {- const ledger = new BudgetLedger(engine);- const r1 = await ledger.reserve({ resolverId: 'perplexity', estimateUsd: 0.8, capUsd: 1.0 });- expect(r1.kind).toBe('held');- const r2 = await ledger.reserve({ resolverId: 'perplexity', estimateUsd: 0.5, capUsd: 1.0 });- expect(r2.kind).toBe('exhausted');- if (r2.kind === 'exhausted') {- expect(r2.reason).toContain('cap');- }- });-- test('commit finalizes reservation and moves money from reserved to committed', async () => {- const ledger = new BudgetLedger(engine);- const r = await ledger.reserve({ resolverId: 'x', estimateUsd: 0.5, capUsd: 1.0 });- expect(r.kind).toBe('held');- if (r.kind !== 'held') return;-- await ledger.commit(r.reservationId, 0.42);- const state = await ledger.state('default', 'x');- expect(state?.reservedUsd).toBe(0);- expect(state?.committedUsd).toBeCloseTo(0.42);- });-- test('actual overage is recorded truthfully, finalized, and reported after commit', async () => {- const ledger = new BudgetLedger(engine);- const r = await ledger.reserve({ resolverId: 'x', estimateUsd: 0.1, capUsd: 1.0 });- if (r.kind !== 'held') throw new Error('setup');-- let caught: unknown;- try {- await ledger.commit(r.reservationId, 1.25);- } catch (error) {- caught = error;- }-- expect(caught).toBeInstanceOf(BudgetError);- expect((caught as BudgetError).code).toBe('cap_exceeded');- const state = await ledger.state('default', 'x');- expect(state?.reservedUsd).toBe(0);- expect(state?.committedUsd).toBeCloseTo(1.25);-- const rows = await engine.executeRaw<{ status: string }>(- 'SELECT status FROM budget_reservations WHERE reservation_id = $1',- [r.reservationId],- );- expect(rows[0]?.status).toBe('committed');-- const next = await ledger.reserve({ resolverId: 'x', estimateUsd: 0.01, capUsd: 1.0 });- expect(next.kind).toBe('exhausted');- });-- test('rollback clears reserved', async () => {- const ledger = new BudgetLedger(engine);- const r = await ledger.reserve({ resolverId: 'x', estimateUsd: 0.5, capUsd: 1.0 });- if (r.kind !== 'held') throw new Error('setup');- await ledger.rollback(r.reservationId);- const state = await ledger.state('default', 'x');- expect(state?.reservedUsd).toBe(0);- expect(state?.committedUsd).toBe(0);- });-- test('commit-then-rollback is a no-op', async () => {- const ledger = new BudgetLedger(engine);- const r = await ledger.reserve({ resolverId: 'x', estimateUsd: 0.5, capUsd: 1.0 });- if (r.kind !== 'held') throw new Error('setup');- await ledger.commit(r.reservationId, 0.3);- // Second rollback should be a no-op, not throw- await ledger.rollback(r.reservationId);- const state = await ledger.state('default', 'x');- expect(state?.committedUsd).toBeCloseTo(0.3);- });-- test('commit-after-commit throws already_finalized', async () => {- const ledger = new BudgetLedger(engine);- const r = await ledger.reserve({ resolverId: 'x', estimateUsd: 0.5, capUsd: 1.0 });- if (r.kind !== 'held') throw new Error('setup');- await ledger.commit(r.reservationId, 0.3);- try {- await ledger.commit(r.reservationId, 0.3);- throw new Error('should have thrown');- } catch (e) {- expect(e).toBeInstanceOf(BudgetError);- expect((e as BudgetError).code).toBe('already_finalized');- }- });-- test('commit-unknown-reservation throws reservation_not_found', async () => {- const ledger = new BudgetLedger(engine);- try {- await ledger.commit('made-up-id', 1.0);- throw new Error('should have thrown');- } catch (e) {- expect((e as BudgetError).code).toBe('reservation_not_found');- }- });-- test('reserve with invalid estimate throws', async () => {- const ledger = new BudgetLedger(engine);- try {- await ledger.reserve({ resolverId: 'x', estimateUsd: -1 });- throw new Error('should have thrown');- } catch (e) {- expect((e as BudgetError).code).toBe('invalid_input');- }- });-- test('state returns null when no row exists yet', async () => {- const ledger = new BudgetLedger(engine);- const state = await ledger.state('default', 'never-called');- expect(state).toBeNull();- });-- test('scope isolation: different scopes have independent caps', async () => {- const ledger = new BudgetLedger(engine);- const a = await ledger.reserve({ scope: 'alice', resolverId: 'x', estimateUsd: 1.0, capUsd: 1.0 });- const b = await ledger.reserve({ scope: 'bob', resolverId: 'x', estimateUsd: 1.0, capUsd: 1.0 });- expect(a.kind).toBe('held');- expect(b.kind).toBe('held');- });-- test('parallel reserves never exceed cap', async () => {- const ledger = new BudgetLedger(engine);- const results = await Promise.all(- Array.from({ length: 10 }, () =>- ledger.reserve({ resolverId: 'race', estimateUsd: 0.3, capUsd: 1.0 }),- ),- );- const heldCount = results.filter(r => r.kind === 'held').length;- // Cap 1.0, estimate 0.3 → at most 3 can hold simultaneously (0.9 <= 1.0)- expect(heldCount).toBeLessThanOrEqual(3);- expect(heldCount).toBeGreaterThanOrEqual(1);-- const state = await ledger.state('default', 'race');- expect(state!.reservedUsd).toBeLessThanOrEqual(1.0);- });-- test('cleanupExpired reclaims TTL-expired held reservations', async () => {- const ledger = new BudgetLedger(engine);- const r = await ledger.reserve({ resolverId: 'x', estimateUsd: 0.5, capUsd: 1.0, ttlSeconds: 0 });- expect(r.kind).toBe('held');- await new Promise(ok => setTimeout(ok, 50));-- const { reclaimed } = await ledger.cleanupExpired();- expect(reclaimed).toBeGreaterThanOrEqual(1);- const state = await ledger.state('default', 'x');- expect(state!.reservedUsd).toBe(0);- });-});--// ----------------------------------------------------------------------------// CompletenessScorer-// -----------------------------------------------------------------------------describe('CompletenessScorer — rubric weights', () => {- test('all seven core rubrics have weights summing to 1', () => {- for (const r of [personRubric, companyRubric, projectRubric, dealRubric, conceptRubric, sourceRubric, mediaRubric, defaultRubric]) {- const sum = r.dimensions.reduce((acc, d) => acc + d.weight, 0);- expect(Math.abs(sum - 1.0)).toBeLessThan(1e-6);- }- });-- test('getRubric returns default for unknown type', () => {- const r = getRubric('civic' as 'civic');- expect(r.entityType).toBe('default');- });-- test('getRubric returns person rubric for person', () => {- expect(getRubric('person').entityType).toBe('person');- });-});--describe('scorePage — person', () => {- test('empty person page scores very low', () => {- const page: Page = {- id: 1, slug: 'people/empty', type: 'person', title: 'Empty',- compiled_truth: '', timeline: '',- frontmatter: {},- created_at: new Date(), updated_at: new Date(),- source_id: 'default',- };- const s = scorePage(page);- expect(s.score).toBeLessThan(0.3);- });-- test('fully enriched person page scores high', () => {- const page: Page = {- id: 1, slug: 'people/alice', type: 'person', title: 'Alice',- compiled_truth: `Alice is the CEO of Acme [Source: X/alice, 2026-04-18](https://x.com/alice/status/1).-She [founded](https://acme.com/about) Acme in 2023.-See also: [Acme](companies/acme.md), [Bob](people/bob.md), [Charlie](people/charlie.md).`,- timeline: '- **2026-04-18** | Met Alice [Source: meeting, 2026-04-18]\n- **2026-03-15** | Event',- frontmatter: {- role: 'CEO',- company: 'Acme',- last_verified: new Date().toISOString(),- },- created_at: new Date(), updated_at: new Date(),- source_id: 'default',- };- const s = scorePage(page);- expect(s.score).toBeGreaterThan(0.8);- });-- test('score exposes all 7 person dimension scores', () => {- const page: Page = {- id: 1, slug: 'people/x', type: 'person', title: 'X',- compiled_truth: 'Some content here.',- timeline: '',- frontmatter: {},- created_at: new Date(), updated_at: new Date(),- source_id: 'default',- };- const s = scorePage(page);- expect(Object.keys(s.dimensionScores)).toHaveLength(7);- });-- test('has_role_and_company fires on role frontmatter', () => {- const page: Page = {- id: 1, slug: 'people/r', type: 'person', title: 'R',- compiled_truth: '', timeline: '',- frontmatter: { role: 'Engineer' },- created_at: new Date(), updated_at: new Date(),- source_id: 'default',- };- const s = scorePage(page);- expect(s.dimensionScores.has_role_and_company).toBe(1);- });-});--describe('scorePage — company / concept / source / media defaults', () => {- test('company rubric scored', () => {- const page: Page = {- id: 1, slug: 'companies/acme', type: 'company', title: 'Acme',- compiled_truth: 'Acme builds things [Source: web, 2026-04-18](https://acme.com).',- timeline: '',- frontmatter: { founders: ['Alice'], funding: '$5M' },- created_at: new Date(), updated_at: new Date(),- source_id: 'default',- };- const s = scorePage(page);- expect(s.rubric).toBe('company');- expect(s.dimensionScores.has_founders).toBe(1);- expect(s.dimensionScores.has_funding).toBe(1);- });-- test('default rubric used for unknown page type', () => {- const page: Page = {- id: 1, slug: 'civic/x', type: 'civic' as 'civic', title: 'Civic',- compiled_truth: 'body content',- timeline: '', frontmatter: {},- created_at: new Date(), updated_at: new Date(),- source_id: 'default',- };- const s = scorePage(page);- expect(s.rubric).toBe('default');- });-- test('recency_score decays with age', () => {- const old: Page = {- id: 1, slug: 'people/old', type: 'person', title: 'x',- compiled_truth: '', timeline: '', frontmatter: {},- created_at: new Date(2020, 0, 1), updated_at: new Date(2020, 0, 1),- source_id: 'default',- };- const fresh: Page = {- id: 2, slug: 'people/fresh', type: 'person', title: 'y',- compiled_truth: '', timeline: '', frontmatter: {},- created_at: new Date(), updated_at: new Date(),- source_id: 'default',- };- const oldScore = scorePage(old);- const freshScore = scorePage(fresh);- expect(freshScore.dimensionScores.recency_score).toBeGreaterThan(oldScore.dimensionScores.recency_score);- });-- test('non_redundancy penalizes repeated-line pages', () => {- const repeated = Array.from({ length: 20 }, () => 'Same line repeated.').join('\n');- const page: Page = {- id: 1, slug: 'people/repetitive', type: 'person', title: 'x',- compiled_truth: repeated, timeline: '', frontmatter: {},- created_at: new Date(), updated_at: new Date(),- source_id: 'default',- };- const s = scorePage(page);- expect(s.dimensionScores.non_redundancy).toBeLessThan(0.2);- });-});diff --git a/test/eval-contradictions-calibration-join.test.ts b/test/eval-contradictions-calibration-join.test.tsdeleted file mode 100644index ed18518777..0000000000--- a/test/eval-contradictions-calibration-join.test.ts+++ /dev/null@@ -1,170 +0,0 @@-/**- * v0.36.1.0 (T9 / E3) — calibration-aware contradictions tests.- *- * Pure-function tests for the calibration-join helper. No DB, no LLM.- *- * Tests cover:- * - R2 regression: no profile → null tag (contradictions output unchanged)- * - happy path: finding matches active bias tag via domain hint- * - geography hint matches over-confident-geography tag- * - macro hint matches late-on-macro-tech tag- * - mismatch: hint produced but tag set doesn't include matching slug- * - empty active_bias_tags: returns null (no false positives)- * - bias context string contains tag name + Brier when present- */--import { describe, test, expect } from 'bun:test';-import {- tagFindingWithCalibration,- computeDomainHint,- buildBiasContextString,-} from '../src/core/eval-contradictions/calibration-join.ts';-import type { ContradictionFinding, PairMember } from '../src/core/eval-contradictions/types.ts';-import type { CalibrationProfileRow } from '../src/commands/calibration.ts';--function buildMember(slug: string, holder: string | null = 'garry'): PairMember {- return {- slug,- chunk_id: 1,- take_id: null, take_row_num: null,- source_tier: 'curated',- holder,- text: 'some text',- effective_date: '2024-01-01',- effective_date_source: 'frontmatter',- };-}--function buildFinding(slugA: string, slugB: string): ContradictionFinding {- return {- kind: 'cross_slug_chunks',- a: buildMember(slugA),- b: buildMember(slugB),- combined_score: 0.85,- verdict: 'contradiction',- severity: 'medium',- axis: 'evidence',- confidence: 0.8,- resolution_kind: 'manual_review',- resolution_command: 'gbrain takes resolve N --quality incorrect',- };-}--function buildProfile(activeTags: string[], brier: number | null = 0.21): CalibrationProfileRow {- return {- id: '1',- source_id: 'default',- holder: 'garry',- wave_version: 'v0.36.1.0',- generated_at: '2026-05-17T00:00:00Z',- published: false,- total_resolved: 12,- brier,- accuracy: 0.6,- partial_rate: 0.1,- grade_completion: 1.0,- pattern_statements: ['something'],- active_bias_tags: activeTags,- voice_gate_passed: true,- voice_gate_attempts: 1,- model_id: 'claude-sonnet-4-6',- };-}--// ─── R2 regression: no profile → byte-identical output ──────────────--describe('tagFindingWithCalibration — R2 regression', () => {- test('null profile returns null tag (contradictions output unchanged)', () => {- const finding = buildFinding('wiki/companies/acme-example', 'wiki/companies/widget-co');- expect(tagFindingWithCalibration(finding, null)).toBeNull();- });-- test('profile with empty active_bias_tags returns null', () => {- const finding = buildFinding('wiki/companies/acme', 'wiki/companies/widget');- expect(tagFindingWithCalibration(finding, buildProfile([]))).toBeNull();- });-});--// ─── computeDomainHint ──────────────────────────────────────────────--describe('computeDomainHint', () => {- test('companies slug → hiring/market-timing hint', () => {- expect(computeDomainHint(buildFinding('wiki/companies/a', 'wiki/companies/b'))).toMatch(/hiring|market-timing/);- });-- test('people slug → founder-behavior hint', () => {- expect(computeDomainHint(buildFinding('wiki/people/a', 'wiki/people/b'))).toMatch(/founder-behavior|hiring/);- });-- test('macro slug → macro hint', () => {- expect(computeDomainHint(buildFinding('wiki/macro/forecast', 'wiki/macro/timing'))).toBe('macro');- });-- test('geography slug → geography hint', () => {- expect(computeDomainHint(buildFinding('wiki/geography/ny', 'wiki/geography/sf'))).toBe('geography');- });-- test('unrecognized slug → empty hint', () => {- expect(computeDomainHint(buildFinding('wiki/random/x', 'wiki/random/y'))).toBe('');- });-});--// ─── Happy path: tag matches ────────────────────────────────────────--describe('tagFindingWithCalibration — match path', () => {- test('macro finding matches "late-on-macro-tech" tag', () => {- const finding = buildFinding('wiki/macro/forecast-2024', 'wiki/macro/forecast-2026');- const profile = buildProfile(['late-on-macro-tech']);- const tag = tagFindingWithCalibration(finding, profile);- expect(tag).not.toBeNull();- expect(tag!.bias_tag).toBe('late-on-macro-tech');- expect(tag!.context).toContain('late-on-macro-tech');- });-- test('geography finding matches "over-confident-geography" tag', () => {- const finding = buildFinding('wiki/geography/ny-tech', 'wiki/geography/sf-tech');- const profile = buildProfile(['over-confident-geography']);- const tag = tagFindingWithCalibration(finding, profile);- expect(tag).not.toBeNull();- expect(tag!.bias_tag).toBe('over-confident-geography');- });-- test('mismatch: companies finding does NOT match macro-only tag', () => {- const finding = buildFinding('wiki/companies/acme', 'wiki/companies/widget');- // Active tag is macro only; companies hint is hiring/market-timing, not macro.- const profile = buildProfile(['late-on-macro-tech']);- const tag = tagFindingWithCalibration(finding, profile);- expect(tag).toBeNull();- });-- test('first-match-wins when multiple tags could match the hint', () => {- const finding = buildFinding('wiki/companies/acme', 'wiki/companies/widget');- const profile = buildProfile(['over-confident-hiring', 'under-calibrated-market-timing']);- const tag = tagFindingWithCalibration(finding, profile);- expect(tag).not.toBeNull();- // companies → first candidate is 'hiring'; the tag containing 'hiring' wins.- expect(tag!.bias_tag).toBe('over-confident-hiring');- });-});--// ─── buildBiasContextString ─────────────────────────────────────────--describe('buildBiasContextString', () => {- test('emits tag name + verdict + severity + Brier', () => {- const finding = buildFinding('wiki/companies/acme', 'wiki/companies/widget');- const profile = buildProfile(['over-confident-hiring'], 0.31);- const ctx = buildBiasContextString('over-confident-hiring', finding, profile);- expect(ctx).toContain('over-confident-hiring');- expect(ctx).toContain('contradiction'); // verdict- expect(ctx).toContain('medium'); // severity- expect(ctx).toContain('Brier 0.31');- });-- test('omits Brier when null', () => {- const finding = buildFinding('wiki/companies/acme', 'wiki/companies/widget');- const profile = buildProfile(['over-confident-hiring'], null);- const ctx = buildBiasContextString('over-confident-hiring', finding, profile);- expect(ctx).not.toContain('Brier null');- expect(ctx).not.toContain('Brier NaN');- });-});diff --git a/test/eval-schema-authoring.test.ts b/test/eval-schema-authoring.test.tsdeleted file mode 100644index 6b9034fae6..0000000000--- a/test/eval-schema-authoring.test.ts+++ /dev/null@@ -1,94 +0,0 @@-// v0.39 T16 — aggregator unit test.-// Pins the pass-criterion codex finding #9 demanded: filing accuracy-// delta is the gate, NOT manifest correctness.-//-// E4 (v0.48.4.0) added the runner contract: until the fixture-brain harness-// lands, running the eval must read as an honest not-implemented verdict-// (#4198 shape), never as a pass or a data-bearing inconclusive.--import { describe, test, expect, spyOn } from 'bun:test';-import {- aggregateVerdict,- parseArgs,- runEvalSchemaAuthoring,- runEvalSchemaAuthoringCli,-} from '../src/commands/eval-schema-authoring.ts';--describe('v0.39 T16 — eval-schema-authoring aggregator', () => {- test('pass when baseline already high + no suggestions needed', () => {- const v = aggregateVerdict(0.95, 0.95, 0, 0);- expect(v.verdict).toBe('pass');- });-- test('pass when filing accuracy improves >=10pp', () => {- const v = aggregateVerdict(0.4, 0.6, 5, 1);- expect(v.verdict).toBe('pass');- expect(v.delta).toBeCloseTo(0.2, 2);- });-- test('inconclusive when delta improvement is <10pp', () => {- const v = aggregateVerdict(0.6, 0.65, 3, 0);- expect(v.verdict).toBe('inconclusive');- });-- test('inconclusive when baseline is low but no suggestions returned', () => {- const v = aggregateVerdict(0.4, 0.4, 0, 0);- expect(v.verdict).toBe('inconclusive');- });-- test('fail when filing accuracy regresses', () => {- const v = aggregateVerdict(0.7, 0.55, 5, 3);- expect(v.verdict).toBe('fail');- expect(v.reasoning).toContain('REGRESSED');- });-- test('parseArgs --fixture + --source + --json', () => {- const a = parseArgs(['--fixture', '/tmp/brain', '--source', 'dept-x', '--json']);- expect(a.fixture).toBe('/tmp/brain');- expect(a.source).toBe('dept-x');- expect(a.json).toBe(true);- });-- test('parseArgs accepts --source-id alias', () => {- const a = parseArgs(['--source-id', 'alt']);- expect(a.source).toBe('alt');- });-});--describe('E4 — eval-schema-authoring runner is an honest not-implemented scaffold (#4198 shape)', () => {- test('runEvalSchemaAuthoring never reads as a pass for work it did not run', async () => {- const r = await runEvalSchemaAuthoring([]);- expect(r.schema_version).toBe(1);- expect(r.ok).toBe(false);- expect(r.status).toBe('not_implemented');- expect(r.details.fixture).toBeNull();- expect(r.details.planned).toBeDefined();- });-- test('records --fixture / --source in details without evaluating', async () => {- const r = await runEvalSchemaAuthoring(['--fixture', '/tmp/brain', '--source', 'dept-x']);- expect(r.ok).toBe(false);- expect(r.status).toBe('not_implemented');- expect(r.details.fixture).toBe('/tmp/brain');- expect(r.details.source).toBe('dept-x');- });-- test('CLI entry exits 1 for the scaffold (json + human) and 0 only for --help', async () => {- const log = spyOn(console, 'log').mockImplementation(() => {});- const err = spyOn(console, 'error').mockImplementation(() => {});- try {- expect(await runEvalSchemaAuthoringCli(['--json'])).toBe(1);- const payload = JSON.parse(String(log.mock.calls.at(-1)?.[0]));- expect(payload.ok).toBe(false);- expect(payload.status).toBe('not_implemented');-- expect(await runEvalSchemaAuthoringCli([])).toBe(1);- expect(err.mock.calls.some((c) => String(c[0]).includes('NOT_IMPLEMENTED'))).toBe(true);-- expect(await runEvalSchemaAuthoringCli(['--help'])).toBe(0);- } finally {- log.mockRestore();- err.mockRestore();- }- });-});diff --git a/test/eval-v041_2-scaffolds.test.ts b/test/eval-v041_2-scaffolds.test.tsindex 216e2afc1c..0c9dc6c6fd 100644--- a/test/eval-v041_2-scaffolds.test.ts+++ b/test/eval-v041_2-scaffolds.test.ts@@ -6,9 +6,7 @@// ran and were deleted by E4 — an eval surface that reads "pass" without// evaluating anything corrodes every other receipt. synthesize-concepts is// the one that stayed: dispatched (#4198) with an honest-// {ok:false, status:'not_implemented'} envelope, pinned here. The-// eval-schema-authoring runner's matching envelope is pinned next to its real-// aggregator in test/eval-schema-authoring.test.ts.+// {ok:false, status:'not_implemented'} envelope, pinned here.import { describe, test, expect } from 'bun:test';import { runEvalSynthesizeConcepts } from '../src/commands/eval-synthesize-concepts.ts';diff --git a/test/eval-whoknows.test.ts b/test/eval-whoknows.test.tsindex b7eb5cbbe2..54dc4bf703 100644--- a/test/eval-whoknows.test.ts+++ b/test/eval-whoknows.test.ts@@ -172,12 +172,6 @@ describe('eval-whoknows / thresholds', () => {// These tests pin the type-level contract and the export presence; full// thin-client routing E2E is in the engine-required integration suite.describe('eval-whoknows / WhoknowsFn contract', () => {- it('module exports WhoknowsFn type alias', async () => {- // The type is structurally `(topic: string, limit: number) => Promise<WhoknowsResult[]>`.- // Confirm import resolves without throwing.- const mod = await import('../src/commands/eval-whoknows.ts');- expect(typeof mod.runEvalWhoknows).toBe('function');- });it('runEvalWhoknows accepts null engine (thin-client signature)', async () => {// Signature gate: the function must be callable with engine=null. We usediff --git a/test/extract-conversation-facts-diagnostics.serial.test.ts b/test/extract-conversation-facts-diagnostics.serial.test.tsindex 980051e0c7..16107f1d39 100644--- a/test/extract-conversation-facts-diagnostics.serial.test.ts+++ b/test/extract-conversation-facts-diagnostics.serial.test.ts@@ -2,29 +2,38 @@ import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { __setChatTransportForTests, __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import * as concurrency from '../src/core/sync-concurrency.ts';-import { runExtractConversationFacts, runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';+import { extractConversationFactsLockId, runExtractConversationFacts, runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';+import type { BrainEngine } from '../src/core/engine.ts';import { runPhaseConversationFactsBackfill } from '../src/core/cycle/conversation-facts-backfill.ts';let engine: PGLiteEngine;let calls = 0;let active = 0;let maxActive = 0;+let chatText = '{"facts":[]}';+let embedVectors = false;+let onChat: (() => Promise<void>) | null = null;+const GATEWAY = { chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' } };const body = "{'source': 'microphone', 'attribution': 'me'}: hello\n{'name': 'alice-example', 'attribution': 'them', 'source': 'speaker'}: hi";beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();- configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' } });+ configureGateway(GATEWAY);__setChatTransportForTests(async () => {calls++;+ if (onChat) await onChat();active++;maxActive = Math.max(maxActive, active);await Bun.sleep(100);active--;- return { text: '{"facts":[]}', blocks: [], stopReason: 'end', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'stub', providerId: 'stub' };+ return { text: chatText, blocks: [], stopReason: 'end', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'stub', providerId: 'stub' };});- __setEmbedTransportForTests((async () => { throw new Error('unexpected embedding call'); }) as never);+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ if (!embedVectors) throw new Error('unexpected embedding call');+ return { embeddings: values.map(() => Array.from({ length: 1536 }, () => 0.1)) };+ }) as never);});afterAll(async () => {@@ -38,7 +47,11 @@ beforeEach(async () => {calls = 0;active = 0;maxActive = 0;+ chatText = '{"facts":[]}';+ embedVectors = false;+ onChat = null;await engine.executeRaw('TRUNCATE facts, pages, op_checkpoints, extract_rollup_7d CASCADE');+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks');await engine.setConfig('facts.extraction_enabled', 'true');await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'true');@@ -130,4 +143,110 @@ describe('#5364 diagnostics across workers, sources, CLI, and cycle', () => {expect(second.details).toMatchObject({ pages_processed: 0, pages_skipped: 2, pages_skipped_unparsed: 2, pages_skipped_insufficient_turns: 0, pages_skipped_completed: 6, pages_skipped_non_extractable: 2, pages_marked_non_extractable: 0 });expect(calls).toBe(6);});++ // The dimension preflight and the Minion job path only run for Postgres+ // engines; this view reports that kind over the same PGLite database.+ function asPostgres(e: PGLiteEngine): BrainEngine {+ return new Proxy(e, { get: (t, k) => (k === 'kind' ? 'postgres' : Reflect.get(t, k, t)) }) as unknown as BrainEngine;+ }++ test('a page locked by another worker is skipped and counted; the CLI exits 3; release lets it run', async () => {+ const slug = 'conversations/object-1';+ await engine.executeRaw(+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at)+ VALUES ($1, 99999, 'other-host', NOW(), NOW() + INTERVAL '10 minutes')`,+ [extractConversationFactsLockId('speaker-a', slug)],+ );+ const held = await runExtractConversationFactsCore(engine, { sourceId: 'speaker-a', types: ['conversation'], sleepMs: 0 });+ expect(held).toMatchObject({ pages_lock_skipped: 1, pages_processed: 2 });+ expect(calls).toBe(2);+ // Page locks are per source: the same slug in another source is free.+ const otherSource = await runExtractConversationFactsCore(engine, { sourceId: 'speaker-b', types: ['conversation'], sleepMs: 0 });+ expect(otherSource).toMatchObject({ pages_lock_skipped: 0, pages_processed: 3 });+ calls = 2;++ const log = spyOn(console, 'log').mockImplementation(() => {});+ const exit = spyOn(process, 'exit').mockImplementation(((code: number) => { throw new Error(`exit:${code}`); }) as never);+ try {+ await expect(runExtractConversationFacts(engine, ['--source-id', 'speaker-a', '--types', 'conversation', '--sleep', '0'])).rejects.toThrow('exit:3');+ expect(log.mock.calls.map(call => call.join(' ')).join('\n')).toContain('Skipped 1 page(s) held by another worker');+ } finally {+ exit.mockRestore();+ log.mockRestore();+ }+ expect(calls).toBe(2);++ await engine.executeRaw('DELETE FROM gbrain_cycle_locks');+ // While a page is being extracted its lock expires within minutes, so a+ // crashed worker's page is reclaimable quickly (D12).+ let ttlSeconds: number | null = null;+ onChat = async () => {+ const [row] = await engine.executeRaw<{ s: number }>(+ `SELECT EXTRACT(EPOCH FROM (ttl_expires_at - NOW()))::float AS s FROM gbrain_cycle_locks WHERE id = $1`,+ [extractConversationFactsLockId('speaker-a', slug)],+ );+ ttlSeconds = row?.s ?? null;+ };+ const released = await runExtractConversationFactsCore(engine, { sourceId: 'speaker-a', types: ['conversation'], sleepMs: 0 });+ expect(released).toMatchObject({ pages_lock_skipped: 0, pages_processed: 1 });+ expect(calls).toBe(3);+ expect(ttlSeconds).not.toBeNull();+ expect(ttlSeconds!).toBeGreaterThan(30);+ expect(ttlSeconds!).toBeLessThanOrEqual(10 * 60);+ });++ test('replay deletes a prior partial run\'s facts before extracting, keeping the new ones (D11)', async () => {+ chatText = JSON.stringify({ facts: [{ fact: 'alice-example said hi', kind: 'event', entity: 'people/alice-example', confidence: 1, notability: 'high' }] });+ embedVectors = true;+ const slug = 'conversations/object-1';+ await engine.executeRaw(+ `INSERT INTO facts (source_id, fact, kind, source, source_session, source_markdown_slug, visibility, notability, confidence)+ VALUES ('speaker-a', 'stale partial-run fact', 'event', 'cli:extract-conversation-facts', $1, $2, 'private', 'high', 1)`,+ [`cli:extract-conversation-facts:${slug}`, slug],+ );+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'speaker-a', slug, sleepMs: 0 });+ expect(result.orphan_facts_cleaned).toBe(1);+ expect(result.facts_inserted).toBeGreaterThan(0);+ const rows = await engine.executeRaw<{ fact: string }>(+ `SELECT fact FROM facts WHERE source_id = 'speaker-a' AND source_markdown_slug = $1 AND source = 'cli:extract-conversation-facts'`,+ [slug],+ );+ expect(rows.map(r => r.fact)).not.toContain('stale partial-run fact');+ expect(rows).toHaveLength(result.facts_inserted);+ });++ test('embedding-width drift fails the run before any page is attempted (D15 preflight)', async () => {+ configureGateway({ ...GATEWAY, embedding_dimensions: 1024 });+ const err = spyOn(process.stderr, 'write').mockImplementation(() => true);+ try {+ await expect(runExtractConversationFactsCore(asPostgres(engine), { sourceId: 'speaker-a', types: ['conversation'], sleepMs: 0 })).rejects.toThrow(/halfvec\(1536\).*1024/);+ const stderr = err.mock.calls.map(c => String(c[0])).join('');+ expect(stderr).not.toContain('conversations/');+ expect(calls).toBe(0);+ } finally {+ err.mockRestore();+ configureGateway(GATEWAY);+ }+ });++ test('--workers reaches the worker resolver and the --background job envelope', async () => {+ const resolve = spyOn(concurrency, 'resolveWorkersWithClamp');+ const log = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await runExtractConversationFacts(engine, ['--source-id', 'speaker-a', '--types', 'conversation', '--sleep', '0', '--workers', '5']);+ expect(resolve.mock.calls[0]?.[1]).toBe(5);+ } finally {+ log.mockRestore();+ resolve.mockRestore();+ }+ const out = spyOn(process.stdout, 'write').mockImplementation(() => true);+ try {+ await runExtractConversationFacts(asPostgres(engine), ['--background', '--source-id', 'speaker-a', '--workers', '20']);+ } finally {+ out.mockRestore();+ }+ const [job] = await engine.executeRaw<{ data: any }>(`SELECT data FROM minion_jobs WHERE name = 'extract-conversation-facts' ORDER BY id DESC LIMIT 1`);+ const data = typeof job!.data === 'string' ? JSON.parse(job!.data) : job!.data;+ expect(data.workers).toBe(20);+ });});diff --git a/test/extract-conversation-facts-workers.test.ts b/test/extract-conversation-facts-workers.test.tsdeleted file mode 100644index d775551480..0000000000--- a/test/extract-conversation-facts-workers.test.ts+++ /dev/null@@ -1,172 +0,0 @@-/**- * Hermetic unit + structural tests for the extract-conversation-facts- * `--workers N` wiring (v0.41.15.0, T5).- *- * What this file pins:- * - parseArgs accepts `--workers N` and routes through parseWorkers- * (rejects 0, negatives, non-integers).- * - parseArgs accepts the alias `--concurrency N`.- * - buildJobParams threads `workers` into the Minion job envelope- * (round-trip via `gbrain extract-conversation-facts --background- * --workers 20`).- * - The exported helpers (`extractConversationFactsLockId`,- * `cpMapToEntries`-shape via the public API) match the load-bearing- * contracts D2 / D11 / D6 rely on.- * - Source-grep structural assertions on the production file: workers- * is threaded through, runSlidingPool is wired in, withRefreshingLock- * wraps each page, delete-orphans-first is called, preflight fires- * at startup, lock-busy is caught + counted + skipped, exit 3 path- * exists.- *- * End-to-end behavioral test (workers=3 on a seeded PGLite brain with- * stubbed LLM extractor + cross-process safety simulation) is filed as- * `test/extract-conversation-facts-workers.serial.test.ts` because it- * uses `mock.module` for the gateway stub. This file lives in the- * parallel fast loop per the test-isolation lint.- */--import { describe, test, expect, beforeEach } from 'bun:test';-import { readFileSync } from 'fs';-import { resolve } from 'path';-import {- extractConversationFactsLockId,- PER_PAGE_LOCK_TTL_MINUTES,- _resetLockBusyLogCacheForTest,-} from '../src/commands/extract-conversation-facts.ts';--const REPO_ROOT = resolve(import.meta.dir, '..');-const SRC_PATH = resolve(REPO_ROOT, 'src/commands/extract-conversation-facts.ts');-const SRC = readFileSync(SRC_PATH, 'utf-8');--beforeEach(() => {- _resetLockBusyLogCacheForTest();-});--describe('extract-conversation-facts — exported helpers (T5)', () => {- test('extractConversationFactsLockId composes source + slug', () => {- expect(extractConversationFactsLockId('default', 'chat/alice')).toBe(- 'extract-conversation-facts:default:chat/alice',- );- expect(extractConversationFactsLockId('media', 'imessage/2024-01')).toBe(- 'extract-conversation-facts:media:imessage/2024-01',- );- });-- test('lock id differs across sources for the same slug', () => {- // Cross-source isolation — the lock primitive must prevent- // double-claim WITHIN a source but allow parallel work ACROSS- // sources. Two sources with the same slug get different lock ids.- const a = extractConversationFactsLockId('dept-a', 'chat/team');- const b = extractConversationFactsLockId('dept-b', 'chat/team');- expect(a).not.toBe(b);- });-- test('PER_PAGE_LOCK_TTL_MINUTES is short enough that holder-death recovers within ~2min', () => {- // The TTL governs how long a dead worker's lock blocks the next- // attempt. 2 minutes balances "long enough for a real page to- // finish" against "short enough that a crash isn't a 30min stall."- // The plan's D12 spec calls for ~10s refresh; with TTL=2min,- // withRefreshingLock fires at max(15s, 120s/6) = 20s, well under.- expect(PER_PAGE_LOCK_TTL_MINUTES).toBeGreaterThanOrEqual(1);- expect(PER_PAGE_LOCK_TTL_MINUTES).toBeLessThanOrEqual(10);- });-});--describe('extract-conversation-facts — structural contracts (T5)', () => {- test('imports runSlidingPool from worker-pool helper', () => {- expect(SRC).toMatch(- /import\s*\{\s*runSlidingPool\s*\}\s*from\s*['"]\.\.\/core\/worker-pool\.ts['"]/,- );- });-- test('imports parseWorkers + resolveWorkersWithClamp from sync-concurrency', () => {- expect(SRC).toMatch(/parseWorkers,\s*resolveWorkersWithClamp/);- expect(SRC).toMatch(/from\s*['"]\.\.\/core\/sync-concurrency\.ts['"]/);- });-- test('imports withRefreshingLock + LockUnavailableError from db-lock', () => {- expect(SRC).toMatch(- /import\s*\{\s*withRefreshingLock,\s*LockUnavailableError\s*\}\s*from\s*['"]\.\.\/core\/db-lock\.ts['"]/,- );- });-- test('imports assertFactsEmbeddingDimMatchesConfig (D15 preflight)', () => {- expect(SRC).toMatch(- /import\s*\{\s*assertFactsEmbeddingDimMatchesConfig\s*\}\s*from\s*['"]\.\.\/core\/embedding-dim-check\.ts['"]/,- );- });-- test('runExtractConversationFactsCore calls resolveWorkersWithClamp', () => {- expect(SRC).toMatch(/resolveWorkersWithClamp\(/);- });-- test('preflight fires inside runExtractConversationFactsCore body, BEFORE work loop', () => {- // Locate the preflight call and the workers resolution; preflight- // must appear before the worker-pool fanout so dim drift surfaces- // before any LLM spend.- const preflightIdx = SRC.indexOf('assertFactsEmbeddingDimMatchesConfig(engine)');- const poolCallIdx = SRC.indexOf('runSlidingPool(');- expect(preflightIdx).toBeGreaterThan(0);- expect(poolCallIdx).toBeGreaterThan(0);- expect(preflightIdx).toBeLessThan(poolCallIdx);- });-- test('per-page work wrapped in withRefreshingLock (D2 + D12)', () => {- expect(SRC).toMatch(/withRefreshingLock\(\s*engine,\s*lockId/);- expect(SRC).toMatch(/ttlMinutes:\s*PER_PAGE_LOCK_TTL_MINUTES/);- });-- test('LockUnavailableError caught + pages_lock_skipped incremented (D6)', () => {- // Both halves of the lock-busy contract.- expect(SRC).toMatch(/instanceof\s+LockUnavailableError/);- expect(SRC).toMatch(/pages_lock_skipped\+\+/);- });-- test('delete-orphans-first called BEFORE segment extraction (D11)', () => {- expect(SRC).toMatch(/deleteOrphanFactsForPage\(/);- // Positional check: the delete-orphans call must appear before the- // segment for-loop. Easier to assert that orphan_facts_cleaned is- // bumped before the segment loop begins.- const cleanedBumpIdx = SRC.indexOf('orphan_facts_cleaned +=');- const segmentLoopIdx = SRC.indexOf('for (const seg of segments)');- expect(cleanedBumpIdx).toBeGreaterThan(0);- expect(segmentLoopIdx).toBeGreaterThan(0);- expect(cleanedBumpIdx).toBeLessThan(segmentLoopIdx);- });-- test('exit 3 fires when lock-busy pages remain (codex #3)', () => {- expect(SRC).toMatch(- /pages_lock_skipped\s*>\s*0[\s\S]{0,200}process\.exit\(3\)/,- );- });-- test('parsedArgs.workers threaded into core opts', () => {- expect(SRC).toMatch(/workers:\s*parsed\.workers/);- });-- test('Minion job envelope includes workers (D9 round-trip)', () => {- expect(SRC).toMatch(/workers:\s*parsed\.workers/);- // buildJobParams shape — there should be a `workers` field in the- // returned object literal.- const bjpRegion = SRC.slice(SRC.indexOf('function buildJobParams'));- expect(bjpRegion).toMatch(/workers:\s*parsed\.workers/);- });-});--describe('extract-conversation-facts — Result type carries new counters', () => {- test('ExtractConversationFactsResult has pages_lock_skipped + orphan_facts_cleaned', () => {- // Source-level shape check (the type is exported but bun:test- // doesn't introspect types at runtime; a grep is honest).- expect(SRC).toMatch(/pages_lock_skipped:\s*number/);- expect(SRC).toMatch(/orphan_facts_cleaned:\s*number/);- });-- test('initial result object literal initializes both counters to 0', () => {- // Both call sites (core init + CLI aggregate init) must initialize- // the new counters or the aggregator will produce NaN under +=.- const initOccurrences = SRC.match(/pages_lock_skipped:\s*0/g) ?? [];- expect(initOccurrences.length).toBeGreaterThanOrEqual(2);- const cleanedOccurrences = SRC.match(/orphan_facts_cleaned:\s*0/g) ?? [];- expect(cleanedOccurrences.length).toBeGreaterThanOrEqual(2);- });-});diff --git a/test/extract-include-frontmatter-config.serial.test.ts b/test/extract-include-frontmatter-config.serial.test.tsindex 50bbb55eb6..ce8a8c310e 100644--- a/test/extract-include-frontmatter-config.serial.test.ts+++ b/test/extract-include-frontmatter-config.serial.test.ts@@ -113,7 +113,7 @@ describe('resolveIncludeFrontmatter', () => {*/describe('no extraction path hardcodes includeFrontmatter', () => {test('call sites do not literalise false; the shared helpers resolve the default', () => {- // test-reads-source-ok: the bug is a literal at the call sites; only a source-text pin can see it come back.+ // test-reads-source-ok[structural]: the bug is a literal at the call sites; only a source-text pin can see it come back.const read = (rel: string) => readFileSync(new URL(`../${rel}`, import.meta.url), 'utf-8');for (const rel of ['src/commands/jobs.ts', 'src/commands/maintain.ts', 'src/core/cycle.ts']) {expect(read(rel)).not.toMatch(/includeFrontmatter:\s*false/);diff --git a/test/extract-stale.test.ts b/test/extract-stale.test.tsindex 48c6b99bca..dc8facd0ab 100644--- a/test/extract-stale.test.ts+++ b/test/extract-stale.test.ts@@ -96,8 +96,10 @@ describe('engine: stale-page extraction methods', () => {});test('markPagesExtractedBatch: empty input is a no-op', async () => {+ await engine.putPage('people/alice', personPage('Alice'));await engine.markPagesExtractedBatch([], new Date().toISOString());- expect(true).toBe(true); // no throw+ expect(await stampOf('people/alice')).toBeNull();+ expect(await engine.countStalePagesForExtraction()).toBe(1);});});diff --git a/test/extract-timeline-attendance.test.ts b/test/extract-timeline-attendance.test.tsindex ba65234836..8161eee84b 100644--- a/test/extract-timeline-attendance.test.ts+++ b/test/extract-timeline-attendance.test.ts@@ -6,11 +6,12 @@ import { prepareAutomaticLinks } from '../src/core/persistence/links-preparationimport { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { resetPgliteState, resetPgliteStateNarrow } from './helpers/reset-pglite.ts';import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';const person = 'people/alice-example';const meeting = 'meetings/planning';-for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]) {+for (const kind of testBackends()) {describe(`meeting timeline attendance roles (${kind})`, () => {let engine: BrainEngine;let close: (() => Promise<void>) | undefined;diff --git a/test/extract-workers.test.ts b/test/extract-workers.test.tsindex 7572cb466c..a712294e70 100644--- a/test/extract-workers.test.ts+++ b/test/extract-workers.test.ts@@ -1,95 +1,110 @@/**- * Structural test for `gbrain extract --workers N` wiring (v0.41.15.0, T7).+ * `gbrain extract --workers N` (v0.41.15.0, T7): the flag is validated at the+ * CLI, threads into runExtractCore, and fans the per-page work out over N+ * concurrent workers on engines that allow parallel writes.*- * Per codex #16/#17 the high-value assertion for a CPU-bound migration- * is that the helper is wired in, not byte-equality. extract is CPU-- * bound (markdown parse + regex), so the speedup is moderate; the- * primary contract is "API surface exists + threads correctly +- * existing serial behavior preserved when --workers is omitted."+ * Concurrency is observed at the engine boundary: a proxy reports the engine+ * as Postgres (so the PGLite single-writer clamp does not apply) and counts+ * the peak number of in-flight per-page `readPageSnapshot` calls. Meeting+ * pages take the snapshot path on both the incremental (slugs) and the+ * directory-walk link loops.*/-import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'fs';-import { resolve } from 'path';+import { describe, test, expect, beforeAll, afterAll, spyOn } from 'bun:test';+import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runExtract, runExtractCore } from '../src/commands/extract.ts';+import type { BrainEngine } from '../src/core/engine.ts';-const REPO_ROOT = resolve(import.meta.dir, '..');-const EXTRACT_SRC = readFileSync(- resolve(REPO_ROOT, 'src/commands/extract.ts'),- 'utf-8',-);+const PAGES = 8;+let engine: PGLiteEngine;+let brainDir: string;+const slugs: string[] = [];-describe('extract.ts → workers wiring (T7)', () => {- test('imports runSlidingPool from worker-pool helper', () => {- expect(EXTRACT_SRC).toMatch(- /import\s*\{\s*runSlidingPool\s*\}\s*from\s*['"]\.\.\/core\/worker-pool\.ts['"]/,- );- });-- test('imports parseWorkers + resolveWorkersWithClamp', () => {- expect(EXTRACT_SRC).toMatch(- /parseWorkers,\s*resolveWorkersWithClamp/,- );- });-- test('ExtractOpts type carries optional workers field', () => {- expect(EXTRACT_SRC).toMatch(/workers\?:\s*number/);- });-- test('runExtractCore resolves workers via the PGLite-clamp wrapper', () => {- expect(EXTRACT_SRC).toMatch(/resolveWorkersWithClamp\(\s*engine,\s*opts\.workers/);- });-- test('CLI runExtract parses --workers via parseWorkers (loud-fail on invalid)', () => {- // The parsed value must come from parseWorkers (validates >=1- // integer) AND must thread into runExtractCore opts.- expect(EXTRACT_SRC).toMatch(/parseWorkers\(args\[/);- expect(EXTRACT_SRC).toMatch(/workers,?\s*\}\);/);- });+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ brainDir = mkdtempSync(join(tmpdir(), 'gbrain-extract-workers-'));+ mkdirSync(join(brainDir, 'meetings'), { recursive: true });+ for (let i = 0; i < PAGES; i++) {+ const slug = `meetings/m${i}`;+ slugs.push(slug);+ await engine.putPage(slug, { type: 'meeting', title: `M${i}`, compiled_truth: '', timeline: '' });+ writeFileSync(join(brainDir, `${slug}.md`), `---\ntitle: M${i}\ntype: meeting\n---\n\nFollow-up: [M](../meetings/m${(i + 1) % PAGES}.md)\n`);+ }+}, 60_000);- test('all three inner loops accept the workers parameter', () => {- // extractForSlugs, extractLinksFromDir, extractTimelineFromDir all- // receive workers (default 1 for back-compat).- expect(EXTRACT_SRC).toMatch(/extractForSlugs[\s\S]*?workers:\s*number/);- expect(EXTRACT_SRC).toMatch(/extractLinksFromDir[\s\S]*?workers:\s*number/);- expect(EXTRACT_SRC).toMatch(/extractTimelineFromDir[\s\S]*?workers:\s*number/);- });+afterAll(async () => {+ await engine.disconnect();+ rmSync(brainDir, { recursive: true, force: true });+});- test('all three inner loops call runSlidingPool', () => {- // 3 inner loops × 1 runSlidingPool call each = 3 occurrences total- // (extract.ts has no other runSlidingPool callers).- const calls = EXTRACT_SRC.match(/runSlidingPool\(/g) ?? [];- expect(calls.length).toBe(3);+function parallelEngine(): { engine: BrainEngine; peak: () => number } {+ let inflight = 0;+ let peak = 0;+ const proxy = new Proxy(engine, {+ get(target, prop) {+ if (prop === 'kind') return 'postgres';+ const value = Reflect.get(target, prop, target);+ if (typeof value !== 'function') return value;+ if (prop !== 'readPageSnapshot') return value.bind(target);+ return async (...args: unknown[]) => {+ inflight++;+ peak = Math.max(peak, inflight);+ try {+ await new Promise(r => setTimeout(r, 5));+ return await value.apply(target, args);+ } finally {+ inflight--;+ }+ };+ },});+ return { engine: proxy as unknown as BrainEngine, peak: () => peak };+}- test('legacy `for (let i = 0; i < files.length; i++)` per-file loops are gone', () => {- // The pre-T7 serial loops would fight the worker-pool semantics.- // After migration only one such loop may remain (acceptable: the- // dir-walker itself which isn't per-file work). We assert <= 1.- const serialLoops = EXTRACT_SRC.match(/for\s*\(\s*let\s+i\s*=\s*0;\s*i\s*<\s*files\.length/g) ?? [];- expect(serialLoops.length).toBeLessThanOrEqual(1);- });+describe('extract --workers', () => {+ for (const [label, extra] of [['incremental slugs', { slugs }], ['directory walk', {}]] as const) {+ test(`${label}: workers=4 runs pages concurrently, workers=1 runs them one at a time`, async () => {+ for (const [workers, expectPeak] of [[1, 1], [4, 4]] as const) {+ const probe = parallelEngine();+ const result = await runExtractCore(probe.engine, { mode: 'links', dir: brainDir, workers, quiet: true, ...extra });+ expect(result.pages_processed).toBe(PAGES);+ expect(probe.peak(), `workers=${workers}`).toBe(expectPeak);+ }+ }, 30_000);+ }- test('extractForSlugs (the CLI/cycle path) is migrated to the pool', () => {- // Two legacy `for (const slug of slugs)` loops survive in- // extractLinksForSlugs + extractTimelineForSlugs — the sync-integration- // hooks. Those are out of T7 scope (called from sync.ts post-sync, not- // from the user-facing `gbrain extract` CLI). T7 covers extractForSlugs- // + extractLinksFromDir + extractTimelineFromDir which carry --workers- // from the CLI surface.- const legacyCount = (EXTRACT_SRC.match(/for\s*\(\s*const\s+slug\s+of\s+slugs\)/g) ?? []).length;- expect(legacyCount).toBeLessThanOrEqual(2);- // The migrated extractForSlugs uses runSlidingPool over `slugs`, not- // a for-of loop. Confirm by checking that one of the 3 runSlidingPool- // call sites operates on `slugs`.- expect(EXTRACT_SRC).toMatch(/runSlidingPool\(\s*\{\s*items:\s*slugs/);+ test('the CLI rejects a non-positive --workers value and exits 1', async () => {+ const errors: string[] = [];+ const err = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errors.push(a.map(String).join(' ')); });+ const exit = spyOn(process, 'exit').mockImplementation(((code?: number) => { throw new Error(`__exit_${code}__`); }) as never);+ try {+ for (const flag of ['--workers', '--concurrency']) {+ await expect(runExtract(engine, ['links', '--dir', brainDir, flag, '0'])).rejects.toThrow('__exit_1__');+ }+ } finally {+ err.mockRestore();+ exit.mockRestore();+ }+ expect(errors.filter(e => e.includes('--workers must be a positive integer'))).toHaveLength(2);});- test('CLI threads workers into runExtractCore call', () => {- // The opts-object passed to runExtractCore must include the workers- // field; without this the parsed CLI flag would silently drop on- // the FS-source happy path.- expect(EXTRACT_SRC).toMatch(- /runExtractCore\(engine,\s*\{[\s\S]*?workers,[\s\S]*?\}\)/,- );+ test('the CLI threads --workers and --concurrency into the core (PGLite clamps them to 1 and says so)', async () => {+ const errors: string[] = [];+ const err = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errors.push(a.map(String).join(' ')); });+ const log = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await runExtract(engine, ['links', '--dir', brainDir, '--workers', '7']);+ await runExtract(engine, ['links', '--dir', brainDir, '--concurrency', '9']);+ } finally {+ err.mockRestore();+ log.mockRestore();+ }+ expect(errors.some(e => e.includes('workers=7 requested, clamped to 1 on PGLite'))).toBe(true);+ expect(errors.some(e => e.includes('workers=9 requested, clamped to 1 on PGLite'))).toBe(true);});});diff --git a/test/extract.test.ts b/test/extract.test.tsindex 068f0ce84e..19e95dee91 100644--- a/test/extract.test.ts+++ b/test/extract.test.ts@@ -3,7 +3,6 @@ import {extractMarkdownLinks,extractLinksFromFile,extractTimelineFromContent,- walkMarkdownFiles,} from '../src/commands/extract.ts';describe('extractMarkdownLinks', () => {@@ -348,12 +347,6 @@ Real claim. [Source: memo, 2025-01-02]`;});});-describe('walkMarkdownFiles', () => {- it('is a function', () => {- expect(typeof walkMarkdownFiles).toBe('function');- });-});-describe('extractLinksFromFile — slug normalization (T-OBS-1 regression)', () => {// Regression coverage for the bug where CAPS-named files (ETHOS.md, AGENTS.md)// generated CAPS slugs from `relPath.replace('.md', '')` while the DB storesdiff --git a/test/e2e/fact-backfill-resident.test.ts b/test/fact-backfill-resident.test.tssimilarity index 93%rename from test/e2e/fact-backfill-resident.test.tsrename to test/fact-backfill-resident.test.tsindex 6600e97f13..99f3f079d2 100644--- a/test/e2e/fact-backfill-resident.test.ts+++ b/test/fact-backfill-resident.test.ts@@ -1,17 +1,22 @@+/**+ * Lane: unit. Run: `bun test test/fact-backfill-resident.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".+ */import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { createHash } from 'node:crypto';import { once } from 'node:events';import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';-import { saveConfig, type GBrainConfig } from '../../src/core/config.ts';-import { createPersistenceIpcProvider } from '../../src/core/persistence/provider.ts';-import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';-import { readLocalWriter, registerLocalWriter, revokeLocalWriter, type LocalRegistration, type LocalGrant } from '../../src/core/persistence/identity.ts';-import { startPersistenceIpcServer, requestPersistenceAdministration, requestPersistenceCapabilities, persistenceSocketPathForConfig, type PersistenceIpcBinding } from '../../src/core/persistence/ipc.ts';-import { withEnv } from '../helpers/with-env.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { saveConfig, type GBrainConfig } from '../src/core/config.ts';+import { createPersistenceIpcProvider } from '../src/core/persistence/provider.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { readLocalWriter, registerLocalWriter, revokeLocalWriter, type LocalRegistration, type LocalGrant } from '../src/core/persistence/identity.ts';+import { startPersistenceIpcServer, requestPersistenceAdministration, requestPersistenceCapabilities, persistenceSocketPathForConfig, type PersistenceIpcBinding } from '../src/core/persistence/ipc.ts';+import { withEnv } from './helpers/with-env.ts';const sourceId = 'resident-facts-example';const foreignSource = 'resident-facts-foreign';@@ -184,7 +189,7 @@ describe('resident managed fact-vector repair', () => {test('the actual CLI delegates before opening the owner-held PGLite database', () => inHome(async () => {const run = async (extra: string[], expectedStatus = 0) => {- const child = Bun.spawn([process.execPath, join(import.meta.dir, '../../src/cli.ts'),+ const child = Bun.spawn([process.execPath, join(import.meta.dir, '../src/cli.ts'),'embed', '--stale', '--facts', '--source', sourceId, '--json', ...extra], {cwd: root, env: { ...process.env, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0' }, stdout: 'pipe', stderr: 'pipe',});diff --git a/test/facts-backstop-remedy-verb.test.ts b/test/facts-backstop-remedy-verb.test.tsindex 996b3cff80..f07920fa59 100644--- a/test/facts-backstop-remedy-verb.test.ts+++ b/test/facts-backstop-remedy-verb.test.ts@@ -13,10 +13,10 @@ import { readFileSync } from 'node:fs';import { join } from 'node:path';const REPO_ROOT = join(import.meta.dir, '..');-// test-reads-source-ok: comment-contract pin — the warning's remedy TEXT is+// test-reads-source-ok[prompt-byte]: comment-contract pin — the warning's remedy TEXT is// the product surface; cross-checked against the dispatcher's case labels.const backstopSrc = readFileSync(join(REPO_ROOT, 'src/core/facts/backstop.ts'), 'utf-8');-// test-reads-source-ok: same pin — dispatcher side of the cross-check above.+// test-reads-source-ok[prompt-byte]: same pin — dispatcher side of the cross-check above.const sourcesSrc = readFileSync(join(REPO_ROOT, 'src/commands/sources.ts'), 'utf-8');describe('facts backstop thin-client-fallback remedy verb (#4489)', () => {diff --git a/test/fail-improve.test.ts b/test/fail-improve.test.tsdeleted file mode 100644index 796139a3dd..0000000000--- a/test/fail-improve.test.ts+++ /dev/null@@ -1,234 +0,0 @@-import { describe, test, expect, beforeEach, afterAll } from 'bun:test';-import { FailImproveLoop } from '../src/core/fail-improve.ts';-import { mkdtempSync, rmSync, existsSync, readFileSync } from 'fs';-import { join } from 'path';-import { tmpdir } from 'os';--describe('fail-improve', () => {- let tempDir: string;- let loop: FailImproveLoop;-- beforeEach(() => {- tempDir = mkdtempSync(join(tmpdir(), 'gbrain-fail-improve-'));- loop = new FailImproveLoop(tempDir);- });-- afterAll(() => {- // Clean up temp dirs- try { rmSync(tempDir, { recursive: true, force: true }); } catch {}- });-- test('execute returns deterministic result when it succeeds', async () => {- const result = await loop.execute(- 'test_op',- 'hello',- (input) => input.toUpperCase(),- async () => 'llm-fallback',- );- expect(result).toBe('HELLO');- });-- test('execute falls back to LLM when deterministic returns null', async () => {- const result = await loop.execute(- 'test_op',- 'hello',- () => null,- async (input) => `llm: ${input}`,- );- expect(result).toBe('llm: hello');- });-- test('execute logs failure when deterministic returns null', async () => {- await loop.execute(- 'test_op',- 'test-input',- () => null,- async () => 'llm-result',- );-- const failures = loop.getFailures('test_op');- expect(failures.length).toBe(1);- expect(failures[0].deterministic_result).toBeNull();- expect(failures[0].llm_result).toContain('llm-result');- expect(failures[0].input).toBe('test-input');- });-- test('execute throws LLM error when both fail (cascade)', async () => {- try {- await loop.execute(- 'cascade_op',- 'input',- () => null,- async () => { throw new Error('LLM failed'); },- );- expect(true).toBe(false); // should not reach- } catch (e: any) {- expect(e.message).toBe('LLM failed');- }-- // Verify both failures are logged- const failures = loop.getFailures('cascade_op');- expect(failures.length).toBe(1);- expect(failures[0].llm_result).toContain('error: LLM failed');- expect(failures[0].metadata?.cascade_failure).toBe(true);- });-- test('logFailure creates JSONL file with valid entries', () => {- loop.logFailure({- timestamp: '2026-04-15T00:00:00Z',- operation: 'jsonl_test',- input: 'test input',- deterministic_result: null,- llm_result: 'llm output',- });-- const filePath = join(tempDir, 'jsonl_test.jsonl');- expect(existsSync(filePath)).toBe(true);- const content = readFileSync(filePath, 'utf-8');- const parsed = JSON.parse(content.trim());- expect(parsed.operation).toBe('jsonl_test');- });-- test('getFailures returns empty array for non-existent operation', () => {- const failures = loop.getFailures('nonexistent');- expect(failures).toEqual([]);- });-- test('getFailuresByPattern groups by input prefix', async () => {- const prefix = 'a]'.repeat(30); // 60 chars, only first 50 used as key- loop.logFailure({ timestamp: 't1', operation: 'group_test', input: prefix + ' suffix1', deterministic_result: null, llm_result: 'a' });- loop.logFailure({ timestamp: 't2', operation: 'group_test', input: prefix + ' suffix2', deterministic_result: null, llm_result: 'b' });- loop.logFailure({ timestamp: 't3', operation: 'group_test', input: 'different input entirely', deterministic_result: null, llm_result: 'c' });-- const patterns = loop.getFailuresByPattern('group_test');- expect(patterns.size).toBe(2); // same 50-char prefix groups together, "different" is separate- });-- test('analyzeFailures computes metrics', async () => {- // Run some executions- await loop.execute('metrics_op', 'a', () => 'det', async () => 'llm');- await loop.execute('metrics_op', 'b', () => null, async () => 'llm');- await loop.execute('metrics_op', 'c', () => 'det', async () => 'llm');-- const analysis = loop.analyzeFailures('metrics_op');- expect(analysis.operation).toBe('metrics_op');- expect(analysis.total_calls).toBe(3);- expect(analysis.deterministic_hits).toBe(2);- expect(analysis.deterministic_rate).toBeCloseTo(2 / 3, 2);- expect(analysis.total_failures).toBe(1); // one LLM fallback logged- });-- test('generateTestCases creates tests from successful LLM fallbacks', async () => {- await loop.execute('testgen_op', 'input-1', () => null, async () => 'expected-1');- await loop.execute('testgen_op', 'input-2', () => null, async () => 'expected-2');-- const cases = loop.generateTestCases('testgen_op');- expect(cases.length).toBe(2);- expect(cases[0].input).toBe('input-1');- expect(cases[0].source).toBe('fail-improve-loop');- });-- test('generateTestCases excludes cascade failures', async () => {- await loop.execute('excl_op', 'ok', () => null, async () => 'good');- try {- await loop.execute('excl_op', 'bad', () => null, async () => { throw new Error('boom'); });- } catch {}-- const cases = loop.generateTestCases('excl_op');- expect(cases.length).toBe(1); // only the successful fallback- });-- test('logImprovement records improvement history', () => {- loop.logImprovement('improve_op', 'Added regex for MRR format');- loop.logImprovement('improve_op', 'Added regex for ARR format');-- const analysis = loop.analyzeFailures('improve_op');- expect(analysis.total_improvements).toBe(2);- });-- test('input is truncated to 1000 chars in log entries', async () => {- const longInput = 'x'.repeat(5000);- await loop.execute('trunc_op', longInput, () => null, async () => 'result');-- const failures = loop.getFailures('trunc_op');- expect(failures[0].input.length).toBe(1000);- });-- // ---- AbortSignal threading (PR 2.5+ guarantees) ------ test('aborts before deterministic call when signal already aborted', async () => {- const controller = new AbortController();- controller.abort();- let detCalled = false;- let llmCalled = false;- await expect(loop.execute(- 'abort_early',- 'x',- () => { detCalled = true; return 'det'; },- async () => { llmCalled = true; return 'llm'; },- { signal: controller.signal },- )).rejects.toMatchObject({ name: 'AbortError' });- expect(detCalled).toBe(false);- expect(llmCalled).toBe(false);- });-- test('aborts between deterministic miss and LLM fallback', async () => {- const controller = new AbortController();- let llmCalled = false;- await expect(loop.execute(- 'abort_between',- 'x',- () => { controller.abort(); return null; },- async () => { llmCalled = true; return 'llm'; },- { signal: controller.signal },- )).rejects.toMatchObject({ name: 'AbortError' });- expect(llmCalled).toBe(false);- });-- test('forwards signal into deterministic + LLM callbacks', async () => {- const controller = new AbortController();- let seenDet: AbortSignal | undefined;- let seenLlm: AbortSignal | undefined;- await loop.execute(- 'fwd',- 'x',- (_i, s) => { seenDet = s; return null; },- async (_i, s) => { seenLlm = s; return 'ok'; },- { signal: controller.signal },- );- expect(seenDet).toBe(controller.signal);- expect(seenLlm).toBe(controller.signal);- });-- test('LLM AbortError propagates without logging a failure entry', async () => {- await expect(loop.execute(- 'abort_llm',- 'x',- () => null,- async () => {- const err = new Error('user aborted');- err.name = 'AbortError';- throw err;- },- )).rejects.toMatchObject({ name: 'AbortError' });- expect(loop.getFailures('abort_llm')).toEqual([]);- });-- test('log rotation keeps last 1000 entries', () => {- // Write 1010 entries- for (let i = 0; i < 1010; i++) {- loop.logFailure({- timestamp: `2026-04-15T00:00:${String(i).padStart(2, '0')}Z`,- operation: 'rotation_test',- input: `entry-${i}`,- deterministic_result: null,- llm_result: `result-${i}`,- });- }-- const failures = loop.getFailures('rotation_test');- expect(failures.length).toBeLessThanOrEqual(1000);- // Last entry should be preserved- expect(failures[failures.length - 1].input).toBe('entry-1009');- });-});diff --git a/test/features.test.ts b/test/features.test.tsindex 4bdac5831a..fd297e1ed3 100644--- a/test/features.test.ts+++ b/test/features.test.ts@@ -1,27 +1,13 @@-import { describe, it, expect } from 'bun:test';--// Test that features module exports correctly-describe('features command', () => {- it('exports runFeatures', async () => {- const mod = await import('../src/commands/features.ts');- expect(typeof mod.runFeatures).toBe('function');- });-- it('exports featuresTeaserForDoctor', async () => {- const mod = await import('../src/commands/features.ts');- expect(typeof mod.featuresTeaserForDoctor).toBe('function');- });-});--// Test the embedded recipe metadata-describe('recipe metadata', () => {- it('covers all 7 recipes', async () => {- // Import the module and check RECIPE_META via the scan behavior- // (RECIPE_META is not exported, but we can verify via features scan output)- const mod = await import('../src/commands/features.ts');- expect(mod.runFeatures).toBeDefined();- });-});+import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, spyOn } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { RECIPE_META, featuresTeaserForDoctor, runFeatures } from '../src/commands/features.ts';+import { VERSION } from '../src/version.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';// #2789: the x-to-brain secret name must be the one the resolver actually// reads. The recipe + RECIPE_META used to pin X_BEARER_TOKEN while the@@ -136,3 +122,188 @@ describe('CLI routing', () => {expect(cliSource).toContain('features [--json] [--auto-fix]');});});++// Behavioral coverage for `gbrain features --json`: every supported feature+// check fires in a fixture brain that has the gap and stays silent in one that+// does not. `dead-links` is not exercised: links.to_page_id cascades on page+// delete, so neither engine can report a dangling link (tracked in TODOS.md).+describe('runFeatures behavior', () => {+ let engine: PGLiteEngine;+ let root: string;+ let home: string;+ let gbrainHome: string;+ const dims = 1536;+ const secretEnv = Object.fromEntries(+ [...new Set(RECIPE_META.flatMap(r => r.secrets))].map(name => [name, undefined]),+ ) as Record<string, string | undefined>;++ beforeAll(async () => {+ resetGateway();+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: dims, env: { OPENAI_API_KEY: 'sk-test' } });+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });++ afterAll(async () => {+ await engine.disconnect();+ resetGateway();+ }, 30_000);++ beforeEach(async () => {+ await resetPgliteState(engine);+ root = mkdtempSync(join(tmpdir(), 'gbrain-features-'));+ home = join(root, 'home');+ gbrainHome = join(root, 'gbrain-home');+ mkdirSync(home, { recursive: true });+ mkdirSync(gbrainHome, { recursive: true });+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ const vector = () => { const v = new Float32Array(dims); v[0] = 1; return v; };++ async function seedPages(count: number) {+ for (let i = 0; i < count; i++) {+ await engine.putPage(`notes/feature-${i}`, { type: 'note', title: `Feature fixture ${i}`, compiled_truth: `Synthetic body ${i}.` });+ }+ }++ async function seedChunks(slug: string, embedded: boolean[]) {+ await engine.upsertChunks(slug, embedded.map((hasVector, i) => ({+ chunk_index: i,+ chunk_source: 'compiled_truth' as const,+ chunk_text: `Synthetic chunk ${i} for ${slug}.`,+ ...(hasVector ? { embedding: vector() } : {}),+ })));+ }++ async function seedHealthyBrain() {+ await seedPages(6);+ for (let i = 0; i < 6; i++) {+ await seedChunks(`notes/feature-${i}`, [true]);+ await engine.addTimelineEntry(`notes/feature-${i}`, { date: '2026-01-0' + (i + 1), summary: `Synthetic event ${i}` });+ await engine.addLink(`notes/feature-${i}`, `notes/feature-${(i + 1) % 6}`);+ }+ await engine.setConfig('sync.repo_path', join(root, 'repo'));+ }++ function writeHeartbeat(recipeId: string) {+ const dir = join(gbrainHome, '.gbrain', 'integrations', recipeId);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'heartbeat.jsonl'), JSON.stringify({ ts: new Date().toISOString(), event: 'setup_complete' }) + '\n');+ }++ const offersFile = () => join(home, '.gbrain', 'feature-offers.json');++ async function features(env: Record<string, string | undefined> = {}) {+ const lines: string[] = [];+ const spy = spyOn(console, 'log').mockImplementation((...args: unknown[]) => { lines.push(args.map(String).join(' ')); });+ try {+ await withEnv({ ...secretEnv, HOME: home, GBRAIN_HOME: gbrainHome, ...env }, () => runFeatures(engine, ['--json']));+ } finally {+ spy.mockRestore();+ }+ const out = JSON.parse(lines.join('\n')) as { version: string; recommendations: { id: string; pitch: string }[] };+ return { out, ids: out.recommendations.map(r => r.id).sort() };+ }++ const pitchOf = (out: { recommendations: { id: string; pitch: string }[] }, id: string) =>+ out.recommendations.find(r => r.id === id)?.pitch ?? '';++ it('a brain with every supported gap reports each check and persists offers under the temporary home', async () => {+ await seedPages(6);+ await seedChunks('notes/feature-0', [true, false]);++ const { out, ids } = await features();++ expect(ids).toEqual(['low-coverage', 'missing-embeddings', 'no-integrations', 'no-sync', 'zero-links', 'zero-timeline']);+ expect(pitchOf(out, 'missing-embeddings')).toContain('1 chunks invisible');+ expect(pitchOf(out, 'low-coverage')).toContain('50% embed coverage');+ const pitch = pitchOf(out, 'no-integrations');+ expect(pitch).toContain(`${RECIPE_META.length} integration recipes`);+ for (const recipe of RECIPE_META) expect(pitch).toContain(recipe.name);++ const saved = JSON.parse(readFileSync(offersFile(), 'utf-8'));+ expect(saved.lastVersion).toBe(VERSION);+ expect(existsSync(join(gbrainHome, '.gbrain', 'feature-offers.json'))).toBe(false);+ });++ it('a healthy, fully configured brain recommends nothing and writes no offers file', async () => {+ await seedHealthyBrain();+ const configured = Object.fromEntries(RECIPE_META.map(r => [r.secrets[0], 'synthetic-token']));++ const { ids } = await features(configured);++ expect(ids).toEqual([]);+ expect(existsSync(offersFile())).toBe(false);+ });++ it('the no-integrations pitch names exactly the recipes with no env secret and no setup heartbeat', async () => {+ await seedHealthyBrain();+ writeHeartbeat('meeting-sync');+ writeHeartbeat('ngrok-tunnel');++ const { out, ids } = await features({ CLAWVISOR_AGENT_TOKEN: 'synthetic-token', TWILIO_AUTH_TOKEN: 'synthetic-token' });++ expect(ids).toEqual(['no-integrations']);+ const pitch = pitchOf(out, 'no-integrations');+ const expected: Record<string, boolean> = {+ 'email-to-brain': false,+ 'calendar-to-brain': false,+ 'credential-gateway': false,+ 'twilio-voice-brain': false,+ 'meeting-sync': false,+ 'ngrok-tunnel': false,+ 'x-to-brain': true,+ };+ for (const recipe of RECIPE_META) expect(pitch.includes(recipe.name), recipe.id).toBe(expected[recipe.id]);+ expect(pitch).toContain('1 integration recipes');+ });++ it('a heartbeat without setup_complete does not count as configured', async () => {+ await seedHealthyBrain();+ const dir = join(gbrainHome, '.gbrain', 'integrations', 'x-to-brain');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'heartbeat.jsonl'), JSON.stringify({ ts: new Date().toISOString(), event: 'health_check' }) + '\n');++ const { out } = await features({ CLAWVISOR_AGENT_TOKEN: 'synthetic-token' });++ expect(pitchOf(out, 'no-integrations')).toContain('X/Twitter to Brain');+ });++ it('a declined priority-2 offer is suppressed for the current version; priority-1 offers are always pitched', async () => {+ await seedPages(6);+ await seedChunks('notes/feature-0', [false]);+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ const declinedAt = { at: '2026-01-01', version: VERSION };+ writeFileSync(offersFile(), JSON.stringify({+ lastVersion: VERSION, lastScan: '', accepted: {},+ declined: { 'zero-links': declinedAt, 'missing-embeddings': declinedAt },+ }));++ const { ids } = await features();++ expect(ids).not.toContain('zero-links');+ expect(ids).toContain('zero-timeline');+ expect(ids).toContain('missing-embeddings');+ });++ it('the doctor teaser names missing embeddings and stays silent on a healthy brain', async () => {+ await seedHealthyBrain();+ expect(await featuresTeaserForDoctor(engine)).toBeNull();++ await seedChunks('notes/feature-0', [true, false]);+ expect(await featuresTeaserForDoctor(engine)).toBe("Tip: 1 missing embeddings. Run 'gbrain features' to fix.");+ });++ it('brains under three pages skip the priority-2 checks', async () => {+ await seedPages(2);++ const { ids } = await features();++ expect(ids).toEqual([]);+ });+});diff --git a/test/fix-wave-structural.test.ts b/test/fix-wave-structural.test.tsindex fc4cfe994b..63241924c2 100644--- a/test/fix-wave-structural.test.ts+++ b/test/fix-wave-structural.test.ts@@ -129,15 +129,6 @@ describe('v0.41.37.0 #1605 — v0.11.0 phaseASchema routes in-process for ALL en});});-describe('v0.36.1.x #1124 — query --no-expand actually negates expand', () => {- test("cli.ts parseOpArgs handles --no-<key> as boolean negation", () => {- const src = readFileSync('src/cli.ts', 'utf8');- expect(src).toMatch(/arg\.startsWith\(['"]--no-['"]\)/);- expect(src).toMatch(/positiveDef\?\.type\s*===\s*'boolean'/);- expect(src).toMatch(/params\[positiveKey\]\s*=\s*false/);- });-});-describe('v0.42.20.0 — background-work registry drains every sink before disconnect', () => {// Supersedes the v0.41.8.0 #1247/#1269/#1290 per-call last-retrieved drain:// last-retrieved is one of four registry sinks. #2084 moved the registry@@ -302,15 +293,6 @@ describe('#2084 — cli.ts owns process-exit teardown via finishCliTeardown', ()});describe('v0.41.8.0 #1340 — PGLite WASM init classifier', () => {- test('pglite-engine.ts exports classifyPgliteInitError + buildPgliteInitErrorMessage', () => {- const src = readFileSync('src/core/pglite-engine.ts', 'utf8');- expect(src).toMatch(/export function classifyPgliteInitError/);- expect(src).toMatch(/export function buildPgliteInitErrorMessage/);- // Per Codex finding #9: regex tightened to $$bunfs OR ENOENT+pglite.data- expect(src).toMatch(/\$\$bunfs/);- expect(src).toMatch(/ENOENT/);- });-test('pglite-engine.ts connect catch block routes through the classifier', () => {const src = readFileSync('src/core/pglite-engine.ts', 'utf8');expect(src).toMatch(/classifyPgliteInitError\(original\)/);diff --git a/test/fixtures/e2e-unmapped-baseline.txt b/test/fixtures/e2e-unmapped-baseline.txtindex a65fb4081e..25335faa6b 100644--- a/test/fixtures/e2e-unmapped-baseline.txt+++ b/test/fixtures/e2e-unmapped-baseline.txt@@ -9,11 +9,9 @@ test/e2e/auth-permissions.test.tstest/e2e/auth-takes-holders-pglite.test.tstest/e2e/autopilot-cooldown-parity.test.tstest/e2e/autopilot-fanout-postgres.test.ts-test/e2e/backfill-perf-pglite.test.tstest/e2e/bootstrap-attach.serial.test.tstest/e2e/bootstrap-compiled-binary.serial.test.tstest/e2e/bootstrap-degraded-modes.serial.test.ts-test/e2e/bootstrap-harness-lifecycle.serial.test.tstest/e2e/bootstrap-keyed-postgres.serial.test.tstest/e2e/bootstrap-lifecycle.serial.test.tstest/e2e/bootstrap-magic-moment.serial.test.ts@@ -38,11 +36,9 @@ test/e2e/cross-modal-eval.test.tstest/e2e/cycle-consolidate-postgres.test.tstest/e2e/cycle-recompute-emotional-weight-pglite.test.tstest/e2e/db-guard.test.ts-test/e2e/db-singleton-shared-recovery.test.tstest/e2e/doctor-silent-death-parity.test.tstest/e2e/dream-allow-list-pglite.test.tstest/e2e/dream-patterns-pglite.test.ts-test/e2e/dream-synthesize-chunking.test.tstest/e2e/dream-synthesize-concurrency-postgres.test.tstest/e2e/dream-triage-postgres.test.tstest/e2e/embed-stale-pagination.test.ts@@ -64,13 +60,11 @@ test/e2e/facts-notability-roundtrip.test.tstest/e2e/facts-recall-event-time-postgres.test.tstest/e2e/facts-recall-render.test.tstest/e2e/facts-separation-postgres.test.ts-test/e2e/fresh-install-pglite.test.tstest/e2e/frontmatter-migration.test.tstest/e2e/global-basename-pglite.test.tstest/e2e/graph-signals-engine.test.tstest/e2e/graph-signals-eval.test.tstest/e2e/import-credential-preflight.test.ts-test/e2e/init-fresh-pglite.test.tstest/e2e/install-real-grok.serial.test.tstest/e2e/install-real-hermes.serial.test.tstest/e2e/install-real-opencode.serial.test.ts@@ -85,11 +79,7 @@ test/e2e/migration-v35-auto-rls.test.tstest/e2e/migration-v35-event-trigger.test.tstest/e2e/migration-v47-notability.test.tstest/e2e/migration-v50-ingest-log-source-id.test.ts-test/e2e/minions-budget-cathedral.test.ts-test/e2e/minions-controller-bounce-only.test.ts-test/e2e/minions-field-report-repro.test.tstest/e2e/minions-prefix-strip-smoke.test.ts-test/e2e/minions-self-fix-flow.test.tstest/e2e/multi-source-emotional-weight-pglite.test.tstest/e2e/multimodal-postgres.test.tstest/e2e/non-tty-output.serial.test.ts@@ -99,10 +89,7 @@ test/e2e/openrouter-anthropic-subagent-replay.live.test.tstest/e2e/orphan-reduction.test.tstest/e2e/pglite-cli-exit.serial.test.tstest/e2e/phantom-redirect.test.ts-test/e2e/postgres-engine-disconnect-idempotency.test.ts-test/e2e/postgres-reconnect-singleton.test.tstest/e2e/purge-deleted-dryrun-postgres.test.ts-test/e2e/qm-provisioning.test.tstest/e2e/quarantine-search-exclusion.test.tstest/e2e/restore-source-config-jsonb-postgres.test.tstest/e2e/salience-llm-routing.test.ts@@ -112,9 +99,7 @@ test/e2e/self-upgrade-binary-swap.test.tstest/e2e/self-upgrade-marker.test.tstest/e2e/serve-http-meta.test.tstest/e2e/serve-http-takes-holders.test.ts-test/e2e/serve-stdio-roundtrip.test.tstest/e2e/skill-brain-first.test.ts-test/e2e/skillpack-flow.test.tstest/e2e/skillpack-third-party.test.tstest/e2e/source-isolation-pglite.test.tstest/e2e/source-routing.test.ts@@ -135,14 +120,10 @@ test/e2e/takes-weight-rounding-postgres.test.tstest/e2e/thin-client.test.tstest/e2e/think-source-isolation-pglite.test.tstest/e2e/think-trajectory-pglite.test.ts-test/e2e/transcripts-ingest-pglite.test.tstest/e2e/transcripts-writeback-fidelity.test.tstest/e2e/type-unification-full-flow.test.tstest/e2e/upsert-chunks-registry-column.test.ts-test/e2e/v030_1-integration-pglite.test.ts-test/e2e/v0_28_5-fix-wave.test.tstest/e2e/v0_29-mcp-dispatch-pglite.test.ts-test/e2e/v0_30_3-fix-wave.test.tstest/e2e/vector-ef-search-postgres.test.tstest/e2e/volunteer-context-postgres.test.tstest/e2e/whoknows.test.tsdiff --git a/test/fixtures/e5-lease-cap-ab/2026-05-24-baseline-dry-run.json b/test/fixtures/e5-lease-cap-ab/2026-05-24-baseline-dry-run.jsondeleted file mode 100644index 3a47320b04..0000000000--- a/test/fixtures/e5-lease-cap-ab/2026-05-24-baseline-dry-run.json+++ /dev/null@@ -1,43 +0,0 @@-{- "schema_version": 1,- "timestamp": "2026-05-24T07:42:34.170Z",- "spec": {- "job_count": 500,- "budget_per_arm_usd": 8,- "injection_at_min": 15- },- "arms": [- {- "arm": "fixed",- "jobs_submitted": 500,- "jobs_completed": 0,- "jobs_dead": 0,- "wall_clock_ms": 1,- "total_cost_usd": 0,- "lease_cap_history": [- 8- ],- "bounces": 0,- "upstream_429s": 0- },- {- "arm": "adaptive",- "jobs_submitted": 500,- "jobs_completed": 0,- "jobs_dead": 0,- "wall_clock_ms": 0,- "total_cost_usd": 0,- "lease_cap_history": [- 8- ],- "bounces": 0,- "upstream_429s": 0- }- ],- "verdict": {- "throughput_advantage_pct": 0,- "cost_efficiency_delta_pct": 0,- "pr_gate_pass": false,- "note": "controller does NOT meet PR gate; defaults stay OFF"- }-}diff --git a/test/fixtures/guards/check-orphan-modules.mjs/good/permitted-test-only.json b/test/fixtures/guards/check-orphan-modules.mjs/good/permitted-test-only.jsonnew file mode 100644index 0000000000..3f31f95096--- /dev/null+++ b/test/fixtures/guards/check-orphan-modules.mjs/good/permitted-test-only.json@@ -0,0 +1,4 @@+[+ { "path": "src/test-helper.ts", "reason": "fixture: deliberate test-only helper" },+ { "path": "src/tool.ts", "reason": "script-reachable" }+]diff --git a/test/fixtures/guards/check-orphan-modules.mjs/good/scripts/gen.ts b/test/fixtures/guards/check-orphan-modules.mjs/good/scripts/gen.tsnew file mode 100644index 0000000000..48cda9a822--- /dev/null+++ b/test/fixtures/guards/check-orphan-modules.mjs/good/scripts/gen.ts@@ -0,0 +1,3 @@+import { tool } from '../src/tool.ts';++export const generated = tool;diff --git a/test/fixtures/guards/check-orphan-modules.mjs/good/src/test-helper.ts b/test/fixtures/guards/check-orphan-modules.mjs/good/src/test-helper.tsnew file mode 100644index 0000000000..3b52f2d84d--- /dev/null+++ b/test/fixtures/guards/check-orphan-modules.mjs/good/src/test-helper.ts@@ -0,0 +1,2 @@+// Imported only by the test tree; permitted by permitted-test-only.json.+export const helper = 'test-only';diff --git a/test/fixtures/guards/check-orphan-modules.mjs/good/src/tool.ts b/test/fixtures/guards/check-orphan-modules.mjs/good/src/tool.tsnew file mode 100644index 0000000000..d62842af64--- /dev/null+++ b/test/fixtures/guards/check-orphan-modules.mjs/good/src/tool.ts@@ -0,0 +1,2 @@+// Imported by scripts/gen.ts and the test tree; permitted as script-reachable.+export const tool = 'script-reachable';diff --git a/test/fixtures/guards/check-orphan-modules.mjs/good/test/uses-helper.ts b/test/fixtures/guards/check-orphan-modules.mjs/good/test/uses-helper.tsnew file mode 100644index 0000000000..02f173d20b--- /dev/null+++ b/test/fixtures/guards/check-orphan-modules.mjs/good/test/uses-helper.ts@@ -0,0 +1,4 @@+import { helper } from '../src/test-helper.ts';+import { tool } from '../src/tool.ts';++export const seen = [helper, tool];diff --git a/test/fixtures/guards/check-test-placeholders.mjs/bad/test/placeholders.test.fixture.ts b/test/fixtures/guards/check-test-placeholders.mjs/bad/test/placeholders.test.fixture.tsnew file mode 100644index 0000000000..2f03e531fc--- /dev/null+++ b/test/fixtures/guards/check-test-placeholders.mjs/bad/test/placeholders.test.fixture.ts@@ -0,0 +1,19 @@+import { describe, expect, test } from 'bun:test';++describe('placeholder forms', () => {+ test('bare expect(true) with no matcher', () => {+ expect(true);+ });++ test('expect(true).toBe(true)', () => {+ expect(true).toBe(true);+ });++ test('expect(true).toBeTruthy()', () => {+ expect(true).toBeTruthy();+ });++ test('expect(1).toBe(1)', () => {+ expect(1).toBe(1);+ });+});diff --git a/test/fixtures/guards/check-test-placeholders.mjs/good/test/fixtures/excluded.test.fixture.ts b/test/fixtures/guards/check-test-placeholders.mjs/good/test/fixtures/excluded.test.fixture.tsnew file mode 100644index 0000000000..a562822a7e--- /dev/null+++ b/test/fixtures/guards/check-test-placeholders.mjs/good/test/fixtures/excluded.test.fixture.ts@@ -0,0 +1,5 @@+import { expect, test } from 'bun:test';++test('files under test/fixtures are not scanned', () => {+ expect(true).toBe(true);+});diff --git a/test/fixtures/guards/check-test-placeholders.mjs/good/test/real-assertions.test.fixture.ts b/test/fixtures/guards/check-test-placeholders.mjs/good/test/real-assertions.test.fixture.tsnew file mode 100644index 0000000000..3b48dacaf7--- /dev/null+++ b/test/fixtures/guards/check-test-placeholders.mjs/good/test/real-assertions.test.fixture.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from 'bun:test';++const SCRIPT = `+ test('inside a template literal', () => {+ expect(true).toBe(true);+ expect(1).toBe(1);+ });+`;++describe('not placeholders', () => {+ test('fail sentinel is allowed', () => {+ try {+ JSON.parse('{');+ expect(true).toBe(false);+ } catch (e) {+ expect(e).toBeInstanceOf(SyntaxError);+ }+ });++ test('strings and comments are ignored', () => {+ // expect(true).toBe(true)+ const text = "expect(true).toBeTruthy()";+ expect(text.length).toBeGreaterThan(0);+ expect(SCRIPT).toContain('expect(1).toBe(1)');+ });++ test('real values are not placeholders', () => {+ const ok = [1, 2].includes(1);+ expect(ok).toBe(true);+ expect(2 - 1).toBe(1);+ });+});diff --git a/test/fixtures/source-read-smell/form-bun-file.fixture.ts b/test/fixtures/source-read-smell/form-bun-file.fixture.tsnew file mode 100644index 0000000000..1b2fdb48ae--- /dev/null+++ b/test/fixtures/source-read-smell/form-bun-file.fixture.ts@@ -0,0 +1,5 @@+// Bun.file(...) on a src path.++export async function load(): Promise<string> {+ return Bun.file(new URL('../../../src/core/example.ts', import.meta.url)).text();+}diff --git a/test/fixtures/source-read-smell/form-constant.fixture.ts b/test/fixtures/source-read-smell/form-constant.fixture.tsnew file mode 100644index 0000000000..f1258f26a8--- /dev/null+++ b/test/fixtures/source-read-smell/form-constant.fixture.ts@@ -0,0 +1,8 @@+import { readFileSync } from 'fs';+import { join } from 'path';++const SRC_DIR = join(import.meta.dir, '..', '..', 'src');+const ENGINE_PATH = join(SRC_DIR, 'core', 'example.ts');++export const ENGINE_SRC = readFileSync(ENGINE_PATH, 'utf8');+export const DIR_SRC = readFileSync(join(SRC_DIR, 'other.ts'), 'utf8');diff --git a/test/fixtures/source-read-smell/form-join-segment.fixture.ts b/test/fixtures/source-read-smell/form-join-segment.fixture.tsnew file mode 100644index 0000000000..27cd45917a--- /dev/null+++ b/test/fixtures/source-read-smell/form-join-segment.fixture.ts@@ -0,0 +1,6 @@+import { readFileSync } from 'fs';+import { join } from 'path';++export function load(): string {+ return readFileSync(join(import.meta.dir, '..', '..', 'src', 'core', 'example.ts'), 'utf8');+}diff --git a/test/fixtures/source-read-smell/form-literal.fixture.ts b/test/fixtures/source-read-smell/form-literal.fixture.tsnew file mode 100644index 0000000000..a8af211a96--- /dev/null+++ b/test/fixtures/source-read-smell/form-literal.fixture.ts@@ -0,0 +1,6 @@+import { readFileSync } from 'fs';++export function load(): string {+ // Same-line literal path.+ return readFileSync('src/core/example.ts', 'utf8');+}diff --git a/test/fixtures/source-read-smell/form-multiline.fixture.ts b/test/fixtures/source-read-smell/form-multiline.fixture.tsnew file mode 100644index 0000000000..55cd1bee42--- /dev/null+++ b/test/fixtures/source-read-smell/form-multiline.fixture.ts@@ -0,0 +1,9 @@+import { readFileSync } from 'fs';+import { join } from 'path';++export function load(): string {+ return readFileSync(+ join(import.meta.dir, '..', '..', 'src/core/example.ts'),+ 'utf8',+ );+}diff --git a/test/fixtures/source-read-smell/form-read-file.fixture.ts b/test/fixtures/source-read-smell/form-read-file.fixture.tsnew file mode 100644index 0000000000..1c5e497e25--- /dev/null+++ b/test/fixtures/source-read-smell/form-read-file.fixture.ts@@ -0,0 +1,9 @@+import * as fs from 'fs';+import { readFile } from 'fs/promises';++export async function load(): Promise<string[]> {+ return [+ await readFile('src/core/example.ts', 'utf8'),+ await fs.promises.readFile('src/core/other.ts', 'utf8'),+ ];+}diff --git a/test/fixtures/source-read-smell/grandfathered.fixture.ts b/test/fixtures/source-read-smell/grandfathered.fixture.tsnew file mode 100644index 0000000000..11ee0296ff--- /dev/null+++ b/test/fixtures/source-read-smell/grandfathered.fixture.ts@@ -0,0 +1,4 @@+import { readFileSync } from 'fs';++export const A = readFileSync('src/core/a.ts', 'utf8');+export const B = readFileSync('src/core/b.ts', 'utf8');diff --git a/test/fixtures/source-read-smell/tagged-ok.fixture.ts b/test/fixtures/source-read-smell/tagged-ok.fixture.tsnew file mode 100644index 0000000000..e82da6323f--- /dev/null+++ b/test/fixtures/source-read-smell/tagged-ok.fixture.ts@@ -0,0 +1,10 @@+import { readFileSync } from 'fs';+import { join } from 'path';++// test-reads-source-ok[structural]: fixture — a tagged marker justifies the read below.+export const ENGINE_SRC = readFileSync(join(import.meta.dir, '..', '..', 'src/core/example.ts'), 'utf8');++// A read that names no src path is not a site, and a mention of+// readFileSync('src/x.ts') inside a comment or string is ignored.+export const README = readFileSync(join(import.meta.dir, 'README.md'), 'utf8');+export const PROSE = "readFileSync('src/core/example.ts')";diff --git a/test/fixtures/source-read-smell/untagged-new.fixture.ts b/test/fixtures/source-read-smell/untagged-new.fixture.tsnew file mode 100644index 0000000000..7d77f3238e--- /dev/null+++ b/test/fixtures/source-read-smell/untagged-new.fixture.ts@@ -0,0 +1,5 @@+import { readFileSync } from 'fs';++// The marker below lacks a category, so it justifies nothing.+// test-reads-source-ok: missing category+export const ENGINE_SRC = readFileSync('src/core/example.ts', 'utf8');diff --git a/test/e2e/fresh-install-pglite.test.ts b/test/fresh-install-pglite.serial.test.tssimilarity index 90%rename from test/e2e/fresh-install-pglite.test.tsrename to test/fresh-install-pglite.serial.test.tsindex 7ecff0a2cb..87e03c1620 100644--- a/test/e2e/fresh-install-pglite.test.ts+++ b/test/fresh-install-pglite.serial.test.ts@@ -9,23 +9,27 @@* tmpdir, embed transport stubbed via `__setEmbedTransportForTests` so we* don't need real provider credentials. CDX2-12 from the plan explicitly* called this design out.+ *+ * Lane: serial. Run: `bash scripts/run-serial-tests.sh test/fresh-install-pglite.serial.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { afterAll, beforeAll, beforeEach, afterEach, describe, expect, test } from 'bun:test';import { mkdtempSync, rmSync, existsSync, readFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { installFixtureChunks } from '../helpers/page-projection.ts';-import { withManagedFixtureWrite } from '../helpers/managed-e2e-fixture-write.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { withManagedFixtureWrite } from './helpers/managed-e2e-fixture-write.ts';import {configureGateway,resetGateway,__setEmbedTransportForTests,-} from '../../src/core/ai/gateway.ts';+} from '../src/core/ai/gateway.ts';import {NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS,-} from '../../src/core/ai/defaults.ts';+} from '../src/core/ai/defaults.ts';describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end', () => {let tmpHome: string;@@ -95,7 +99,7 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'embeddings: args.values.map(() => synthVec),}) as any);- const { runInit } = await import('../../src/commands/init.ts');+ const { runInit } = await import('../src/commands/init.ts');// Capture stderr to verify init prints the resolved choice.const origStderrWrite = process.stderr.write.bind(process.stderr);@@ -132,11 +136,11 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'expect(cfg.embedding_model).toBe(NEW_INSTALL_DEFAULT_EMBEDDING_MODEL);expect(cfg.embedding_dimensions).toBe(NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS);- const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');+ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');const engine = new PGLiteEngine();await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });try {- const { readContentChunksEmbeddingDim } = await import('../../src/core/embedding-dim-check.ts');+ const { readContentChunksEmbeddingDim } = await import('../src/core/embedding-dim-check.ts');const colDim = await readContentChunksEmbeddingDim(engine);expect(colDim.exists).toBe(true);expect(colDim.dims).toBe(NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS);@@ -144,7 +148,7 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'// init writes NO explicit row; the RESOLVED reranker is the default.expect(await engine.getConfig('search.reranker.model')).toBeNull();{- const { loadSearchModeConfig, resolveSearchMode } = await import('../../src/core/search/mode.ts');+ const { loadSearchModeConfig, resolveSearchMode } = await import('../src/core/search/mode.ts');const knobs = resolveSearchMode(await loadSearchModeConfig(engine));expect(knobs.reranker_model).toBe('voyage:rerank-2.5');// (reranker_enabled follows the picked mode — non-TTY init may auto-select a@@ -167,11 +171,11 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'console.log = () => {};console.warn = () => {};try {- const { runInit } = await import('../../src/commands/init.ts');+ const { runInit } = await import('../src/commands/init.ts');await runInit(['--pglite', '--non-interactive']);const cfgPath = join(tmpHome, '.gbrain', 'config.json');const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));- const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');+ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');const engine = new PGLiteEngine();await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });try {@@ -204,11 +208,11 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'console.log = () => {};console.error = () => {};try {- const { runInit } = await import('../../src/commands/init.ts');+ const { runInit } = await import('../src/commands/init.ts');await runInit(['--pglite', '--non-interactive']);const cfg = JSON.parse(readFileSync(join(tmpHome, '.gbrain', 'config.json'), 'utf-8'));expect(cfg.embedding_model).toBe('openai:text-embedding-3-large');- const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');+ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');const engine = new PGLiteEngine();await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });try {@@ -235,15 +239,15 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'console.warn = () => {};console.error = () => {};try {- const { runInit } = await import('../../src/commands/init.ts');+ const { runInit } = await import('../src/commands/init.ts');await runInit(['--pglite', '--non-interactive']);const cfg = JSON.parse(readFileSync(join(tmpHome, '.gbrain', 'config.json'), 'utf-8'));expect(cfg.embedding_disabled).toBe(true);- const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');+ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');const engine = new PGLiteEngine();await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });try {- const { readContentChunksEmbeddingDim } = await import('../../src/core/embedding-dim-check.ts');+ const { readContentChunksEmbeddingDim } = await import('../src/core/embedding-dim-check.ts');const colDim = await readContentChunksEmbeddingDim(engine);expect(colDim.exists).toBe(true);expect(colDim.dims).toBe(NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS);@@ -272,7 +276,7 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'console.warn = () => {};console.error = () => {};try {- const { runInit } = await import('../../src/commands/init.ts');+ const { runInit } = await import('../src/commands/init.ts');// Step 1: keyless install → deferred-setup sentinel persisted.delete process.env.VOYAGE_API_KEY;await runInit(['--pglite', '--non-interactive']);@@ -287,7 +291,7 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'expect(cfg.embedding_disabled).toBeUndefined();// Keyless init wrote NO reranker config (deliberate), so the recovery// re-init's voyage override lands instead of being never-clobbered.- const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');+ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');const engine = new PGLiteEngine();await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });try {@@ -295,7 +299,7 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'// init writes NO explicit row; the RESOLVED reranker is the default.expect(await engine.getConfig('search.reranker.model')).toBeNull();{- const { loadSearchModeConfig, resolveSearchMode } = await import('../../src/core/search/mode.ts');+ const { loadSearchModeConfig, resolveSearchMode } = await import('../src/core/search/mode.ts');const knobs = resolveSearchMode(await loadSearchModeConfig(engine));expect(knobs.reranker_model).toBe('voyage:rerank-2.5');// (reranker_enabled follows the picked mode — non-TTY init may auto-select a@@ -326,7 +330,7 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'console.warn = () => {};try {- const { runInit } = await import('../../src/commands/init.ts');+ const { runInit } = await import('../src/commands/init.ts');await runInit(['--pglite', '--non-interactive']);} finally {console.log = origLog;@@ -336,7 +340,7 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'const cfgPath = join(tmpHome, '.gbrain', 'config.json');const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));- const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');+ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');const engine = new PGLiteEngine();await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });try {@@ -355,7 +359,7 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'// Run embed --stale via the public CLI entry point. This goes// through runEmbedCore including the pre-flight dim check.- const { runEmbedCore } = await import('../../src/commands/embed.ts');+ const { runEmbedCore } = await import('../src/commands/embed.ts');const result = await runEmbedCore(engine, { stale: true });expect(result.embedded).toBeGreaterThan(0);diff --git a/test/gbrain-home-isolation.test.ts b/test/gbrain-home-isolation.test.tsindex d4ce3c29fc..5b0440ad96 100644--- a/test/gbrain-home-isolation.test.ts+++ b/test/gbrain-home-isolation.test.ts@@ -116,7 +116,6 @@ describe('GBRAIN_HOME write-side isolation', () => {gbrainPath('migrations', 'pending-host-work.jsonl'), // src/commands/migrations/v0_14_0.tsgbrainPath('audit'), // shell-audit / backpressure-auditgbrainPath('cycle.lock'), // src/core/cycle.ts- gbrainPath('fail-improve'), // src/core/fail-improve.tsgbrainPath('validator-lint.jsonl'), // src/core/output/post-write.tsgbrainPath('brain.pglite'), // init pglite default];diff --git a/test/handlers.test.ts b/test/handlers.test.tsindex b926c9f821..829976b048 100644--- a/test/handlers.test.ts+++ b/test/handlers.test.ts@@ -14,6 +14,9 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { MinionWorker } from '../src/core/minions/worker.ts';import { registerBuiltinHandlers } from '../src/commands/jobs.ts';import { configureGateway, getChatModel, resetGateway } from '../src/core/ai/gateway.ts';+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';let engine: PGLiteEngine;let worker: MinionWorker;@@ -281,3 +284,45 @@ describe('autopilot-cycle handler — phase passthrough', () => {expect(phaseNames).toContain('embed');}, 30_000);});++describe('backlinks handler — empty payload checks, never rewrites pages', () => {+ // Post-ingestion sync→embed→backlinks chains submit backlinks jobs with an+ // empty payload. Those must report gaps without writing generated+ // "Referenced in" bullets into tracked brain pages; 'fix' is opt-in.+ function makeBrainWithGap(): string {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-backlinks-handler-'));+ mkdirSync(join(dir, 'people'));+ mkdirSync(join(dir, 'companies'));+ writeFileSync(join(dir, 'people/alice-example.md'), '# Alice\n\nWorks at [Acme](../companies/acme-example.md).\n');+ writeFileSync(join(dir, 'companies/acme-example.md'), '# Acme\n\nNo links back.\n');+ return dir;+ }++ test('no action in job.data → check: gap reported, target page untouched', async () => {+ const dir = makeBrainWithGap();+ try {+ const before = readFileSync(join(dir, 'companies/acme-example.md'), 'utf8');+ const handler = (worker as any).handlers.get('backlinks');+ const result = await handler({ data: { dir }, signal: { aborted: false } as any, job: { id: 20, name: 'backlinks' } as any });+ expect(result.action).toBe('check');+ expect(result.gaps_found).toBe(1);+ expect(result.fixed).toBe(0);+ expect(readFileSync(join(dir, 'companies/acme-example.md'), 'utf8')).toBe(before);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("explicit action 'fix' still rewrites the gap (the fixture is fixable)", async () => {+ const dir = makeBrainWithGap();+ try {+ const handler = (worker as any).handlers.get('backlinks');+ const result = await handler({ data: { dir, action: 'fix' }, signal: { aborted: false } as any, job: { id: 21, name: 'backlinks' } as any });+ expect(result.action).toBe('fix');+ expect(result.fixed).toBe(1);+ expect(readFileSync(join(dir, 'companies/acme-example.md'), 'utf8')).toContain('alice-example');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/test/helpers/agent-harness.unit.test.ts b/test/helpers/agent-harness.unit.test.tsindex daee8cfd95..11b6807176 100644--- a/test/helpers/agent-harness.unit.test.ts+++ b/test/helpers/agent-harness.unit.test.ts@@ -8,9 +8,6 @@* - hermeticChildEnv: drops CONDUCTOR_* / CLAUDE_* / GSTACK_* / MCP_* /* GBRAIN_*, promotes GSTACK_ANTHROPIC_API_KEY, honors extraAllow, and lets* overrides win.- * - resolveClaudeBinary / resolveCodexBinary SMOKE (whatever this machine- * has — assertion is only that the result is a string-or-null, plus a note- * printed when found).** The env test mutates process.env and restores it in finally so it never* leaks into sibling tests.@@ -27,9 +24,6 @@ import {hermesChildEnv,grokChildEnv,promotedEnv,- resolveClaudeBinary,- resolveCodexBinary,- resolveHermesBinary,resolveGrokBinary,hasHermesAuth,hasGrokAuth,@@ -219,30 +213,6 @@ describe('hermeticChildEnv', () => {});});-describe('binary resolution SMOKE', () => {- test('resolveClaudeBinary returns a string or null', () => {- const bin = resolveClaudeBinary();- expect(bin === null || typeof bin === 'string').toBe(true);- if (bin) console.log(`[smoke] claude resolved at: ${bin}`);- });-- test('resolveCodexBinary returns a string or null', () => {- const bin = resolveCodexBinary();- expect(bin === null || typeof bin === 'string').toBe(true);- if (bin) console.log(`[smoke] codex resolved at: ${bin}`);- });-- test('resolveHermesBinary returns a string or null', () => {- const bin = resolveHermesBinary();- expect(bin === null || typeof bin === 'string').toBe(true);- if (bin) console.log(`[smoke] hermes resolved at: ${bin}`);- });-- test('hasHermesAuth returns a boolean', () => {- expect(typeof hasHermesAuth()).toBe('boolean');- });-});-describe('hasHermesAuth truth table (env leg — pins the anthropic-only, non-empty-value gate)', () => {// The .env-file leg reads the operator's real ~/.hermes/.env, so only the// env-var leg is exercised hermetically here; the file PARSING contract isdiff --git a/test/helpers/cli-command-surface.ts b/test/helpers/cli-command-surface.tsnew file mode 100644index 0000000000..1936597b38--- /dev/null+++ b/test/helpers/cli-command-surface.ts@@ -0,0 +1,169 @@+/**+ * Shared `gbrain <verb> [--flag ...]` scanner for the doc↔CLI truth checks+ * (test/docs-cli-commands.test.ts, test/remediation-command-resolution.test.ts).+ *+ * One definition of "a live verb", "command position", "code regions of a+ * markdown file" and "does this invocation's argv pass the real flag+ * validator", so both gates agree on the CLI surface by construction.+ *+ * Flags are checked by the production pipeline itself: parseGlobalFlags+ * (strips --brain/--quiet/--progress-*) followed by validateCommandFlags+ * (op commands: op.params + CLI-local flags; CLI_ONLY commands: the generated+ * CLI_FLAG_REGISTRY row). Limitations inherited from that validator: CLI_ONLY+ * flags are per top-level command, not per subcommand, and commands it exempts+ * (`call`, `config`, `jobs submit`, `eval brainbench`) are verb-checked only.+ *+ * Plain helper: no env mutation, no engine, no network.+ */+import { CLI_ONLY, cliAliases, validateCommandFlags } from '../../src/cli.ts';+import { parseGlobalFlags } from '../../src/core/cli-options.ts';+import { migrationCliArgumentError } from '../../src/core/embedding-migration-cli.ts';+import { operations } from '../../src/core/operations.ts';++/** Every verb the dispatcher accepts: CLI_ONLY, non-hidden op names, aliases. */+export function liveCliVerbs(): Set<string> {+ const valid = new Set<string>(CLI_ONLY);+ for (const op of operations) {+ const name = op.cliHints?.name;+ if (name && !op.cliHints?.hidden) valid.add(name);+ }+ for (const alias of cliAliases.keys()) valid.add(alias);+ return valid;+}++/** True when `gbrain` sits at command position (not mid-prose). */+export function commandPosition(prefix: string): boolean {+ const p = prefix.trimEnd();+ return p === '' || /[|;&`(={[]$/.test(p) || /\$$/.test(p);+}++/**+ * Marker that exempts one example from the truth check because it documents+ * an older release's CLI. Place it on the line directly above a code fence+ * (covers the whole block) or on/above a line with inline code.+ */+export const HISTORICAL_MARKER = '<!-- gbrain-cli: historical -->';++export interface CodeLine { code: string; line: number; historical: boolean }++/**+ * Fenced-block lines (backslash continuations joined) + inline code spans+ * that START with `gbrain `. Comment and ASCII-diagram lines are skipped.+ */+export function codeRegions(text: string): CodeLine[] {+ const out: CodeLine[] = [];+ const lines = text.split('\n');+ const markedAbove = (i: number) => i > 0 && lines[i - 1]!.includes(HISTORICAL_MARKER);+ let inFence = false;+ let fenceHistorical = false;+ for (let i = 0; i < lines.length; i++) {+ const l = lines[i]!;+ if (/^\s*(```|~~~)/.test(l)) {+ inFence = !inFence;+ fenceHistorical = inFence && markedAbove(i);+ continue;+ }+ if (inFence) {+ const t = l.trim();+ if (/^(#|\/\/|--|\*)/.test(t)) continue;+ if (/[│┌┐└┘├┤─═╔╗╚╝]/.test(l)) continue;+ let code = l;+ const start = i;+ while (/\\\s*$/.test(code) && i + 1 < lines.length && !/^\s*(```|~~~)/.test(lines[i + 1]!)) {+ code = code.replace(/\\\s*$/, ' ') + lines[++i]!.trim();+ }+ out.push({ code, line: start + 1, historical: fenceHistorical });+ continue;+ }+ const historical = l.includes(HISTORICAL_MARKER) || markedAbove(i);+ for (const m of l.matchAll(/`(gbrain [^`]+)`/g)) out.push({ code: m[1]!, line: i + 1, historical });+ }+ return out;+}++export interface Invocation { verb: string; argv: string[] }++/** `gbrain <verb>` invocations at command position, with their argv up to the next shell operator. */+export function gbrainInvocations(code: string): Invocation[] {+ const out: Invocation[] = [];+ for (const m of code.matchAll(/\bgbrain\s+([A-Za-z][\w-]*)/g)) {+ const verb = m[1]!;+ if (!/^[a-z][a-z0-9_-]{2,}$/.test(verb)) continue;+ if (!commandPosition(code.slice(0, m.index))) continue;+ out.push({ verb, argv: shellWords(code.slice(m.index! + m[0].length - verb.length)) });+ }+ return out;+}++/**+ * Shell-ish word split of one command: honors quotes, stops at an unquoted+ * pipe/list/redirect/substitution boundary or `#` comment. `[...]` optional+ * groups are unwrapped (their inner `|` is alternation, not a pipe).+ * Placeholder words (`<slug>`, `$VAR`, `{a,b}`, `N`, `CLIENT_ID`) become `1`,+ * a value every typed parser (ids, counts, costs, brain names) accepts.+ */+function shellWords(s: string): string[] {+ const words: string[] = [];+ let cur = '';+ let has = false;+ let depth = 0;+ const flush = () => {+ if (has) words.push(/^[A-Z][A-Z0-9_]*$/.test(cur) ? '1' : cur.replace(/^(--[a-z0-9-]+=)?[<${].*$/i, '$11'));+ cur = '';+ has = false;+ };+ for (let i = 0; i < s.length; i++) {+ const c = s[i]!;+ if (c === "'" || c === '"') {+ const end = s.indexOf(c, i + 1);+ cur += end === -1 ? s.slice(i + 1) : s.slice(i + 1, end);+ has = true;+ if (end === -1) break;+ i = end;+ continue;+ }+ if (c === '[') { depth++; continue; }+ if (c === ']') { depth = Math.max(0, depth - 1); continue; }+ if (/\s/.test(c)) { flush(); continue; }+ if (c === '|' && depth > 0) { flush(); continue; }+ if (/[|;&`)]/.test(c) || (c === '>' && !cur.startsWith('<')) || (c === '#' && !has)) break;+ if (c === '<' && !has && /^<\s/.test(s.slice(i))) break;+ cur += c;+ has = true;+ }+ flush();+ return words.filter((w) => w !== '...' && w !== '…');+}++/**+ * Routes src/cli.ts main() dispatches BEFORE the unknown-flag validator runs:+ * their handlers parse their own flags, so only the verb is checked here.+ */+function dispatchedBeforeValidation(command: string, subArgs: string[]): boolean {+ if (command === 'search') return ['modes', 'stats', 'tune', 'diagnose'].includes(subArgs[0] ?? '');+ if (command === 'sources') return ['inspect', 'connect'].includes(subArgs[0] ?? '')+ || (subArgs[0] === 'demo' && subArgs[1] === 'company-brain');+ return false;+}++/**+ * Run an invocation through the production global-flag parser and the+ * pre-dispatch argument validators, in main()'s order. Returns the reason the+ * real CLI would reject it, or null when it accepts its flags.+ */+export function flagRejection(inv: Invocation): string | null {+ let rest: string[];+ try {+ rest = parseGlobalFlags(inv.argv).rest;+ } catch (e) {+ return (e as Error).message;+ }+ const [typed, ...subArgs] = rest;+ if (!typed || subArgs.some((a) => a === '--help' || a === '-h')) return null;+ const command = typed === 'ask' ? 'query' : typed;+ if (dispatchedBeforeValidation(command, subArgs)) return null;+ const migrationError = migrationCliArgumentError(command, subArgs);+ if (migrationError) return migrationError.message;+ const flag = validateCommandFlags(command, subArgs);+ return flag ? `unknown flag ${flag} for 'gbrain ${typed}'` : null;+}diff --git a/test/hook-push-spawn-env.test.ts b/test/hook-push-spawn-env.test.tsindex f939b9c3e5..fb8ee21bfd 100644--- a/test/hook-push-spawn-env.test.ts+++ b/test/hook-push-spawn-env.test.ts@@ -10,7 +10,7 @@ import { describe, expect, test } from 'bun:test';import { readFileSync } from 'node:fs';import { join } from 'node:path';-// test-reads-source-ok: the property under test is a source SHAPE — every detached/exec spawn in hook.ts must pass `env: process.env` so the cwd-.env quarantine reaches the child; a runtime probe cannot enumerate spawn sites, only grepping the source can.+// test-reads-source-ok[trust-boundary]: the property under test is a source SHAPE — every detached/exec spawn in hook.ts must pass `env: process.env` so the cwd-.env quarantine reaches the child; a runtime probe cannot enumerate spawn sites, only grepping the source can.const SRC = readFileSync(join(import.meta.dir, '../src/commands/hook.ts'), 'utf8');function spawnDetachedPushBody(): string {diff --git a/test/init-env-detection.test.ts b/test/init-env-detection.test.tsindex 0f2fb5cfa8..e244b1e9e5 100644--- a/test/init-env-detection.test.ts+++ b/test/init-env-detection.test.ts@@ -4,7 +4,7 @@* These tests exercise the exported pure helpers (groupReadyByProvider,* findEnvKeyTypos) with hermetic env injections. The resolveAIOptions* orchestration itself is exercised end-to-end via T12's- * test/e2e/init-fresh-pglite.test.ts (piped-stdin, real CLI — non-TTY+ * test/init-fresh-pglite.slow.test.ts (piped-stdin, real CLI — non-TTY* branches) and test/init-picker-pty.serial.test.ts (real PTY — the* interactive picker branches).*diff --git a/test/e2e/init-fresh-pglite.test.ts b/test/init-fresh-pglite.slow.test.tssimilarity index 98%rename from test/e2e/init-fresh-pglite.test.tsrename to test/init-fresh-pglite.slow.test.tsindex 247c0eb572..e6d80b0dc1 100644--- a/test/e2e/init-fresh-pglite.test.ts+++ b/test/init-fresh-pglite.slow.test.ts@@ -17,6 +17,10 @@* at test/init-picker-pty.serial.test.ts (keyless provider choice plus a* non-default search mode, driven through a true pseudo-terminal). This file* stays piped-stdin on purpose: it exercises the NON-TTY branches.+ *+ * Lane: slow. Run: `bash scripts/run-slow-tests.sh test/init-fresh-pglite.slow.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';@@ -24,7 +28,7 @@ import { mkdtempSync, rmSync, existsSync, readFileSync, mkdirSync, writeFileSyncimport { tmpdir } from 'os';import { join } from 'path';-const REPO_ROOT = join(import.meta.dir, '..', '..');+const REPO_ROOT = join(import.meta.dir, '..');const CLI = `bun run ${REPO_ROOT}/src/cli.ts`;/** Run a CLI invocation with a clean GBRAIN_HOME + chosen env. Returns { stdout, stderr, exitCode }. */diff --git a/test/integrations.test.ts b/test/integrations.test.tsindex dd942af673..f0cb8f800b 100644--- a/test/integrations.test.ts+++ b/test/integrations.test.ts@@ -198,76 +198,13 @@ describe('CLI integration', () => {// --- Recipe file validation ---describe('twilio-voice-brain recipe', () => {- test('recipe file parses correctly', () => {+ test('declares the Twilio and OpenAI secrets, each with an https console URL', () => {const { readFileSync } = require('fs');- const content = readFileSync(- new URL('../recipes/twilio-voice-brain.md', import.meta.url),- 'utf-8'- );- const recipe = parseRecipe(content, 'twilio-voice-brain.md');- expect(recipe).not.toBeNull();- expect(recipe!.frontmatter.id).toBe('twilio-voice-brain');- expect(recipe!.frontmatter.category).toBe('sense');- expect(recipe!.frontmatter.secrets.length).toBeGreaterThan(0);- expect(recipe!.frontmatter.health_checks.length).toBeGreaterThan(0);- // Body should not be corrupted (contains --- horizontal rules)- expect(recipe!.body.length).toBeGreaterThan(100);- });-- test('recipe has required secrets with where URLs', () => {- const { readFileSync } = require('fs');- const content = readFileSync(- new URL('../recipes/twilio-voice-brain.md', import.meta.url),- 'utf-8'- );- const recipe = parseRecipe(content, 'twilio-voice-brain.md');- expect(recipe).not.toBeNull();- for (const secret of recipe!.frontmatter.secrets) {- expect(secret.name).toBeTruthy();- expect(secret.where).toBeTruthy();- expect(secret.where).toContain('https://');- }- });-- test('recipe has all required secrets', () => {- const { readFileSync } = require('fs');- const content = readFileSync(- new URL('../recipes/twilio-voice-brain.md', import.meta.url),- 'utf-8'- );- const recipe = parseRecipe(content, 'twilio-voice-brain.md');+ const recipe = parseRecipe(readFileSync(resolve(RECIPES_DIR, 'twilio-voice-brain.md'), 'utf-8'), 'twilio-voice-brain.md');expect(recipe).not.toBeNull();const secretNames = recipe!.frontmatter.secrets.map((s: any) => s.name);- expect(secretNames).toContain('TWILIO_ACCOUNT_SID');- expect(secretNames).toContain('TWILIO_AUTH_TOKEN');- expect(secretNames).toContain('OPENAI_API_KEY');- });-- test('recipe version is valid semver', () => {- const { readFileSync } = require('fs');- const content = readFileSync(- new URL('../recipes/twilio-voice-brain.md', import.meta.url),- 'utf-8'- );- const recipe = parseRecipe(content, 'twilio-voice-brain.md');- expect(recipe).not.toBeNull();- expect(recipe!.frontmatter.version).toMatch(/^\d+\.\d+\.\d+$/);- });-- test('recipe requires resolve to existing recipe files', () => {- const { readFileSync, existsSync } = require('fs');- const { resolve } = require('path');- const content = readFileSync(- new URL('../recipes/twilio-voice-brain.md', import.meta.url),- 'utf-8'- );- const recipe = parseRecipe(content, 'twilio-voice-brain.md');- expect(recipe).not.toBeNull();- const recipesDir = RECIPES_DIR;- for (const dep of recipe!.frontmatter.requires) {- const depPath = resolve(recipesDir, `${dep}.md`);- expect(existsSync(depPath)).toBe(true);- }+ expect(secretNames).toEqual(expect.arrayContaining(['TWILIO_ACCOUNT_SID', 'TWILIO_AUTH_TOKEN', 'OPENAI_API_KEY']));+ for (const secret of recipe!.frontmatter.secrets) expect(secret.where).toContain('https://');});});@@ -312,8 +249,24 @@ describe('all recipes', () => {for (const file of files) {const content = readFileSync(resolve(recipesDir, file), 'utf-8');const recipe = parseRecipe(content, file);- expect(recipe).not.toBeNull();- expect(recipe!.frontmatter.id).toBeTruthy();+ expect(recipe, file).not.toBeNull();+ expect(recipe!.frontmatter.id, file).toBeTruthy();+ }+ });++ test('every recipe has a semver version, named secrets that say where to get them, and requires that resolve', () => {+ const { readFileSync, readdirSync, existsSync } = require('fs');+ const files = readdirSync(RECIPES_DIR).filter((f: string) => f.endsWith('.md'));+ for (const file of files) {+ const recipe = parseRecipe(readFileSync(resolve(RECIPES_DIR, file), 'utf-8'), file)!;+ expect(recipe.frontmatter.version, file).toMatch(/^\d+\.\d+\.\d+$/);+ for (const secret of recipe.frontmatter.secrets) {+ expect(secret.name, file).toBeTruthy();+ expect(secret.where, `${file} ${secret.name}`).toBeTruthy();+ }+ for (const dep of recipe.frontmatter.requires) {+ expect(existsSync(resolve(RECIPES_DIR, `${dep}.md`)), `${file} requires ${dep}`).toBe(true);+ }}});diff --git a/test/lease-cap-controller.test.ts b/test/lease-cap-controller.test.tsdeleted file mode 100644index e79e8159b3..0000000000--- a/test/lease-cap-controller.test.ts+++ /dev/null@@ -1,160 +0,0 @@-/**- * v0.41 E5 + Eng D6 — lease-cap controller tests.- *- * IRON-RULE regression suite for the Eng D6 sign-error correction:- * bounces with NO 429s = workers starving = cap should go UP not DOWN.- * Pre-correction, the controller would crater the cap during a healthy- * 100-job burst (the field-report scenario). This test pins the right- * sign so a future "let's simplify the rule" PR can't silently regress it.- *- * Pure-function tests on nextLeaseCap; no DB needed.- */--import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';-import {- nextLeaseCap,- controllerTick,- readControllerWindow,- readCurrentLeaseCap,- writeLeaseCap,- DEFAULT_CONTROLLER_OPTS,- type ControllerWindowStats,-} from '../src/core/minions/lease-cap-controller.ts';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';--function stableWindow(opts: Partial<ControllerWindowStats> = {}): ControllerWindowStats {- return {- bounce_count: 0,- upstream_429_count: 0,- lease_utilization: 0.7,- latency_stable: true,- window_ms: 60_000,- ...opts,- };-}--describe('nextLeaseCap (Eng D6 IRON-RULE: bounces without 429 = ramp UP)', () => {- test('REGRESSION GUARD: bounces only + no 429 = RAMP UP (was: ramp down)', () => {- const next = nextLeaseCap(32, stableWindow({ bounce_count: 5, upstream_429_count: 0 }));- expect(next).toBeGreaterThan(32);- });-- test('429s only + no bounces = ramp DOWN', () => {- const next = nextLeaseCap(32, stableWindow({ upstream_429_count: 2 }));- expect(next).toBeLessThan(32);- });-- test('429s + bounces (mixed) = ramp DOWN (upstream signal wins)', () => {- // Codex pass-3 verified this case explicitly.- const next = nextLeaseCap(32, stableWindow({ bounce_count: 10, upstream_429_count: 2 }));- expect(next).toBeLessThan(32);- });-- test('latency unstable = ramp DOWN even on bounces-only', () => {- const next = nextLeaseCap(32, stableWindow({ bounce_count: 5, latency_stable: false }));- expect(next).toBeLessThan(32);- });-- test('healthy window (no bounces, util > threshold, latency stable) = ramp UP slow', () => {- const next = nextLeaseCap(32, stableWindow({ lease_utilization: 0.8 }));- expect(next).toBeGreaterThan(32);- });-- test('deadband (no bounces + low util) = no change', () => {- const next = nextLeaseCap(32, stableWindow({ lease_utilization: 0.2 }));- expect(next).toBe(32);- });-- test('ceiling clamps ramp UP', () => {- const next = nextLeaseCap(127, stableWindow({ bounce_count: 10 }));- expect(next).toBe(128); // hit the ceiling- });-- test('floor clamps ramp DOWN', () => {- const next = nextLeaseCap(4, stableWindow({ upstream_429_count: 5 }));- expect(next).toBe(4); // already at floor- });-- test('asymmetric AIMD steps: ramp-down step > ramp-up step', () => {- expect(DEFAULT_CONTROLLER_OPTS.ramp_down_step).toBeGreaterThan(DEFAULT_CONTROLLER_OPTS.ramp_up_step);- });-});--describe('field-report scenario simulation', () => {- test('starving workers (bounces but no upstream pushback) get MORE capacity, not less', () => {- // Simulates the field report: 100 jobs at concurrency=10 with cap=8.- // Workers bounce because the lease is full; upstream is healthy- // (Azure Sweden, no provider rate limit → no 429s; latency stable).- // Correct behavior: cap goes UP to 12, 16, 20... until either- // bounces stop or upstream pushes back.- let cap = 8;- const window: ControllerWindowStats = stableWindow({- bounce_count: 50,- upstream_429_count: 0,- lease_utilization: 1.0,- latency_stable: true,- });- // Run 5 controller ticks under steady starvation.- for (let i = 0; i < 5; i++) {- cap = nextLeaseCap(cap, window);- }- // After 5 ticks of starvation signal, cap should have ramped up.- expect(cap).toBeGreaterThan(8);- expect(cap).toBeGreaterThanOrEqual(8 + 5 * DEFAULT_CONTROLLER_OPTS.ramp_up_step - 0);- });-- test('upstream overload (429 burst) ramps cap DOWN aggressively', () => {- let cap = 64;- const window: ControllerWindowStats = stableWindow({- upstream_429_count: 10,- latency_stable: false,- });- for (let i = 0; i < 5; i++) {- cap = nextLeaseCap(cap, window);- }- // 5 ticks at ramp_down_step=8 = -40 from 64. Floor stops at 4.- expect(cap).toBeLessThanOrEqual(64 - 5 * DEFAULT_CONTROLLER_OPTS.ramp_down_step);- expect(cap).toBeGreaterThanOrEqual(DEFAULT_CONTROLLER_OPTS.min_floor);- });-});--describe('controllerTick integration (PGLite)', () => {- let engine: PGLiteEngine;-- beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({ database_url: '' });- await engine.initSchema();- });-- afterAll(async () => {- await engine.disconnect();- });-- beforeEach(async () => {- await engine.executeRaw(`DELETE FROM gbrain_cycle_locks WHERE id = 'minions-lease-cap-controller'`);- await engine.executeRaw(`DELETE FROM minion_lease_pressure_log`);- await engine.executeRaw(`DELETE FROM minion_jobs`);- await engine.executeRaw(`DELETE FROM config WHERE key = 'minions.lease_cap_current'`);- });-- test('first tick on empty brain returns no change (deadband)', async () => {- const r = await controllerTick(engine);- expect(r).not.toBeNull();- expect(r!.changed).toBe(false);- expect(r!.next).toBe(r!.previous);- });-- test('writeLeaseCap + readCurrentLeaseCap roundtrip', async () => {- await writeLeaseCap(engine, 48);- const got = await readCurrentLeaseCap(engine);- expect(got).toBe(48);- });-- test('readControllerWindow returns zero counts on empty brain', async () => {- const w = await readControllerWindow(engine, 60_000);- expect(w.bounce_count).toBe(0);- expect(w.upstream_429_count).toBe(0);- expect(w.latency_stable).toBe(true); // default-true- });-});diff --git a/test/link-extraction-relative-path.test.ts b/test/link-extraction-relative-path.test.tsindex 569d5543d8..f8ada3e607 100644--- a/test/link-extraction-relative-path.test.ts+++ b/test/link-extraction-relative-path.test.ts@@ -92,16 +92,6 @@ describe('relative markdown-link resolution (nested / subtree-scoped content)',expect(candidates.map(c => c.targetSlug)).toContain('ops/services/pointer-agent');});- test('flat layout unchanged: verb inference still fires on the resolved slug', async () => {- const { candidates } = await extractPageLinks(- 'people/carol', 'Carol founded [Widget Co](../startups/widget-co.md) in 2024.',- {}, 'person', nullResolver, { skipFrontmatter: true },- );- const c = candidates.find(x => x.targetSlug === 'startups/widget-co');- expect(c).toBeDefined();- expect(c!.linkType).toBe('founded');- });-test('LINK_EXTRACTOR_VERSION_TS was bumped so stamped pages re-extract', () => {// Behavior changed, so previously-stamped pages must re-sweep to pick up// the newly-resolvable cross-dir edges.diff --git a/test/mcp-instructions-writeback.test.ts b/test/mcp-instructions-writeback.test.tsindex 489f241ee6..431c006270 100644--- a/test/mcp-instructions-writeback.test.ts+++ b/test/mcp-instructions-writeback.test.ts@@ -8,8 +8,8 @@* (stdio + OAuth enabled-state coverage rides the hermetic e2e fixture,* test/e2e/ambient-writeback-lifecycle.serial.test.ts — those transports need* a real subprocess/app boot. The three existing byte-exact OFF pins are- * test/e2e/serve-stdio-roundtrip.test.ts, test/http-transport.test.ts, and- * test/e2e/connect-bearer.test.ts and run unchanged.)+ * test/serve-stdio-roundtrip.test.ts, test/http-transport.test.ts, and+ * test/connect-bearer.test.ts and run unchanged.)*/import { describe, test, expect, afterAll } from 'bun:test';import { createHash } from 'node:crypto';diff --git a/test/mcp-registration-blocks.test.ts b/test/mcp-registration-blocks.test.tsindex 3a2cd5fb60..0b9b243483 100644--- a/test/mcp-registration-blocks.test.ts+++ b/test/mcp-registration-blocks.test.ts@@ -9,29 +9,9 @@*/import { describe, expect, test } from 'bun:test';-import { readFileSync } from 'fs';-import { dirname, join } from 'path';import { OAUTH_SECRET_NOTE, openclawThinClientBlock } from '../src/core/mcp-registration.ts';import { OAUTH_SECRET_NOTE as CONNECT_REEXPORTED_NOTE } from '../src/commands/connect.ts';-const ROOT = dirname(import.meta.dir);--describe('OpenClaw stdio registration docs (#4842)', () => {- // OpenClaw 2026.8.x reads ~/.openclaw/openclaw.json `mcp.servers`, never- // ~/.openclaw/config.json `mcpServers`; the supported wiring is the CLI.- const openclawDoc = readFileSync(join(ROOT, 'docs/mcp/OPENCLAW.md'), 'utf8');- const readme = readFileSync(join(ROOT, 'README.md'), 'utf8');-- test('no doc prescribes the retired ~/.openclaw/config.json path', () => {- expect(openclawDoc).not.toMatch(/~\/\.openclaw\/config\.json/);- expect(readme).not.toMatch(/~\/\.openclaw\/config\.json/);- });-- test('OPENCLAW.md registers via the openclaw mcp CLI', () => {- expect(openclawDoc).toContain('openclaw mcp add');- });-});-const OPTS = {issuerUrl: 'https://brain.example.com',mcpUrl: 'https://brain.example.com/mcp',diff --git a/test/migrate.test.ts b/test/migrate.test.tsindex 68d2badfe0..d6dcddc095 100644--- a/test/migrate.test.ts+++ b/test/migrate.test.ts@@ -13,10 +13,6 @@ describe('migrate', () => {expect(LATEST_VERSION).toBeGreaterThanOrEqual(1);});- test('runMigrations is exported and callable', async () => {- expect(typeof runMigrations).toBe('function');- });-// Integration tests for actual migration execution require DATABASE_URL// and are covered in the E2E suite (test/e2e/mechanical.test.ts)});diff --git a/test/migration-orchestrator-v0_21_0.test.ts b/test/migration-orchestrator-v0_21_0.test.tsindex 6621003f03..3bbb609871 100644--- a/test/migration-orchestrator-v0_21_0.test.ts+++ b/test/migration-orchestrator-v0_21_0.test.ts@@ -29,13 +29,6 @@ describe('v0.21.0 orchestrator — Cathedral II migration', () => {expect(desc).toContain('fence extraction');});- test('phase functions exported for unit testing', async () => {- const { __testing } = await import('../src/commands/migrations/v0_21_0.ts');- expect(typeof __testing.phaseASchema).toBe('function');- expect(typeof __testing.phaseBBackfillPrompt).toBe('function');- expect(typeof __testing.phaseCVerify).toBe('function');- });-test('dry-run skips all side-effect phases', async () => {const { v0_21_0 } = await import('../src/commands/migrations/v0_21_0.ts');const result = await v0_21_0.orchestrator({diff --git a/test/migrations-v0_12_0.test.ts b/test/migrations-v0_12_0.test.tsindex 049a9886f7..b6ac8c6e85 100644--- a/test/migrations-v0_12_0.test.ts+++ b/test/migrations-v0_12_0.test.ts@@ -7,7 +7,6 @@* - Empty brain → succeeds (the Phase E branch that says "auto-link will* wire entities as you write pages").* - auto_link disabled → backfill phases skipped, recorded as complete.- * - Phase functions exported via __testing for unit-level coverage.*/import { describe, test, expect } from 'bun:test';@@ -34,16 +33,6 @@ describe('v0.12.0 — Knowledge Graph auto-wire migration', () => {expect(desc).toContain('57.8%');});- test('phase functions exported for unit testing', async () => {- const { __testing } = await import('../src/commands/migrations/v0_12_0.ts');- expect(typeof __testing.phaseASchema).toBe('function');- expect(typeof __testing.phaseBConfigCheck).toBe('function');- expect(typeof __testing.phaseCBackfillLinks).toBe('function');- expect(typeof __testing.phaseDBackfillTimeline).toBe('function');- expect(typeof __testing.phaseEVerify).toBe('function');- expect(typeof __testing.readStats).toBe('function');- });-test('dry-run skips all side-effect phases', async () => {const { v0_12_0 } = await import('../src/commands/migrations/v0_12_0.ts');const result = await v0_12_0.orchestrator({diff --git a/test/migrations-v0_12_2.test.ts b/test/migrations-v0_12_2.test.tsindex 14e6163181..4f79f3b1b0 100644--- a/test/migrations-v0_12_2.test.ts+++ b/test/migrations-v0_12_2.test.ts@@ -3,7 +3,6 @@** Covers the contract that makes this migration safe to ship:* - Registered in the TS registry (so apply-migrations sees it).- * - Phase functions exported via __testing for unit-level coverage.* - Dry-run skips all side-effect phases.* - Feature pitch explains what the user can NOW do that they couldn't.*@@ -35,13 +34,6 @@ describe('v0.12.2 — JSONB double-encode repair migration', () => {expect(desc).toContain('gbrain sync --full');});- test('phase functions exported for unit testing', async () => {- const { __testing } = await import('../src/commands/migrations/v0_12_2.ts');- expect(typeof __testing.phaseASchema).toBe('function');- expect(typeof __testing.phaseBRepair).toBe('function');- expect(typeof __testing.phaseCVerify).toBe('function');- });-test('dry-run skips all side-effect phases', async () => {const { v0_12_2 } = await import('../src/commands/migrations/v0_12_2.ts');const result = await v0_12_2.orchestrator({diff --git a/test/migrations-v0_13_0.test.ts b/test/migrations-v0_13_0.test.tsindex 6882dd5058..8e213fe5d2 100644--- a/test/migrations-v0_13_0.test.ts+++ b/test/migrations-v0_13_0.test.ts@@ -24,13 +24,6 @@ describe('v0.13.0 — Frontmatter relationship indexing migration', () => {expect(typeof m!.orchestrator).toBe('function');});- test('phase functions exported for unit testing', async () => {- const { __testing } = await import('../src/commands/migrations/v0_13_0.ts');- expect(typeof __testing.phaseASchema).toBe('function');- expect(typeof __testing.phaseBBackfill).toBe('function');- expect(typeof __testing.phaseCVerify).toBe('function');- });-test('dry-run skips all side-effect phases', async () => {const { v0_13_0 } = await import('../src/commands/migrations/v0_13_0.ts');const result = await v0_13_0.orchestrator({ yes: true, dryRun: true, noAutopilotInstall: true });diff --git a/test/e2e/minions-field-report-repro.test.ts b/test/minions-field-report-repro.test.tssimilarity index 79%rename from test/e2e/minions-field-report-repro.test.tsrename to test/minions-field-report-repro.test.tsindex 801f6f29d6..505a8e19d7 100644--- a/test/e2e/minions-field-report-repro.test.ts+++ b/test/minions-field-report-repro.test.ts@@ -13,13 +13,18 @@* 5x then succeeds exercises the same code path as the real handler.** Runs against PGLite — no DATABASE_URL needed.+ *+ * Lane: unit. Run: `bun test test/minions-field-report-repro.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { MinionQueue } from '../../src/core/minions/queue.ts';-import { MinionWorker } from '../../src/core/minions/worker.ts';-import { RateLeaseUnavailableError } from '../../src/core/minions/handlers/subagent.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { MinionWorker } from '../src/core/minions/worker.ts';+import { RateLeaseUnavailableError } from '../src/core/minions/handlers/subagent.ts';+import { waitFor } from './helpers/wait-for.ts';let engine: PGLiteEngine;let queue: MinionQueue;@@ -72,11 +77,16 @@ describe('v0.41 field-report repro (Bug 2 IRON-RULE regression)', () => {});const workerPromise = worker.start();- // Give the worker enough wall-clock for 12 jobs × 2 bounces × ~2s- // jitter avg + 1 success per job. Pad generously.- await new Promise(r => setTimeout(r, 25_000));- worker.stop();- await workerPromise;+ const settled = new Set(['completed', 'dead', 'failed', 'cancelled']);+ try {+ await waitFor(async () => {+ const jobs = await Promise.all(ids.map(id => queue.getJob(id)));+ return jobs.every(j => settled.has(j!.status));+ }, { timeoutMs: 30_000, intervalMs: 100, label: 'all repro jobs settled' });+ } finally {+ worker.stop();+ await workerPromise;+ }// Every job should be completed.const final = await Promise.all(ids.map(id => queue.getJob(id)));diff --git a/test/minions-quiet-hours.test.ts b/test/minions-quiet-hours.test.tsindex a9d238cd51..04357d01e7 100644--- a/test/minions-quiet-hours.test.ts+++ b/test/minions-quiet-hours.test.ts@@ -1,5 +1,5 @@/**- * Quiet-hours + stagger tests — pure primitives + migration verification.+ * Quiet-hours tests — pure primitives + migration verification.** Worker-loop integration (claim → release on quiet verdict) is covered by* the existing Minions resilience E2E when combined with this unit coverage:@@ -20,7 +20,6 @@ import {localHour,type QuietHoursConfig,} from '../src/core/minions/quiet-hours.ts';-import { staggerMinuteOffset, staggerSecondOffset } from '../src/core/minions/stagger.ts';// ---------------------------------------------------------------------------// Pure: evaluateQuietHours@@ -130,45 +129,6 @@ describe('localHour', () => {});});-// ----------------------------------------------------------------------------// Pure: staggerMinuteOffset-// -----------------------------------------------------------------------------describe('staggerMinuteOffset', () => {- test('empty or non-string → 0', () => {- expect(staggerMinuteOffset('')).toBe(0);- // @ts-expect-error: runtime guard- expect(staggerMinuteOffset(null)).toBe(0);- });-- test('returns 0–59', () => {- for (const k of ['social-radar', 'x-ingest', 'perplexity', 'sync-all']) {- const v = staggerMinuteOffset(k);- expect(v).toBeGreaterThanOrEqual(0);- expect(v).toBeLessThan(60);- }- });-- test('deterministic: same key always same offset', () => {- const a = staggerMinuteOffset('social-radar');- const b = staggerMinuteOffset('social-radar');- expect(a).toBe(b);- });-- test('different keys produce different offsets (most of the time)', () => {- const keys = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];- const offsets = new Set(keys.map(staggerMinuteOffset));- // With 10 distinct keys and 60 buckets, expect at least 5 unique- // (collision rate stays well under 50% at this small sample size)- expect(offsets.size).toBeGreaterThanOrEqual(5);- });-- test('second offset is 60x minute offset', () => {- const key = 'social-radar';- expect(staggerSecondOffset(key)).toBe(staggerMinuteOffset(key) * 60);- });-});-// ---------------------------------------------------------------------------// Schema migration v12 applies// ---------------------------------------------------------------------------diff --git a/test/models-doctor-embed.test.ts b/test/models-doctor-embed.test.tsindex bf718a9a90..df3d453373 100644--- a/test/models-doctor-embed.test.ts+++ b/test/models-doctor-embed.test.ts@@ -1,50 +1,82 @@-import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'node:fs';-import { join } from 'node:path';-/*** v0.40.x — `gbrain models doctor` embedding reachability probe.*- * `probeEmbeddingReachability` is an internal (non-exported) function with a- * network side effect, mirroring the existing `probeRerankerReachability`- * which has no behavioral test either. Rather than export it purely for a- * test and reconstruct the embed dim-check stub, this pins the three- * structural invariants codex flagged during plan review (the error-branch- * classification itself comes from `classifyError`, already covered):- *- * #6 — uses `embed(...)`, NOT `embedQuery` (embedQuery takes no abortSignal)- * #7 — a distinct `'embedding_reachability'` ProbeResult.touchpoint member- * #8 — gated on probeEmbeddingConfig returning 'ok' (no double-reporting)- *- * Source-text assertions, same convention as test/v0_37_gap_fill.serial.test.ts.+ * The probe sends one real `embed(['probe'])` as a query with an abort signal+ * (embedQuery takes no signal) and reports a distinct+ * `embedding_reachability` row; runModels runs it only when the zero-network+ * embedding config probe passed, so a config failure is not reported twice.+ * The embed transport is injected and fetch is stubbed offline; chat probes are+ * skipped with --skip=anthropic.*/++import { afterEach, describe, expect, spyOn, test } from 'bun:test';+import { probeEmbeddingReachability, runModels } from '../src/commands/models.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';++type EmbedFn = typeof import('../src/core/ai/gateway.ts').embed;+type EmbedManyFn = Parameters<typeof __setEmbedTransportForTests>[0];++afterEach(() => {+ __setEmbedTransportForTests(null);+ resetGateway();+});++const stubEngine = { getConfig: async () => null, getPage: async () => ({ source_id: 'default' }) };++async function doctor(embeddingModel: string, dims: number): Promise<{ probes: Array<{ touchpoint: string; status: string }>; embedCalls: number }> {+ configureGateway({+ embedding_model: embeddingModel,+ embedding_dimensions: dims,+ chat_model: 'anthropic:claude-sonnet-5',+ expansion_model: 'anthropic:claude-haiku-4-5',+ env: { OPENAI_API_KEY: 'test-key', VOYAGE_API_KEY: 'test-key' },+ });+ let embedCalls = 0;+ __setEmbedTransportForTests((async (opts: { values: string[] }) => {+ embedCalls++;+ return { embeddings: opts.values.map(() => new Array(dims).fill(0.1)), usage: { tokens: 1 } };+ }) as unknown as EmbedManyFn);+ let stdout = '';+ const write = spyOn(process.stdout, 'write').mockImplementation(((chunk: string | Uint8Array) => { stdout += String(chunk); return true; }) as never);+ const stderr = spyOn(process.stderr, 'write').mockImplementation((() => true) as never);+ const exit = spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ const offline = spyOn(globalThis, 'fetch').mockImplementation((async () => { throw new Error('offline'); }) as never);+ try {+ await runModels(stubEngine as never, ['doctor', '--json', '--skip=anthropic']);+ } finally {+ write.mockRestore(); stderr.mockRestore(); exit.mockRestore(); offline.mockRestore();+ }+ return { probes: JSON.parse(stdout).probes, embedCalls };+}+describe('models doctor — embedding reachability probe (v0.40.x)', () => {- const src = readFileSync(join(__dirname, '..', 'src', 'commands', 'models.ts'), 'utf-8');+ test('sends one query-typed embed with an abort signal and reports embedding_reachability', async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'test-key' } });+ const calls: Array<{ texts: string[]; opts: Record<string, unknown> }> = [];+ const embed = (async (texts: string[], opts: Record<string, unknown>) => { calls.push({ texts, opts }); return [new Float32Array(1536)]; }) as unknown as EmbedFn;+ const ok = await probeEmbeddingReachability({ embed });+ expect(calls).toHaveLength(1);+ expect(calls[0].texts).toEqual(['probe']);+ expect(calls[0].opts.inputType).toBe('query');+ expect(calls[0].opts.abortSignal).toBeInstanceOf(AbortSignal);+ expect(ok).toMatchObject({ touchpoint: 'embedding_reachability', status: 'ok' });- test("ProbeResult.touchpoint declares 'embedding_reachability' (codex #7)", () => {- expect(src).toContain("'embedding_reachability'");- // Distinct from the zero-network config probe's touchpoint.- expect(src).toContain("'embedding_config'");+ const failing = (async () => { throw new Error('401 Unauthorized'); }) as unknown as EmbedFn;+ expect(await probeEmbeddingReachability({ embed: failing, fetchImpl: (async () => { throw new Error('offline'); }) as unknown as typeof fetch }))+ .toMatchObject({ touchpoint: 'embedding_reachability', status: 'auth' });});- test('probeEmbeddingReachability uses embed() with inputType query + abort signal (codex #6)', () => {- const fnIdx = src.indexOf('async function probeEmbeddingReachability');- expect(fnIdx).toBeGreaterThan(0);- const slice = src.slice(fnIdx, fnIdx + 1500);- expect(slice).toContain('embed([');- expect(slice).toContain("inputType: 'query'");- expect(slice).toContain('abortSignal');- // Must NOT use embedQuery (no abort signal support — codex #6).- expect(slice).not.toContain('embedQuery(');+ test('runModels probes reachability once when the embedding config is valid', async () => {+ const { probes, embedCalls } = await doctor('openai:text-embedding-3-small', 1536);+ expect(probes.find(p => p.touchpoint === 'embedding_config')?.status).toBe('ok');+ expect(probes.filter(p => p.touchpoint === 'embedding_reachability')).toEqual([expect.objectContaining({ status: 'ok' })]);+ expect(embedCalls).toBe(1);});- test('runModels gates embedding reachability on config-probe ok (codex #8)', () => {- const runIdx = src.indexOf('export async function runModels');- expect(runIdx).toBeGreaterThan(0);- const slice = src.slice(runIdx);- // The config probe result is captured and the reachability call is gated- // on its status === 'ok' before firing.- expect(slice).toContain('const embeddingConfig = await probeEmbeddingConfig()');- expect(slice).toMatch(/embeddingConfig\.status === 'ok'[\s\S]*probeEmbeddingReachability\(/);+ test('runModels skips the reachability probe when the embedding config probe fails', async () => {+ const { probes, embedCalls } = await doctor('voyage:voyage-4', 999);+ expect(probes.find(p => p.touchpoint === 'embedding_config')?.status).toBe('config');+ expect(probes.some(p => p.touchpoint === 'embedding_reachability')).toBe(false);+ expect(embedCalls).toBe(0);});});diff --git a/test/e2e/mounts-routing-pglite.test.ts b/test/mounts-routing-pglite.slow.test.tssimilarity index 96%rename from test/e2e/mounts-routing-pglite.test.tsrename to test/mounts-routing-pglite.slow.test.tsindex 9240fa6506..ffe557333a 100644--- a/test/e2e/mounts-routing-pglite.test.ts+++ b/test/mounts-routing-pglite.slow.test.ts@@ -2,8 +2,8 @@* G4 (test-gap plan) — the mount ROUTING journey: brain-resolver → engine* wiring exercised over REAL CLI spawns against two REAL PGLite databases* (host brain + one mount). Hermetic: no DATABASE_URL, no provider keys.- * Lives in test/e2e/ because it spawns `bun run src/cli.ts` repeatedly, not- * because it needs a live Postgres.+ * Runs in the slow lane because it spawns `bun run src/cli.ts` repeatedly;+ * it needs no live Postgres.** The REAL tier order (pinned from src/core/brain-resolver.ts:resolveBrainId):* 1. explicit `--brain <id>` flag@@ -39,19 +39,23 @@* the in-process seed); every later spawn just reopens the data dir (~1.5s).* The subcommand DISPATCH surface (parseAddArgs, redactUrl, flag verbs) is* already covered in test/mounts-cli.test.ts — not duplicated here.+ *+ * Lane: slow. Run: `bash scripts/run-slow-tests.sh test/mounts-routing-pglite.slow.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test as testRaw, expect, beforeAll, afterAll } from 'bun:test';import { mkdtempSync, rmSync, mkdirSync, writeFileSync, symlinkSync, chmodSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';function test(name: string, fn: () => void | Promise<unknown>): void {testRaw(name, fn, 120000);}-const CLI = join(import.meta.dir, '..', '..', 'src', 'cli.ts');+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');const SLUG = 'routing-marker';const HOST_MARKER = 'HOST-MARKER-7f3a1c';diff --git a/test/no-tracked-symlinks-guard.test.ts b/test/no-tracked-symlinks-guard.test.tsindex bc730d9fbf..4b0eb51f02 100644--- a/test/no-tracked-symlinks-guard.test.ts+++ b/test/no-tracked-symlinks-guard.test.ts@@ -16,20 +16,15 @@*/import { describe, it, expect } from 'bun:test';-import { existsSync, statSync, mkdtempSync, rmSync, writeFileSync, symlinkSync } from 'fs';+import { mkdtempSync, rmSync, writeFileSync, symlinkSync } from 'fs';import { resolve, join } from 'path';import { tmpdir } from 'os';import { spawnSync } from 'child_process';const REPO_ROOT = resolve(import.meta.dir, '..');const GUARD = resolve(REPO_ROOT, 'scripts/check-no-tracked-symlinks.sh');-const VERIFY_DISPATCHER = resolve(REPO_ROOT, 'scripts/run-verify-parallel.sh');describe('check-no-tracked-symlinks.sh', () => {- it('exists and is executable', () => {- expect(existsSync(GUARD)).toBe(true);- expect((statSync(GUARD).mode & 0o100) !== 0).toBe(true);- });it('passes on this repo (no tracked symlinks)', () => {const r = spawnSync('bash', [GUARD], { cwd: REPO_ROOT, encoding: 'utf-8' });@@ -62,14 +57,6 @@ describe('check-no-tracked-symlinks.sh', () => {}});- it('is wired into the verify dispatcher', () => {- const r = spawnSync('bash', [VERIFY_DISPATCHER, '--dry-list'], {- cwd: REPO_ROOT,- encoding: 'utf-8',- });- expect(r.status).toBe(0);- expect(new Set(r.stdout.trim().split('\n'))).toContain('check:no-tracked-symlinks');- });});describe('.gitignore node_modules patterns', () => {diff --git a/test/nudge.test.ts b/test/nudge.test.tsdeleted file mode 100644index 80721eb051..0000000000--- a/test/nudge.test.ts+++ /dev/null@@ -1,299 +0,0 @@-/**- * v0.36.1.0 (T13 / E7) — nudge cooldown + threshold tests.- *- * Hermetic. Mock engine + injected stderr stream. No production stderr writes.- *- * Tests cover:- * - threshold gates: no profile, wrong holder, below conviction, no domain match- * - happy match path: above conviction + bias tag matches domain hint- * - cooldown: same pattern fired in last 14 days → silently skip- * - cooldown: same pattern fired > 14 days ago → fire (cooldown expired)- * - takeDomainHint: companies → hiring, macro/geography/tactics keywords match- * - resetNudgeCooldown: deletes rows for the take- * - log insertion captures (source_id, take_id, pattern, channel='stderr')- */--import { describe, test, expect } from 'bun:test';-import {- evaluateAndFireNudge,- evaluateNudgeRule,- takeDomainHint,- checkCooldown,- resetNudgeCooldown,- buildNudgeText,- NUDGE_COOLDOWN_DAYS,- NUDGE_CONVICTION_THRESHOLD,-} from '../src/core/calibration/nudge.ts';-import type { CalibrationProfileRow } from '../src/commands/calibration.ts';-import type { BrainEngine, Take } from '../src/core/engine.ts';--function buildTake(overrides: Partial<Take> = {}): Take {- return {- id: 1,- page_id: 100,- page_slug: 'wiki/companies/acme-example',- row_num: 1,- claim: 'Marketplaces with cold-start liquidity always win.',- kind: 'bet',- holder: 'garry',- weight: 0.85,- since_date: '2026-05-17',- until_date: null,- source: null,- superseded_by: null,- active: true,- resolved_at: null,- resolved_outcome: null,- resolved_quality: null,- resolved_value: null,- resolved_unit: null,- resolved_source: null,- resolved_by: null,- created_at: '2026-05-17T00:00:00Z',- updated_at: '2026-05-17T00:00:00Z',- ...overrides,- } as Take;-}--function buildProfile(activeBiasTags: string[], holder = 'garry'): CalibrationProfileRow {- return {- id: '1',- source_id: 'default',- holder,- wave_version: 'v0.36.1.0',- generated_at: '2026-05-17T00:00:00Z',- published: false,- total_resolved: 20,- brier: 0.21,- accuracy: 0.6,- partial_rate: 0.1,- grade_completion: 1.0,- pattern_statements: ['some pattern'],- active_bias_tags: activeBiasTags,- voice_gate_passed: true,- voice_gate_attempts: 1,- model_id: 'claude-sonnet-4-6',- };-}--interface SqlCall {- sql: string;- params: unknown[];-}--function buildMockEngine(opts: {- cooldownRows?: number; // 1 = active cooldown, 0 = no cooldown- deleteReturning?: number; // count of rows DELETE...RETURNING simulates-}): { engine: BrainEngine; sqls: SqlCall[] } {- const sqls: SqlCall[] = [];- const engine = {- kind: 'pglite',- async executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> {- sqls.push({ sql, params: params ?? [] });- if (sql.includes('SELECT id FROM take_nudge_log')) {- return new Array(opts.cooldownRows ?? 0).fill({ id: 1 }) as unknown as T[];- }- if (sql.includes('DELETE FROM take_nudge_log')) {- return new Array(opts.deleteReturning ?? 0).fill({ id: 1 }) as unknown as T[];- }- return [];- },- } as unknown as BrainEngine;- return { engine, sqls };-}--// ─── takeDomainHint ─────────────────────────────────────────────────--describe('takeDomainHint', () => {- test('companies/ slug → hiring', () => {- expect(takeDomainHint(buildTake({ page_slug: 'wiki/companies/acme' }))).toBe('hiring');- });-- test('people/ slug → founder-behavior', () => {- expect(takeDomainHint(buildTake({ page_slug: 'wiki/people/alice' }))).toBe('founder-behavior');- });-- test('macro keyword → macro', () => {- expect(takeDomainHint(buildTake({ page_slug: 'wiki/macro/forecast' }))).toBe('macro');- });-- test('geography keyword → geography', () => {- expect(takeDomainHint(buildTake({ page_slug: 'wiki/geography/ny' }))).toBe('geography');- });-- test('unrecognized slug → empty hint', () => {- expect(takeDomainHint(buildTake({ page_slug: 'wiki/random/x' }))).toBe('');- });-});--// ─── evaluateNudgeRule (pure) ───────────────────────────────────────--describe('evaluateNudgeRule', () => {- test('no profile → matched=false with reason=no_profile', () => {- expect(evaluateNudgeRule(buildTake(), null)).toEqual({ matched: false, reason: 'no_profile' });- });-- test('wrong holder → matched=false with reason=wrong_holder', () => {- const profile = buildProfile(['over-confident-hiring'], 'alice');- expect(evaluateNudgeRule(buildTake({ holder: 'garry' }), profile).reason).toBe('wrong_holder');- });-- test('conviction at threshold → matched=false (strict >)', () => {- const profile = buildProfile(['over-confident-hiring']);- expect(- evaluateNudgeRule(buildTake({ weight: NUDGE_CONVICTION_THRESHOLD }), profile).reason,- ).toBe('below_conviction_threshold');- });-- test('no matching bias tag → matched=false with reason=no_matching_bias_tag', () => {- const profile = buildProfile(['late-on-macro-tech']);- expect(- evaluateNudgeRule(buildTake({ page_slug: 'wiki/companies/acme' }), profile).reason,- ).toBe('no_matching_bias_tag');- });-- test('happy match: companies slug + hiring tag', () => {- const profile = buildProfile(['over-confident-hiring']);- const out = evaluateNudgeRule(buildTake({ page_slug: 'wiki/companies/acme' }), profile);- expect(out.matched).toBe(true);- expect(out.matchedTag).toBe('over-confident-hiring');- });-- test('first-match-wins when multiple tags could match the hint', () => {- const profile = buildProfile([- 'over-confident-hiring',- 'late-on-hiring-cycles',- ]);- const out = evaluateNudgeRule(buildTake({ page_slug: 'wiki/companies/acme' }), profile);- expect(out.matchedTag).toBe('over-confident-hiring');- });-});--// ─── checkCooldown ──────────────────────────────────────────────────--describe('checkCooldown', () => {- test('returns true when a recent row exists', async () => {- const { engine } = buildMockEngine({ cooldownRows: 1 });- expect(await checkCooldown(engine, 1, 'over-confident-hiring')).toBe(true);- });-- test('returns false when no recent row', async () => {- const { engine } = buildMockEngine({ cooldownRows: 0 });- expect(await checkCooldown(engine, 1, 'over-confident-hiring')).toBe(false);- });-- test('cutoff date param is NUDGE_COOLDOWN_DAYS ago', async () => {- const { engine, sqls } = buildMockEngine({});- await checkCooldown(engine, 1, 'tag');- const cutoffISO = sqls[0]!.params[2] as string;- const cutoff = new Date(cutoffISO).getTime();- const expected = Date.now() - NUDGE_COOLDOWN_DAYS * 24 * 60 * 60 * 1000;- expect(Math.abs(cutoff - expected)).toBeLessThan(1000); // within 1s- });-});--// ─── evaluateAndFireNudge ───────────────────────────────────────────--describe('evaluateAndFireNudge', () => {- test('happy path: matches + no cooldown → fires + writes log + returns text', async () => {- const { engine, sqls } = buildMockEngine({ cooldownRows: 0 });- const profile = buildProfile(['over-confident-hiring']);- let stderrWrites = '';- const stderr = { write: (s: string) => { stderrWrites += s; } };- const out = await evaluateAndFireNudge({- engine,- take: buildTake({ page_slug: 'wiki/companies/acme' }),- profile,- sourceId: 'default',- stderr,- });- expect(out.shouldFire).toBe(true);- expect(out.matchedTag).toBe('over-confident-hiring');- expect(stderrWrites).toContain('[gbrain]');- expect(stderrWrites).toContain('over-confident-hiring');- const insertCall = sqls.find(s => s.sql.includes('INSERT INTO take_nudge_log'));- expect(insertCall).toBeDefined();- expect(insertCall!.params).toEqual(['default', 1, 'over-confident-hiring', 'stderr']);- });-- test('cooldown active → silently skips, no insert, no stderr', async () => {- const { engine, sqls } = buildMockEngine({ cooldownRows: 1 });- const profile = buildProfile(['over-confident-hiring']);- let stderrWrites = '';- const stderr = { write: (s: string) => { stderrWrites += s; } };- const out = await evaluateAndFireNudge({- engine,- take: buildTake({ page_slug: 'wiki/companies/acme' }),- profile,- sourceId: 'default',- stderr,- });- expect(out.shouldFire).toBe(false);- expect(out.reason).toBe('cooldown_active');- expect(stderrWrites).toBe('');- expect(sqls.find(s => s.sql.includes('INSERT'))).toBeUndefined();- });-- test('no profile → silently skips with reason=no_profile', async () => {- const { engine } = buildMockEngine({});- const out = await evaluateAndFireNudge({- engine,- take: buildTake(),- profile: null,- sourceId: 'default',- });- expect(out.shouldFire).toBe(false);- expect(out.reason).toBe('no_profile');- });-- test('below conviction threshold → silently skips', async () => {- const { engine, sqls } = buildMockEngine({});- const profile = buildProfile(['over-confident-hiring']);- const out = await evaluateAndFireNudge({- engine,- take: buildTake({ weight: 0.6, page_slug: 'wiki/companies/acme' }),- profile,- sourceId: 'default',- });- expect(out.shouldFire).toBe(false);- expect(out.reason).toBe('below_conviction_threshold');- // No cooldown query, no INSERT — both gated above the cooldown probe.- expect(sqls.find(s => s.sql.includes('SELECT id FROM take_nudge_log'))).toBeUndefined();- });-});--// ─── buildNudgeText ─────────────────────────────────────────────────--describe('buildNudgeText', () => {- test('contains the matched tag and the auto-quiet notice (no fake hush command, #3697)', () => {- const out = buildNudgeText({ matchedTag: 'over-confident-geography', conviction: 0.85 });- expect(out).toContain('over-confident-geography');- // #3697: `gbrain takes nudge --hush` does not exist — the 14-day quiet- // period is automatic (take_nudge_log cooldown). The text must say that- // instead of advertising a subcommand that exits "Unknown subcommand".- expect(out).not.toContain('gbrain takes nudge --hush');- expect(out).toContain('auto-quiets');- });-- test('contains the conviction value', () => {- const out = buildNudgeText({ matchedTag: 'over-confident-hiring', conviction: 0.92 });- expect(out).toContain('0.92');- });-});--// ─── resetNudgeCooldown ─────────────────────────────────────────────--describe('resetNudgeCooldown', () => {- test('deletes rows for the take; returns count', async () => {- const { engine, sqls } = buildMockEngine({ deleteReturning: 3 });- const out = await resetNudgeCooldown(engine, 42);- expect(out.deleted).toBe(3);- expect(sqls[0]!.sql).toContain('DELETE FROM take_nudge_log');- expect(sqls[0]!.params).toEqual([42]);- });-- test('returns 0 when no rows to delete (idempotent)', async () => {- const { engine } = buildMockEngine({ deleteReturning: 0 });- expect((await resetNudgeCooldown(engine, 99)).deleted).toBe(0);- });-});diff --git a/test/ocr-run-budget.test.ts b/test/ocr-run-budget.test.tsindex fc0b9b465c..6807826ca0 100644--- a/test/ocr-run-budget.test.ts+++ b/test/ocr-run-budget.test.ts@@ -1,114 +1,206 @@/**- * #3973: per-run OCR ceiling in maybeOcr. An OCR-opted-in bulk import over a- * large image corpus was an unbounded per-image LLM spend; the gate caps it- * per process run via config embedding_image_ocr_max_images / _max_usd- * (finite defaults), skips OCR over-cap, and bumps the persistent- * `ocr_skipped_budget` counter that doctor's ocr_health check surfaces.+ * Image OCR through the real import boundary (importImageFile): the+ * GBRAIN_EMBEDDING_IMAGE_OCR opt-in, the hash-unchanged re-import that+ * retries OCR once it is wanted, and the #3973 per-run OCR ceiling+ * (config embedding_image_ocr_max_images / _max_usd with finite defaults;+ * over-cap skips OCR and bumps the `ocr_skipped_budget` counter that+ * doctor's ocr_health check surfaces).*- * Tests drive the gated body directly (_maybeOcrGatedForTests) so no env- * mutation is needed, and preset the run state so the over-cap paths never- * reach the gateway (deterministic offline). The under-cap path stubs the- * generateText transport so a key-carrying dev environment can't make a- * real call.+ * Keyless and offline: a synthetic gateway config makes the OCR model+ * available, the generateText transport is stubbed, and the Voyage+ * multimodal embed is a fetch stub. Every case uses unique image bytes.*/-import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import {- _maybeOcrGatedForTests,+ importImageFile,_resetOcrRunBudgetForTests,_getOcrRunBudgetForTests,} from '../src/core/import-file.ts';-import { __setGenerateTextTransportForTests } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway, __setGenerateTextTransportForTests } from '../src/core/ai/gateway.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');+const OCR_TEXT = 'Synthetic whiteboard text';+const PROVIDER_KEYS = { OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined, GOOGLE_GENERATIVE_AI_API_KEY: undefined };let engine: PGLiteEngine;-const buf = Buffer.from('fake-image-bytes');+let dir: string;+let caseNo = 0;+let ocrCalls = 0;+let embedCalls = 0;+const origFetch = globalThis.fetch;beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();-});+}, 60_000);afterAll(async () => {await engine.disconnect();_resetOcrRunBudgetForTests();- __setGenerateTextTransportForTests(null);-});+}, 60_000);beforeEach(async () => {await resetPgliteState(engine);_resetOcrRunBudgetForTests();+ dir = mkdtempSync(join(tmpdir(), 'gbrain-ocr-'));+ ocrCalls = 0;+ embedCalls = 0;+ configureGateway({+ embedding_model: 'voyage:voyage-multimodal-3',+ embedding_multimodal_model: 'voyage:voyage-multimodal-3',+ embedding_dimensions: 1024,+ expansion_model: 'anthropic:claude-haiku-4-5',+ env: { VOYAGE_API_KEY: 'test-key', ANTHROPIC_API_KEY: 'test-key' },+ });+ __setGenerateTextTransportForTests((async () => {+ ocrCalls++;+ return { text: OCR_TEXT, usage: { inputTokens: 10, outputTokens: 5 } };+ }) as never);+ globalThis.fetch = (async () => {+ embedCalls++;+ return new Response(JSON.stringify({+ data: [{ embedding: Array.from({ length: 1024 }, () => 0.1), index: 0 }], model: 'voyage-multimodal-3',+ }), { status: 200, headers: { 'Content-Type': 'application/json' } });+ }) as unknown as typeof fetch;+});++afterEach(() => {+ globalThis.fetch = origFetch;+ __setGenerateTextTransportForTests(null);+ resetGateway();+ rmSync(dir, { recursive: true, force: true });+});++function writeImage(): { file: string; rel: string; name: string } {+ caseNo++;+ const name = `case-${caseNo}.png`;+ const rel = `photos/${name}`;+ const file = join(dir, name);+ writeFileSync(file, Buffer.concat([PNG, Buffer.from(`unique-${caseNo}-${Date.now()}`)]));+ return { file, rel, name };+}++const importWith = (ocr: string | undefined, img: { file: string; rel: string }) =>+ withEnv({ ...PROVIDER_KEYS, GBRAIN_EMBEDDING_IMAGE_OCR: ocr }, () => importImageFile(engine, img.file, img.rel));++async function stored(slug: string) {+ const page = await engine.getPage(slug, { sourceId: 'default' });+ const [chunk] = await engine.executeRaw<{ chunk_text: string; has_vec: boolean }>(+ `SELECT c.chunk_text, c.embedding_image IS NOT NULL AS has_vec FROM content_chunks c JOIN pages p ON p.id = c.page_id WHERE p.slug = $1`, [slug]);+ return { page, chunk };+}++const counter = (key: string) => engine.getConfig(key);++describe('image OCR opt-in through importImageFile', () => {+ test('opt-in on: OCR runs once, its text becomes the page body and chunk text, and the run budget is charged', async () => {+ const img = writeImage();+ const result = await importWith('true', img);+ expect(result.status).toBe('imported');+ expect(ocrCalls).toBe(1);+ const { page, chunk } = await stored(img.rel);+ expect(page!.compiled_truth).toBe(OCR_TEXT);+ expect((page!.frontmatter as Record<string, unknown>).ocr_status).toBe('done');+ expect(chunk).toEqual({ chunk_text: OCR_TEXT, has_vec: true });+ expect(await counter('ocr_attempted')).toBe('1');+ expect(await counter('ocr_succeeded')).toBe('1');+ expect(_getOcrRunBudgetForTests().images).toBe(1);+ });++ test('opt-in off with the same OCR availability: no OCR attempt, no budget use, filename-only text', async () => {+ for (const value of [undefined, 'false', '1']) {+ const img = writeImage();+ const result = await importWith(value, img);+ expect(result.status).toBe('imported');+ const { page, chunk } = await stored(img.rel);+ expect(page!.compiled_truth).toBe('');+ expect((page!.frontmatter as Record<string, unknown>).ocr_status).toBeUndefined();+ expect(chunk).toEqual({ chunk_text: img.name, has_vec: true });+ }+ expect(ocrCalls).toBe(0);+ expect(embedCalls).toBe(3);+ expect(_getOcrRunBudgetForTests()).toEqual({ images: 0, estUsd: 0, warned: false });+ expect(await counter('ocr_attempted')).toBeFalsy();+ });++ test('unchanged bytes skip while OCR is off, re-import once OCR is wanted, then skip again', async () => {+ const img = writeImage();+ expect((await importWith(undefined, img)).status).toBe('imported');+ expect((await importWith(undefined, img)).status).toBe('skipped');+ expect(ocrCalls).toBe(0);++ expect((await importWith('true', img)).status).toBe('imported');+ expect(ocrCalls).toBe(1);+ expect((await stored(img.rel)).page!.compiled_truth).toBe(OCR_TEXT);++ expect((await importWith('true', img)).status).toBe('skipped');+ expect(ocrCalls).toBe(1);+ });});describe('per-run OCR budget gate (#3973)', () => {test('over the default image cap: skips OCR, bumps ocr_skipped_budget, never counts an attempt', async () => {- _resetOcrRunBudgetForTests({ images: 200 }); // default cap is 200- const out = await _maybeOcrGatedForTests(engine, buf, 'image/png');- expect(out).toBe('');- expect(await engine.getConfig('ocr_skipped_budget')).toBe('1');- expect(await engine.getConfig('ocr_attempted')).toBeFalsy();- // Skips don't consume budget.- expect(_getOcrRunBudgetForTests().images).toBe(200);- // Warned exactly once per run; a second skip stays quiet but still counts.- expect(_getOcrRunBudgetForTests().warned).toBe(true);- await _maybeOcrGatedForTests(engine, buf, 'image/png');- expect(await engine.getConfig('ocr_skipped_budget')).toBe('2');+ _resetOcrRunBudgetForTests({ images: 200 });+ const first = writeImage();+ expect((await importWith('true', first)).status).toBe('imported');+ expect((await stored(first.rel)).page!.compiled_truth).toBe('');+ expect(ocrCalls).toBe(0);+ expect(await counter('ocr_skipped_budget')).toBe('1');+ expect(await counter('ocr_attempted')).toBeFalsy();+ expect(_getOcrRunBudgetForTests()).toMatchObject({ images: 200, warned: true });+ await importWith('true', writeImage());+ expect(await counter('ocr_skipped_budget')).toBe('2');});test('over the default estimated-USD cap trips independently of the image cap', async () => {- _resetOcrRunBudgetForTests({ images: 1, estUsd: 1.0 }); // default USD cap is 1.0- const out = await _maybeOcrGatedForTests(engine, buf, 'image/png');- expect(out).toBe('');- expect(await engine.getConfig('ocr_skipped_budget')).toBe('1');- expect(await engine.getConfig('ocr_attempted')).toBeFalsy();+ _resetOcrRunBudgetForTests({ images: 1, estUsd: 1.0 });+ await importWith('true', writeImage());+ expect(ocrCalls).toBe(0);+ expect(await counter('ocr_skipped_budget')).toBe('1');+ expect(await counter('ocr_attempted')).toBeFalsy();});test('config lowers the image cap below the default', async () => {await engine.setConfig('embedding_image_ocr_max_images', '5');_resetOcrRunBudgetForTests({ images: 5 });- const out = await _maybeOcrGatedForTests(engine, buf, 'image/png');- expect(out).toBe('');- expect(await engine.getConfig('ocr_skipped_budget')).toBe('1');+ await importWith('true', writeImage());+ expect(ocrCalls).toBe(0);+ expect(await counter('ocr_skipped_budget')).toBe('1');});test('config lowers the USD cap below the default', async () => {await engine.setConfig('embedding_image_ocr_max_usd', '0.01');_resetOcrRunBudgetForTests({ images: 1, estUsd: 0.02 });- const out = await _maybeOcrGatedForTests(engine, buf, 'image/png');- expect(out).toBe('');- expect(await engine.getConfig('ocr_skipped_budget')).toBe('1');+ await importWith('true', writeImage());+ expect(ocrCalls).toBe(0);+ expect(await counter('ocr_skipped_budget')).toBe('1');});- test('under the cap: the gate passes, consumes budget, and never bumps the skip counter', async () => {- // Stub the final generateText call so a dev machine with a real API key- // can't make a network call; keyless environments take the- // ocr_failed_no_key branch. Either way the GATE behavior is identical.- __setGenerateTextTransportForTests(async () => ({ text: 'stubbed ocr text', usage: {} }) as never);- try {- await _maybeOcrGatedForTests(engine, buf, 'image/png');- const state = _getOcrRunBudgetForTests();- expect(state.images).toBe(1);- expect(state.estUsd).toBeGreaterThan(0);- expect(await engine.getConfig('ocr_skipped_budget')).toBeFalsy();- expect(await engine.getConfig('ocr_attempted')).toBe('1');- } finally {- __setGenerateTextTransportForTests(null);- }+ test('under the cap: OCR runs, consumes budget, and never bumps the skip counter', async () => {+ _resetOcrRunBudgetForTests({ images: 199, estUsd: 0.5 });+ await importWith('true', writeImage());+ expect(ocrCalls).toBe(1);+ expect(_getOcrRunBudgetForTests().images).toBe(200);+ expect(_getOcrRunBudgetForTests().estUsd).toBeCloseTo(0.502, 9);+ expect(await counter('ocr_skipped_budget')).toBeFalsy();+ expect(await counter('ocr_attempted')).toBe('1');});test('cap of 0 disables that ceiling (explicit unlimited opt-out)', async () => {await engine.setConfig('embedding_image_ocr_max_images', '0');await engine.setConfig('embedding_image_ocr_max_usd', '0');_resetOcrRunBudgetForTests({ images: 100_000, estUsd: 500 });- __setGenerateTextTransportForTests(async () => ({ text: 'stubbed', usage: {} }) as never);- try {- await _maybeOcrGatedForTests(engine, buf, 'image/png');- expect(await engine.getConfig('ocr_skipped_budget')).toBeFalsy();- expect(_getOcrRunBudgetForTests().images).toBe(100_001);- } finally {- __setGenerateTextTransportForTests(null);- }+ await importWith('true', writeImage());+ expect(ocrCalls).toBe(1);+ expect(await counter('ocr_skipped_budget')).toBeFalsy();+ expect(_getOcrRunBudgetForTests().images).toBe(100_001);});});diff --git a/test/operations-embedding-column.test.ts b/test/operations-embedding-column.test.tsindex 4b54358c7a..d56b770cda 100644--- a/test/operations-embedding-column.test.ts+++ b/test/operations-embedding-column.test.ts@@ -16,10 +16,6 @@ import { operationsByName } from '../src/core/operations.ts';describe('query op — embedding_column param (D15)', () => {const queryOp = operationsByName.query;- test('exists', () => {- expect(queryOp).toBeDefined();- });-test('declares embedding_column in params allowlist', () => {expect(queryOp.params.embedding_column).toBeDefined();expect(queryOp.params.embedding_column.type).toBe('string');@@ -41,10 +37,6 @@ describe('query op — embedding_column param (D15)', () => {describe('search op — does NOT declare embedding_column (CDX-9)', () => {const searchOp = operationsByName.search;- test('exists', () => {- expect(searchOp).toBeDefined();- });-test('does NOT include embedding_column in params (search is keyword-only)', () => {// Adding embedding_column to the keyword-only `search` op would// either be silently ignored (footgun for agents) or change the op'sdiff --git a/test/pglite-repair-command.serial.test.ts b/test/pglite-repair-command.serial.test.tsindex ad2f7bac3f..45f4a9e0cf 100644--- a/test/pglite-repair-command.serial.test.ts+++ b/test/pglite-repair-command.serial.test.ts@@ -482,7 +482,7 @@ describe('gbrain pglite-repair — interactive confirm wiring (#4318 residual)',// change that reintroduces a local `promptYesNo`/`createInterface` here// (rather than importing the shared, race-free helper) fails this test,// even though `test/confirm-prompt.test.ts` cannot see this file at all.- // test-reads-source-ok: pins that the local reimplementation stays gone+ // test-reads-source-ok[structural]: pins that the local reimplementation stays gone// and the shared helper is wired with the exact stderr-preserving args —// there's no exported/injectable seam to assert this behaviorally.const src = readFileSync(join(import.meta.dir, '../src/commands/pglite-repair.ts'), 'utf8');diff --git a/test/phantom-redirect-per-source-lock.test.ts b/test/phantom-redirect-per-source-lock.test.tsdeleted file mode 100644index 65e8f4e662..0000000000--- a/test/phantom-redirect-per-source-lock.test.ts+++ /dev/null@@ -1,46 +0,0 @@-/**- * v0.40 D16 regression test: phantom-redirect uses per-source lock.- *- * Pre-v0.40 phantom-redirect acquired the bare `gbrain-sync` lock, blocking- * every concurrent sync brain-wide. After D16, phantom acquires- * `gbrain-sync:<sourceId>` — same-source sync still serializes; cross-source- * sync proceeds unblocked.- *- * Pure source-text regression guard. The full behavior is covered by- * `test/e2e/phantom-redirect.test.ts` (DATABASE_URL-gated). This file pins- * the lock-id construction so any future drift back to the bare constant- * fails loudly in the fast unit loop.- */-import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'node:fs';-import { syncLockId } from '../src/core/db-lock.ts';--const SRC = readFileSync('src/core/cycle/phantom-redirect.ts', 'utf8');--describe('phantom-redirect lock contract', () => {- test('IRON-RULE: import line uses syncLockId, not bare SYNC_LOCK_ID', () => {- // syncLockId must be imported; SYNC_LOCK_ID must NOT be (per-source posture).- const importLine = SRC.split('\n').find((l) =>- l.includes("from '../db-lock.ts'") && l.includes('import'),- );- expect(importLine).toBeDefined();- expect(importLine).toContain('syncLockId');- expect(importLine).not.toMatch(/\bSYNC_LOCK_ID\b/);- });-- test('IRON-RULE: acquireLockWithRetry call passes syncLockId(sourceId)', () => {- // Banned: the bare `SYNC_LOCK_ID` constant slipped back in.- // Required: the per-source helper threaded with the active sourceId.- // #1972: the call now threads an optional abort signal as a third arg- // (acquireLockWithRetry(engine, syncLockId(sourceId), signal)). The IRON-RULE- // is unchanged: it must pass the per-source syncLockId(sourceId), never bare- // SYNC_LOCK_ID. Allow the optional trailing signal arg.- expect(SRC).toMatch(/acquireLockWithRetry\s*\(\s*engine\s*,\s*syncLockId\s*\(\s*sourceId\s*\)\s*(?:,\s*signal\s*)?\)/);- expect(SRC).not.toMatch(/acquireLockWithRetry\s*\(\s*engine\s*,\s*SYNC_LOCK_ID\s*\)/);- });-- test('helper sanity: syncLockId returns gbrain-sync:<source> shape', () => {- expect(syncLockId('default')).toBe('gbrain-sync:default');- expect(syncLockId('zion-brain')).toBe('gbrain-sync:zion-brain');- });-});diff --git a/test/phantom-redirect.test.ts b/test/phantom-redirect.test.tsindex 96ffa022fd..8d6733aa74 100644--- a/test/phantom-redirect.test.ts+++ b/test/phantom-redirect.test.ts@@ -712,40 +712,31 @@ describe('runPhantomRedirectPass (per-cycle pass)', () => {// ─── Lock retry semantics (C4) ─────────────────────────────────────-describe('lock contention (C4)', () => {- test('lock_busy when another holder has it → pass skipped, audit entry, retries next cycle', async () => {- await withTempDirs(async ({ brainDir }) => {- // Manually claim the gbrain-sync lock with a future TTL- await engine.executeRaw(- `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at)- VALUES ('gbrain-sync', 9999, 'other-host', now(), now() + interval '1 hour')`,- );-- // Need a phantom + canonical or scanned would be 0 regardless- await putPage('people/alice-example', '# alice-example\n', { type: 'person' });- writeMd(brainDir, 'people/alice-example', '# alice-example\n');- await putPage('alice', STUB_BODY);- writeMd(brainDir, 'alice', STUB_BODY);+describe('lock contention (C4) — per-source sync lock (v0.40 D16)', () => {+ // A held lock makes acquireLockWithRetry loop until its 30s budget or the+ // caller's abort; the short abort keeps the busy case fast.+ async function holdLock(id: string): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at)+ VALUES ($1, 9999, 'other-host', now(), now() + interval '1 hour')`,+ [id],+ );+ }- // Reduce retry window so the test finishes quickly. The handler's- // 30s default would slow the suite. We don't expose a knob, but the- // 30s+1s-backoff loop ends in ~30 retries; since we want this to be- // an honest assertion let's run with a short manual lock and then- // release it mid-loop... actually simpler: assert lock_busy after- // the full retry window (slow). For a fast test, we'll instead- // assert via withEnv shortcut: set the env var to abbreviate, but- // since the handler has hardcoded 30s, the cleanest fast assertion- // is to release the lock right away then re-acquire AFTER the pass- // proves the timeout path. Instead we'll just verify the lock IS- // held externally; the lock_busy result is asserted in a slow- // companion test if needed.- const lockBefore = await engine.executeRaw<{ holder_pid: number }>(- `SELECT holder_pid FROM gbrain_cycle_locks WHERE id='gbrain-sync'`,- );- expect(lockBefore[0].holder_pid).toBe(9999);+ test('same-source sync lock held → pass skipped as lock_busy', async () => {+ await withTempDirs(async ({ brainDir }) => {+ await holdLock('gbrain-sync:src-b');+ const result = await runPhantomRedirectPass(engine, brainDir, 'src-b', false, AbortSignal.timeout(200));+ expect(result.lock_busy).toBe(true);+ });+ });- // Cleanup- await engine.executeRaw(`DELETE FROM gbrain_cycle_locks WHERE id='gbrain-sync'`);+ test('bare and default-source sync locks held → another source still runs', async () => {+ await withTempDirs(async ({ brainDir }) => {+ await holdLock('gbrain-sync');+ await holdLock('gbrain-sync:default');+ const result = await runPhantomRedirectPass(engine, brainDir, 'src-b', false, AbortSignal.timeout(200));+ expect(result.lock_busy).toBe(false);});});});diff --git a/test/postgres-engine-singleton-lifecycle.test.ts b/test/postgres-engine-singleton-lifecycle.test.tsnew file mode 100644index 0000000000..b528578bab--- /dev/null+++ b/test/postgres-engine-singleton-lifecycle.test.ts@@ -0,0 +1,134 @@+/**+ * Module-singleton lifecycle races in `src/core/db.ts` and+ * `src/core/postgres-engine.ts` (#1471, #1745), driven DB-free: the pools+ * dial a local TCP endpoint that accepts connections and never answers the+ * Postgres handshake, so each `SELECT 1` stays pending until the test makes+ * the endpoint answer with a FATAL error. That holds a connect "in flight"+ * for as long as a case needs.+ *+ * The live owner/borrower lifecycle against real Postgres is owned by+ * test/e2e/postgres-engine-disconnect-idempotency.test.ts,+ * test/e2e/db-singleton-shared-recovery.test.ts and+ * test/e2e/postgres-reconnect-singleton.test.ts.+ */++import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { createServer, type AddressInfo, type Socket } from 'net';+import * as db from '../src/core/db.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';++function fatal(): Buffer {+ const body = Buffer.from('SFATAL\0C57P01\0Mtest endpoint refused\0\0');+ const head = Buffer.alloc(5);+ head.write('E', 0);+ head.writeInt32BE(body.length + 4, 1);+ return Buffer.concat([head, body]);+}++async function openEndpoint() {+ const held: Socket[] = [];+ let refusing = false;+ let dials = 0;+ const server = createServer(socket => {+ dials++;+ held.push(socket);+ socket.on('data', () => { if (refusing) socket.end(fatal()); });+ });+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ return {+ url: `postgres://[email protected]:${(server.address() as AddressInfo).port}/gbrain`,+ dials: () => dials,+ refuse() { refusing = true; for (const socket of held.splice(0)) socket.end(fatal()); },+ hold() { refusing = false; },+ close() { server.close(); },+ };+}++let endpoint: Awaited<ReturnType<typeof openEndpoint>>;+let url: string;+let pending: Promise<unknown>[] = [];++const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));+const settle = <T>(p: Promise<T>) => { const s = p.catch(e => e); pending.push(s); return s; };+const within = <T>(p: Promise<T>, ms = 500) => Promise.race([p.then(() => 'resolved'), sleep(ms).then(() => 'pending')]);++async function dialedAfterSettling(): Promise<number> {+ await sleep(150);+ return endpoint.dials();+}++beforeEach(async () => {+ endpoint = await openEndpoint();+ url = endpoint.url;+});++afterEach(async () => {+ endpoint.refuse();+ await Promise.all(pending);+ pending = [];+ await db.disconnect();+ endpoint.close();+});++describe('module-singleton ownership under concurrent connects', () => {+ test('an engine that joins an in-flight create is a borrower: one pool is dialed and its disconnect leaves it', async () => {+ const owner = new PostgresEngine();+ const borrower = new PostgresEngine();++ settle(owner.connect({ database_url: url }));+ const borrowerConnect = settle(borrower.connect({ database_url: url }));++ expect(await within(borrowerConnect)).toBe('resolved');+ const pool = db.getConnection();+ await borrower.disconnect();++ expect(db.getConnection()).toBe(pool);+ expect(await dialedAfterSettling()).toBe(1);+ });+});++describe('db.disconnect()', () => {+ test('detaches the singleton before awaiting end(), so a concurrent connect builds a fresh pool', async () => {+ settle(db.connect({ database_url: url }));+ const closing = db.getConnection();+ let endStarted!: () => void;+ const started = new Promise<void>(resolve => { endStarted = resolve; });+ let finishEnd!: () => void;+ Object.assign(closing, { end: () => { endStarted(); return new Promise<void>(resolve => { finishEnd = resolve; }); } });++ const disconnecting = db.disconnect();+ try {+ await started;+ const reconnect = settle(db.connect({ database_url: url }));++ expect(db.getConnection()).not.toBe(closing);+ expect(await within(reconnect, 50)).toBe('pending');+ } finally {+ finishEnd();+ await disconnecting;+ }+ });+});++describe('instance-pool reconnect()', () => {+ test('a reconnect during a running rebuild returns at once, and the next one after it settles rebuilds again', async () => {+ const engine = new PostgresEngine();+ const livePool = { end: async () => {} };+ Object.assign(engine as unknown as Record<string, unknown>, {+ _savedConfig: { database_url: url, poolSize: 1 },+ _connectionStyle: 'instance',+ _sql: livePool,+ });++ const first = settle(engine.reconnect());+ expect(await within(engine.reconnect())).toBe('resolved');+ expect(await dialedAfterSettling()).toBe(1);++ endpoint.refuse();+ expect(await first).toBeInstanceOf(Error);+ endpoint.hold();++ settle(engine.reconnect());+ expect(await dialedAfterSettling()).toBe(2);+ });+});diff --git a/test/postgres-engine-singleton-ownership.test.ts b/test/postgres-engine-singleton-ownership.test.tsdeleted file mode 100644index 28ab314d6d..0000000000--- a/test/postgres-engine-singleton-ownership.test.ts+++ /dev/null@@ -1,159 +0,0 @@-/**- * postgres-engine.ts module-singleton ownership guardrails (#1471).- *- * Root cause: when an engine connects via the module-singleton path (no- * poolSize), BOTH the engine that creates the shared db.ts `sql` singleton- * (the owner, e.g. the CLI cycle engine) and any engine constructed while- * that singleton already exists (a borrower, e.g. the probe engine in- * resolveLintContentSanity / doctor) got `_connectionStyle = 'module'`. The- * old disconnect() then called `db.disconnect()` for BOTH, so a short-lived- * borrower's teardown nulled the shared `sql` the owner was still using —- * every later cycle phase then threw "No database connection: connect() has- * not been called" and stranded the cycle lock.- *- * Fix: track ownership via a token returned atomically by db.connect(). Only- * the engine whose connect() actually created the singleton may db.disconnect()- * it; borrowers clear their own marker without touching the shared connection.- *- * Source-level, DB-free guardrails — matching the existing- * postgres-engine.test.ts convention (runtime mocking of postgres.js's- * tagged-template interface is painful under bun ESM; live behaviour is- * exercised by test/e2e/postgres-engine-disconnect-idempotency.test.ts).- */--import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'fs';-import { join } from 'path';--const ENGINE_SRC = readFileSync(- join(import.meta.dir, '..', 'src', 'core', 'postgres-engine.ts'),- 'utf-8',-);-const DB_SRC = readFileSync(- join(import.meta.dir, '..', 'src', 'core', 'db.ts'),- 'utf-8',-);--describe('postgres-engine / module-singleton ownership (#1471)', () => {- // Boolean assertions on purpose: matching a regex against the 4500-line- // source dumps the whole file into the failure message. `.test()` -> bool- // keeps RED output (and CI logs) readable.-- test('db.connect() returns the ownership token (Promise<boolean>), not void', () => {- const sig = /export async function connect\(config: EngineConfig\): Promise<boolean>/.test(DB_SRC);- expect(sig).toBe(true);- });-- test('db.connect() borrower path returns false; creator path returns true', () => {- const connect = stripComments(extractFn(DB_SRC, 'connect'));- // Borrower (singleton already exists) → return false.- expect(/if\s*\(\s*sql\s*\)\s*\{[\s\S]*?return false/.test(connect)).toBe(true);- // Creator (built + validated the pool) → return true.- expect(/return true/.test(connect)).toBe(true);- });-- test('PostgresEngine tracks module-singleton ownership with a dedicated flag', () => {- expect(ENGINE_SRC.includes('_ownsModuleSingleton')).toBe(true);- });-- test('connect() stores the ownership token from db.connect() — no separate pre-sample (TOCTOU guard)', () => {- const connect = stripComments(extractMethod(ENGINE_SRC, 'connect'));- // Ownership is the RETURN of db.connect(), assigned to the flag.- expect(/_ownsModuleSingleton\s*=\s*await\s+db\.connect\s*\(/.test(connect)).toBe(true);- // Regression guard against the original TOCTOU shape: no separate- // db.isConnected() probe sampled before db.connect().- expect(/db\.isConnected\s*\(/.test(connect)).toBe(false);- });-- test('disconnect() calls db.disconnect() ONLY when this engine owns the singleton', () => {- const wrapper = stripComments(extractMethod(ENGINE_SRC, 'disconnect'));- expect(wrapper.includes('this.disconnectInternal()')).toBe(true);- expect(/db\.disconnect\s*\(/.test(wrapper)).toBe(false);- const disconnect = stripComments(extractMethod(ENGINE_SRC, 'disconnectInternal'));- // The shared-singleton teardown must be guarded by the ownership flag — a- // borrower clears its marker without nulling the owner's connection.- const guarded = /if\s*\(\s*this\._ownsModuleSingleton\s*\)\s*\{[\s\S]*?db\.disconnect\s*\(\s*\)/.test(disconnect);- expect(guarded).toBe(true);- // And the only db.disconnect() in the method is the guarded one (no- // unconditional clobber survives).- const calls = [...disconnect.matchAll(/db\.disconnect\s*\(\s*\)/g)];- expect(calls.length).toBe(1);- });-- test('db.disconnect() snapshots + nulls the singleton BEFORE awaiting end() (codex #6)', () => {- const disconnect = stripComments(extractFn(DB_SRC, 'disconnect'));- const snapshotIdx = disconnect.search(/const\s+s\s*=\s*sql/);- const nullIdx = disconnect.search(/\bsql\s*=\s*null/);- // #1972: the pool end is now wrapped in the gbrain-owned hard bound- // `endPoolBounded(s)` instead of a bare `s.end()`. The ordering contract is- // unchanged: snapshot + null the singleton BEFORE awaiting the end.- const endIdx = disconnect.search(/\bawait\s+(?:s\.end\s*\(|endPoolBounded\s*\(\s*s\b)/);- expect(snapshotIdx).toBeGreaterThanOrEqual(0);- expect(nullIdx).toBeGreaterThanOrEqual(0);- expect(endIdx).toBeGreaterThanOrEqual(0);- // null the module ref BEFORE the await, so a concurrent connect() can't- // join a pool that's already closing.- expect(nullIdx < endIdx).toBe(true);- });-- test('reconnect() is connection-style aware: module-singleton path never tears down the shared pool (#1745)', () => {- const reconnect = stripComments(extractMethod(ENGINE_SRC, 'reconnect'));- // Module-singleton engines must NOT route through this.disconnect()/db.disconnect()- // on reconnect — they recover idempotently via db.connect() + setReadPool, so a- // transient blip can't null the shared singleton other phases are using.- expect(/this\._connectionStyle\s*!==\s*'instance'/.test(reconnect)).toBe(true);- expect(/db\.connect\(this\._savedConfig\)/.test(reconnect)).toBe(true);- expect(/setReadPool\(db\.getConnection\(\)\)/.test(reconnect)).toBe(true);- // The instance path keeps the `_reconnecting` re-entrancy guard.- expect(/this\._reconnecting\s*=\s*true/.test(reconnect)).toBe(true);- });-});--function stripComments(s: string): string {- return s- .replace(/\/\*[\s\S]*?\*\//g, '')- .replace(/(^|\s)\/\/[^\n]*/g, '$1');-}--// Balance a `{...}` body starting at the first `{` after `headerIdx`, where-// headerIdx points at (or before) the signature's parameter list. Skips the-// parameter-list parens so a `{` inside a param type isn't mistaken for the body.-function balanceBodyFrom(source: string, headerIdx: number, what: string): string {- let i = source.indexOf('(', headerIdx);- let pdepth = 0;- for (; i < source.length; i++) {- if (source[i] === '(') pdepth++;- else if (source[i] === ')') {- pdepth--;- if (pdepth === 0) { i++; break; }- }- }- i = source.indexOf('{', i);- if (i < 0) throw new Error(`no body brace for ${what}`);- const start = i;- let depth = 0;- for (; i < source.length; i++) {- if (source[i] === '{') depth++;- else if (source[i] === '}') {- depth--;- if (depth === 0) return source.slice(start, i + 1);- }- }- throw new Error(`unbalanced body for ${what}`);-}--// Class method body by name (async or not).-function extractMethod(source: string, name: string): string {- const openRe = new RegExp(`^\\s+(?:private\\s+)?(?:async\\s+)?${name}\\s*\\(`, 'm');- const match = openRe.exec(source);- if (!match) throw new Error(`method ${name} not found`);- return balanceBodyFrom(source, match.index, name);-}--// Top-level exported function body by name.-function extractFn(source: string, name: string): string {- const openRe = new RegExp(`export async function ${name}\\s*\\(`);- const match = openRe.exec(source);- if (!match) throw new Error(`function ${name} not found`);- return balanceBodyFrom(source, match.index, name);-}diff --git a/test/privacy-script-wired.test.ts b/test/privacy-script-wired.test.tsindex 313fd237ce..95d82bd58f 100644--- a/test/privacy-script-wired.test.ts+++ b/test/privacy-script-wired.test.ts@@ -1,35 +1,22 @@/**- * Regression guard: scripts/check-privacy.sh must run in CI's auto-pipeline.+ * scripts/check-privacy.sh behavior: name/path violations, allowlists, staged+ * mode and batching.*- * CLAUDE.md bans the private OpenClaw fork name from public artifacts.- * scripts/check-privacy.sh is the enforcement mechanism. If someone- * refactors the script chain and drops the privacy check, this test- * fails loudly.- *- * v0.26.4 split: `bun run test` is now the fast parallel loop and does- * NOT chain pre-checks; the privacy gate moved to `bun run verify`,- * which CI's test.yml runs as its own job before the matrix fans out.- *- * v0.41.4+ wave: `bun run verify` now delegates to- * scripts/run-verify-parallel.sh which fans out all 20 checks in- * parallel via & + wait. The privacy check is one entry in that- * script's CHECKS[] array. Regression guard updated to follow the- * indirection: (1) verify points at the parallel dispatcher,- * (2) the dispatcher's CHECKS array contains check:privacy,- * (3) CI workflow's verify job calls `bun run verify`.+ * CLAUDE.md bans the private OpenClaw fork name from public artifacts, and this+ * script is the enforcement mechanism. Its verify wiring is owned generically:+ * test/scripts/run-verify-parallel.test.ts requires every manifest guard to be+ * executed by verify, and test/scripts/ci-gates.test.ts requires the CI verify+ * job to run `bun run verify`.*/import { describe, it, expect } from 'bun:test';-import { readFileSync, existsSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';+import { readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';import { join, resolve } from 'path';import { tmpdir } from 'os';import { spawnSync } from 'child_process';const REPO_ROOT = resolve(import.meta.dir, '..');-const PACKAGE_JSON = resolve(REPO_ROOT, 'package.json');const PRIVACY_SCRIPT = resolve(REPO_ROOT, 'scripts/check-privacy.sh');-const VERIFY_DISPATCHER = resolve(REPO_ROOT, 'scripts/run-verify-parallel.sh');-const TEST_WORKFLOW = resolve(REPO_ROOT, '.github/workflows/test.yml');const guardSource = readFileSync(PRIVACY_SCRIPT, 'utf8');const bannedName = guardSource.match(/^BANNED_NAME='([^']+)'/m)![1]!;const bannedPath = guardSource.match(/BANNED_PATHS=\(\s*'([^']+)'/)![1]!;@@ -52,47 +39,7 @@ function runPrivacy(root: string, args: string[] = [], env: Record<string, strinreturn spawnSync('bash', [PRIVACY_SCRIPT, ...args], { cwd: root, encoding: 'utf8', env: { ...process.env, ...env } });}-describe('check-privacy.sh CI wiring', () => {- it('scripts/check-privacy.sh exists and is executable', () => {- expect(existsSync(PRIVACY_SCRIPT)).toBe(true);- const stat = require('fs').statSync(PRIVACY_SCRIPT);- // eslint-disable-next-line no-bitwise- expect((stat.mode & 0o100) !== 0).toBe(true);- });-- it('package.json "verify" script delegates to run-verify-parallel.sh', () => {- const pkg = JSON.parse(readFileSync(PACKAGE_JSON, 'utf-8'));- expect(typeof pkg.scripts?.verify).toBe('string');- // verify body is now `bash scripts/run-verify-parallel.sh`. The- // direct check:privacy substring assertion broke when the && chain- // was replaced with the parallel dispatcher. Follow the indirection.- expect(pkg.scripts.verify).toContain('run-verify-parallel.sh');- });-- it('run-verify-parallel.sh dispatches check:privacy', () => {- expect(existsSync(VERIFY_DISPATCHER)).toBe(true);- // The dispatcher exposes --dry-list which prints one check name per- // line. Authoritative check than substring-grepping the script body- // (which could pass on a commented-out entry).- const r = spawnSync('bash', [VERIFY_DISPATCHER, '--dry-list'], {- cwd: REPO_ROOT,- encoding: 'utf-8',- });- expect(r.status).toBe(0);- const checks = r.stdout.trim().split('\n');- expect(checks).toContain('check:privacy');- });-- it('package.json "check:privacy" alias points at the script', () => {- const pkg = JSON.parse(readFileSync(PACKAGE_JSON, 'utf-8'));- expect(pkg.scripts?.['check:privacy']).toContain('check-privacy.sh');- });-- it('CI test.yml runs `bun run verify` so the privacy gate fires', () => {- expect(existsSync(TEST_WORKFLOW)).toBe(true);- const yml = readFileSync(TEST_WORKFLOW, 'utf-8');- expect(yml).toContain('bun run verify');- });+describe('check-privacy.sh', () => {it('reports every name and path violation with its original line number', () => {const root = privacyFixture({diff --git a/test/private-visibility.test.ts b/test/private-visibility.test.tsindex fe8f784875..0c13ef504c 100644--- a/test/private-visibility.test.ts+++ b/test/private-visibility.test.ts@@ -374,7 +374,7 @@ describe('sibling read ops (#4352 remediation — no bypass around get_page)', (describe('shared private predicate lives once (#4352 remediation)', () => {test('entity-card composes privatePagesFilterFragment instead of hand-rolling the predicate', () => {- // test-reads-source-ok: structural "lives ONCE" guard — a duplicated predicate behaves identically until visibility semantics drift, so only the text can catch it (#4352)+ // test-reads-source-ok[trust-boundary]: structural "lives ONCE" guard — a duplicated predicate behaves identically until visibility semantics drift, so only the text can catch it (#4352)const src = readFileSync(join(import.meta.dir, '../src/core/verbs/entity-card.ts'), 'utf8');expect(src).toContain('privatePagesFilterFragment');// The predicate TEXT must not be duplicated — silent drift risk ifdiff --git a/test/process-cleanup.test.ts b/test/process-cleanup.test.tsindex 030e7e097f..f3353e9629 100644--- a/test/process-cleanup.test.ts+++ b/test/process-cleanup.test.ts@@ -5,14 +5,16 @@* - registerCleanup adds + returned deregister removes* - triggerCleanupAndExit walks registry via Promise.allSettled* - cleanup callback throw doesn't break other callbacks (allSettled)- * - idempotent on double-trigger (second call during cleanup is NO-OP)+ * - idempotent on double-trigger (callbacks run once; a later signal or+ * EPIPE waits for the running pass before exiting)* - 3s deadline honored (longer callbacks don't block exit)* - deregister-then-release race: no double-fire** Signal-handler installation contract is verified by:* - installSignalHandlers() idempotency (this file)- * - E2E sync-lock-cleanup-on-sigterm.test.ts (real SIGTERM → real DELETE)- * - E2E sync-pipe-sigpipe.test.ts (real EPIPE → real DELETE)+ * - E2E test/e2e/sync-lock-recovery.test.ts: real SIGTERM mid-sync →+ * real lock-row DELETE, and a real closed output pipe mid-sync →+ * broken-pipe cleanup route → real lock-row DELETE** NOT covered here: the SIGINT coexistence test (eng-review D9) — moved* to E2E because spawning a subprocess and verifying both AbortController@@ -199,6 +201,31 @@ describe('installSignalHandlers', () => {expect(process.listenerCount('SIGPIPE')).toBe(before.sigpipe + 1);});+ test('later signals and a stdout EPIPE during the cleanup pass wait for it before exiting', async () => {+ let releaseCleanup!: () => void;+ let cleanupFinished = false;+ registerCleanup('lock-row', async () => {+ await new Promise<void>(resolve => { releaseCleanup = resolve; });+ cleanupFinished = true;+ });+ const exits: Array<{ code: number; cleanupFinished: boolean }> = [];+ const origExit = process.exit;+ (process as any).exit = (code?: number) => { exits.push({ code: code ?? 0, cleanupFinished }); };+ try {+ installSignalHandlers();+ process.emit('SIGTERM');+ process.emit('SIGPIPE');+ process.stdout.emit('error', Object.assign(new Error('write EPIPE'), { code: 'EPIPE' }));+ await new Promise(r => setTimeout(r, 20));+ expect(exits).toEqual([]);+ releaseCleanup();+ await new Promise(r => setTimeout(r, 20));+ } finally {+ (process as any).exit = origExit;+ }+ expect(exits).toEqual([{ code: 143, cleanupFinished: true }, { code: 141, cleanupFinished: true }, { code: 0, cleanupFinished: true }]);+ });+test('_resetForTests DETACHES every listener installSignalHandlers attached', () => {// Regression pin for the suite-wide-kill class: a flags-only reset left// a live SIGTERM→exit(143) listener on the shared bun test runner, so adiff --git a/test/put-page-remote-autolink-hint.test.ts b/test/put-page-remote-autolink-hint.test.tsindex 770186daf8..6ba5536f70 100644--- a/test/put-page-remote-autolink-hint.test.ts+++ b/test/put-page-remote-autolink-hint.test.ts@@ -99,18 +99,6 @@ describe('put_page remote auto-link disclosure (#4525)', () => {expect(skill).not.toMatch(/\(at startup and on 10-minute idle ticks\)/);});- // The paste-in template downstream forks copy (UPGRADING_DOWNSTREAM_AGENTS.md)- // and the enrich skill carried the same inline promise one file over.- test('downstream-upgrade doc and enrich skill state the MCP skip, not an inline auto_links promise', () => {- for (const rel of ['docs/UPGRADING_DOWNSTREAM_AGENTS.md', 'skills/enrich/SKILL.md']) {- const flat = readFileSync(join(import.meta.dir, '..', rel), 'utf8').replace(/\s+/g, ' ');- expect(flat).not.toContain('MCP response includes `auto_links: { created');- expect(flat).not.toContain('Verify via the `auto_links` field in the put_page response (`{ created');- expect(flat).toContain('skipped: "remote"');- expect(flat).toContain('sweep');- }- });-test('local write does not carry the remote skip marker', async () => {const result = (await putPage.handler(makeCtx({ remote: false }),diff --git a/test/e2e/qm-provisioning.test.ts b/test/qm-provisioning.test.tssimilarity index 96%rename from test/e2e/qm-provisioning.test.tsrename to test/qm-provisioning.test.tsindex 78331bf57c..d896eb7665 100644--- a/test/e2e/qm-provisioning.test.ts+++ b/test/qm-provisioning.test.ts@@ -15,21 +15,25 @@* them (v0.42.70.0 enforceClientSlugFence, over the real transport);* - reads stay source-granular (a bob-example client CAN read* chan-eng/ — the documented shared-source tradeoff).+ *+ * Lane: unit. Run: `bun test test/qm-provisioning.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test as testRaw, expect, beforeAll, afterAll } from 'bun:test';import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';-import { keylessBrainEnv } from '../helpers/provider-env.ts';-import { cliDiagnostic, fixtureDiagnostic } from '../helpers/fixture-diagnostics.ts';+import { keylessBrainEnv } from './helpers/provider-env.ts';+import { cliDiagnostic, fixtureDiagnostic } from './helpers/fixture-diagnostics.ts';function test(name: string, fn: () => void | Promise<unknown>): void {testRaw(name, fn, 120000);}-const CLI = join(__dirname, '..', '..', 'src', 'cli.ts');-const SCRIPT = join(__dirname, '..', '..', 'docs', 'integrations', 'qm-harness-snippets', 'provision-scopes.sh');+const CLI = join(__dirname, '..', 'src', 'cli.ts');+const SCRIPT = join(__dirname, '..', 'docs', 'integrations', 'qm-harness-snippets', 'provision-scopes.sh');interface RunResult { exitCode: number; stdout: string; stderr: string; }diff --git a/test/readme-hero-anchors.test.ts b/test/readme-hero-anchors.test.tsdeleted file mode 100644index 2769ce0f78..0000000000--- a/test/readme-hero-anchors.test.ts+++ /dev/null@@ -1,52 +0,0 @@-/**- * v0.36.0.0 (D9) — README hero anchor regression test.- *- * Pins load-bearing strings in the first ~50 lines of README.md so future- * "cleanup" PRs can't silently drop the headline framing or the- * OpenClaw/Hermes credit. The anchors are intentionally NARROW (substrings,- * not full hero text) so legitimate voice/structure edits don't fight the- * test.- *- * If this test fails, ask: did we deliberately rotate the headline?- * - If yes: update the anchors here AND in the corresponding plan/spec.- * - If no: the README rewrite dropped something it shouldn't have.- */--import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'fs';-import { resolve } from 'path';--describe('README hero anchors (D9 regression guard)', () => {- const readme = readFileSync(resolve(process.cwd(), 'README.md'), 'utf8');- // First 50 lines is enough headroom for hero + first sub-section.- const hero = readme.split('\n').slice(0, 50).join('\n');-- test('mentions OpenClaw (the public agent platform credit)', () => {- expect(hero).toContain('OpenClaw');- });-- test('mentions Hermes (the public agent platform credit)', () => {- expect(hero).toContain('Hermes');- });-- test('leads with controlled memory and the two distinct setup paths', () => {- // The accepted harness onboarding plan deliberately rotates the headline.- // Keep the primary local path ahead of the separate hosted connection.- expect(hero).toContain('Give the agent you already use a memory you control');- expect(hero).toContain('facts with their sources');- expect(hero.indexOf('Add GBrain to my existing agent')).toBeLessThan(- hero.indexOf('Connect my existing hosted brain'),- );- expect(hero).toContain('Start with keyless memory');- });-- test('includes at least one production number (pages/people/companies)', () => {- // Matches "17,888 pages", "4,383 people", "723 companies" style.- expect(hero).toMatch(/\d{1,3},?\d{3}\s+(pages|people|companies)/i);- });-- test('includes BrainBench framing (P@5 or R@5)', () => {- // Either P@5 or R@5 anchors the retrieval-eval credibility story.- expect(hero).toMatch(/P@5|R@5/);- });-});diff --git a/test/recall-footer.test.ts b/test/recall-footer.test.tsdeleted file mode 100644index fda612d5b8..0000000000--- a/test/recall-footer.test.ts+++ /dev/null@@ -1,154 +0,0 @@-/**- * v0.36.1.0 (T16) — recall morning pulse calibration footer tests.- *- * Pure formatter tests. No engine, no LLM.- *- * Tests cover:- * - cold-brain branch: null profile → empty string- * - insufficient resolved (< 5) → empty string- * - happy path: section header + Brier + patterns- * - abandoned threads section: optional, formatted, capped at 5- * - trend note maps Brier ranges to conversational copy- * - patterns capped at 4- * - column alignment on abandoned threads- */--import { describe, test, expect } from 'bun:test';-import { buildRecallCalibrationFooter } from '../src/core/calibration/recall-footer.ts';-import type { CalibrationProfileRow } from '../src/commands/calibration.ts';--function buildProfile(opts: Partial<CalibrationProfileRow> = {}): CalibrationProfileRow {- return {- id: '1',- source_id: 'default',- holder: 'garry',- wave_version: 'v0.36.1.0',- generated_at: '2026-05-17T00:00:00Z',- published: false,- total_resolved: 12,- brier: 0.18,- accuracy: 0.6,- partial_rate: 0.1,- grade_completion: 1.0,- pattern_statements: ['Right on early-stage tactics, late on macro by 18 months.'],- active_bias_tags: ['over-confident-geography'],- voice_gate_passed: true,- voice_gate_attempts: 1,- model_id: 'claude-sonnet-4-6',- ...opts,- };-}--describe('buildRecallCalibrationFooter — cold-brain branch', () => {- test('null profile → empty string', () => {- expect(buildRecallCalibrationFooter({ profile: null })).toBe('');- });-- test('insufficient resolved (< 5) → empty string', () => {- expect(buildRecallCalibrationFooter({ profile: buildProfile({ total_resolved: 3 }) })).toBe(- '',- );- });-- test('zero resolved → empty string', () => {- expect(buildRecallCalibrationFooter({ profile: buildProfile({ total_resolved: 0 }) })).toBe(- '',- );- });-});--describe('buildRecallCalibrationFooter — happy path', () => {- test('emits header + Brier + pattern block', () => {- const out = buildRecallCalibrationFooter({ profile: buildProfile() });- expect(out).toContain('Calibration this quarter:');- expect(out).toContain('Brier 0.18');- expect(out).toContain('Right on early-stage tactics');- });-- test('Brier line includes trend note ("solid")', () => {- expect(buildRecallCalibrationFooter({ profile: buildProfile({ brier: 0.18 }) })).toContain(- '(solid)',- );- });-- test('Brier near-baseline range', () => {- expect(- buildRecallCalibrationFooter({ profile: buildProfile({ brier: 0.24 }) }),- ).toContain('(near baseline)');- });-- test('Brier worse than baseline → review hint', () => {- expect(buildRecallCalibrationFooter({ profile: buildProfile({ brier: 0.32 }) })).toContain(- 'worse than always-50%',- );- });-- test('Brier strong calibration', () => {- expect(- buildRecallCalibrationFooter({ profile: buildProfile({ brier: 0.08 }) }),- ).toContain('(strong calibration)');- });-- test('omits Brier line when brier=null (resolved correct+incorrect = 0)', () => {- const out = buildRecallCalibrationFooter({ profile: buildProfile({ brier: null }) });- expect(out).not.toContain('Brier null');- expect(out).toContain('Calibration this quarter:'); // header still emitted- });-- test('caps at 4 pattern statements', () => {- const out = buildRecallCalibrationFooter({- profile: buildProfile({ pattern_statements: ['a', 'b', 'c', 'd', 'e', 'f'] }),- });- const aIdx = out.indexOf(' a\n');- expect(out).toContain(' a');- expect(out).toContain(' d');- // 'e' and 'f' should NOT appear as standalone bullets.- const lines = out.split('\n');- const bullets = lines.filter(l => /^ {2}[abcdef]$/.test(l));- expect(bullets.length).toBe(4);- void aIdx;- });-});--describe('buildRecallCalibrationFooter — abandoned threads', () => {- test('omits the abandoned-threads section when no threads passed', () => {- const out = buildRecallCalibrationFooter({ profile: buildProfile() });- expect(out).not.toContain('Threads you opened');- });-- test('emits section + rows when threads provided', () => {- const out = buildRecallCalibrationFooter({- profile: buildProfile(),- abandonedThreads: [- { claim: 'AI search platform differentiation', monthsSilent: 17 },- { claim: 'International expansion playbook', monthsSilent: 12 },- ],- });- expect(out).toContain('Threads you opened and never came back to:');- expect(out).toContain('AI search platform differentiation');- expect(out).toContain('17 months silent');- expect(out).toContain('International expansion playbook');- expect(out).toContain('12 months silent');- });-- test('caps at 5 abandoned threads', () => {- const threads = Array.from({ length: 8 }, (_, i) => ({- claim: `thread ${i}`,- monthsSilent: 12 + i,- }));- const out = buildRecallCalibrationFooter({ profile: buildProfile(), abandonedThreads: threads });- expect(out).toContain('thread 0');- expect(out).toContain('thread 4');- expect(out).not.toContain('thread 5');- });-- test('truncates long claim text with ellipsis', () => {- const longClaim = 'x'.repeat(100);- const out = buildRecallCalibrationFooter({- profile: buildProfile(),- abandonedThreads: [{ claim: longClaim, monthsSilent: 12 }],- threadColumnWidth: 30,- });- expect(out).toContain('x'.repeat(29) + '…');- });-});diff --git a/test/regression-strict-source-id.test.ts b/test/regression-strict-source-id.test.tsindex bc77cdd265..cc0135d04a 100644--- a/test/regression-strict-source-id.test.ts+++ b/test/regression-strict-source-id.test.ts@@ -14,23 +14,33 @@* cycle reverse-write check but fail source add.** v0.38 consolidated both paths through `src/core/source-id.ts` and chose- * the strict regex as canonical. This test pins that change: the regex- * used at the cycle reverse-write sites must be the strict one, and the- * import path must be the consolidated one.- *- * IRON-RULE: this is a structural regression test. If a future refactor- * splits the import path or widens the regex, this test fails first.+ * the strict regex as canonical. This test pins that change at both+ * boundaries: the re-exported validator rejects exactly what the canonical+ * one rejects, and the patterns + synthesize reverse-write helpers refuse an+ * underscore or traversal source_id BEFORE any file lands under+ * `brainDir/.sources/<id>/`.*/import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'fs';+import { existsSync, mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';import { join } from 'path';import { validateSourceId } from '../src/core/utils.ts';import {SOURCE_ID_RE,assertValidSourceId,} from '../src/core/source-id.ts';+import { __testing as patterns } from '../src/core/cycle/patterns.ts';+import { __testing as synthesize } from '../src/core/cycle/synthesize.ts';+import type { BrainEngine } from '../src/core/engine.ts';-const REPO_ROOT = join(import.meta.dir, '..');+// Every slug resolves to a page, so the only thing standing between a bad+// source_id and a file write is the validator.+const pageEngine = {+ getPage: async (slug: string) => ({+ slug, type: 'note', title: slug, compiled_truth: 'body', timeline: '', frontmatter: {},+ }),+ getTags: async () => [],+} as unknown as BrainEngine;describe('strict-regex blast radius — patterns.ts + synthesize.ts (codex r2 P1-D)', () => {describe('utils.ts re-export contract', () => {@@ -63,54 +73,28 @@ describe('strict-regex blast radius — patterns.ts + synthesize.ts (codex r2 P1});});- describe('cycle reverse-write call sites use the consolidated path', () => {- test('patterns.ts imports validateSourceId from utils.ts', () => {- const src = readFileSync(join(REPO_ROOT, 'src/core/cycle/patterns.ts'), 'utf8');- // Whichever import shape — relative path varies — must reach utils.ts- // (which now re-exports the strict assertValidSourceId).- expect(src).toMatch(/import\s+\{[^}]*validateSourceId[^}]*\}\s+from\s+['"]\.\.\/utils\.ts['"]/);- });-- test('synthesize.ts imports validateSourceId from utils.ts', () => {- const src = readFileSync(join(REPO_ROOT, 'src/core/cycle/synthesize.ts'), 'utf8');- expect(src).toMatch(/import\s+\{[^}]*validateSourceId[^}]*\}\s+from\s+['"]\.\.\/utils\.ts['"]/);- });-- test('patterns.ts calls validateSourceId before reverse-write join (defense ordering)', () => {- const src = readFileSync(join(REPO_ROOT, 'src/core/cycle/patterns.ts'), 'utf8');- // Look for the canonical reverseWriteRefs body: validateSourceId(source_id)- // must appear inside a function that later calls join(brainDir, '.sources', source_id, ...).- const validatePos = src.indexOf('validateSourceId(source_id)');- const joinPos = src.indexOf(".sources', source_id");- expect(validatePos).toBeGreaterThan(-1);- expect(joinPos).toBeGreaterThan(-1);- expect(validatePos).toBeLessThan(joinPos);- });-- test('synthesize.ts calls validateSourceId before reverse-write join', () => {- const src = readFileSync(join(REPO_ROOT, 'src/core/cycle/synthesize.ts'), 'utf8');- const validatePos = src.indexOf('validateSourceId(source_id)');- const joinPos = src.indexOf(".sources', source_id");- expect(validatePos).toBeGreaterThan(-1);- expect(joinPos).toBeGreaterThan(-1);- expect(validatePos).toBeLessThan(joinPos);- });- });-- describe('utils.ts no longer carries an inline permissive regex', () => {- test('utils.ts source text contains no `^[a-z0-9_-]+$` regex literal', () => {- // Pre-v0.38 had this exact regex. The blast-radius fix tightened it.- // If a future refactor reintroduces a permissive shape in utils.ts,- // this test fails first.- const src = readFileSync(join(REPO_ROOT, 'src/core/utils.ts'), 'utf8');- expect(src).not.toMatch(/\/\^\[a-z0-9_-\]\+\$\//);- });-- test('utils.ts re-exports assertValidSourceId from source-id.ts as validateSourceId', () => {- const src = readFileSync(join(REPO_ROOT, 'src/core/utils.ts'), 'utf8');- // Either named alias re-export or any other shape that produces the- // same observable contract (validateSourceId === assertValidSourceId).- expect(src).toMatch(/assertValidSourceId\s+as\s+validateSourceId.*from\s+['"]\.\/source-id\.ts['"]/);- });+ describe('cycle reverse-write helpers reject non-canonical source ids before writing', () => {+ for (const [name, reverseWriteRefs] of [+ ['patterns', patterns.reverseWriteRefs],+ ['synthesize', synthesize.reverseWriteRefs],+ ] as const) {+ test(`${name}: snake_id and traversal ids throw and write nothing`, async () => {+ const brainDir = mkdtempSync(join(tmpdir(), `gbrain-strict-source-${name}-`));+ try {+ for (const bad of ['snake_id', '../escape']) {+ await expect(+ reverseWriteRefs(pageEngine, brainDir, [{ slug: 'wiki/x', source_id: bad }], 'default'),+ ).rejects.toThrow();+ expect(existsSync(join(brainDir, '.sources', bad, 'wiki/x.md'))).toBe(false);+ }+ expect(existsSync(join(brainDir, 'escape'))).toBe(false);+ const written = await reverseWriteRefs(pageEngine, brainDir, [{ slug: 'wiki/x', source_id: 'my-source' }], 'default');+ expect(written).toBe(1);+ expect(existsSync(join(brainDir, '.sources', 'my-source', 'wiki/x.md'))).toBe(true);+ } finally {+ rmSync(brainDir, { recursive: true, force: true });+ }+ });+ }});});diff --git a/test/regressions/v0.36.1.0-iron-rule.test.ts b/test/regressions/v0.36.1.0-iron-rule.test.tsdeleted file mode 100644index b056629cff..0000000000--- a/test/regressions/v0.36.1.0-iron-rule.test.ts+++ /dev/null@@ -1,156 +0,0 @@-/**- * v0.36.1.0 IRON RULE regression suite (T21).- *- * Per /plan-eng-review D26 IRON RULE: regressions get added to the test- * suite without AskUserQuestion. A regression is when code that previously- * worked breaks because of the wave. Five identified:- *- * R1: think baseline UNCHANGED when --with-calibration absent- * R2: contradictions probe output UNCHANGED when no profile for holder- * R3: takes resolution flow works when grade_takes phase disabled- * R4: search/list_pages/get_page work identically through new source_id paths- * R5: existing search modes (conservative/balanced/tokenmax) unaffected- *- * Some regressions are covered structurally elsewhere; this file is the- * INDEX so future contributors see all five enumerated in one place.- */--import { describe, test, expect } from 'bun:test';--// R1: see test/think-with-calibration.test.ts — 'buildThinkSystemPrompt —-// anti-bias rewrite rules (E1)' / 'withCalibration:false omits the anti-bias-// section (R1 regression guard)'. The default user message shape stays-// identical when --with-calibration is absent.--import { buildThinkUserMessage, buildThinkSystemPrompt } from '../../src/core/think/prompt.ts';--describe('R1: think baseline UNCHANGED when --with-calibration absent', () => {- test('user message default path: question first, then retrieval', () => {- const out = buildThinkUserMessage({- question: 'q',- pagesBlock: 'p',- takesBlock: 't',- });- const qIdx = out.indexOf('Question:');- const pagesIdx = out.indexOf('<pages>');- expect(qIdx).toBeLessThan(pagesIdx);- expect(out).not.toContain('<calibration');- });-- test('system prompt: no anti-bias section when withCalibration omitted', () => {- const out = buildThinkSystemPrompt({});- expect(out).not.toContain('Calibration-aware mode');- expect(out).not.toContain('PRIOR');- expect(out).not.toContain('COUNTER-PRIOR');- });-});--// R2: see test/eval-contradictions-calibration-join.test.ts —-// 'tagFindingWithCalibration — R2 regression'. Null profile returns null tag.--import { tagFindingWithCalibration } from '../../src/core/eval-contradictions/calibration-join.ts';--describe('R2: contradictions probe UNCHANGED when no calibration profile', () => {- test('null profile → null tag (output byte-identical to v0.32.6)', () => {- const finding = {- kind: 'cross_slug_chunks' as const,- a: {- slug: 'wiki/companies/x',- chunk_id: 1,- take_id: null, take_row_num: null,- source_tier: 'curated' as const,- holder: 'garry',- text: 't',- effective_date: '2024-01-01',- effective_date_source: 'fm',- },- b: {- slug: 'wiki/companies/y',- chunk_id: 1,- take_id: null, take_row_num: null,- source_tier: 'curated' as const,- holder: 'garry',- text: 't',- effective_date: '2024-01-01',- effective_date_source: 'fm',- },- combined_score: 0.8,- verdict: 'contradiction' as const,- severity: 'medium' as const,- axis: 'evidence',- confidence: 0.8,- resolution_kind: 'manual_review' as const,- resolution_command: 'gbrain takes resolve N',- };- expect(tagFindingWithCalibration(finding, null)).toBeNull();- });-});--// R3: takes resolution flow works when grade_takes phase disabled.-// Translates to: importing engine + calling resolveTake doesn't transitively-// depend on grade_takes-related modules in any way that would crash when-// grade_takes is opted out. Confirmed structurally: grade_takes module is-// imported only by cycle phase orchestrators, NOT by engine or-// takes-resolution.ts.--import { deriveResolutionTuple } from '../../src/core/takes-resolution.ts';--describe('R3: takes resolution works regardless of grade_takes phase state', () => {- test('deriveResolutionTuple operates without any grade_takes imports', () => {- // The function is pure and has no dependency on the grade_takes phase- // module. This test exists to pin the import surface — if a future- // refactor accidentally couples them, this test will fail to compile.- const out = deriveResolutionTuple({ quality: 'correct', resolvedBy: 'garry' });- expect(out.quality).toBe('correct');- expect(out.outcome).toBe(true);- });-});--// R4: search/list_pages/get_page work identically through new source_id paths.-// Already covered by the existing v0.34.1 source-isolation test suite-// (test/source-isolation-pglite.test.ts and the matching e2e tests). The-// v0.36.1.0 wave does NOT add new source-scoped paths to these ops —-// calibration is a NEW op surface, not a modification to existing ones.--describe('R4: existing read-side ops unchanged (covered structurally)', () => {- test('this regression is covered by existing v0.34.1 source-isolation suite', () => {- // Marker test. The actual coverage is at:- // - test/source-isolation-pglite.test.ts- // - test/e2e/source-isolation-pglite.test.ts- // v0.36.1.0 does NOT modify those code paths. If the calibration wave- // accidentally couples to listPages/getPage/search, the existing tests- // catch it. This marker test exists for the IRON RULE inventory.- expect(true).toBe(true);- });-});--// R5: existing search modes (conservative/balanced/tokenmax) unaffected.-// Same shape as R4 — the wave does NOT modify the search-mode resolution-// layer. Existing test/search-mode.test.ts coverage stays intact.--describe('R5: search modes unaffected by calibration wave', () => {- test('this regression is covered by existing search-mode test suite', () => {- // Marker test. v0.36.1.0 calibration code DOES NOT IMPORT from- // src/core/search/mode.ts or modify the search-mode bundle resolution.- // If a future refactor changes that, the existing search-mode tests- // (test/search-mode.test.ts) catch the behavioral regression. This- // marker exists for the IRON RULE inventory.- expect(true).toBe(true);- });-});--// Inventory check: confirm the 5 regressions are addressed somewhere.-describe('IRON RULE inventory', () => {- test('all 5 regressions have an addressed status', () => {- const inventory = {- R1: 'covered (test/think-with-calibration.test.ts + this file)',- R2: 'covered (test/eval-contradictions-calibration-join.test.ts + this file)',- R3: 'covered (this file — import-surface coupling test)',- R4: 'covered (existing v0.34.1 source-isolation suite — v0.36 does not modify those paths)',- R5: 'covered (existing search-mode suite — v0.36 does not modify those paths)',- };- for (const key of ['R1', 'R2', 'R3', 'R4', 'R5'] as const) {- expect(inventory[key]).toContain('covered');- }- });-});diff --git a/test/remediation-command-resolution.test.ts b/test/remediation-command-resolution.test.tsindex 93ba3cfa74..e87c8c8fa4 100644--- a/test/remediation-command-resolution.test.ts+++ b/test/remediation-command-resolution.test.ts@@ -28,27 +28,17 @@* build expects" would drown the signal) — documented limitation.** The companion sibling is test/docs-cli-commands.test.ts (#3502), which- * gates verbs in README/docs/skills.+ * gates verbs (and flags) in README/docs/skills; both share the scanner in+ * test/helpers/cli-command-surface.ts.*/import { describe, expect, test } from 'bun:test';import { readdirSync, readFileSync, statSync } from 'fs';import { dirname, join, relative } from 'path';-import { CLI_ONLY, cliAliases } from '../src/cli.ts';-import { operations } from '../src/core/operations.ts';import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';+import { codeRegions, gbrainInvocations, liveCliVerbs } from './helpers/cli-command-surface.ts';const ROOT = dirname(import.meta.dir);-function validCommands(): Set<string> {- const valid = new Set<string>(CLI_ONLY);- for (const op of operations) {- const name = op.cliHints?.name;- if (name && !op.cliHints?.hidden) valid.add(name);- }- for (const alias of cliAliases.keys()) valid.add(alias);- return valid;-}-/** Flags accepted globally (parsed before command dispatch) or so widely* shared that a per-command registry miss would be a false positive. */const GLOBAL_FLAGS = new Set([@@ -89,36 +79,13 @@ function topChangelogEntry(): string {return second === -1 ? text.slice(first) : text.slice(first, second);}-function commandPosition(prefix: string): boolean {- const p = prefix.trimEnd();- return p === '' || /[|;&`(={[]$/.test(p) || /\$$/.test(p);-}-function scanChangelogTopEntry(): string[] {- const valid = validCommands();+ const valid = liveCliVerbs();const violations: string[] = [];- const lines = topChangelogEntry().split('\n');- let inFence = false;- for (let i = 0; i < lines.length; i++) {- const l = lines[i]!;- if (/^\s*(```|~~~)/.test(l)) { inFence = !inFence; continue; }- const candidates: string[] = [];- if (inFence) {- const t = l.trim();- if (/^(#|\/\/|--|\*)/.test(t)) continue;- candidates.push(l);- } else {- for (const m of l.matchAll(/`(gbrain [^`]+)`/g)) candidates.push(m[1]!);- }- for (const code of candidates) {- for (const m of code.matchAll(/\bgbrain\s+([A-Za-z][\w-]*)/g)) {- const verb = m[1]!;- if (!/^[a-z][a-z0-9_-]{2,}$/.test(verb)) continue;- if (!commandPosition(code.slice(0, m.index))) continue;- if (valid.has(verb)) continue;- if (CHANGELOG_ALLOWLIST.has(verb)) continue;- violations.push(`CHANGELOG.md (top entry): \`gbrain ${verb}\` is not a real command — ${code.trim().slice(0, 90)}`);- }+ for (const { code } of codeRegions(topChangelogEntry())) {+ for (const { verb } of gbrainInvocations(code)) {+ if (valid.has(verb) || CHANGELOG_ALLOWLIST.has(verb)) continue;+ violations.push(`CHANGELOG.md (top entry): \`gbrain ${verb}\` is not a real command — ${code.trim().slice(0, 90)}`);}}return violations;@@ -146,7 +113,7 @@ function srcExcluded(rel: string): boolean {}function scanSrcStrings(): string[] {- const valid = validCommands();+ const valid = liveCliVerbs();const violations: string[] = [];for (const file of tsFiles(join(ROOT, 'src'))) {const rel = relative(ROOT, file);@@ -208,7 +175,7 @@ describe('#3697 — remediation text resolves against the live CLI surface', ()// gate is itself the #3665 pattern (an assertion nobody checks discriminates).test('scanner self-check: the historical rot shapes would have been caught', () => {// fake verb: never a command- expect(validCommands().has('reinit-everything')).toBe(false);+ expect(liveCliVerbs().has('reinit-everything')).toBe(false);// fake flag on a real verb: the shipped #3697 instances. If a future// registry regen adds these flags, the commands grew them for real and// this pin should flip WITH the hint text.diff --git a/test/remote-ping-status-field.test.ts b/test/remote-ping-status-field.test.tsdeleted file mode 100644index 11e74e9050..0000000000--- a/test/remote-ping-status-field.test.ts+++ /dev/null@@ -1,53 +0,0 @@-/**- * Regression guard: `gbrain remote ping` must poll the MinionJob `status`- * field, never `state`.- *- * submit_job and get_job (src/core/operations.ts) return the MinionJob row- * verbatim, whose lifecycle field is `status`- * (src/core/minions/types.ts). remote.ts once typed and read `state`- * instead: every poll then saw `undefined`, the terminal check- * (`['completed','failed','dead','cancelled'].includes(job.state)`) never- * matched, and ping exhausted its full --timeout and exited 1 even when- * the autopilot-cycle had completed — printing- * "Job #N is still undefined." on the way out.- *- * Source-audit style (same idiom as thin-client-routing-audit.test.ts):- * pins the reads without needing a live MCP transport.- */--import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'node:fs';-import { join } from 'node:path';--const REMOTE_TS_PATH = join(import.meta.dir, '..', 'src', 'commands', 'remote.ts');-const REMOTE_SOURCE = readFileSync(REMOTE_TS_PATH, 'utf8');--describe('remote ping polls MinionJob.status, not .state', () => {- test('no `.state` property reads on job objects remain', () => {- // Catches `submitted.state`, `job.state` — any resurrection of the- // wrong field. The ping's JSON *output* keys (`state:`, `last_state:`)- // are object-literal keys, not property reads, and don't match this.- expect(REMOTE_SOURCE).not.toMatch(/\b(?:job|submitted)\.state\b/);- });-- test('poll loop reads job.status', () => {- expect(REMOTE_SOURCE).toMatch(/\bjob\.status\b/);- expect(REMOTE_SOURCE).toMatch(/\bsubmitted\.status\b/);- });-- test('terminal-state check tests job.status', () => {- expect(REMOTE_SOURCE).toMatch(/terminal\.includes\(job\.status\)/);- });-- test('unpack generics type the lifecycle field as status', () => {- // Both the submit and poll unpack sites must carry `status: string` in- // their type argument, and none may reintroduce `state: string`.- const unpackShapes = REMOTE_SOURCE.match(/unpackToolResult<\{[^}]*\}>/g) ?? [];- const jobShapes = unpackShapes.filter((s) => s.includes('id: number'));- expect(jobShapes.length).toBeGreaterThanOrEqual(2);- for (const shape of jobShapes) {- expect(shape).toContain('status: string');- expect(shape).not.toContain('state: string');- }- });-});diff --git a/test/e2e/remote-privacy-journeys.test.ts b/test/remote-privacy-journeys.serial.test.tssimilarity index 93%rename from test/e2e/remote-privacy-journeys.test.tsrename to test/remote-privacy-journeys.serial.test.tsindex 1f06ac6e16..11b0ea9de3 100644--- a/test/e2e/remote-privacy-journeys.test.ts+++ b/test/remote-privacy-journeys.serial.test.ts@@ -1,6 +1,10 @@/** Real MCP transport journeys over isolated, persistent PGLite brains.* Data seeding uses the engine before serve starts (PGLite is single-writer).* No provider keys, model calls, ambient brain, or external database is used.+ *+ * Lane: serial. Run: `bash scripts/run-serial-tests.sh test/remote-privacy-journeys.serial.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { spawn, spawnSync, type ChildProcess } from 'node:child_process';@@ -11,18 +15,18 @@ import { join } from 'node:path';import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { importFromContent } from '../../src/core/import-file.ts';-import { serializeMarkdown } from '../../src/core/markdown.ts';-import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';-import { renderFactsTable } from '../../src/core/facts-fence.ts';-import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';-import { operationsByName, type OperationContext } from '../../src/core/operations.ts';-import { unpackToolResult } from '../../src/core/mcp-client.ts';-import { keylessBrainEnv } from '../helpers/provider-env.ts';-import { cliDiagnostic, fixtureDiagnostic, toolDiagnostic } from '../helpers/fixture-diagnostics.ts';-import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';-import { createManagedFixtureSource, withManagedFixtureWrite } from '../helpers/managed-e2e-fixture-write.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { renderFactsTable } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../src/core/takes-fence.ts';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import { unpackToolResult } from '../src/core/mcp-client.ts';+import { keylessBrainEnv } from './helpers/provider-env.ts';+import { cliDiagnostic, fixtureDiagnostic, toolDiagnostic } from './helpers/fixture-diagnostics.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { createManagedFixtureSource, withManagedFixtureWrite } from './helpers/managed-e2e-fixture-write.ts';const PUBLIC = 'privacyjourneypublic';const PRIVATE = 'PRIVATE_PAGE_JOURNEY_CANARY';diff --git a/test/resolver.test.ts b/test/resolver.test.tsindex 7c0d62a83a..7858e2c60e 100644--- a/test/resolver.test.ts+++ b/test/resolver.test.ts@@ -1,7 +1,6 @@import { describe, test, expect } from "bun:test";import { readFileSync, existsSync, readdirSync, statSync } from "fs";import { join } from "path";-import { checkResolvable } from "../src/core/check-resolvable.ts";import { PROTECTED_JOB_NAMES } from "../src/core/minions/protected-names.ts";import { operations } from "../src/core/operations.ts";@@ -17,13 +16,6 @@ describe("RESOLVER.md", () => {? readFileSync(RESOLVER_PATH, "utf-8"): "";- test("references only existing skill files", () => {- // Delegates to checkResolvable — no reimplemented parsing logic- const report = checkResolvable(SKILLS_DIR);- const missingFiles = report.issues.filter(i => i.type === "missing_file");- expect(missingFiles.length).toBe(0);- });-test("has categorized sections", () => {expect(resolverContent).toContain("## Always-on");expect(resolverContent).toContain("## Brain operations");@@ -39,17 +31,6 @@ describe("RESOLVER.md", () => {expect(resolverContent).toContain("conventions/quality.md");expect(resolverContent).toContain("_brain-filing-rules.md");});-- test("every manifest skill is reachable from resolver", () => {- // Delegates to checkResolvable — the shared function handles all validation- const report = checkResolvable(SKILLS_DIR);- const unreachable = report.issues.filter(i => i.type === "unreachable");- if (unreachable.length > 0) {- const names = unreachable.map(i => `${i.skill}: ${i.action}`).join("\n ");- throw new Error(`Unreachable skills:\n ${names}`);- }- expect(report.summary.unreachable).toBe(0);- });});// D5/C — resolver round-trip: every quoted trigger in a RESOLVER.md table rowdiff --git a/test/resolvers.test.ts b/test/resolvers.test.tsindex a577270cd5..1e00e8ae13 100644--- a/test/resolvers.test.ts+++ b/test/resolvers.test.ts@@ -18,7 +18,7 @@ import type {ResolverRequest,ResolverResult,} from '../src/core/resolvers/index.ts';-import { urlReachableResolver, checkDnsRebinding } from '../src/core/resolvers/builtin/url-reachable.ts';+import { urlReachableResolver } from '../src/core/resolvers/builtin/url-reachable.ts';import { __setDnsLookupForTests } from '../src/core/ssrf-validate.ts';import { xHandleToTweetResolver, computeBackoffMs } from '../src/core/resolvers/builtin/x-api/handle-to-tweet.ts';@@ -168,15 +168,6 @@ describe('getDefaultRegistry', () => {const b = getDefaultRegistry();expect(a).toBe(b);});-- test('_resetDefaultRegistry gives a fresh instance', () => {- const a = getDefaultRegistry();- a.register(echoResolver);- _resetDefaultRegistry();- const b = getDefaultRegistry();- expect(b).not.toBe(a);- expect(b.size()).toBe(0);- });});// ---------------------------------------------------------------------------@@ -338,22 +329,6 @@ describe('url_reachable resolver', () => {expect(result.value.reason).not.toContain('private-');});- test('checkDnsRebinding: validates IP literals using the shared policy', async () => {- expect(await checkDnsRebinding('http://8.8.8.8/')).toBeNull();- expect(await checkDnsRebinding('http://127.0.0.1/')).toMatch(/internal|private/i);- expect(await checkDnsRebinding('http://[::1]/')).toMatch(/internal|private/i);- });-- test('checkDnsRebinding: rejects an unparseable URL', async () => {- expect(await checkDnsRebinding('not a url')).toMatch(/malformed/i);- });-- test('checkDnsRebinding: fails closed on DNS failure', async () => {- __setDnsLookupForTests((async () => { throw new Error('ENOTFOUND'); }) as any);- const r = await checkDnsRebinding('http://definitely-not-a-real-tld.invalidtld123/');- expect(r).toMatch(/resolve|DNS/i);- });-test('AbortSignal fires mid-flight → ResolverError(aborted)', async () => {const ac = new AbortController();globalThis.fetch = (async () => {diff --git a/test/salience.test.ts b/test/salience.test.tsindex d9dd97954f..3e3f0ca411 100644--- a/test/salience.test.ts+++ b/test/salience.test.ts@@ -1,5 +1,4 @@import { describe, expect, test } from 'bun:test';-import { computeAnomaliesFromBuckets } from '../src/core/cycle/anomaly.ts';/*** Unit-level salience checks. The full Garry-test fixture lives in@@ -32,11 +31,3 @@ describe('v0.29 — salience SQL shape pinned via type contract', () => {expect(typeof mod).toBe('object');});});--describe('v0.29 — anomaly cohort buckets connect to the engine', () => {- test('computeAnomaliesFromBuckets is exported and pure', () => {- // Smoke that the import path engines use is wired. The behavior is- // covered exhaustively in test/anomalies.test.ts.- expect(typeof computeAnomaliesFromBuckets).toBe('function');- });-});diff --git a/test/schema-cli-contract.test.ts b/test/schema-cli-contract.test.tsindex 00fe2aa703..18dde4e47b 100644--- a/test/schema-cli-contract.test.ts+++ b/test/schema-cli-contract.test.ts@@ -1,93 +1,121 @@-// v0.39 T6 — CLI contract pinning test.+// v0.39 T6 — schema CLI contract, driven through runSchema.//-// Every schema CLI verb supports --json output and (where source-scoping-// makes sense) --source <id>. Pin in CI so future verbs can't drift.-// The structural check is a source grep against src/commands/schema.ts:-// every verb-handler function MUST consult parseFlags() (which yields-// {json, source, positional}). The grep is intentionally simple — a verb-// that wants to opt OUT of the contract must do so explicitly and-// document why.+// Every v0.39+ schema verb prints a `schema_version: 1` JSON envelope under+// --json; the experimental-tier verbs tag that envelope `tier:+// 'experimental'`; the engine-backed verbs honor --source, --source-id and+// their `=` forms. Each case runs the real dispatcher against a temporary+// GBRAIN_HOME with a file-backed PGLite brain.-import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'node:fs';+import { describe, test, expect, spyOn, beforeAll, afterAll } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runSchema } from '../src/commands/schema.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { withEnv } from './helpers/with-env.ts';-const SCHEMA_TS = readFileSync('src/commands/schema.ts', 'utf-8');+let home: string;-// Verbs that take any input (not the bare router cases).-// `active`/`list`/`show`/`validate`/`use` are legacy v0.38 — they don't-// follow the parseFlags() contract; opt-out documented.-const LEGACY_OPT_OUT = new Set(['active', 'list', 'show', 'validate', 'use']);--const NEW_VERBS = [- 'detect', 'suggest', 'review-candidates',- 'init', 'fork', 'edit', 'diff', 'graph', 'lint', 'explain', 'review-orphans',- 'downgrade', 'usage',-];--describe('v0.39 T6 — schema CLI contract', () => {- test('every new verb routes through runSchema dispatch', () => {- for (const v of NEW_VERBS) {- expect(SCHEMA_TS).toContain(`case '${v}':`);+beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-schema-contract-'));+ const brain = join(home, '.gbrain');+ mkdirSync(brain, { recursive: true });+ const databasePath = join(brain, 'brain.pglite');+ writeFileSync(join(brain, 'config.json'), JSON.stringify({ engine: 'pglite', database_path: databasePath }));+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: databasePath });+ try {+ await engine.initSchema();+ for (const slug of ['projects/alpha', 'projects/beta', 'projects/gamma']) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'Fixture page.' });}- });+ } finally {+ await engine.disconnect();+ }+}, 60_000);- test('every new verb-handler reads parseFlags() for --json + --source', () => {- // The handler function name pattern is run<PascalCase>Cmd. Each must- // call parseFlags. Source-grep is sufficient: if a future verb forgets- // parseFlags, this test fails.- const handlerNames = NEW_VERBS.map((v) => {- const pascal = v.split('-').map((p) => p[0].toUpperCase() + p.slice(1)).join('');- return `run${pascal}Cmd`;- });- for (const h of handlerNames) {- // Each handler must exist as a function declaration.- expect(SCHEMA_TS).toContain(`async function ${h}(`);- // And must contain a parseFlags() call (the contract gate).- const handlerStart = SCHEMA_TS.indexOf(`async function ${h}(`);- const handlerEnd = SCHEMA_TS.indexOf('async function ', handlerStart + 1);- const handlerBody = SCHEMA_TS.slice(handlerStart, handlerEnd > 0 ? handlerEnd : undefined);- expect(handlerBody).toContain('parseFlags(');- }- });+afterAll(() => { rmSync(home, { recursive: true, force: true }); });- test('parseFlags() returns the documented shape', () => {- expect(SCHEMA_TS).toContain('function parseFlags(args: string[]): ParsedFlags');- expect(SCHEMA_TS).toContain('interface ParsedFlags');- expect(SCHEMA_TS).toContain('json: boolean');- expect(SCHEMA_TS).toContain('source: string | undefined');- expect(SCHEMA_TS).toContain('positional: string[]');- });+async function runJson(args: string[]): Promise<{ json: Record<string, unknown>; exitCode: number | undefined }> {+ const lines: string[] = [];+ let exitCode: number | undefined;+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });+ const err = spyOn(console, 'error').mockImplementation(() => {});+ const exit = spyOn(process, 'exit').mockImplementation(((code?: number) => { exitCode = code; throw new Error('__exit__'); }) as never);+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: undefined }, () => runSchema(args));+ } catch (e) {+ if ((e as Error).message !== '__exit__') throw e;+ } finally {+ log.mockRestore(); err.mockRestore(); exit.mockRestore();+ }+ const out = lines.join('\n');+ expect(out.trimStart().startsWith('{'), `${args.join(' ')} printed non-JSON:\n${out}`).toBe(true);+ return { json: JSON.parse(out), exitCode };+}- test('parseFlags accepts both --source and --source-id forms', () => {- expect(SCHEMA_TS).toContain("'--source'");- expect(SCHEMA_TS).toContain("'--source-id'");- });+describe('v0.39 T6 — schema CLI contract', () => {+ const cases: Array<{ args: string[]; experimental: boolean }> = [+ { args: ['detect'], experimental: false },+ { args: ['suggest'], experimental: false },+ { args: ['review-candidates'], experimental: false },+ { args: ['init', 'contract-pack'], experimental: true },+ { args: ['fork', 'gbrain-base', 'contract-fork'], experimental: true },+ { args: ['edit', 'contract-fork'], experimental: true },+ { args: ['diff', 'gbrain-base', 'contract-fork'], experimental: true },+ { args: ['graph'], experimental: true },+ { args: ['lint'], experimental: false },+ { args: ['explain', 'writing'], experimental: true },+ { args: ['review-orphans'], experimental: false },+ { args: ['downgrade', '--to', 'gbrain-base'], experimental: false },+ { args: ['usage'], experimental: false },+ ];- test('every new verb when --json passed produces a JSON envelope', () => {- // schema_version: 1 is the contract for every JSON output.- // Source-grep: count occurrences of `schema_version: 1` near JSON output sites.- const matches = SCHEMA_TS.match(/schema_version:\s*1/g) ?? [];- expect(matches.length).toBeGreaterThanOrEqual(NEW_VERBS.length - 2);- // ^ allow up to 2 verbs to skip the envelope where it's degenerate- // (e.g. edit just prints a path; usage prints aggregate).- });+ test('every v0.39+ verb prints a schema_version 1 JSON envelope, tagged experimental exactly for the experimental tier', async () => {+ for (const { args, experimental } of cases) {+ const { json, exitCode } = await runJson([...args, '--json']);+ expect(exitCode ?? 0, args.join(' ')).toBe(0);+ expect(json.schema_version, args.join(' ')).toBe(1);+ expect(json.tier, args.join(' ')).toBe(experimental ? 'experimental' : undefined);+ }+ }, 60_000);- test('legacy v0.38 verbs are explicitly NOT in NEW_VERBS', () => {- // Regression guard: do not silently let a legacy verb opt-in without- // also updating LEGACY_OPT_OUT documentation.- for (const v of NEW_VERBS) {- expect(LEGACY_OPT_OUT.has(v)).toBe(false);+ test('engine-backed verbs scope to --source, --source-id and their = forms', async () => {+ expect((await runJson(['detect', '--json'])).json.total_pages).toBe(3);+ for (const flag of [['--source', 'contract-empty'], ['--source-id', 'contract-empty'], ['--source=contract-empty'], ['--source-id=contract-empty']]) {+ expect((await runJson(['detect', '--json', ...flag])).json.total_pages, flag.join(' ')).toBe(0);}- });+ for (const verb of ['suggest', 'review-candidates', 'review-orphans']) {+ expect((await runJson([verb, '--json', '--source-id', 'contract-empty'])).json.source_id, verb).toBe('contract-empty');+ }+ }, 60_000);- test('EXPERIMENTAL_VERBS set matches the documented D14 hybrid choice', () => {- expect(SCHEMA_TS).toContain('init');- expect(SCHEMA_TS).toContain('fork');- expect(SCHEMA_TS).toContain('edit');- expect(SCHEMA_TS).toContain('diff');- expect(SCHEMA_TS).toContain('graph');- expect(SCHEMA_TS).toContain('explain');- expect(SCHEMA_TS).toContain('EXPERIMENTAL_VERBS');- // ^ the marker constant must be present so T23 telemetry can read it.+ test('schema usage reports and tags exactly the D14 experimental verbs', async () => {+ const auditDir = mkdtempSync(join(tmpdir(), 'gbrain-schema-usage-'));+ try {+ const ts = new Date().toISOString();+ writeFileSync(join(auditDir, 'schema-events-fixture.jsonl'), ['init', 'explain', 'lint', 'detect']+ .map(verb => JSON.stringify({ ts, verb, outcome: 'success' })).join('\n') + '\n');+ const lines: string[] = [];+ const spy = spyOn(console, 'log').mockImplementation((...args: unknown[]) => { lines.push(args.map(String).join(' ')); });+ try {+ await withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ await runSchema(['usage', '--json']);+ const json = JSON.parse(lines.join('\n'));+ expect([...json.experimental_verbs].sort()).toEqual(['diff', 'edit', 'explain', 'fork', 'graph', 'init']);+ lines.length = 0;+ await runSchema(['usage']);+ });+ } finally {+ spy.mockRestore();+ }+ const row = (verb: string) => lines.find(l => l.trim().startsWith(verb + ' ')) ?? '';+ expect(row('init')).toContain('(experimental)');+ expect(row('explain')).toContain('(experimental)');+ expect(row('lint')).not.toContain('(experimental)');+ expect(row('detect')).not.toContain('(experimental)');+ } finally {+ rmSync(auditDir, { recursive: true, force: true });+ }});});diff --git a/test/schema-pack-expand-type-filter.test.ts b/test/schema-pack-expand-type-filter.test.tsdeleted file mode 100644index a9a5437d44..0000000000--- a/test/schema-pack-expand-type-filter.test.ts+++ /dev/null@@ -1,145 +0,0 @@-// v0.42 Type Unification (T29) — expandTypeFilter + buildTypeFilterSql.-//-// Coverage: alias-to-canonical expansion with frontmatter subtype, alias-// without subtype falls back to subtype=alias-name, canonical pass-through,-// unknown type pass-through, SQL fragment generation.--import { describe, expect, it } from 'bun:test';-import { expandTypeFilter, buildTypeFilterSql } from '../src/core/schema-pack/expand-type-filter.ts';-import type { SchemaPackManifest } from '../src/core/schema-pack/manifest-v1.ts';--function packOf(page_types: SchemaPackManifest['page_types']): Pick<SchemaPackManifest, 'page_types'> {- return { page_types };-}--const fmAlias = packOf([- {- name: 'tweet',- primitive: 'media',- path_prefixes: [],- aliases: ['tweet-single', 'tweet-bundle'],- extractable: false,- expert_routing: false,- subtypes: [- { name: 'single', when: { frontmatter_field: 'thread_length', frontmatter_value: 1 } },- { name: 'bundle', when: { frontmatter_field: 'bundle', frontmatter_value: true } },- ],- },-]);--describe('expandTypeFilter', () => {- it('null pack → pass-through (D4 EMPTY FILTER)', () => {- expect(expandTypeFilter('article', null)).toEqual({- canonical: 'article',- subtypeFilter: null,- isAliasExpansion: false,- originalInput: 'article',- });- });-- it('canonical type → pass-through', () => {- expect(expandTypeFilter('tweet', fmAlias)).toEqual({- canonical: 'tweet',- subtypeFilter: null,- isAliasExpansion: false,- originalInput: 'tweet',- });- });-- it('alias with mapping_rule → uses retype rule subtype (canonical answer)', () => {- // gbrain-base-v2 shape: mapping_rule says- // { from_type: 'tweet-single', to_type: 'tweet', subtype: 'single' }- // so --type tweet-single matches pages where unify stamped subtype='single'.- const packWithRules = {- ...fmAlias,- mapping_rules: [- { kind: 'retype', from_type: 'tweet-single', to_type: 'tweet', subtype: 'single' },- ],- };- const result = expandTypeFilter('tweet-single', packWithRules);- expect(result.isAliasExpansion).toBe(true);- expect(result.canonical).toBe('tweet');- expect(result.originalInput).toBe('tweet-single');- expect(result.subtypeFilter).toEqual({- canonical: 'tweet',- subtypeField: 'subtype',- subtypeValue: 'single',- });- });-- it('alias without mapping_rule, with matching subtype name → uses subtype rule', () => {- // Edge case for hand-written packs: subtype rule whose name === alias.- const pack = packOf([{- name: 'tweet',- primitive: 'media',- path_prefixes: [],- aliases: ['bundle'],- extractable: false,- expert_routing: false,- subtypes: [- { name: 'bundle', when: { frontmatter_field: 'bundle', frontmatter_value: true } },- ],- }]);- const result = expandTypeFilter('bundle', pack);- expect(result.isAliasExpansion).toBe(true);- expect(result.canonical).toBe('tweet');- expect(result.subtypeFilter).toEqual({- canonical: 'tweet',- subtypeField: 'bundle',- subtypeValue: 'true',- });- });-- it('alias without matching subtype rule → falls back to subtype=alias-name', () => {- const pack = packOf([{- name: 'media',- primitive: 'media',- path_prefixes: [],- aliases: ['article'],- extractable: false,- expert_routing: false,- }]);- const result = expandTypeFilter('article', pack);- expect(result.isAliasExpansion).toBe(true);- expect(result.canonical).toBe('media');- expect(result.subtypeFilter?.subtypeField).toBe('subtype');- expect(result.subtypeFilter?.subtypeValue).toBe('article');- });-- it('unknown type → pass-through', () => {- const result = expandTypeFilter('unknown-type', fmAlias);- expect(result.canonical).toBe('unknown-type');- expect(result.isAliasExpansion).toBe(false);- expect(result.subtypeFilter).toBeNull();- });-});--describe('buildTypeFilterSql', () => {- it('non-expansion → simple type = $1', () => {- const expanded = { canonical: 'media', subtypeFilter: null, isAliasExpansion: false, originalInput: 'media' };- const { sql, params } = buildTypeFilterSql(expanded);- expect(sql).toBe('type = $1');- expect(params).toEqual(['media']);- });-- it('alias expansion → OR fragment with 4 params', () => {- const expanded = {- canonical: 'tweet',- subtypeFilter: { canonical: 'tweet', subtypeField: 'thread_length', subtypeValue: '1' },- isAliasExpansion: true,- originalInput: 'tweet-single',- };- const { sql, params } = buildTypeFilterSql(expanded);- expect(sql).toContain('type = $1');- expect(sql).toContain('type = $2');- expect(sql).toContain("frontmatter ->> $3 = $4");- expect(params).toEqual(['tweet-single', 'tweet', 'thread_length', '1']);- });-- it('respects startParamIndex offset', () => {- const expanded = { canonical: 'media', subtypeFilter: null, isAliasExpansion: false, originalInput: 'media' };- const { sql, params } = buildTypeFilterSql(expanded, 5);- expect(sql).toBe('type = $5');- expect(params).toEqual(['media']);- });-});diff --git a/test/schema-pack-manifest-v041_2.test.ts b/test/schema-pack-manifest-v041_2.test.tsindex b515f84d4e..09246bad97 100644--- a/test/schema-pack-manifest-v041_2.test.ts+++ b/test/schema-pack-manifest-v041_2.test.ts@@ -15,7 +15,6 @@ import { describe, test, expect } from 'bun:test';import {parseSchemaPackManifest,AGGREGATOR_KINDS,- type AggregatorKind,type CalibrationDomain,type SchemaPackManifest,} from '../src/core/schema-pack/manifest-v1.ts';@@ -38,14 +37,6 @@ describe('v0.41 T3: AggregatorKind closed registry', () => {'cluster_summary',]);});-- test('AggregatorKind type union covers exactly the enum values', () => {- // Compile-time + runtime test: every AGGREGATOR_KINDS value is a valid AggregatorKind- for (const k of AGGREGATOR_KINDS) {- const typed: AggregatorKind = k;- expect(typeof typed).toBe('string');- }- });});describe('v0.41 T3: SchemaPackManifestSchema phases field', () => {diff --git a/test/schema-pack-rewrite-links-batch.test.ts b/test/schema-pack-rewrite-links-batch.test.tsdeleted file mode 100644index 6deae27399..0000000000--- a/test/schema-pack-rewrite-links-batch.test.ts+++ /dev/null@@ -1,83 +0,0 @@-// v0.42 Type Unification (T30) — rewriteLinksBatch unit tests.-//-// Coverage: empty pair list no-op, single pair, multi pair, source-scoped-// (each pair carries its own sourceId), missing endpoints skip.--import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'bun:test';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { resetPgliteState } from './helpers/reset-pglite.ts';-import { rewriteLinksBatch } from '../src/core/schema-pack/rewrite-links-batch.ts';--let engine: PGLiteEngine;--beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({});- await engine.initSchema();-});--afterAll(async () => {- await engine.disconnect();-});--beforeEach(async () => {- await resetPgliteState(engine);-});--async function seed(slug: string) {- await engine.putPage(slug, {- title: slug, type: 'concept' as never,- compiled_truth: 'body that is long enough to pass any minimum length backstop',- timeline: '', frontmatter: {}, source_path: `${slug}.md`,- });-}--describe('rewriteLinksBatch', () => {- it('empty array no-op', async () => {- const count = await rewriteLinksBatch(engine, []);- expect(count).toBe(0);- });-- it('rewrites links referencing old page to point at new page', async () => {- await seed('old-canonical');- await seed('new-canonical');- await seed('referrer-page');- // Insert a link from referrer-page → old-canonical- await engine.addLinksBatch([- {- from_slug: 'referrer-page',- to_slug: 'old-canonical',- link_type: 'mentions',- link_source: 'manual',- from_source_id: 'default',- to_source_id: 'default',- },- ]);- // Verify link exists- const before = await engine.executeRaw<{ cnt: string }>(- `SELECT COUNT(*)::text AS cnt FROM links l- JOIN pages p ON l.to_page_id = p.id- WHERE p.slug = 'old-canonical'`,- );- expect(parseInt(before[0].cnt, 10)).toBe(1);- // Rewrite- const touched = await rewriteLinksBatch(engine, [- { from_slug: 'old-canonical', to_slug: 'new-canonical', source_id: 'default' },- ]);- expect(touched).toBeGreaterThan(0);- // Link now points at new-canonical- const after = await engine.executeRaw<{ cnt: string }>(- `SELECT COUNT(*)::text AS cnt FROM links l- JOIN pages p ON l.to_page_id = p.id- WHERE p.slug = 'new-canonical'`,- );- expect(parseInt(after[0].cnt, 10)).toBe(1);- });-- it('skips pairs whose endpoints do not exist', async () => {- const touched = await rewriteLinksBatch(engine, [- { from_slug: 'nonexistent-a', to_slug: 'nonexistent-b', source_id: 'default' },- ]);- expect(touched).toBe(0);- });-});diff --git a/test/schema-pack/suggest.test.ts b/test/schema-pack/suggest.test.tsindex db743b3d8c..85c208cb42 100644--- a/test/schema-pack/suggest.test.ts+++ b/test/schema-pack/suggest.test.ts@@ -9,8 +9,8 @@* emits at confidence EXACTLY 0.5, strictly below the 0.6 auto-apply floor* (codex finding #9: consumers MUST treat < 0.6 as manual-review-only), so a* keyless install can never auto-apply a schema change. 0.6 exists only as a- * documented contract (suggest.ts comment, skills/eiirp/SKILL.md,- * eval-schema-authoring's low_confidence_count) — the source-text guard below+ * documented contract (suggest.ts comment, skills/eiirp/SKILL.md) — the+ * source-text guard below* pins both literals so neither side can drift alone.** The heuristic tests intentionally pass NO suggestFn: every branch of the@@ -177,8 +177,7 @@ describe('runSuggest — heuristic fallback (no suggestFn)', () => {describe('runSuggest — source-text contract (structural)', () => {test('the 0.5 heuristic constant and the documented 0.6 floor stay in suggest.ts together', () => {// The 0.6 auto-apply floor has no exported constant — it is a documented- // contract (suggest.ts, skills/eiirp/SKILL.md, eval-schema-authoring's- // low_confidence_count). Pin both literals in the one file that carries+ // contract (suggest.ts, skills/eiirp/SKILL.md). Pin both literals in the one file that carries// the safe-by-construction pairing, so a change to either side must// reconcile this test (and thus the other side) explicitly.const src = readFileSync(join(import.meta.dir, '..', '..', 'src', 'core', 'schema-pack', 'suggest.ts'), 'utf-8');diff --git a/test/scripts/check-engine-dynamic-import.test.ts b/test/scripts/check-engine-dynamic-import.test.tsindex 36452e6e16..41a1009052 100644--- a/test/scripts/check-engine-dynamic-import.test.ts+++ b/test/scripts/check-engine-dynamic-import.test.ts@@ -5,9 +5,7 @@ import { basename, join, resolve } from 'node:path';import { spawnSync } from 'node:child_process';const REPO_ROOT = resolve(import.meta.dir, '..', '..');-const PACKAGE_JSON = resolve(REPO_ROOT, 'package.json');const GUARD = resolve(REPO_ROOT, 'scripts', 'check-engine-dynamic-import.sh');-const VERIFY_DISPATCHER = resolve(REPO_ROOT, 'scripts', 'run-verify-parallel.sh');const BASH = process.platform === 'win32'? resolve(process.env.ProgramFiles ?? 'C:\\Program Files', 'Git', 'bin', 'bash.exe'): 'bash';@@ -60,9 +58,6 @@ afterEach(() => {});describe('check-engine-dynamic-import.sh', () => {- it('exists', () => {- expect(existsSync(GUARD)).toBe(true);- });it('rejects and reports an unmarked dynamic import', () => {const path = fixture('violator.ts', "async function load() {\n return await import('./helper.ts');\n}\n");@@ -323,34 +318,3 @@ describe('check-engine-dynamic-import.sh', () => {);}, 30_000);});--describe('engine dynamic-import guard wiring', () => {- it('is wired into the verify registry (W0: check:all deleted; CHECKS array is THE registry)', () => {- const pkg = JSON.parse(readFileSync(PACKAGE_JSON, 'utf8')) as {- scripts: Record<string, string>;- };- expect(pkg.scripts['check:engine-dynamic-import']).toBe(- 'bash scripts/check-engine-dynamic-import.sh',- );- // The stale duplicate registry is gone for good…- expect(pkg.scripts['check:all']).toBeUndefined();- // …and the single registry carries this guard.- const checks = readFileSync(- new URL('../../scripts/run-verify-parallel.sh', import.meta.url),- 'utf8',- );- expect(checks).toContain('"check:engine-dynamic-import"');- });-- it('is listed by the authoritative verify dispatcher', () => {- const result = spawnSync(BASH, [VERIFY_DISPATCHER, '--dry-list'], {- cwd: REPO_ROOT,- encoding: 'utf8',- timeout: 30_000,- });- expect(result.status).toBe(0);- expect(new Set((result.stdout ?? '').trim().split('\n'))).toContain(- 'check:engine-dynamic-import',- );- });-});diff --git a/test/scripts/check-orphan-modules.test.ts b/test/scripts/check-orphan-modules.test.tsnew file mode 100644index 0000000000..9f5cbaa614--- /dev/null+++ b/test/scripts/check-orphan-modules.test.ts@@ -0,0 +1,128 @@+/**+ * Failing-side proof for every check-orphan-modules.mjs rule. The+ * guard-self-test fixtures cover the hard-orphan rule (bad) and the pass path+ * with a permitted test-only and a script-reachable module (good); these tests+ * drive the named permitted-set rules through GBRAIN_GUARD_ROOT temp trees and+ * pin the diagnostic contract (rule, module, importers, reason, remedy, rerun+ * command, docs anchor), so a delete-one-add-one swap or a stale entry cannot+ * pass silently.+ */+import { describe, test, expect, afterEach } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { spawnSync } from 'node:child_process';++const REPO_ROOT = resolve(import.meta.dir, '..', '..');+const GUARD = join(REPO_ROOT, 'scripts', 'check-orphan-modules.mjs');+const tempDirs: string[] = [];++afterEach(() => {+ for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++type Permitted = Array<{ path?: string; reason?: string }>;++function makeTree(files: Record<string, string>, permitted?: Permitted): string {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-orphan-modules-'));+ tempDirs.push(root);+ const all: Record<string, string> = {+ 'src/entry.ts': "import { used } from './used.ts';\nconsole.log(used);\n",+ 'src/used.ts': "export const used = 'reachable';\n",+ ...files,+ };+ for (const [rel, content] of Object.entries(all)) {+ const full = join(root, rel);+ mkdirSync(join(full, '..'), { recursive: true });+ writeFileSync(full, content);+ }+ if (permitted) writeFileSync(join(root, 'permitted-test-only.json'), JSON.stringify(permitted));+ return root;+}++function runGuard(root: string) {+ const r = spawnSync('node', [GUARD], { env: { ...process.env, GBRAIN_GUARD_ROOT: root }, encoding: 'utf8' });+ return { status: r.status, stdout: r.stdout, stderr: r.stderr };+}++function expectDiagnostic(stderr: string, rule: string, path: string) {+ expect(stderr).toContain(`FAIL [orphan-modules/${rule}] ${path}`);+ expect(stderr).toContain('rerun: bun run check:orphan-modules');+ expect(stderr).toContain('docs: docs/TESTING.md#orphan-module-guard');+}++const helperTree = {+ 'src/helper.ts': "export const helper = 1;\n",+ 'test/uses-helper.ts': "import { helper } from '../src/helper.ts';\nexport const h = helper;\n",+};++describe('check-orphan-modules permitted test-only set', () => {+ test('a permitted test-only module passes', () => {+ const r = runGuard(makeTree(helperTree, [{ path: 'src/helper.ts', reason: 'fixture helper' }]));+ expect(r.status).toBe(0);+ expect(r.stdout).toContain('1 permitted test-only');+ });++ test('a new test-only module missing from the set fails with its importing tests', () => {+ const r = runGuard(makeTree(helperTree, []));+ expect(r.status).toBe(1);+ expectDiagnostic(r.stderr, 'unpermitted-test-only', 'src/helper.ts');+ expect(r.stderr).toContain('imported by: test/uses-helper.ts');+ expect(r.stderr).toContain('reachable from tests but from no runtime entrypoint');+ expect(r.stderr).toContain('add { path, reason } to PERMITTED_TEST_ONLY');+ });++ test('a delete-one-add-one swap fails: the new module is unpermitted and the old entry is stale', () => {+ const r = runGuard(makeTree(helperTree, [{ path: 'src/removed.ts', reason: 'fixture helper' }]));+ expect(r.status).toBe(1);+ expectDiagnostic(r.stderr, 'unpermitted-test-only', 'src/helper.ts');+ expectDiagnostic(r.stderr, 'stale-permitted-entry', 'src/removed.ts');+ expect(r.stderr).toContain('reason: the module no longer exists');+ });++ test('an entry whose module became runtime-reachable is stale', () => {+ const r = runGuard(makeTree({+ ...helperTree,+ 'src/entry.ts': "import { used } from './used.ts';\nimport { helper } from './helper.ts';\nconsole.log(used, helper);\n",+ }, [{ path: 'src/helper.ts', reason: 'fixture helper' }]));+ expect(r.status).toBe(1);+ expectDiagnostic(r.stderr, 'stale-permitted-entry', 'src/helper.ts');+ expect(r.stderr).toContain('reason: the module is now reachable from a runtime entrypoint');+ expect(r.stderr).toContain('do not restore code to satisfy the list');+ });++ test('an entry no test imports any more is stale (and the module is a hard orphan)', () => {+ const r = runGuard(makeTree({ 'src/helper.ts': "export const helper = 1;\n" }, [{ path: 'src/helper.ts', reason: 'fixture helper' }]));+ expect(r.status).toBe(1);+ expectDiagnostic(r.stderr, 'stale-permitted-entry', 'src/helper.ts');+ expect(r.stderr).toContain('reason: no test imports the module any more');+ });++ test("a 'script-reachable' entry must be imported from scripts/**", () => {+ const tagged: Permitted = [{ path: 'src/helper.ts', reason: 'script-reachable' }];+ const stale = runGuard(makeTree(helperTree, tagged));+ expect(stale.status).toBe(1);+ expectDiagnostic(stale.stderr, 'stale-permitted-entry', 'src/helper.ts');+ expect(stale.stderr).toContain("tagged 'script-reachable' but no scripts/** file imports it");++ const reached = runGuard(makeTree({+ ...helperTree,+ 'scripts/gen.ts': "import { helper } from '../src/helper.ts';\nexport const g = helper;\n",+ }, tagged));+ expect(reached.status).toBe(0);+ });++ test('an entry without a reason is invalid', () => {+ const r = runGuard(makeTree(helperTree, [{ path: 'src/helper.ts', reason: ' ' }]));+ expect(r.status).toBe(1);+ expectDiagnostic(r.stderr, 'invalid-permitted-entry', 'src/helper.ts');+ expect(r.stderr).toContain('every permitted test-only module needs one');+ });++ test('a module imported by nothing is a hard orphan', () => {+ const r = runGuard(makeTree({ 'src/orphan.ts': "export const o = 1;\n" }));+ expect(r.status).toBe(1);+ expectDiagnostic(r.stderr, 'hard-orphan', 'src/orphan.ts');+ expect(r.stderr).toContain('unreachable from every runtime entrypoint and every test');+ });+});diff --git a/test/scripts/check-test-placeholders.test.ts b/test/scripts/check-test-placeholders.test.tsnew file mode 100644index 0000000000..badc11eec8--- /dev/null+++ b/test/scripts/check-test-placeholders.test.ts@@ -0,0 +1,93 @@+import { describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { evaluate, scanTree } from '../../scripts/check-test-placeholders.mjs';++const ROOT = join(import.meta.dir, '..', '..');+const SCRIPT = join(ROOT, 'scripts', 'check-test-placeholders.mjs');+const FIXTURES = join(ROOT, 'test', 'fixtures', 'guards', 'check-test-placeholders.mjs');++function run(fixtureRoot: string) {+ const r = spawnSync('node', [SCRIPT, fixtureRoot], { cwd: ROOT, encoding: 'utf8' });+ return { status: r.status, out: `${r.stdout}${r.stderr}` };+}++function tree(files: Record<string, string>): string {+ const dir = mkdtempSync(join(tmpdir(), 'placeholder-guard-'));+ for (const [rel, body] of Object.entries(files)) {+ mkdirSync(join(dir, rel, '..'), { recursive: true });+ writeFileSync(join(dir, rel), body);+ }+ return dir;+}++describe('check-test-placeholders fixtures', () => {+ test('bad fixture fails with one diagnostic per placeholder form', () => {+ const { status, out } = run(join(FIXTURES, 'bad'));+ expect(status).toBe(1);+ for (const [line, form] of [[5, 'expect(true)'], [9, 'expect(true).toBe(true)'], [13, 'expect(true).toBeTruthy()'], [17, 'expect(1).toBe(1)']] as const) {+ expect(out).toContain(`test-placeholder-assertion: test/placeholders.test.fixture.ts:${line} uses \`${form}\``);+ }+ expect(out).toContain('reason: this assertion passes whatever the product does');+ expect(out).toContain('remedy: assert the observable outcome');+ expect(out).toContain('rerun: bun run check:test-placeholders');+ expect(out).toContain('docs: docs/TESTING.md#placeholder-assertions');+ expect(out).toContain('count: expected 0 placeholder(s) for this test, found 1.');+ });++ test('good fixture passes: fail sentinels, strings, templates, comments and test/fixtures are ignored', () => {+ const { status, out } = run(join(FIXTURES, 'good'));+ expect(status).toBe(0);+ expect(out).toContain('check-test-placeholders: OK (1 test files, 0 allowlisted placeholder site(s))');+ });+});++describe('check-test-placeholders allowlist', () => {+ const body = (n: number) => `import { describe, expect, test } from 'bun:test';+describe('suite', () => {+ test('marker', () => {+${' expect(true).toBe(true);\n'.repeat(n)} });+});+`;++ test('an allowlisted count passes; one more site fails with expected versus actual', () => {+ const dir = tree({ 'test/a.test.ts': body(2) });+ try {+ const scan = scanTree(dir, false)!;+ const entry = { path: 'test/a.test.ts', test: 'suite > marker', reason: 'r', count: 2 };+ expect(evaluate(scan.sites, [entry], dir).problems).toEqual([]);+ const over = evaluate(scan.sites, [{ ...entry, count: 1 }], dir).problems;+ expect(over).toHaveLength(2);+ expect(over[0]).toContain('test/a.test.ts:4 uses `expect(true).toBe(true)` in "suite > marker"');+ expect(over[0]).toContain('count: allowlist expects 1 placeholder(s) for this test, found 2.');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('stale entries fail with a distinct message that says to shrink the allowlist', () => {+ const dir = tree({ 'test/a.test.ts': body(1) });+ try {+ const scan = scanTree(dir, false)!;+ const problems = evaluate(scan.sites, [+ { path: 'test/a.test.ts', test: 'suite > marker', reason: 'r', count: 3 },+ { path: 'test/a.test.ts', test: 'suite > renamed', reason: 'r' },+ { path: 'test/gone.test.ts', test: 'x', reason: 'r' },+ ], dir).problems;+ expect(problems).toHaveLength(3);+ expect(problems[0]).toContain('(stale allowlist entry): test/a.test.ts "suite > marker": the placeholder count dropped.');+ expect(problems[0]).toContain('count: allowlist expects 3, found 1.');+ expect(problems[1]).toContain('"suite > renamed": no placeholder remains for this test.');+ expect(problems[2]).toContain('test/gone.test.ts "x": its file no longer exists.');+ for (const p of problems) {+ expect(p).toContain('remedy: remove the entry or reduce its count in scripts/check-test-placeholders.mjs; do not restore the placeholder.');+ expect(p).toContain('rerun: bun run check:test-placeholders');+ expect(p).toContain('docs: docs/TESTING.md#placeholder-assertions');+ }+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/test/scripts/ci-gates.test.ts b/test/scripts/ci-gates.test.tsindex 693eb68944..349e1f9b9c 100644--- a/test/scripts/ci-gates.test.ts+++ b/test/scripts/ci-gates.test.ts@@ -43,6 +43,12 @@ describe('CI execution evidence', () => {expect(e2e.jobs.tier2.if).toBeUndefined();});+ test('the verify job runs `bun run verify`, which dispatches through run-verify-parallel.sh', () => {+ expect(unit.jobs.verify.steps.some(step => step.run === 'bun run verify')).toBe(true);+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { scripts: Record<string, string> };+ expect(pkg.scripts.verify).toContain('scripts/run-verify-parallel.sh');+ });+test('unit aggregate rejects failed, cancelled or skipped required jobs', () => {expect(unit.jobs['test-status'].if).toBe("${{ always() && (github.event_name != 'workflow_dispatch' || inputs.native_only != true) }}");expect(unit.jobs['test-status'].needs).toEqual([diff --git a/test/scripts/classify-tests.test.ts b/test/scripts/classify-tests.test.tsindex 2d25554fc6..717146a5f0 100644--- a/test/scripts/classify-tests.test.ts+++ b/test/scripts/classify-tests.test.ts@@ -37,6 +37,18 @@ describe('classify-tests detectors', () => {expect(classifyFile('test/fake.test.ts', src).rows).toHaveLength(0);});+ test('a dynamic import of src/ beside a non-repo read is behavioral', () => {+ const src = [+ "describe('init writes config', () => {",+ " test('reads its own config', async () => {",+ " const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));",+ " const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');",+ ' });',+ '});',+ ].join('\n');+ expect(classifyFile('test/fake.test.ts', src).rows).toHaveLength(0);+ });+test('Bun.file reader on src/ is structural', () => {const src = ["const text = await Bun.file(new URL('../src/core/migrate.ts', import.meta.url)).text();",diff --git a/test/scripts/e2e-matrix.test.ts b/test/scripts/e2e-matrix.test.tsindex c0c33f8476..bbdd699f5a 100644--- a/test/scripts/e2e-matrix.test.ts+++ b/test/scripts/e2e-matrix.test.ts@@ -1,4 +1,4 @@-import { describe, test, expect } from 'bun:test';+import { describe, test, expect, spyOn } from 'bun:test';import { existsSync, mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, symlinkSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -35,6 +35,18 @@ describe('frozen E2E matrix', () => {expect(prepareMatrix([], weights).include).toEqual([{ shard: 1, files: [], empty: true }]);expect(prepareMatrix([...E2E_EXCLUSIONS], weights).include[0].empty).toBe(true);});+ test('drops the persistence-validation.yml crash suites and names their owner', () => {+ const notices: string[] = [];+ const spy = spyOn(console, 'error').mockImplementation((line: string) => { notices.push(line); });+ try {+ expect(prepareMatrix(['test/e2e/reconcile-crash.test.ts', 'test/e2e/reconcile-crash-unactivated.test.ts', paths[0]], weights).include)+ .toEqual([{ shard: 1, files: [paths[0]], empty: false }]);+ } finally { spy.mockRestore(); }+ expect(notices).toEqual([+ 'excluded: test/e2e/reconcile-crash.test.ts (owned by persistence-validation.yml)',+ 'excluded: test/e2e/reconcile-crash-unactivated.test.ts (owned by persistence-validation.yml)',+ ]);+ });test('refuses invalid selections and duplicate paths', () => {for (const files of [[paths[0], paths[0]], ['../outside.test.ts'], ['test/e2e/../escape.test.ts'], ['test/e2e/$(touch marker).test.ts']]) expect(() => prepareMatrix(files, weights)).toThrow();});diff --git a/test/scripts/e2e-wiring.test.ts b/test/scripts/e2e-wiring.test.tsindex 209bc0550c..0f962f6dcb 100644--- a/test/scripts/e2e-wiring.test.ts+++ b/test/scripts/e2e-wiring.test.ts@@ -27,11 +27,12 @@ import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync,import { join } from 'node:path';import { tmpdir } from 'node:os';import { spawnSync } from 'node:child_process';-import { E2E_EXCLUSIONS, prepareMatrix } from '../../scripts/e2e-matrix.ts';+import { E2E_EXCLUSIONS, PERSISTENCE_VALIDATION_OWNED, prepareMatrix } from '../../scripts/e2e-matrix.ts';import { E2E_TEST_MAP } from '../../scripts/e2e-test-map.ts';const repoRoot = join(import.meta.dir, '..', '..');const yml = readFileSync(join(repoRoot, '.github/workflows/e2e.yml'), 'utf8');+const persistenceYml = readFileSync(join(repoRoot, '.github/workflows/persistence-validation.yml'), 'utf8');/** Slice one top-level job block out of the workflow (2-space-indented keys). */function jobBlock(name: string): string {@@ -103,12 +104,12 @@ describe('selected-e2e job wiring', () => {}});- test('every EXCLUDE entry is named by another job here or is a live-key spender', () => {+ test('every EXCLUDE entry is named by another job here, by persistence-validation.yml, or is a live-key spender', () => {const excluded = [...E2E_EXCLUSIONS];expect(excluded.length).toBeGreaterThan(0);const restOfWorkflow = yml.replace(job, '');for (const f of excluded) {- const honest = LIVE_KEY_FILES.has(f) || restOfWorkflow.includes(f);+ const honest = LIVE_KEY_FILES.has(f) || restOfWorkflow.includes(f) || (PERSISTENCE_VALIDATION_OWNED.has(f) && persistenceYml.includes(f));if (!honest) throw new Error(`EXCLUDE entry not carried by any named job and not a live-key file: ${f}`);}});@@ -119,7 +120,7 @@ describe('selected-e2e job wiring', () => {* baseline shrinks (a file gets mapped or deleted), lower this constant IN* THE SAME COMMIT (the module-size ratchet's no-stale-slack convention).*/-const BASELINE_SEEDED_LENGTH = 150;+const BASELINE_SEEDED_LENGTH = 126;describe('e2e file claim ratchet', () => {const mapped = new Set(Object.values(E2E_TEST_MAP).flat());diff --git a/test/scripts/nightly-e2e.test.ts b/test/scripts/nightly-e2e.test.tsindex 1126e413f1..b5379c5a4e 100644--- a/test/scripts/nightly-e2e.test.ts+++ b/test/scripts/nightly-e2e.test.ts@@ -71,8 +71,16 @@ describe('nightly E2E scheduling', () => {expect(result.status, result.stderr).toBe(0);return result.stdout.trim().split('\n').filter(Boolean);};- const corpus = [...readdirSync(join(repo, 'test/e2e')).filter(file => file.endsWith('.test.ts')).map(file => `test/e2e/${file}`), 'test/phantom-redirect-engine-parity.test.ts'].sort();+ const liveKeyOnly = [+ 'test/e2e/openrouter-anthropic-subagent-replay.live.test.ts',+ 'test/e2e/openrouter-deepseek-subagent-replay.live.test.ts',+ 'test/e2e/voyage-multimodal.test.ts',+ 'test/e2e/voyage-rerank-live.test.ts',+ ];+ const corpus = [...readdirSync(join(repo, 'test/e2e')).filter(file => file.endsWith('.test.ts')).map(file => `test/e2e/${file}`).filter(file => !liveKeyOnly.includes(file)), 'test/phantom-redirect-engine-parity.test.ts'].sort();expect(discover('').sort()).toEqual(corpus);+ const byName = spawnSync('bash', ['scripts/run-e2e.sh', '--dry-run-list', ...liveKeyOnly], { cwd: repo, encoding: 'utf8', env: { ...process.env, SHARD: '', COVERAGE_DIR: '' } });+ expect(byName.stdout.trim().split('\n')).toEqual(liveKeyOnly);const partitions = [1, 2, 3, 4].map(n => discover(`${n}/4`));expect(partitions.every(files => files.length > 0)).toBe(true);expect(partitions.flat().sort()).toEqual(corpus);diff --git a/test/e2e/search-readiness-http.test.ts b/test/search-readiness-http.test.tssimilarity index 95%rename from test/e2e/search-readiness-http.test.tsrename to test/search-readiness-http.test.tsindex 1a0c35c0a9..4fb04e7d9b 100644--- a/test/e2e/search-readiness-http.test.ts+++ b/test/search-readiness-http.test.ts@@ -2,6 +2,10 @@* Real legacy-bearer HTTP MCP regression for projection-readiness response* metadata. The fixture is disk-backed because the CLI HTTP server owns the* PGLite lock; all pages are seeded before it starts.+ *+ * Lane: unit. Run: `bun test test/search-readiness-http.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { spawn, spawnSync, type ChildProcess } from 'node:child_process';@@ -11,11 +15,11 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { importFromContent } from '../../src/core/import-file.ts';-import { keylessBrainEnv } from '../helpers/provider-env.ts';-import { cliDiagnostic, fixtureDiagnostic, toolDiagnostic } from '../helpers/fixture-diagnostics.ts';-import { createManagedFixtureSource, withManagedFixtureWrite } from '../helpers/managed-e2e-fixture-write.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { keylessBrainEnv } from './helpers/provider-env.ts';+import { cliDiagnostic, fixtureDiagnostic, toolDiagnostic } from './helpers/fixture-diagnostics.ts';+import { createManagedFixtureSource, withManagedFixtureWrite } from './helpers/managed-e2e-fixture-write.ts';const MATCH = 'http-readiness-public-match';const PRIVATE_PENDING = 'http-readiness-private-pending-canary';diff --git a/test/search/query-op-adaptive-return.test.ts b/test/search/query-op-adaptive-return.test.tsindex 35b2cde4b4..be1c5a3421 100644--- a/test/search/query-op-adaptive-return.test.ts+++ b/test/search/query-op-adaptive-return.test.ts@@ -12,10 +12,6 @@ import { operationsByName } from '../../src/core/operations.ts';describe('query op — adaptive_return agent surface', () => {const query = operationsByName['query'];- test('query op exists', () => {- expect(query).toBeDefined();- });-test('adaptive_return is a boolean param on query', () => {const param = query.params?.adaptive_return as { type?: string; description?: string } | undefined;expect(param).toBeDefined();diff --git a/test/search/query-op-autocut.test.ts b/test/search/query-op-autocut.test.tsindex ca4aac6986..35a73dd90c 100644--- a/test/search/query-op-autocut.test.ts+++ b/test/search/query-op-autocut.test.ts@@ -13,10 +13,6 @@ import { operationsByName } from '../../src/core/operations.ts';describe('query op — autocut agent surface', () => {const query = operationsByName['query'];- test('query op exists', () => {- expect(query).toBeDefined();- });-test('autocut is a boolean param on query', () => {const param = query.params?.autocut as { type?: string; description?: string } | undefined;expect(param).toBeDefined();diff --git a/test/search/title-match.test.ts b/test/search/title-match.test.tsindex 7b158665dc..41cd77194b 100644--- a/test/search/title-match.test.ts+++ b/test/search/title-match.test.ts@@ -7,7 +7,7 @@*/import { describe, test, expect } from 'bun:test';-import { isTitlePhraseMatch, tokenizeTitle, __test__ } from '../../src/core/search/title-match.ts';+import { isTitlePhraseMatch, tokenizeTitle } from '../../src/core/search/title-match.ts';describe('isTitlePhraseMatch — positive (the incident)', () => {const MINGTANG = 'The Mingtang (明堂) — Indoor Greek Amphitheater for Adversarial Debate';@@ -62,7 +62,4 @@ describe('tokenizeTitle', () => {test('keeps CJK runs as tokens', () => {expect(tokenizeTitle('明堂 hall')).toEqual(['明堂', 'hall']);});- test('MIN_CONTENT_TOKENS is 2 (the precision floor)', () => {- expect(__test__.MIN_CONTENT_TOKENS).toBe(2);- });});diff --git a/test/seed-pglite.serial.test.ts b/test/seed-pglite.serial.test.tsindex 411eb33322..8130024470 100644--- a/test/seed-pglite.serial.test.ts+++ b/test/seed-pglite.serial.test.ts@@ -4,7 +4,7 @@*/import { describe, test, expect, beforeEach, afterEach } from 'bun:test';-import { mkdtempSync, rmSync, writeFileSync } from 'fs';+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { seedPglite, seedPgliteFromFile, _internal } from '../src/core/claw-test/seed-pglite.ts';@@ -86,8 +86,7 @@ describe('seedPglite', () => {test('creates parent directories when needed', async () => {const dbPath = join(tmp, 'nested', 'deeper', 'brain.pglite');await seedPglite({ dbPath, sql: 'CREATE TABLE x(y int);' });- // No throw means the dir was created.- expect(true).toBe(true);+ expect(existsSync(dbPath)).toBe(true);}, 30_000);test('empty SQL is a no-op (just creates the .pglite)', async () => {diff --git a/test/select-e2e.test.ts b/test/select-e2e.test.tsindex 83c0e8b1e2..e5c7119e10 100644--- a/test/select-e2e.test.ts+++ b/test/select-e2e.test.ts@@ -5,6 +5,10 @@// unmapped src/) are explicitly named.import { describe, expect, test } from "bun:test";+import { spawnSync } from "node:child_process";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";import {E2E_TEST_MAP,@@ -12,6 +16,7 @@ import {import {classify,matchGlob,+ persistenceOwnedNotices,selectTests,} from "../scripts/select-e2e.ts";@@ -24,12 +29,10 @@ const ALL_E2E = ["test/e2e/engine-content-privacy.test.ts","test/e2e/legacy-chunk-privacy.test.ts","test/e2e/read-enrichment-privacy.test.ts",- "test/e2e/remote-privacy-journeys.test.ts","test/e2e/graph-quality.test.ts","test/e2e/http-transport.test.ts","test/e2e/integrity-batch.test.ts","test/e2e/jsonb-roundtrip.test.ts",- "test/e2e/mcp.test.ts","test/e2e/mechanical.test.ts","test/e2e/migrate-chain.test.ts","test/e2e/migration-flow.test.ts",@@ -134,6 +137,21 @@ describe("selectTests", () => {]);});+ test("postgres-engine.ts changes select its shared-singleton owners", () => {+ const singletonOwners = [+ "test/e2e/db-singleton-shared-recovery.test.ts",+ "test/e2e/postgres-engine-disconnect-idempotency.test.ts",+ "test/e2e/postgres-reconnect-singleton.test.ts",+ ];+ const selected = selectTests({+ changedFiles: ["src/core/postgres-engine.ts"],+ allE2ETests: [...singletonOwners, "test/e2e/graph-quality.test.ts"],+ map: E2E_TEST_MAP,+ });+ for (const owner of singletonOwners) expect(selected).toContain(owner);+ expect(selected).not.toContain("test/e2e/graph-quality.test.ts");+ });+test("case 1: empty diff -> all E2E", () => {expect(select([])).toEqual(ALL_E2E.slice().sort());});@@ -152,11 +170,9 @@ describe("selectTests", () => {"test/e2e/projection-readiness-currency.test.ts","test/e2e/projection-statistics-postgres.test.ts","test/e2e/read-enrichment-privacy.test.ts",- "test/e2e/remote-privacy-journeys.test.ts","test/e2e/search-exclude.test.ts","test/e2e/search-quality.test.ts","test/e2e/search-query-contract-postgres.test.ts",- "test/e2e/search-readiness-http.test.ts","test/e2e/search-swamp.test.ts","test/e2e/unsupported-embedding-identity-postgres.test.ts","test/e2e/vector-candidate-safety-postgres.test.ts",@@ -242,11 +258,9 @@ describe("selectTests", () => {"test/e2e/projection-readiness-currency.test.ts","test/e2e/projection-statistics-postgres.test.ts","test/e2e/read-enrichment-privacy.test.ts",- "test/e2e/remote-privacy-journeys.test.ts","test/e2e/search-exclude.test.ts","test/e2e/search-quality.test.ts","test/e2e/search-query-contract-postgres.test.ts",- "test/e2e/search-readiness-http.test.ts","test/e2e/search-swamp.test.ts","test/e2e/unsupported-embedding-identity-postgres.test.ts","test/e2e/vector-candidate-safety-postgres.test.ts",@@ -284,3 +298,40 @@ describe("selectTests", () => {);});});++describe("persistenceOwnedNotices", () => {+ test("a mapped reconcile source names both crash suites and their owner", () => {+ expect(persistenceOwnedNotices(["src/commands/source-reconcile.ts"], E2E_TEST_MAP)).toEqual([+ "excluded: test/e2e/reconcile-crash-unactivated.test.ts (owned by persistence-validation.yml)",+ "excluded: test/e2e/reconcile-crash.test.ts (owned by persistence-validation.yml)",+ ]);+ });++ test("editing a crash suite directly names it", () => {+ expect(persistenceOwnedNotices(["test/e2e/reconcile-crash.test.ts"], E2E_TEST_MAP)).toEqual([+ "excluded: test/e2e/reconcile-crash.test.ts (owned by persistence-validation.yml)",+ ]);+ });++ test("the CLI prints the notice on stderr and still lists the files on stdout", () => {+ const root = mkdtempSync(join(tmpdir(), "gbrain-select-e2e-"));+ try {+ const git = (...args: string[]) => spawnSync("git", args, { cwd: root, encoding: "utf8" });+ git("init", "-q");+ git("-c", "user.name=fixture", "-c", "[email protected]", "commit", "-q", "--allow-empty", "-m", "base");+ git("update-ref", "refs/remotes/origin/master", "HEAD");+ mkdirSync(join(root, "src/commands"), { recursive: true });+ writeFileSync(join(root, "src/commands/source-reconcile.ts"), "// changed\n");+ const r = spawnSync(process.execPath, [join(import.meta.dir, "../scripts/select-e2e.ts")], { cwd: root, encoding: "utf8" });+ expect(r.status, r.stderr).toBe(0);+ expect(r.stderr).toContain("excluded: test/e2e/reconcile-crash.test.ts (owned by persistence-validation.yml)");+ expect(r.stdout.split("\n")).toContain("test/e2e/reconcile-crash.test.ts");+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ test("unrelated sources print nothing", () => {+ expect(persistenceOwnedNotices(["src/core/derived-links.ts", "README.md"], E2E_TEST_MAP)).toEqual([]);+ });+});diff --git a/test/self-fix.test.ts b/test/self-fix.test.tsdeleted file mode 100644index f001fadb94..0000000000--- a/test/self-fix.test.ts+++ /dev/null@@ -1,223 +0,0 @@-/**- * v0.41 E6 (codex pass-2 #4 narrowing) — self-fix tests.- *- * Pins the load-bearing contracts:- *- * - decideSelfFix returns should_fix=false for non-recoverable clusters- * (tool_crash, tool_unavailable, tool_permission) — codex pass-2 #4- * - decideSelfFix respects `data.no_self_fix` per-job opt-out- * - decideSelfFix respects global `enabled=false` setting- * - decideSelfFix caps at max_depth (default 2 per D15)- * - computeChainDepth correctly counts self_fix_child ancestors- * - buildSelfFixPrompt produces cluster-specific text + preserves the- * leaf user task on prompt_too_long (codex pass-1 #11)- * - submitSelfFixChild inherits budget owner from parent (Eng D7 + D10)- * - Audit row written for both success and submit-fail paths- */--import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { MinionQueue } from '../src/core/minions/queue.ts';-import {- decideSelfFix,- buildSelfFixPrompt,- submitSelfFixChild,- computeChainDepth,-} from '../src/core/minions/self-fix.ts';-import { setOwnerBudget, inheritBudgetOwner, getBudgetOwner } from '../src/core/minions/budget-tracker.ts';--let engine: PGLiteEngine;-let queue: MinionQueue;--beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({ database_url: '' });- await engine.initSchema();- queue = new MinionQueue(engine);-});--afterAll(async () => {- await engine.disconnect();-});--beforeEach(async () => {- await engine.executeRaw('DELETE FROM minion_self_fix_log');- await engine.executeRaw('DELETE FROM minion_budget_log');- await engine.executeRaw('DELETE FROM minion_jobs');-});--describe('decideSelfFix', () => {- test('global disabled → no fix regardless of cluster', async () => {- const parent = await queue.add('subagent', { prompt: 'hi' }, {}, { allowProtectedSubmit: true });- const d = await decideSelfFix(engine, parent.id, { prompt: 'hi' }, 'prompt is too long', { enabled: false });- expect(d.should_fix).toBe(false);- expect(d.reason).toBe('self_fix_disabled_globally');- });-- test('per-job no_self_fix flag → no fix', async () => {- const parent = await queue.add('subagent', { prompt: 'hi' }, {}, { allowProtectedSubmit: true });- const d = await decideSelfFix(- engine,- parent.id,- { prompt: 'hi', no_self_fix: true },- 'prompt is too long',- );- expect(d.should_fix).toBe(false);- expect(d.reason).toBe('no_self_fix_flag_on_job');- });-- test('non-recoverable cluster (tool_crash) → no fix', async () => {- const parent = await queue.add('subagent', { prompt: 'hi' }, {}, { allowProtectedSubmit: true });- const d = await decideSelfFix(engine, parent.id, { prompt: 'hi' }, 'tool "git" failed: ENOENT');- expect(d.should_fix).toBe(false);- expect(d.cluster).toBe('tool_crash');- expect(d.reason).toContain('cluster_not_recoverable');- });-- test('non-recoverable cluster (tool_unavailable) → no fix', async () => {- const parent = await queue.add('subagent', { prompt: 'hi' }, {}, { allowProtectedSubmit: true });- const d = await decideSelfFix(engine, parent.id, { prompt: 'hi' }, 'tool "ghost" is not in the registry for this subagent');- expect(d.should_fix).toBe(false);- expect(d.cluster).toBe('tool_unavailable');- });-- test('recoverable cluster (prompt_too_long) → fix at depth 0', async () => {- const parent = await queue.add('subagent', { prompt: 'hi' }, {}, { allowProtectedSubmit: true });- const d = await decideSelfFix(engine, parent.id, { prompt: 'hi' }, 'prompt is too long');- expect(d.should_fix).toBe(true);- expect(d.cluster).toBe('prompt_too_long');- expect(d.reason).toBe('recoverable:prompt_too_long_at_depth_0');- });-- test('recoverable cluster (tool_schema_mismatch) → fix', async () => {- const parent = await queue.add('subagent', { prompt: 'hi' }, {}, { allowProtectedSubmit: true });- const d = await decideSelfFix(- engine,- parent.id,- { prompt: 'hi' },- 'invalid input: missing required field "slug"',- );- expect(d.should_fix).toBe(true);- expect(d.cluster).toBe('tool_schema_mismatch');- });-- test('recoverable cluster (malformed_json) → fix', async () => {- const parent = await queue.add('subagent', { prompt: 'hi' }, {}, { allowProtectedSubmit: true });- const d = await decideSelfFix(engine, parent.id, { prompt: 'hi' }, 'Unexpected token } in JSON at position 47');- expect(d.should_fix).toBe(true);- expect(d.cluster).toBe('malformed_json');- });-- test('depth cap (default 2): grandchild self-fix refused', async () => {- // Build a chain: root → self_fix_child_1 → self_fix_child_2- const root = await queue.add('subagent', { prompt: 'r' }, {}, { allowProtectedSubmit: true });- const c1 = await queue.add(- 'subagent', { prompt: 'c1', is_self_fix_child: true },- { parent_job_id: root.id }, { allowProtectedSubmit: true },- );- const c2 = await queue.add(- 'subagent', { prompt: 'c2', is_self_fix_child: true },- { parent_job_id: c1.id }, { allowProtectedSubmit: true },- );- const d = await decideSelfFix(- engine, c2.id, { prompt: 'c2', is_self_fix_child: true }, 'prompt is too long',- );- expect(d.should_fix).toBe(false);- expect(d.reason).toContain('max_depth_reached');- });-- test('depth cap respects opts.max_depth=1', async () => {- const root = await queue.add('subagent', { prompt: 'r' }, {}, { allowProtectedSubmit: true });- const c1 = await queue.add(- 'subagent', { prompt: 'c1', is_self_fix_child: true },- { parent_job_id: root.id }, { allowProtectedSubmit: true },- );- const d = await decideSelfFix(- engine, c1.id, { prompt: 'c1', is_self_fix_child: true }, 'prompt is too long',- { max_depth: 1 },- );- expect(d.should_fix).toBe(false);- expect(d.reason).toContain('max_depth_reached');- });-});--describe('computeChainDepth', () => {- test('non-self-fix child = depth 0', async () => {- const j = await queue.add('subagent', { prompt: 'x' }, {}, { allowProtectedSubmit: true });- expect(await computeChainDepth(engine, j.id)).toBe(0);- });-- test('one self-fix ancestor = depth 1', async () => {- const root = await queue.add('subagent', { prompt: 'r' }, {}, { allowProtectedSubmit: true });- const c1 = await queue.add(- 'subagent', { prompt: 'c1', is_self_fix_child: true },- { parent_job_id: root.id }, { allowProtectedSubmit: true },- );- expect(await computeChainDepth(engine, c1.id)).toBe(1);- });-});--describe('buildSelfFixPrompt', () => {- test('prompt_too_long: truncates middle, keeps leaf intent', () => {- const long = 'A'.repeat(5000);- const out = buildSelfFixPrompt(long, 'prompt_too_long', 'prompt is too long: 2M tokens');- expect(out).toContain('truncated');- expect(out).toContain('middle truncated');- expect(out.startsWith).toBeDefined();- // Smaller than the original.- expect(out.length).toBeLessThan(long.length);- });-- test('tool_schema_mismatch: surfaces the schema error verbatim', () => {- const out = buildSelfFixPrompt('original task', 'tool_schema_mismatch', 'invalid arg "slug" missing');- expect(out).toContain('invalid arg');- expect(out).toContain('input_schema');- expect(out).toContain('original task');- });-- test('malformed_json: instructs JSON-only retry', () => {- const out = buildSelfFixPrompt('original task', 'malformed_json', 'parse fail');- expect(out).toContain('valid JSON');- expect(out).toContain('no prose, no markdown');- expect(out).toContain('original task');- });-});--describe('submitSelfFixChild', () => {- test('child gets parent_job_id + is_self_fix_child marker + audit row', async () => {- const parent = await queue.add('subagent', { prompt: 'p' }, {}, { allowProtectedSubmit: true });- const r = await submitSelfFixChild(- engine,- queue,- { id: parent.id, data: { prompt: 'p' }, last_error: 'prompt is too long' },- 'prompt_too_long',- );- expect(r).not.toBeNull();- const childRow = await queue.getJob(r!.child_id);- expect(childRow!.parent_job_id).toBe(parent.id);- const data = childRow!.data as Record<string, unknown>;- expect(data.is_self_fix_child).toBe(true);- expect(data.self_fix_cluster).toBe('prompt_too_long');- // Audit row.- const audit = await engine.executeRaw<{ count: string }>(- `SELECT count(*)::text AS count FROM minion_self_fix_log- WHERE parent_id = $1 AND outcome = 'submitted'`,- [parent.id],- );- expect(parseInt(audit[0]!.count, 10)).toBe(1);- });-- test('child inherits budget owner from parent (Eng D7 + D10)', async () => {- const parent = await queue.add('subagent', { prompt: 'p' }, {}, { allowProtectedSubmit: true });- await setOwnerBudget(engine, parent.id, 1.0);- const r = await submitSelfFixChild(- engine,- queue,- { id: parent.id, data: { prompt: 'p' }, last_error: 'prompt is too long' },- 'prompt_too_long',- );- const info = await getBudgetOwner(engine, r!.child_id);- expect(info!.budget_owner_job_id).toBe(parent.id);- expect(info!.budget_root_owner_id).toBe(parent.id);- });-});diff --git a/test/serve-http-metrics.test.ts b/test/serve-http-metrics.test.tsindex c457a59164..9bfb74a2b8 100644--- a/test/serve-http-metrics.test.ts+++ b/test/serve-http-metrics.test.ts@@ -138,7 +138,7 @@ describe('metricsTrackingMiddleware — Express wiring (serve-http.ts order)', (});describe('serve-http.ts wiring (structural — the two defects of the original PR)', () => {- // test-reads-source-ok: mount ORDER (middleware before first route) and the requireAdmin+ // test-reads-source-ok[trust-boundary]: mount ORDER (middleware before first route) and the requireAdmin// gate are wiring properties of the real serve-http.ts; the behavioral tests above run a// rebuilt harness app, so only a source scan pins the real module without booting it.const src = readFileSync(new URL('../src/commands/serve-http.ts', import.meta.url), 'utf-8');diff --git a/test/e2e/serve-http-surface-ceiling.test.ts b/test/serve-http-surface-ceiling.test.tssimilarity index 97%rename from test/e2e/serve-http-surface-ceiling.test.tsrename to test/serve-http-surface-ceiling.test.tsindex e85fb23751..37f8e840ec 100644--- a/test/e2e/serve-http-surface-ceiling.test.ts+++ b/test/serve-http-surface-ceiling.test.ts@@ -25,17 +25,21 @@** Two hermetic brains because PGLite is single-writer and the kill-switch env* must be pinned at a SECOND server process's spawn time.+ *+ * Lane: unit. Run: `bun test test/serve-http-surface-ceiling.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { spawn, spawnSync, type ChildProcess } from 'child_process';import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';-import { keylessBrainEnv } from '../helpers/provider-env.ts';-import { cliDiagnostic, fixtureDiagnostic, toolDiagnostic } from '../helpers/fixture-diagnostics.ts';+import { keylessBrainEnv } from './helpers/provider-env.ts';+import { cliDiagnostic, fixtureDiagnostic, toolDiagnostic } from './helpers/fixture-diagnostics.ts';import { join } from 'path';-import { VERB_NAMES } from '../../src/core/verbs.ts';-import { operations } from '../../src/core/operations.ts';+import { VERB_NAMES } from '../src/core/verbs.ts';+import { operations } from '../src/core/operations.ts';const PORT_A = 19833; // plain --surface verbs (unique across the e2e suite)const PORT_B = 19834; // --surface verbs + GBRAIN_MCP_FORCE_SURFACE=fulldiff --git a/test/serve-stdin-eof-drain.test.ts b/test/serve-stdin-eof-drain.test.tsindex 7449667833..0c77fd5877 100644--- a/test/serve-stdin-eof-drain.test.ts+++ b/test/serve-stdin-eof-drain.test.ts@@ -179,7 +179,7 @@ describe('in-flight RPC counter (#4409)', () => {describe('serve-sync-runner stays off the boot path (#4409)', () => {test('serve.ts has no static import of serve-sync-runner', () => {- // test-reads-source-ok: structural module-graph guard — a static import+ // test-reads-source-ok[structural]: structural module-graph guard — a static import// is invisible at runtime once loaded; only the source text can prove// the runner stays off the serve boot path (#4409).const src = readFileSync(join(import.meta.dir, '../src/commands/serve.ts'), 'utf8');diff --git a/test/e2e/serve-stdio-roundtrip.test.ts b/test/serve-stdio-roundtrip.test.tssimilarity index 97%rename from test/e2e/serve-stdio-roundtrip.test.tsrename to test/serve-stdio-roundtrip.test.tsindex 22856f60e4..22c08a0107 100644--- a/test/e2e/serve-stdio-roundtrip.test.ts+++ b/test/serve-stdio-roundtrip.test.ts@@ -23,20 +23,24 @@* exact tool list, the two ambient-recall verbs (context_pack + delta),* fail-closed dispatch on hidden ops, and the delta session cursor advancing* across two wakes.+ *+ * Lane: unit. Run: `bun test test/serve-stdio-roundtrip.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { spawnSync } from 'child_process';-import { keylessBrainEnv } from '../helpers/provider-env.ts';-import { cliDiagnostic, toolDiagnostic } from '../helpers/fixture-diagnostics.ts';+import { keylessBrainEnv } from './helpers/provider-env.ts';+import { cliDiagnostic, toolDiagnostic } from './helpers/fixture-diagnostics.ts';import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';-import { VERB_NAMES } from '../../src/core/verbs.ts';-import { GBRAIN_MCP_INSTRUCTIONS } from '../../src/mcp/instructions.ts';+import { VERB_NAMES } from '../src/core/verbs.ts';+import { GBRAIN_MCP_INSTRUCTIONS } from '../src/mcp/instructions.ts';function execFixture(args: string[], env: Record<string, string>): void {const result = spawnSync('bun', ['--no-env-file', ...args], { cwd: process.cwd(), env, encoding: 'utf8' });diff --git a/test/skillopt/deadline-and-hermetic.test.ts b/test/skillopt/deadline-and-hermetic.test.tsindex 3d819ab974..6a31af037e 100644--- a/test/skillopt/deadline-and-hermetic.test.ts+++ b/test/skillopt/deadline-and-hermetic.test.ts@@ -13,13 +13,10 @@* (off by default — the config dir carries the CLI's session credentials,* so the empty-dir form logs the child out wherever the CLI reads its* session from the config dir; hermetic mode is a deliberate choice,- * never a default). #4741: the docs/code comment may not claim any- * platform "survives" the empty-dir form — nothing in the code seeds or- * looks up credential material, and macOS was observed logged out.+ * never a default).*/import { describe, test, expect } from 'bun:test';-import { existsSync, readFileSync } from 'fs';-import { join } from 'path';+import { existsSync } from 'fs';import {runValidationGate,scoreSkillOnTasks,@@ -127,17 +124,3 @@ describe('#4119 — resolveHermeticConfigDir (opt-in)', () => {);});});--describe('#4741 — hermetic-config docs make no platform-survives-logout claim', () => {- const root = join(import.meta.dir, '..', '..');- test('docs/guides/skillopt.md does not promise the empty-dir form keeps macOS logged in', () => {- const doc = readFileSync(join(root, 'docs/guides/skillopt.md'), 'utf8');- expect(doc).not.toMatch(/keychain and survives/);- expect(doc).toMatch(/logs the child out/);- });- test('the provider doc comment does not promise it either', () => {- // test-reads-source-ok: pins a doc-comment contract (#4741) — comment text has no runtime surface to assert.- const src = readFileSync(join(root, 'src/core/ai/providers/claude-cli-language-model.ts'), 'utf8');- expect(src).not.toMatch(/keychain and survives/);- });-});diff --git a/test/skillopt/silent-abort-3516.test.ts b/test/skillopt/silent-abort-3516.test.tsindex 71b17f2856..0130410886 100644--- a/test/skillopt/silent-abort-3516.test.ts+++ b/test/skillopt/silent-abort-3516.test.ts@@ -31,7 +31,6 @@ import { withEnv } from '../helpers/with-env.ts';import { parseFlags } from '../../src/commands/skillopt.ts';import { estimateCost, formatPreflightReport, preflight } from '../../src/core/skillopt/preflight.ts';import { BudgetTracker, BudgetExhausted, _resetBudgetTrackerWarningsForTest } from '../../src/core/budget/budget-tracker.ts';-import { BudgetExhausted as MinionsBudgetExhausted } from '../../src/core/minions/budget-tracker.ts';import { classifyAbortError } from '../../src/core/skillopt/orchestrator.ts';import {_resetAuditWriterForTests,@@ -234,19 +233,6 @@ describe('classifyAbortError — real BudgetExhausted instances (not string-fakeexpect(r.abortReason).toBe('runtime_exceeded');});- test('a BudgetExhausted from the UNRELATED minions/budget-tracker.ts class is not misclassified as budget_exhausted', () => {- // Two distinct BudgetExhausted classes exist in this repo (core/budget,- // used here, and core/minions, a differently-shaped job-cost tracker- // with an unrelated (owner_id, balance_cents) constructor) — instanceof- // is nominal, not structural, so an instance of the wrong one must NOT- // satisfy this check. Guards against a future refactor importing the- // wrong one and silently reintroducing this exact bug class.- const wrongClassErr = new MinionsBudgetExhausted(42, 0);- const r = classifyAbortError(wrongClassErr, { maxRuntimeMin: 30 });- expect(r.abortReason).not.toBe('budget_exhausted');- expect(r.outcome).toBe('errored');- });-test('skillopt_runtime_exceeded (plain Error, the orchestrator wall-clock deadline) still classifies correctly', () => {const err = new Error('skillopt_runtime_exceeded');const r = classifyAbortError(err, { maxRuntimeMin: 30 });diff --git a/test/e2e/skillpack-flow.test.ts b/test/skillpack-flow.test.tssimilarity index 98%rename from test/e2e/skillpack-flow.test.tsrename to test/skillpack-flow.test.tsindex 476fbfdc33..9de06bf0c9 100644--- a/test/e2e/skillpack-flow.test.ts+++ b/test/skillpack-flow.test.ts@@ -15,6 +15,10 @@* 7. harvest privacy-lint catches Wintermute (exit non-zero)* 8. harvest --no-lint bypasses* 9. install returns unknown-subcommand error (clean break, no alias)+ *+ * Lane: unit. Run: `bun test test/skillpack-flow.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test, expect, afterAll } from 'bun:test';@@ -23,7 +27,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSyncimport { join } from 'path';import { tmpdir } from 'os';-const REPO_ROOT = join(import.meta.dir, '..', '..');+const REPO_ROOT = join(import.meta.dir, '..');const GBRAIN_CMD = 'bun';const GBRAIN_ARGS = ['run', join(REPO_ROOT, 'src', 'cli.ts')];diff --git a/test/skillpack-init-brain-pack.test.ts b/test/skillpack-init-brain-pack.test.tsindex 3ea52dfa3a..cd559ee417 100644--- a/test/skillpack-init-brain-pack.test.ts+++ b/test/skillpack-init-brain-pack.test.ts@@ -1,6 +1,6 @@/*** Tests for src/core/skillpack/init-brain-pack.ts (the brain-resident pack- * scaffolder) and src/core/skillpack/brain-pack-lint.ts (E6 version-skew lint).+ * scaffolder).*/import { describe, test, expect, beforeEach, afterEach } from 'bun:test';import { mkdtempSync, rmSync, readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs';@@ -12,7 +12,6 @@ import {InitBrainPackError,} from '../src/core/skillpack/init-brain-pack.ts';import { validateSkillpackManifest } from '../src/core/skillpack/manifest-v1.ts';-import { lintBrainPackTools } from '../src/core/skillpack/brain-pack-lint.ts';import { VERSION } from '../src/version.ts';let dir: string;@@ -61,23 +60,3 @@ describe('runInitBrainPack', () => {expect(() => runInitBrainPack({ targetDir: dir, name: 'Deal Brain' })).toThrow(InitBrainPackError);});});--describe('lintBrainPackTools (E6)', () => {- test('flags a declared tool the serving op set does not have', () => {- runInitBrainPack({ targetDir: dir, name: 'deal-brain', firstSkillSlug: 'diligence' });- // Inject a tools: frontmatter with one known + one unknown op.- const skillMd = join(dir, 'skills/diligence/SKILL.md');- writeFileSync(- skillMd,- ['---', 'name: diligence', 'description: x', 'tools: [search, totally_made_up_op]', '---', '', '# diligence', ''].join('\n'),- );- const result = lintBrainPackTools(dir, new Set(['search', 'put_page']));- expect(result.unknownTools).toEqual([{ skill: 'skills/diligence', tool: 'totally_made_up_op' }]);- });-- test('no findings when all tools known (fresh pack has no tools:)', () => {- runInitBrainPack({ targetDir: dir, name: 'deal-brain', firstSkillSlug: 'diligence' });- const result = lintBrainPackTools(dir, new Set(['search', 'put_page']));- expect(result.unknownTools).toEqual([]);- });-});diff --git a/test/snapshot-shape-guard.test.ts b/test/snapshot-shape-guard.test.tsindex 89c0e037b7..d30240d34c 100644--- a/test/snapshot-shape-guard.test.ts+++ b/test/snapshot-shape-guard.test.ts@@ -127,7 +127,7 @@ test('D5.13: the coverage-immune hash includes schema entry modules and importedexpected.update('files:v3\n');for (const file of schemaInputs) {expected.update(`${file}\n`);- // test-reads-source-ok: independent raw-byte hash contract, including imported SQL/handlers.+ // test-reads-source-ok[raw-bytes]: independent raw-byte hash contract, including imported SQL/handlers.expected.update(readFileSync(`src/core/${file}`));expected.update('\n--\n');}@@ -141,7 +141,7 @@ test.each(schemaInputs)('editing imported snapshot input %s invalidates the cachconst changedFs = {...fsModule,readFileSync: (path: Parameters<typeof fsModule.readFileSync>[0]) => {- // test-reads-source-ok: emulate a changed source without mutating shared checkout files.+ // test-reads-source-ok[raw-bytes]: emulate a changed source without mutating shared checkout files.const bytes = fsModule.readFileSync(path);return String(path).endsWith(`/src/core/${file}`)? Buffer.concat([bytes, Buffer.from('\n// schema dependency changed\n')]) : bytes;@@ -155,7 +155,7 @@ test('an unreadable imported schema dependency disables snapshot reuse', () => {...fsModule,readFileSync: (path: Parameters<typeof fsModule.readFileSync>[0]) => {if (String(path).endsWith('/grants/schema.ts')) throw new Error('ENOENT');- // test-reads-source-ok: raw-byte hash failure-path regression.+ // test-reads-source-ok[raw-bytes]: raw-byte hash failure-path regression.return fsModule.readFileSync(path);},} as typeof fsModule;diff --git a/test/source-config-secret-surfaces.test.ts b/test/source-config-secret-surfaces.test.tsnew file mode 100644index 0000000000..5be7db4e4f--- /dev/null+++ b/test/source-config-secret-surfaces.test.ts@@ -0,0 +1,267 @@+/**+ * Behavioral secret-exposure contract for every surface that reads and+ * serializes `sources.config` (source-config security audit; audited surface+ * list lives in the header of scripts/check-source-config-leak.sh).+ *+ * Each test stores a secret-bearing config (`webhook_secret`, the only+ * secret-valued key in SECRET_KEYS) and drives the real surface: the+ * `gbrain sources` CLI, `gbrain call`, MCP source operations for remote+ * callers, `doctor --json`, managed source administration and its retained+ * receipts, and parse warnings. The secret must never appear in their+ * output. The two intentional reveals, `sources webhook set` and+ * `sources webhook rotate`, must print the NEW secret exactly once.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations } from '../src/core/operations.ts';+import type { AuthInfo, OperationContext } from '../src/core/operations.ts';+import { runSources } from '../src/commands/sources.ts';+import { runCall } from '../src/commands/call.ts';+import { runDoctor } from '../src/commands/doctor.ts';+import { setCliOptions } from '../src/core/cli-options.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+let home: string;+let secret: string;++const HOOKED = 'hooked';++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ setCliOptions({ quiet: true, progressJson: false, progressInterval: 1000, explain: false, timeoutMs: null, brain: null });+}, 60_000);++afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ secret = `whsec-sentinel-${randomUUID()}`;+});++function freshHome(): string {+ home = mkdtempSync(join(tmpdir(), 'gbrain-source-secret-'));+ return home;+}++async function inHome<T>(fn: () => Promise<T>): Promise<T> {+ const dir = freshHome();+ try {+ return await withEnv({ GBRAIN_HOME: dir, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_SOURCE: undefined }, fn);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++async function insertSource(id: string, localPath: string | null, config: unknown): Promise<void> {+ await engine.executeRaw(+ 'INSERT INTO sources (id, name, local_path, config) VALUES ($1, $1, $2, $3::text::jsonb)',+ [id, localPath, JSON.stringify(config)],+ );+}++function hookedConfig(extra: Record<string, unknown> = {}): Record<string, unknown> {+ return { federated: true, github_repo: 'acme-example/brain', tracked_branch: 'main', webhook_secret: secret, ...extra };+}++function gitRepo(dir: string): string {+ mkdirSync(dir, { recursive: true });+ const git = (args: string[]) => execFileSync('git', ['-C', dir, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });+ git(['init', '-q']);+ git(['config', 'user.email', '[email protected]']);+ git(['config', 'user.name', 't']);+ writeFileSync(join(dir, 'note.md'), '# Note\n');+ git(['add', '-A']);+ git(['commit', '-q', '-m', 'init']);+ return dir;+}++/** Capture everything the CLI writes to console.* and treat process.exit as a throw. */+async function captureCli(fn: () => Promise<unknown>): Promise<string> {+ const lines: string[] = [];+ const saved = { log: console.log, error: console.error, warn: console.warn, info: console.info, exit: process.exit };+ const sink = (...args: unknown[]) => { lines.push(args.map(a => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ')); };+ console.log = sink; console.error = sink; console.warn = sink; console.info = sink;+ (process as { exit: unknown }).exit = ((code?: number) => { throw new Error(`__exit ${code ?? 0}`); }) as unknown as typeof process.exit;+ try {+ await fn();+ } catch (error) {+ if (!(error instanceof Error && error.message.startsWith('__exit'))) throw error;+ } finally {+ console.log = saved.log; console.error = saved.error; console.warn = saved.warn; console.info = saved.info;+ (process as { exit: unknown }).exit = saved.exit;+ }+ return lines.join('\n');+}++function occurrences(haystack: string, needle: string): number {+ return haystack.split(needle).length - 1;+}++function filesUnder(dir: string): string[] {+ if (!existsSync(dir)) return [];+ return readdirSync(dir).flatMap((name) => {+ const path = join(dir, name);+ return statSync(path).isDirectory() ? filesUnder(path) : [path];+ });+}++function remoteCtx(allowedSources: string[], scopes = ['read', 'admin']): OperationContext {+ const auth: AuthInfo = {+ token: 'gbrain_at_fixture', clientId: 'gbrain_cl_fixture', clientName: 'fixture-client',+ scopes, expiresAt: Math.floor(Date.now() / 1000) + 3600, allowedSources,+ };+ return {+ engine, config: { engine: 'pglite' } as OperationContext['config'],+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true, auth, sourceId: allowedSources[0],+ };+}++function op(name: string) {+ const found = operations.find(o => o.name === name);+ if (!found) throw new Error(`op not found: ${name}`);+ return found;+}++describe('sources CLI output never contains a stored webhook secret', () => {+ test('list, status, webhook show, current, archived and remove --dry-run', () => inHome(async () => {+ const dir = gitRepo(join(home, 'repo'));+ await insertSource(HOOKED, dir, hookedConfig());+ await insertSource('parked', null, hookedConfig());+ await runSources(engine, ['archive', 'parked']);+ const output = await captureCli(async () => {+ for (const args of [+ ['list'], ['list', '--json'], ['status'], ['status', '--json'],+ ['webhook', 'show', HOOKED], ['current', '--source', HOOKED, '--json'],+ ['archived'], ['archived', '--json'], ['remove', HOOKED, '--dry-run'],+ ]) await runSources(engine, args);+ });+ expect(output).toContain(HOOKED);+ expect(output).toContain('<set — use `webhook rotate` to reveal a new one>');+ expect(output).not.toContain(secret);+ }), 60_000);++ test('a re-wrapped config warns without echoing its secret', () => inHome(async () => {+ await engine.executeRaw(+ 'INSERT INTO sources (id, name, config) VALUES ($1, $1, to_jsonb($2::text))',+ [HOOKED, JSON.stringify(JSON.stringify(hookedConfig()))],+ );+ const output = await captureCli(async () => {+ await runSources(engine, ['list', '--json']);+ await runSources(engine, ['webhook', 'show', HOOKED]);+ });+ expect(output).toContain('source config was stored as a');+ expect(output).not.toContain(secret);+ }), 60_000);+});++describe('intentional one-time reveals', () => {+ test('webhook set prints the new secret exactly once', () => inHome(async () => {+ await insertSource(HOOKED, null, { federated: true });+ const output = await captureCli(() => runSources(engine, ['webhook', 'set', HOOKED, '--github-repo', 'acme-example/brain']));+ const [row] = await engine.executeRaw<{ secret: string }>("SELECT config->>'webhook_secret' AS secret FROM sources WHERE id = $1", [HOOKED]);+ expect(row.secret).toMatch(/^[0-9a-f]{64}$/);+ expect(occurrences(output, row.secret)).toBe(1);+ expect(output).toContain(`Secret: ${row.secret}`);+ const later = await captureCli(async () => {+ await runSources(engine, ['webhook', 'show', HOOKED]);+ await runSources(engine, ['list', '--json']);+ });+ expect(later).not.toContain(row.secret);+ }), 60_000);++ test('webhook rotate prints only the new secret, exactly once', () => inHome(async () => {+ await insertSource(HOOKED, null, hookedConfig());+ const output = await captureCli(() => runSources(engine, ['webhook', 'rotate', HOOKED]));+ const [row] = await engine.executeRaw<{ secret: string }>("SELECT config->>'webhook_secret' AS secret FROM sources WHERE id = $1", [HOOKED]);+ expect(row.secret).not.toBe(secret);+ expect(occurrences(output, row.secret)).toBe(1);+ expect(output).not.toContain(secret);+ }), 60_000);+});++describe('operation surfaces never return a stored webhook secret', () => {+ test('gbrain call sources_add attaching a path to a secret-bearing source', () => inHome(async () => {+ const dir = gitRepo(join(home, 'attach'));+ await insertSource(HOOKED, null, hookedConfig());+ let printed = '';+ await runCall(engine, ['sources_add', JSON.stringify({ id: HOOKED, path: dir })], async (payload) => { printed += payload; });+ const result = JSON.parse(printed);+ expect(result.local_path).toBe(dir);+ expect(result.config.webhook_secret).toBe('<redacted>');+ expect(result.config.github_repo).toBe('acme-example/brain');+ expect(printed).not.toContain(secret);+ const [stored] = await engine.executeRaw<{ secret: string }>("SELECT config->>'webhook_secret' AS secret FROM sources WHERE id = $1", [HOOKED]);+ expect(stored.secret).toBe(secret);+ }), 60_000);++ test('remote MCP sources_list, sources_status and get_status_snapshot', () => inHome(async () => {+ await insertSource(HOOKED, null, hookedConfig());+ const ctx = remoteCtx([HOOKED]);+ const listed = await op('sources_list').handler(ctx, {});+ expect(JSON.stringify(listed)).toContain(HOOKED);+ const payloads = [+ listed,+ await op('sources_status').handler(ctx, { id: HOOKED }),+ await op('get_status_snapshot').handler(ctx, {}),+ ];+ for (const payload of payloads) expect(JSON.stringify(payload)).not.toContain(secret);+ }), 60_000);++ test('local doctor --json and remote run_doctor', () => inHome(async () => {+ await insertSource(HOOKED, null, hookedConfig());+ const output = await captureCli(() => runDoctor(engine, ['--json']));+ expect(output).toContain('"source_config_shape"');+ expect(output).not.toContain(secret);+ const remote = JSON.stringify(await op('run_doctor').handler(remoteCtx([HOOKED]), {}));+ expect(remote).toContain('federation_health');+ expect(remote).not.toContain(secret);+ }), 120_000);+});++describe('managed source administration never returns or retains a stored webhook secret', () => {+ test('attaching a path returns and replays a redacted receipt', () => inHome(async () => {+ await registerLocalWriter(engine, 'cli');+ const owned = join(home, 'owned');+ mkdirSync(owned);+ writeFileSync(join(owned, 'note.md'), '---\ntitle: Note\ntype: note\n---\n\nOwned\n');+ await insertSource('owned', owned, {});+ await claimWorktree(engine, 'owned', owned);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await engine.executeRaw("SELECT set_config('gbrain.topology_change','on',false)");+ await insertSource(HOOKED, null, hookedConfig());+ await engine.executeRaw("SELECT set_config('gbrain.topology_change','off',false)");+ const dir = join(home, 'attach');+ mkdirSync(dir);+ writeFileSync(join(dir, 'note.md'), '# Note\n');+ const requestId = randomUUID();+ const result = await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: HOOKED, path: dir, requestId });+ expect(result.state).toBe('committed');+ expect((result.config as Record<string, unknown>).webhook_secret).toBe('<redacted>');+ const replayed = await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: HOOKED, path: dir, requestId });+ const viaAdministration = await runPersistenceAdministration(engine, 'source_lifecycle', { action: 'add', source_id: HOOKED, path: dir, request_id: requestId });+ const journal = await engine.executeRaw('SELECT * FROM persistence_topology_changes');+ for (const payload of [result, replayed, viaAdministration, journal]) expect(JSON.stringify(payload)).not.toContain(secret);+ const [stored] = await engine.executeRaw<{ secret: string }>("SELECT config->>'webhook_secret' AS secret FROM sources WHERE id = $1", [HOOKED]);+ expect(stored.secret).toBe(secret);+ for (const file of filesUnder(home)) {+ if (file.endsWith('.jsonl') || file.endsWith('.log')) expect(readFileSync(file, 'utf8')).not.toContain(secret);+ }+ }), 60_000);+});diff --git a/test/source-resolver-default-write-guard.test.ts b/test/source-resolver-default-write-guard.test.tsindex 96f8984e58..3cc2fa3e71 100644--- a/test/source-resolver-default-write-guard.test.ts+++ b/test/source-resolver-default-write-guard.test.ts@@ -18,7 +18,7 @@ import {defaultWriteAllowedByEnv,formatDefaultWriteRefusal,formatDefaultWriteWarning,- maybeWarnUnscopedDefaultWrite,+ assessUnscopedDefaultWrite,GBRAIN_ALLOW_DEFAULT_WRITE_ENV,} from '../src/core/source-resolver.ts';import { withEnv } from './helpers/with-env.ts';@@ -169,9 +169,9 @@ describe('formatDefaultWriteWarning', () => {});});-describe('maybeWarnUnscopedDefaultWrite (stdio MCP lane, keyed on the RESOLVED tier)', () => {+describe('assessUnscopedDefaultWrite warning (stdio MCP lane, keyed on the RESOLVED tier)', () => {test('warns for a mutating call on tier seed_default when the guard fires', async () => {- const msg = await maybeWarnUnscopedDefaultWrite(makeStub(BULK_NON_DEFAULT), 'seed_default', true);+ const msg = (await assessUnscopedDefaultWrite(makeStub(BULK_NON_DEFAULT), 'seed_default', true)).warning;expect(msg).not.toBeNull();expect(msg).toContain('GBRAIN_SOURCE=<id>');});@@ -182,23 +182,23 @@ describe('maybeWarnUnscopedDefaultWrite (stdio MCP lane, keyed on the RESOLVED t// shape) would false-positive on every one of these.for (const tier of ['flag', 'env', 'dotfile', 'local_path', 'brain_default', 'sole_non_default'] as const) {test(`stays silent on tier '${tier}' even on a bulk-non-default brain`, async () => {- expect(await maybeWarnUnscopedDefaultWrite(makeStub(BULK_NON_DEFAULT), tier, true)).toBeNull();+ expect((await assessUnscopedDefaultWrite(makeStub(BULK_NON_DEFAULT), tier, true)).warning).toBeNull();});}test('stays silent for non-mutating calls', async () => {- expect(await maybeWarnUnscopedDefaultWrite(makeStub(BULK_NON_DEFAULT), 'seed_default', false)).toBeNull();+ expect((await assessUnscopedDefaultWrite(makeStub(BULK_NON_DEFAULT), 'seed_default', false)).warning).toBeNull();});test('stays silent when the guard assessment does not fire', async () => {- expect(await maybeWarnUnscopedDefaultWrite(+ expect((await assessUnscopedDefaultWrite(makeStub({ defaultPages: 100, nonDefaultPages: 1, nonDefaultSources: 1 }), 'seed_default', true,- )).toBeNull();+ )).warning).toBeNull();});test('honors the env escape hatch', async () => {await withEnv({ [GBRAIN_ALLOW_DEFAULT_WRITE_ENV]: '1' }, async () => {- expect(await maybeWarnUnscopedDefaultWrite(makeStub(BULK_NON_DEFAULT), 'seed_default', true)).toBeNull();+ expect((await assessUnscopedDefaultWrite(makeStub(BULK_NON_DEFAULT), 'seed_default', true)).warning).toBeNull();});});});diff --git a/test/supervisor-health-reconnect.test.ts b/test/supervisor-health-reconnect.test.tsnew file mode 100644index 0000000000..c24a7f4249--- /dev/null+++ b/test/supervisor-health-reconnect.test.ts@@ -0,0 +1,142 @@+/**+ * Supervisor DB-health branch: consecutive health-query failures, the third+ * failure's degraded warning + engine.reconnect(), counter reset on a+ * successful reconnect, retry on every later failing tick when reconnect+ * fails, and suppression while stopping or configuration-blocked. Driven+ * through the real healthCheck() body with a fake engine; no DB, no spawn.+ */++import { describe, it, expect } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { MinionSupervisor } from '../src/core/minions/supervisor.ts';+import { OwnerProcessingState, writeWorkerProcessingStatus } from '../src/core/minions/processing-state.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { withEnv } from './helpers/with-env.ts';++type Emission = { event: string; reason?: string; [k: string]: unknown };++const healthyRow = [{+ stalled: '0', active_healthy: '0', waiting: '0', waiting_claimable: '0',+ last_completed: null, last_completed_claimable: null,+}];++function harness(opts: { reconnect?: () => Promise<void> } = {}) {+ const events: Emission[] = [];+ const state = { healthy: false, reconnects: 0, pending: null as null | ((e: Error) => void) };+ const engine = {+ kind: 'postgres',+ async executeRaw() {+ if (state.healthy) return healthyRow;+ throw new Error('connection terminated');+ },+ async reconnect() {+ state.reconnects++;+ if (opts.reconnect) await opts.reconnect();+ },+ } as unknown as BrainEngine;+ const sup = new MinionSupervisor(engine, {+ cliPath: '/bin/true',+ maxRssMb: 0,+ healthInterval: 60_000,+ wedgeRestartMinutes: 0,+ onEvent: (e) => events.push(e as Emission),+ });+ sup._setChildSupervisorForTests({ childAlive: true, inBackoff: false, restartCurrentChild: async () => {} } as never);+ const health = () => events.filter(e => e.event === 'health_warn' || e.event === 'health_error');+ return { sup, engine, events, health, state };+}++describe('supervisor DB health failures', () => {+ it('the first two failures emit health_error only and never reconnect', async () => {+ const h = harness();+ await h.sup._healthCheckOnceForTests();+ await h.sup._healthCheckOnceForTests();+ expect(h.state.reconnects).toBe(0);+ expect(h.health().map(e => [e.event, e.reason ?? null, e.error])).toEqual([+ ['health_error', null, 'connection terminated'],+ ['health_error', null, 'connection terminated'],+ ]);+ });++ it('the third consecutive failure emits db_connection_degraded, reconnects, then resets the counter', async () => {+ const h = harness();+ for (let i = 0; i < 3; i++) await h.sup._healthCheckOnceForTests();+ expect(h.state.reconnects).toBe(1);+ const degraded = h.health().find(e => e.reason === 'db_connection_degraded');+ expect(degraded).toMatchObject({ event: 'health_warn', consecutive_failures: 3, error: 'connection terminated' });+ expect(h.health().at(-1)).toMatchObject({ event: 'health_warn', reason: 'db_reconnected' });++ await h.sup._healthCheckOnceForTests();+ await h.sup._healthCheckOnceForTests();+ expect(h.state.reconnects).toBe(1);+ await h.sup._healthCheckOnceForTests();+ expect(h.state.reconnects).toBe(2);+ });++ it('a successful health query between failures restarts the three-strike count', async () => {+ const h = harness();+ await h.sup._healthCheckOnceForTests();+ await h.sup._healthCheckOnceForTests();+ h.state.healthy = true;+ await h.sup._healthCheckOnceForTests();+ h.state.healthy = false;+ await h.sup._healthCheckOnceForTests();+ await h.sup._healthCheckOnceForTests();+ expect(h.state.reconnects).toBe(0);+ await h.sup._healthCheckOnceForTests();+ expect(h.state.reconnects).toBe(1);+ });++ it('a failed reconnect keeps the counter, so every later failing tick degrades and reconnects again', async () => {+ const h = harness({ reconnect: async () => { throw new Error('pool refused'); } });+ for (let i = 0; i < 3; i++) await h.sup._healthCheckOnceForTests();+ expect(h.state.reconnects).toBe(1);+ expect(h.health().at(-1)).toMatchObject({ event: 'health_error', reconnect_failed: true, error: 'reconnect failed: pool refused' });+ expect(h.health().some(e => e.reason === 'db_reconnected')).toBe(false);++ await h.sup._healthCheckOnceForTests();+ expect(h.state.reconnects).toBe(2);+ expect(h.health().filter(e => e.reason === 'db_connection_degraded').map(e => e.consecutive_failures)).toEqual([3, 4]);+ });++ it('a failure that lands after stop began is not reported and does not reconnect', async () => {+ const h = harness();+ Object.assign(h.sup, { consecutiveHealthFailures: 2 });+ let reject!: (e: Error) => void;+ (h.engine as unknown as { executeRaw: () => Promise<unknown> }).executeRaw = () => new Promise((_r, rej) => { reject = rej; });+ const tick = h.sup._healthCheckOnceForTests();+ Object.assign(h.sup, { stopping: true });+ reject(new Error('connection terminated'));+ await tick;+ expect(h.state.reconnects).toBe(0);+ expect(h.health()).toEqual([]);+ });++ it('a failure that lands after the owner became configuration-blocked is not reported and does not reconnect', async () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-sup-health-'));+ try {+ await withEnv({ GBRAIN_HOME: root, HOME: root }, async () => {+ const h = harness();+ const owner = new OwnerProcessingState('supervisor', 'fixture');+ try {+ Object.assign(h.sup, { processingState: owner, consecutiveHealthFailures: 2 });+ writeWorkerProcessingStatus({ state: 'ready' }, owner.prepareChild());+ let reject!: (e: Error) => void;+ (h.engine as unknown as { executeRaw: () => Promise<unknown> }).executeRaw = () => new Promise((_r, rej) => { reject = rej; });+ const tick = h.sup._healthCheckOnceForTests();+ owner.block('postgres_cancellation_unavailable');+ reject(new Error('connection terminated'));+ await tick;+ expect(h.state.reconnects).toBe(0);+ expect(h.health()).toEqual([]);+ } finally {+ owner.close();+ }+ });+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });+});diff --git a/test/take-forecast.test.ts b/test/take-forecast.test.tsdeleted file mode 100644index 6fe724d6ff..0000000000--- a/test/take-forecast.test.ts+++ /dev/null@@ -1,213 +0,0 @@-/**- * v0.36.1.0 (T10 / E5) — Brier-trend forecasting tests.- *- * Hermetic. Pure-function tests + mock-engine path. No real LLM, no DB.- *- * Tests cover:- * - computeForecast: insufficient_data when bucket_n < MIN_BUCKET_N- * - computeForecast: stable forecast when bucket_n >= MIN_BUCKET_N- * - resolveDomainPrefix: slug-prefix-looking → kept, free-form → undefined- * - forecastForTake: routes through engine.getScorecard with proper args- * - batchForecast: caches per (holder, domain) tuple → minimal engine calls- * - exposes overall_brier alongside bucket_brier for comparison messaging- */--import { describe, test, expect } from 'bun:test';-import {- computeForecast,- resolveDomainPrefix,- forecastForTake,- batchForecast,- MIN_BUCKET_N,-} from '../src/core/calibration/take-forecast.ts';-import type { BrainEngine, TakesScorecard } from '../src/core/engine.ts';--function buildScorecard(opts: { resolved: number; brier: number | null }): TakesScorecard {- return {- total_bets: opts.resolved + 2,- resolved: opts.resolved,- correct: Math.floor(opts.resolved * 0.6),- incorrect: Math.floor(opts.resolved * 0.3),- partial: 0,- accuracy: 0.6,- brier: opts.brier,- partial_rate: 0,- unresolvable_count: 0,- unresolvable_rate: null,- };-}--interface ScorecardCall {- holder: string | undefined;- domainPrefix: string | undefined;-}--function buildMockEngine(opts: {- scorecards: Record<string, TakesScorecard>; // key = `${holder}|${domainPrefix ?? ''}`-}): { engine: BrainEngine; calls: ScorecardCall[] } {- const calls: ScorecardCall[] = [];- const engine = {- kind: 'pglite',- async getScorecard(scOpts: { holder?: string; domainPrefix?: string }): Promise<TakesScorecard> {- calls.push({ holder: scOpts.holder, domainPrefix: scOpts.domainPrefix });- const key = `${scOpts.holder ?? ''}|${scOpts.domainPrefix ?? ''}`;- return opts.scorecards[key] ?? buildScorecard({ resolved: 0, brier: null });- },- } as unknown as BrainEngine;- return { engine, calls };-}--// ─── computeForecast (pure) ─────────────────────────────────────────--describe('computeForecast', () => {- test('insufficient_data when bucket has fewer than MIN_BUCKET_N resolved', () => {- const overall = buildScorecard({ resolved: 20, brier: 0.18 });- const bucket = buildScorecard({ resolved: 3, brier: 0.31 });- const out = computeForecast({- conviction: 0.7,- domain: 'macro',- overallScorecard: overall,- bucketScorecard: bucket,- });- expect(out.insufficient_data).toBe(true);- expect(out.predicted_brier).toBeNull();- expect(out.bucket_n).toBe(3);- expect(out.overall_brier).toBe(0.18);- });-- test('stable forecast when bucket_n >= MIN_BUCKET_N', () => {- const overall = buildScorecard({ resolved: 20, brier: 0.18 });- const bucket = buildScorecard({ resolved: 7, brier: 0.31 });- const out = computeForecast({- conviction: 0.7,- domain: 'macro',- overallScorecard: overall,- bucketScorecard: bucket,- });- expect(out.insufficient_data).toBe(false);- expect(out.predicted_brier).toBe(0.31);- expect(out.overall_brier).toBe(0.18);- expect(out.bucket_domain).toBe('macro');- });-- test('falls back to overall scorecard when no bucket provided', () => {- const overall = buildScorecard({ resolved: 12, brier: 0.21 });- const out = computeForecast({ conviction: 0.7, overallScorecard: overall });- expect(out.bucket_domain).toBe('overall');- expect(out.predicted_brier).toBe(0.21);- });-- test(`MIN_BUCKET_N constant is exported (currently ${MIN_BUCKET_N})`, () => {- expect(MIN_BUCKET_N).toBeGreaterThan(0);- });-});--// ─── resolveDomainPrefix ────────────────────────────────────────────--describe('resolveDomainPrefix', () => {- test('undefined → undefined', () => {- expect(resolveDomainPrefix(undefined)).toBeUndefined();- });-- test('empty / whitespace → undefined', () => {- expect(resolveDomainPrefix('')).toBeUndefined();- expect(resolveDomainPrefix(' ')).toBeUndefined();- });-- test('slug-prefix value (trailing slash) → kept', () => {- expect(resolveDomainPrefix('companies/')).toBe('companies/');- });-- test('wiki-prefix value → kept', () => {- expect(resolveDomainPrefix('wiki/macro')).toBe('wiki/macro');- });-- test('free-form word → undefined (falls back to overall)', () => {- expect(resolveDomainPrefix('macro tech')).toBeUndefined();- expect(resolveDomainPrefix('geography')).toBeUndefined();- });-});--// ─── forecastForTake ────────────────────────────────────────────────--describe('forecastForTake', () => {- test('no domain → 1 engine call for overall scorecard', async () => {- const { engine, calls } = buildMockEngine({- scorecards: {- 'garry|': buildScorecard({ resolved: 12, brier: 0.21 }),- },- });- const out = await forecastForTake(engine, { holder: 'garry', conviction: 0.7 });- expect(calls).toHaveLength(1);- expect(calls[0]).toEqual({ holder: 'garry', domainPrefix: undefined });- expect(out.bucket_domain).toBe('overall');- expect(out.predicted_brier).toBe(0.21);- });-- test('with slug-prefix domain → 2 engine calls (overall + bucket)', async () => {- const { engine, calls } = buildMockEngine({- scorecards: {- 'garry|': buildScorecard({ resolved: 20, brier: 0.18 }),- 'garry|companies/': buildScorecard({ resolved: 7, brier: 0.25 }),- },- });- const out = await forecastForTake(engine, {- holder: 'garry',- conviction: 0.7,- domain: 'companies/',- });- expect(calls).toHaveLength(2);- expect(calls[1]!.domainPrefix).toBe('companies/');- expect(out.predicted_brier).toBe(0.25);- expect(out.overall_brier).toBe(0.18);- });-- test('free-form domain falls back to overall (1 engine call, undefined prefix)', async () => {- const { engine, calls } = buildMockEngine({- scorecards: { 'garry|': buildScorecard({ resolved: 12, brier: 0.21 }) },- });- const out = await forecastForTake(engine, {- holder: 'garry',- conviction: 0.7,- domain: 'macro tech',- });- expect(calls).toHaveLength(1);- expect(out.bucket_domain).toBe('macro tech');- });-});--// ─── batchForecast (memo) ───────────────────────────────────────────--describe('batchForecast', () => {- test('caches per (holder, domain) tuple — repeat queries collapse', async () => {- const { engine, calls } = buildMockEngine({- scorecards: {- 'garry|': buildScorecard({ resolved: 20, brier: 0.18 }),- 'garry|companies/': buildScorecard({ resolved: 7, brier: 0.25 }),- },- });- const out = await batchForecast(engine, [- { holder: 'garry', conviction: 0.7, domain: 'companies/' },- { holder: 'garry', conviction: 0.8, domain: 'companies/' },- { holder: 'garry', conviction: 0.5 },- ]);- expect(out).toHaveLength(3);- // 2 unique queries: (garry, undefined) + (garry, companies/).- // 3 input takes but cache collapses to 2 actual engine calls.- expect(calls).toHaveLength(2);- });-- test('different holders do NOT collapse', async () => {- const { engine, calls } = buildMockEngine({- scorecards: {- 'garry|': buildScorecard({ resolved: 10, brier: 0.2 }),- 'alice|': buildScorecard({ resolved: 5, brier: 0.18 }),- },- });- await batchForecast(engine, [- { holder: 'garry', conviction: 0.7 },- { holder: 'alice', conviction: 0.6 },- ]);- expect(calls).toHaveLength(2);- });-});diff --git a/test/test-reads-source-smell.test.ts b/test/test-reads-source-smell.test.tsindex 80059889eb..8ee835a82a 100644--- a/test/test-reads-source-smell.test.ts+++ b/test/test-reads-source-smell.test.ts@@ -1,130 +1,365 @@/*** #3665 — source-text-assertion smell gate.*- * A test whose assertions run over `readFileSync`'d src/ TEXT pins spelling,- * not behavior: it keeps passing when the behavior breaks in a way that- * preserves the grepped token, and it breaks when a harmless rename lands.- * Sometimes that is exactly the right tool (structural guards over generated- * files, comment-contract pins, guards for code that cannot run in a unit- * test) — but it must be a deliberate choice, not the default.+ * A test whose assertions run over src/ TEXT pins spelling, not behavior: it+ * keeps passing when the behavior breaks in a way that preserves the grepped+ * token, and it breaks when a harmless rename lands. Sometimes that is exactly+ * the right tool, but it must be a deliberate, reviewable choice.*- * Rule: a line in a test file that readFileSync's a literal src/ path needs a- * `test-reads-source-ok: <why>` comment on the line or within the 3 lines- * above. Files that predate the rule are in FROZEN_ALLOWLIST below; the list- * must only SHRINK (stale entries fail the suite so pruning is forced).+ * Detected read sites: a `readFileSync(` / `readFile(` (including+ * `fs.promises.readFile(`) / `Bun.file(` call whose balanced argument span+ * names a src path — a string literal containing `src/`, a `'src'` path+ * segment (e.g. `join(ROOT, 'src', 'core', 'x.ts')`), or a constant whose+ * initializer holds such a path (followed transitively).*- * Limitation (documented): only literal same-line `src/` paths are caught —- * a path built from variables slips through. That keeps false positives at- * zero, which is what lets this run in CI at all.+ * Rule: a read site needs a tagged marker on its line or within the 3 lines+ * above:+ *+ * // test-reads-source-ok[<category>]: <why>+ *+ * with one category from MARKER_TAGS. Every marker must carry a category.+ * Files that predate the rule are ratcheted by their exact count of+ * unjustified read sites in GRANDFATHERED: a new unjustified read in such a+ * file fails, and a count that drops must be lowered here. The ratchet counts+ * read sites only; new assertions over an existing source binding are the+ * authoring gate's responsibility (docs/TESTING.md#authoring-gate).*/import { describe, expect, test } from 'bun:test';import { readdirSync, readFileSync, statSync } from 'fs';import { join, relative } from 'path';+import ts from 'typescript';const TEST_DIR = import.meta.dir;+const FIXTURE_DIR = join(TEST_DIR, 'fixtures', 'source-read-smell');+const SELF = 'test-reads-source-smell.test.ts';-/** Same-line literal read into src/ (or ../src/, or a URL/join ending there). */-const READS_SRC = /readFileSync[^;\n]*['"`(/][^;\n]*\bsrc\//;+const RULE = 'test-reads-source';+const RERUN = 'bun test test/test-reads-source-smell.test.ts';+const DOC = 'docs/TESTING.md#source-reads-in-tests';const MARKER = 'test-reads-source-ok';+const MARKER_TAGS = ['prompt-byte', 'trust-boundary', 'generated-artifact', 'structural', 'raw-bytes'] as const;+const TAGGED_MARKER = new RegExp(`${MARKER}\\[(?:${MARKER_TAGS.join('|')})\\]:\\s*\\S`);++const READ_FNS = new Set(['readFileSync', 'readFile']);+const SRC_PATH = /^(?:(?:\.{1,2}\/)+|\/)?(?:admin\/)?src(?:\/|$)/;/**- * Files with unannotated src-text reads that predate the rule. FROZEN:- * never add an entry — annotate the read with `test-reads-source-ok: <why>`- * (or assert runtime behavior instead). Prune entries as files get cleaned;- * a stale entry fails the suite.+ * Exact unjustified read-site counts for files that predate the rule. Never+ * add an entry or raise a count: tag the read with a marker, or assert+ * runtime behavior instead. Lower or remove an entry when sites go away.*/-const FROZEN_ALLOWLIST = new Set([- 'admin-sse-eventsource.test.ts',- 'agent-register.test.ts',- 'apply-migrations.test.ts',- 'archived-source-scoping.test.ts',- 'autopilot-auto-drain-wiring.test.ts',- 'autopilot-install.test.ts',- 'autopilot-pause-marker.test.ts',- 'autopilot-self-upgrade.test.ts',- 'backlinks-job-default.test.ts',- 'cli-force-exit-teardown-arming.test.ts',- 'cli.test.ts',- 'connection-resilience.test.ts',- 'conversation-facts-type-allowlist-drift.test.ts',- 'cycle-abort.test.ts',- 'cycle-drain-renewal.test.ts',- 'cycle-patterns-deadline-budget.test.ts',- 'destructive-guard.test.ts',- 'doctor-orphan-ratio.test.ts',- 'dream-cli-flags.test.ts',- 'exit-classification.test.ts',- 'extract-atoms-drain.test.ts',- 'fence-extraction.test.ts',- 'fix-wave-structural.test.ts',- 'integrations.test.ts',- 'migrate-stdout-clean.test.ts',- 'migrate.test.ts',- 'migrations-v0_22_4.test.ts',- 'pglite-engine.test.ts',- 'pglite-wal-repair.serial.test.ts',- 'phantom-redirect-per-source-lock.test.ts',- 'register-client-source-normalize.test.ts',- 'regression-strict-source-id.test.ts',- 'reindex-code-recovery.test.ts',- 'schema-cli-contract.test.ts',- 'schema-pack-unify-types-handler.test.ts',- 'scripts/classify-tests.test.ts',- 'serve-http-github-webhook.test.ts',- 'serve-http-mcp-transport-cleanup.test.ts',- 'timing-safe.test.ts',- 'transcription-injection.test.ts',-]);--function* testFiles(dir: string): Generator<string> {+const GRANDFATHERED: Record<string, number> = {+ 'admin-sse-eventsource.test.ts': 1,+ 'agent-register.test.ts': 2,+ 'ai/silent-drop-regression.test.ts': 2,+ 'apply-migrations.test.ts': 3,+ 'archived-source-scoping.test.ts': 1,+ 'autopilot-auto-drain-wiring.test.ts': 1,+ 'autopilot-cycle-failure-classification.test.ts': 2,+ 'autopilot-fanout-wiring.test.ts': 2,+ 'autopilot-install.test.ts': 5,+ 'autopilot-nightly-probe-wiring.test.ts': 1,+ 'autopilot-parser-probe-wiring.test.ts': 1,+ 'autopilot-pause-marker.test.ts': 1,+ 'autopilot-self-upgrade.test.ts': 1,+ 'autopilot-shutdown-engine-close.test.ts': 1,+ 'autopilot-supervisor-wiring.test.ts': 1,+ 'backup-cli.serial.test.ts': 2,+ 'backup-invalidation.serial.test.ts': 1,+ 'book-mirror.test.ts': 1,+ 'brain-score-breakdown.test.ts': 1,+ 'brainstorm-timeout.test.ts': 2,+ 'check-update.test.ts': 1,+ 'child-worker-supervisor.test.ts': 1,+ 'chunkers/code-bash.test.ts': 2,+ 'claude-cli-recipe.test.ts': 1,+ 'cli-force-exit-teardown-arming.test.ts': 2,+ 'compile-view.test.ts': 1,+ 'config.test.ts': 1,+ 'connection-resilience.test.ts': 3,+ 'contextual-retrieval-service-pure.test.ts': 1,+ 'conversation-facts-type-allowlist-drift.test.ts': 1,+ 'cycle-abort.test.ts': 7,+ 'cycle-drain-renewal.test.ts': 2,+ 'cycle-patterns-deadline-budget.test.ts': 5,+ 'cycle-phase-deadline-drift.test.ts': 2,+ 'cycle/nightly-probe-adapters.test.ts': 5,+ 'cycle/regression-pr-wave-r1-r2-r4.test.ts': 2,+ 'cycle/yield-during-phase-throttle.test.ts': 1,+ 'destructive-guard.test.ts': 1,+ 'detached-stderr.test.ts': 1,+ 'doctor-categories.test.ts': 1,+ 'doctor-orphan-ratio.test.ts': 3,+ 'doctor-volunteer-channels.test.ts': 3,+ 'doctor.test.ts': 1,+ 'embedding-dim-check-facts.test.ts': 1,+ 'eval-capture-db-plane.serial.test.ts': 2,+ 'eval-synthesize-concepts-routing.test.ts': 2,+ 'exit-classification.test.ts': 2,+ 'extract-atoms-drain-errors.test.ts': 1,+ 'extract-atoms-drain.test.ts': 3,+ 'features.test.ts': 2,+ 'fence-extraction.test.ts': 1,+ 'files.test.ts': 2,+ 'fix-wave-structural.test.ts': 35,+ 'hook-command.serial.test.ts': 1,+ 'integrations.test.ts': 1,+ 'jobs-embed-background-parity.serial.test.ts': 2,+ 'jobs-gateway-refresh-set.test.ts': 1,+ 'jobs-list-get-json.serial.test.ts': 1,+ 'jobs-thin-client-date-rehydration.test.ts': 1,+ 'jobs-worker-startup-recovery.test.ts': 1,+ 'lens-pack-manifests.test.ts': 1,+ 'link-inference-pack.test.ts': 1,+ 'link-source-check-repair.test.ts': 1,+ 'longmemeval-embed-cache.test.ts': 1,+ 'loops-extract-wiring.test.ts': 2,+ 'migrate-stdout-clean.test.ts': 1,+ 'migrate.test.ts': 11,+ 'migration-in-process.serial.test.ts': 3,+ 'migration-resume.test.ts': 6,+ 'migrations-v0_13_0.test.ts': 4,+ 'migrations-v0_14_0.test.ts': 4,+ 'migrations-v0_22_4.test.ts': 1,+ 'model-pricing.test.ts': 1,+ 'openclaw-plugin-manifest.test.ts': 1,+ 'operations-trust-boundary.test.ts': 1,+ 'pglite-engine.test.ts': 1,+ 'pglite-wal-repair.serial.test.ts': 1,+ 'postgres-engine.test.ts': 1,+ 'redos-hardening.test.ts': 2,+ 'register-client-source-normalize.test.ts': 1,+ 'reindex-code-recovery.test.ts': 1,+ 'reranker-default-seam.test.ts': 1,+ 'retrieval-reflex-recipe-routing.test.ts': 1,+ 'schema-bootstrap-coverage.test.ts': 5,+ 'schema-pack-best-effort.test.ts': 1,+ 'schema-pack-unify-types-handler.test.ts': 2,+ 'schema-pack/suggest.test.ts': 1,+ 'search/graph-signals-wire-integration.test.ts': 1,+ 'search/knobs-hash-reranker.test.ts': 2,+ 'serve-http-admin-route-guard.test.ts': 1,+ 'serve-http-github-webhook.test.ts': 1,+ 'serve-http-mcp-transport-cleanup.test.ts': 1,+ 'skillpack-scaffold.test.ts': 1,+ 'sources-webhook.test.ts': 1,+ 'spend-off-switch.test.ts': 3,+ 'supervisor.test.ts': 1,+ 'sync-failures.test.ts': 6,+ 'sync-include-hidden.test.ts': 1,+ 'sync.test.ts': 1,+ 'timing-safe.test.ts': 1,+ 'transcript-adapters.test.ts': 1,+ 'transcription-injection.test.ts': 1,+ 'v0_37_fix_wave.serial.test.ts': 2,+ 'v0_37_gap_fill.serial.test.ts': 3,+ 'worker-lock-renewal-shape.test.ts': 1,+ 'worker-supervised-db-probe.test.ts': 1,+};++function isReadCall(node: ts.Node): node is ts.CallExpression {+ if (!ts.isCallExpression(node)) return false;+ const callee = node.expression;+ if (ts.isIdentifier(callee)) return READ_FNS.has(callee.text);+ if (!ts.isPropertyAccessExpression(callee)) return false;+ if (READ_FNS.has(callee.name.text)) return true;+ return callee.name.text === 'file' && ts.isIdentifier(callee.expression) && callee.expression.text === 'Bun';+}++/** True when the subtree holds a src path literal, a 'src' segment, or a src-path constant. */+function namesSrcPath(node: ts.Node, srcConsts: Set<string>): boolean {+ let found = false;+ const visit = (n: ts.Node): void => {+ if (found || (ts.isCallExpression(n) && n.expression.kind === ts.SyntaxKind.ImportKeyword)) return;+ if (ts.isStringLiteral(n) || ts.isNoSubstitutionTemplateLiteral(n) || ts.isTemplateHead(n) || ts.isTemplateMiddle(n) || ts.isTemplateTail(n)) {+ if (SRC_PATH.test(n.text)) found = true;+ } else if (ts.isIdentifier(n) && srcConsts.has(n.text) && !(ts.isPropertyAccessExpression(n.parent) && n.parent.name === n)) {+ found = true;+ }+ ts.forEachChild(n, visit);+ };+ visit(node);+ return found;+}++const PATH_BUILDER = /join|resolve|normalize|url/i;++/** A declaration initializer that builds a path: a literal, template, concatenation or path-builder call. */+function isPathExpression(node: ts.Expression): boolean {+ while (ts.isParenthesizedExpression(node) || ts.isAsExpression(node)) node = node.expression;+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateExpression(node)) return true;+ if (ts.isIdentifier(node) || ts.isBinaryExpression(node)) return true;+ if (ts.isCallExpression(node) || ts.isNewExpression(node)) {+ const callee = node.expression;+ const name = ts.isIdentifier(callee) ? callee.text : ts.isPropertyAccessExpression(callee) ? callee.name.text : '';+ return PATH_BUILDER.test(name);+ }+ return false;+}++function containsReadCall(node: ts.Node): boolean {+ if (isReadCall(node)) return true;+ return ts.forEachChild(node, containsReadCall) ?? false;+}++type FileScan = { unjustified: number[]; untaggedMarkers: number[] };++function scanSource(text: string): FileScan {+ const lines = text.split('\n');+ const untaggedMarkers = lines+ .map((l, i) => (l.includes(MARKER) && !TAGGED_MARKER.test(l) ? i + 1 : 0))+ .filter(Boolean);+ if (!/readFile|Bun\.file/.test(text)) return { unjustified: [], untaggedMarkers };++ const sf = ts.createSourceFile('scan.ts', text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);+ const decls: ts.VariableDeclaration[] = [];+ const reads: ts.CallExpression[] = [];+ const collect = (n: ts.Node): void => {+ if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.initializer && isPathExpression(n.initializer) && !containsReadCall(n.initializer)) decls.push(n);+ if (isReadCall(n)) reads.push(n);+ ts.forEachChild(n, collect);+ };+ collect(sf);++ const srcConsts = new Set<string>();+ for (let grew = true; grew;) {+ grew = false;+ for (const d of decls) {+ const name = (d.name as ts.Identifier).text;+ if (!srcConsts.has(name) && namesSrcPath(d.initializer!, srcConsts)) {+ srcConsts.add(name);+ grew = true;+ }+ }+ }++ const sites = new Set<number>();+ for (const call of reads) {+ if (call.arguments.some((a) => namesSrcPath(a, srcConsts))) {+ sites.add(sf.getLineAndCharacterOfPosition(call.getStart(sf)).line + 1);+ }+ }+ const unjustified = [...sites].sort((a, b) => a - b).filter((line) => {+ const context = lines.slice(Math.max(0, line - 4), line);+ return !context.some((l) => TAGGED_MARKER.test(l));+ });+ return { unjustified, untaggedMarkers };+}++function* files(dir: string, suffix: string): Generator<string> {for (const entry of readdirSync(dir)) {const p = join(dir, entry);- if (statSync(p).isDirectory()) yield* testFiles(p);- else if (p.endsWith('.test.ts')) yield p;+ if (statSync(p).isDirectory()) yield* files(p, suffix);+ else if (p.endsWith(suffix)) yield p;}}-function offendingFiles(): Map<string, number[]> {- const out = new Map<string, number[]>();- for (const f of testFiles(TEST_DIR)) {- const rel = relative(TEST_DIR, f);- if (rel === 'test-reads-source-smell.test.ts') continue; // this file names the pattern in prose- const lines = readFileSync(f, 'utf-8').split('\n');- const hits: number[] = [];- for (let i = 0; i < lines.length; i++) {- if (!READS_SRC.test(lines[i]!)) continue;- const context = lines.slice(Math.max(0, i - 3), i + 1).join('\n');- if (context.includes(MARKER)) continue;- hits.push(i + 1);- }- if (hits.length > 0) out.set(rel, hits);+function scanTree(dir: string, suffix: string): Map<string, FileScan> {+ const out = new Map<string, FileScan>();+ for (const f of files(dir, suffix)) {+ const rel = relative(dir, f);+ if (rel === SELF) continue;+ const scan = scanSource(readFileSync(f, 'utf-8'));+ if (scan.unjustified.length || scan.untaggedMarkers.length) out.set(rel, scan);}return out;}-describe('#3665 — tests that read src/ text need a justification', () => {- test('no NEW test file readFileSyncs src/* without a test-reads-source-ok comment', () => {- const offenders = offendingFiles();- const fresh = [...offenders.entries()].filter(([rel]) => !FROZEN_ALLOWLIST.has(rel));- const msg = fresh- .map(([rel, lines]) => `test/${rel}:${lines.join(',')}`)- .join('\n');- expect(- fresh.map(([rel]) => rel),- `New source-text reads in tests without justification:\n${msg}\n` +- `Either assert runtime behavior instead, or add a comment within 3 lines above the read:\n` +- ` // ${MARKER}: <why grepping source text is the right tool here>\n` +- `Do NOT add entries to FROZEN_ALLOWLIST — it only shrinks.`,- ).toEqual([]);+const footer = ` rerun: ${RERUN}\n docs: ${DOC}`;++function problemsFor(scans: Map<string, FileScan>, baseline: Record<string, number>, prefix = 'test/') {+ const fresh: string[] = [];+ const stale: string[] = [];+ const untagged: string[] = [];+ for (const [rel, scan] of scans) {+ for (const line of scan.untaggedMarkers) {+ untagged.push([+ `${RULE} (untagged marker): ${prefix}${rel}:${line}`,+ ` reason: every ${MARKER} marker must name one category so reviewers can see why a source read is legitimate.`,+ ` remedy: write it as // ${MARKER}[<category>]: <why>, with <category> one of ${MARKER_TAGS.join(', ')}.`,+ footer,+ ].join('\n'));+ }+ const expected = baseline[rel] ?? 0;+ if (scan.unjustified.length > expected) {+ fresh.push([+ `${RULE}: ${prefix}${rel}:${scan.unjustified.join(',')} reads src/ text without a tagged justification.`,+ ` count: expected at most ${expected} unjustified read site(s) in this file, found ${scan.unjustified.length}.`,+ ` reason: a source-text assertion pins spelling, not behavior.`,+ ` remedy: assert runtime behavior instead, or add // ${MARKER}[<category>]: <why> on the read or within the 3 lines above.`,+ footer,+ ].join('\n'));+ }+ }+ for (const [rel, expected] of Object.entries(baseline)) {+ const actual = scans.get(rel)?.unjustified.length ?? 0;+ if (actual >= expected) continue;+ stale.push([+ `${RULE} (stale ratchet entry): ${prefix}${rel} now has ${actual} unjustified read site(s); GRANDFATHERED records ${expected}.`,+ ` remedy: ${actual === 0 ? 'remove the entry' : `lower the entry to ${actual}`} in test/test-reads-source-smell.test.ts; do not add reads back.`,+ footer,+ ].join('\n'));+ }+ return { fresh, stale, untagged };+}++describe('#3665 — tests that read src/ text need a tagged justification', () => {+ const corpus = problemsFor(scanTree(TEST_DIR, '.test.ts'), GRANDFATHERED);++ test('every test-reads-source-ok marker carries a category tag', () => {+ expect(corpus.untagged, corpus.untagged.join('\n\n')).toEqual([]);+ });++ test('no new unjustified src/ read sites (per-file exact-count ratchet)', () => {+ expect(corpus.fresh, corpus.fresh.join('\n\n')).toEqual([]);+ });++ test('the ratchet only shrinks (stale counts must be lowered)', () => {+ expect(corpus.stale, corpus.stale.join('\n\n')).toEqual([]);+ });+});++describe('source-read detector fixtures', () => {+ const fixture = (name: string) => scanSource(readFileSync(join(FIXTURE_DIR, name), 'utf-8'));++ test.each([+ ['same-line literal path', 'form-literal.fixture.ts', [5]],+ ['multi-line read call', 'form-multiline.fixture.ts', [5]],+ ["join(...) with a 'src' segment", 'form-join-segment.fixture.ts', [5]],+ ['Bun.file(...)', 'form-bun-file.fixture.ts', [4]],+ ['readFile and fs.promises.readFile', 'form-read-file.fixture.ts', [6, 7]],+ ['constant holding a src path, followed transitively', 'form-constant.fixture.ts', [7, 8]],+ ])('detects %s', (_label, name, lines) => {+ expect(fixture(name).unjustified).toEqual(lines);+ });++ test('a tagged marker justifies the read; non-src reads are not sites', () => {+ expect(fixture('tagged-ok.fixture.ts')).toEqual({ unjustified: [], untaggedMarkers: [] });+ });++ test('an untagged new read fails with the full diagnostic', () => {+ const scans = new Map([['untagged-new.fixture.ts', fixture('untagged-new.fixture.ts')]]);+ const { fresh, untagged } = problemsFor(scans, {}, '');+ expect(untagged).toHaveLength(1);+ expect(untagged[0]).toContain(`${RULE} (untagged marker): untagged-new.fixture.ts:4`);+ expect(untagged[0]).toContain(`remedy: write it as // ${MARKER}[<category>]: <why>`);+ expect(fresh).toHaveLength(1);+ expect(fresh[0]).toContain(`${RULE}: untagged-new.fixture.ts:5 reads src/ text without a tagged justification.`);+ expect(fresh[0]).toContain('count: expected at most 0 unjustified read site(s) in this file, found 1.');+ expect(fresh[0]).toContain(`rerun: ${RERUN}`);+ expect(fresh[0]).toContain(`docs: ${DOC}`);});- test('the frozen allowlist only shrinks (stale entries must be pruned)', () => {- const offenders = offendingFiles();- const stale = [...FROZEN_ALLOWLIST].filter((rel) => !offenders.has(rel));- expect(- stale,- `Allowlist entries whose files no longer have unannotated src reads (or were deleted) — prune them:\n${stale.join('\n')}`,- ).toEqual([]);+ test('a new pin in a grandfathered file fails; a dropped count is stale', () => {+ const scans = new Map([['grandfathered.fixture.ts', fixture('grandfathered.fixture.ts')]]);+ const grown = problemsFor(scans, { 'grandfathered.fixture.ts': 1 }, '');+ expect(grown.fresh).toHaveLength(1);+ expect(grown.fresh[0]).toContain('count: expected at most 1 unjustified read site(s) in this file, found 2.');+ const shrunk = problemsFor(scans, { 'grandfathered.fixture.ts': 3 }, '');+ expect(shrunk.fresh).toEqual([]);+ expect(shrunk.stale).toHaveLength(1);+ expect(shrunk.stale[0]).toContain('(stale ratchet entry): grandfathered.fixture.ts now has 2 unjustified read site(s); GRANDFATHERED records 3.');+ expect(shrunk.stale[0]).toContain('remedy: lower the entry to 2 in test/test-reads-source-smell.test.ts; do not add reads back.');});});diff --git a/test/thin-client-routing-audit.test.ts b/test/thin-client-routing-audit.test.tsindex 33ef9ac83d..1b3cd9725e 100644--- a/test/thin-client-routing-audit.test.ts+++ b/test/thin-client-routing-audit.test.ts@@ -1,176 +1,100 @@/**- * v0.32 — thin-client routing audit regression guard.+ * v0.32/v0.33 thin-client routing audit — the ROUTE additions.*- * The v0.32 audit (eng-review D3 + Codex round 2 #4) classified every- * `case '...'` in src/cli.ts's dispatch switch as one of:- * - already routed (4 commands)- * - already refused (14 commands)- * - CLI-local (24 commands)- * - route fix added (recall, forget, jobs list/get)- * - REFUSE added (7 commands: pages, files, eval, code-def, code-refs,- * code-callers, code-callees)+ * On a thin-client install (`remote_mcp` in config) `gbrain forget` and+ * `gbrain jobs list|get` must call the remote MCP op instead of reading an+ * empty local store, and `runJobs` must refuse any other subcommand that+ * arrives with a null engine. The REFUSE additions are spawned in+ * test/cli-dispatch-thin-client.test.ts (refusedCommands); the recall route+ * is owned by test/recall-thin-client-fallback.serial.test.ts.*- * This test pins the REFUSE additions. A future refactor that drops one of- * these from THIN_CLIENT_REFUSED_COMMANDS would silently re-introduce the- * silent-empty-results bug class v0.31.1 was fixing.- *- * The deeper transport-mock routing tests (recall/forget/jobs actually call- * callRemoteTool with the right params) live in a serial test follow-up; the- * structural invariants pinned here catch the most common regression mode.+ * callRemoteTool is stubbed with spyOn on the module namespace (the pattern+ * in test/thin-client-routing.test.ts) and returns a real MCP content+ * envelope, so the real unpackToolResult runs.*/-import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'node:fs';+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';import { join } from 'node:path';--const CLI_TS_PATH = join(import.meta.dir, '..', 'src', 'cli.ts');-const CLI_SOURCE = readFileSync(CLI_TS_PATH, 'utf8');--// Codex round 2 #4 + audit table: every member of this list must be in-// THIN_CLIENT_REFUSED_COMMANDS and have a hint in THIN_CLIENT_REFUSE_HINTS.-// Justifications:-// - pages: pages.purge-deleted is admin+localOnly (operations.ts:856-864)-// - files: file_list + file_url MCP ops are localOnly:true-// - eval: export/prune/replay touch local engine; no MCP equivalent-// - code-def / code-refs / code-callers / code-callees: NO MCP ops exist-const V032_REFUSE_ADDITIONS = [- 'pages', 'files', 'eval',- 'code-def', 'code-refs', 'code-callers', 'code-callees',-];--describe('thin-client routing audit — v0.32 REFUSE additions stay in the table', () => {- test('THIN_CLIENT_REFUSED_COMMANDS set declaration is intact', () => {- expect(CLI_SOURCE).toContain('const THIN_CLIENT_REFUSED_COMMANDS = new Set([');- });-- for (const command of V032_REFUSE_ADDITIONS) {- test(`'${command}' is in THIN_CLIENT_REFUSED_COMMANDS`, () => {- // We look for the literal in the set declaration. The set is plain- // text in src/cli.ts so a simple string check is honest: a future- // refactor that drops the entry would also drop the literal.- const setStart = CLI_SOURCE.indexOf('const THIN_CLIENT_REFUSED_COMMANDS = new Set([');- const setEnd = CLI_SOURCE.indexOf(']);', setStart);- const setBlock = CLI_SOURCE.slice(setStart, setEnd);- expect(setBlock).toContain(`'${command}'`);- });-- test(`'${command}' has a hint in THIN_CLIENT_REFUSE_HINTS`, () => {- const hintsStart = CLI_SOURCE.indexOf(- 'const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {',- );- const hintsEnd = CLI_SOURCE.indexOf('};', hintsStart);- const hintsBlock = CLI_SOURCE.slice(hintsStart, hintsEnd);- // Hint keys with embedded dashes are quoted (`'code-def':`); others- // can be bare (`pages:`). Accept either shape.- const bareKey = new RegExp(`\\b${command.replace(/-/g, '\\-')}\\s*:`);- const quotedKey = new RegExp(`['"]${command.replace(/-/g, '\\-')}['"]\\s*:`);- expect(bareKey.test(hintsBlock) || quotedKey.test(hintsBlock)).toBe(true);- });- }-- test('every v0.31.1-era REFUSED command is still in the set (no accidental removals)', () => {- const setStart = CLI_SOURCE.indexOf('const THIN_CLIENT_REFUSED_COMMANDS = new Set([');- const setEnd = CLI_SOURCE.indexOf(']);', setStart);- const setBlock = CLI_SOURCE.slice(setStart, setEnd);- const v0_31_originals = [- 'sync', 'embed', 'extract', 'migrate', 'apply-migrations',- 'repair-jsonb', 'orphans', 'integrity', 'serve',- 'dream', 'transcripts', 'storage', 'takes', 'sources',- ];- for (const cmd of v0_31_originals) {- expect(setBlock).toContain(`'${cmd}'`);- }- });+import * as mcpClient from '../src/core/mcp-client.ts';+import { runForget } from '../src/commands/recall.ts';+import { runJobs } from '../src/commands/jobs.ts';+import { withEnv } from './helpers/with-env.ts';++let home: string;+const calls: Array<{ tool: string; args: Record<string, unknown> }> = [];+let reply: unknown = null;+let callSpy: ReturnType<typeof spyOn>;++beforeAll(() => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-thin-route-'));+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'pglite',+ remote_mcp: { issuer_url: 'http://127.0.0.1:1', mcp_url: 'http://127.0.0.1:1/mcp', oauth_client_id: 'fixture', oauth_client_secret: 'fixture' },+ }));+ callSpy = spyOn(mcpClient, 'callRemoteTool').mockImplementation(+ async (_cfg: unknown, tool: string, args: Record<string, unknown> = {}) => {+ calls.push({ tool, args });+ return { content: [{ type: 'text', text: JSON.stringify(reply) }] } as never;+ },+ );});-describe('thin-client routing audit — v0.32 ROUTE additions wire callRemoteTool', () => {- // The route additions are: recall, forget (in recall.ts) + jobs list / get- // (in jobs.ts). Each file must import callRemoteTool from mcp-client AND- // call it at least once. If a future refactor removes the import without- // removing the routing path, the call would fail at runtime — easier to- // catch at the source-string level.-- test('src/commands/recall.ts imports callRemoteTool + isThinClient', () => {- const src = readFileSync(- join(import.meta.dir, '..', 'src', 'commands', 'recall.ts'),- 'utf8',- );- expect(src).toContain(`from '../core/config.ts'`);- expect(src).toContain('isThinClient');- expect(src).toContain(`from '../core/mcp-client.ts'`);- expect(src).toContain('callRemoteTool');- });-- test('src/commands/recall.ts: recall routing branch calls callRemoteTool with op="recall"', () => {- const src = readFileSync(- join(import.meta.dir, '..', 'src', 'commands', 'recall.ts'),- 'utf8',- );- expect(src).toContain(`callRemoteTool(cfg!, 'recall'`);- });-- test('src/commands/recall.ts: forget routing branch calls callRemoteTool with op="forget"', () => {- const src = readFileSync(- join(import.meta.dir, '..', 'src', 'commands', 'recall.ts'),- 'utf8',- );- expect(src).toContain(`callRemoteTool(cfg!, 'forget'`);- });-- test('src/commands/jobs.ts: list/get routing branches call callRemoteTool', () => {- const src = readFileSync(- join(import.meta.dir, '..', 'src', 'commands', 'jobs.ts'),- 'utf8',- );- expect(src).toContain(`from '../core/mcp-client.ts'`);- expect(src).toContain(`callRemoteTool(cfg!, 'list_jobs'`);- expect(src).toContain(`callRemoteTool(cfg!, 'get_job'`);- });+afterAll(() => {+ callSpy.mockRestore();+ rmSync(home, { recursive: true, force: true });});-describe('thin-client routing audit — scratch-DB additions (jobs partial dispatch + config refusal)', () => {- // `jobs list|get` route over MCP but the CLI shell still connected a- // local engine first, fabricating an empty scratch PGLite in the- // thin-client GBRAIN_HOME and replaying the full migration chain on- // every invocation. `config` did the same with no remote path at all.-- test('cli.ts dispatches thin-client jobs list/get engine-free (runJobs(null, ...))', () => {- expect(CLI_SOURCE).toMatch(/command === 'jobs'/);- expect(CLI_SOURCE).toMatch(/runJobs\(null, args\)/);- });-- test('cli.ts refuses non-routable jobs subcommands on thin clients via refuseThinClient', () => {- const dispatchStart = CLI_SOURCE.indexOf("if (command === 'jobs') {");- expect(dispatchStart).toBeGreaterThan(-1);- const dispatchBlock = CLI_SOURCE.slice(dispatchStart, dispatchStart + 900);- expect(dispatchBlock).toContain('isThinClient');- expect(dispatchBlock).toContain("refuseThinClient('jobs'");+beforeEach(() => { calls.length = 0; });++async function thinClient(fn: () => Promise<void>): Promise<{ out: string; exitCode: number | undefined }> {+ const out: string[] = [];+ let exitCode: number | undefined;+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.map(String).join(' ')); });+ const err = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { out.push(a.map(String).join(' ')); });+ const write = spyOn(process.stdout, 'write').mockImplementation(((chunk: string | Uint8Array) => { out.push(String(chunk)); return true; }) as never);+ const exit = spyOn(process, 'exit').mockImplementation(((code?: number) => { exitCode = code; throw new Error('__exit__'); }) as never);+ try {+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, fn);+ } catch (e) {+ if ((e as Error).message !== '__exit__') throw e;+ } finally {+ log.mockRestore(); err.mockRestore(); write.mockRestore(); exit.mockRestore();+ }+ return { out: out.join('\n'), exitCode };+}++const job = { id: 7, name: 'embed', queue: 'default', status: 'completed', priority: 0, attempts_made: 1, max_attempts: 3, attempts_started: 1, stalled_counter: 0, max_stalled: 1, backoff_type: 'fixed', backoff_delay: 0, backoff_jitter: 0, stacktrace: [], data: {}, created_at: '2026-01-01T00:00:00.000Z' };++describe('thin-client routing audit — ROUTE additions call the remote op', () => {+ test('gbrain forget <id> calls the remote forget op and never a local engine', async () => {+ reply = { id: '42', expired: true };+ const { out } = await thinClient(() => runForget(async () => { throw new Error('local engine opened'); }, ['42', '--reason', 'fixture']));+ expect(calls.map(c => c.tool)).toEqual(['forget']);+ expect(calls[0].args).toMatchObject({ id: '42' });+ expect(out).toContain('Forgot fact id=42');});- test("'config' is in THIN_CLIENT_REFUSED_COMMANDS with a hint", () => {- const setStart = CLI_SOURCE.indexOf('const THIN_CLIENT_REFUSED_COMMANDS = new Set([');- const setEnd = CLI_SOURCE.indexOf(']);', setStart);- expect(CLI_SOURCE.slice(setStart, setEnd)).toContain("'config'");- const hintsStart = CLI_SOURCE.indexOf(- 'const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {',- );- const hintsEnd = CLI_SOURCE.indexOf('};', hintsStart);- expect(/\bconfig\s*:/.test(CLI_SOURCE.slice(hintsStart, hintsEnd))).toBe(true);+ test('gbrain jobs list calls list_jobs with the parsed filters', async () => {+ reply = [job];+ const { out } = await thinClient(() => runJobs(null, ['list', '--status', 'completed', '--queue', 'default', '--limit', '5', '--json']));+ expect(calls).toEqual([{ tool: 'list_jobs', args: { status: 'completed', queue: 'default', limit: 5 } }]);+ expect(JSON.parse(out)[0].id).toBe(7);});- test("'jobs' is NOT in THIN_CLIENT_REFUSED_COMMANDS (partial dispatch owns it)", () => {- const setStart = CLI_SOURCE.indexOf('const THIN_CLIENT_REFUSED_COMMANDS = new Set([');- const setEnd = CLI_SOURCE.indexOf(']);', setStart);- expect(CLI_SOURCE.slice(setStart, setEnd)).not.toContain("'jobs'");+ test('gbrain jobs get <id> calls get_job with a numeric id', async () => {+ reply = job;+ const { out } = await thinClient(() => runJobs(null, ['get', '7']));+ expect(calls).toEqual([{ tool: 'get_job', args: { id: 7 } }]);+ expect(out).toContain('Job #7: embed (COMPLETED)');});- test('jobs.ts guards the null-engine path to list/get only', () => {- const src = readFileSync(- join(import.meta.dir, '..', 'src', 'commands', 'jobs.ts'),- 'utf8',- );- expect(src).toContain('engineOrNull: BrainEngine | null');- expect(src).toContain("const localSupervisorStatus = sub === 'supervisor' && args[1] === 'status';");- expect(src).toMatch(/if \(!engineOrNull && sub !== 'list' && sub !== 'get' && !localSupervisorStatus\)/);+ test('runJobs refuses a non-routable subcommand that arrives with a null engine', async () => {+ const { out, exitCode } = await thinClient(() => runJobs(null, ['stats']));+ expect(exitCode).toBe(1);+ expect(out).toContain('`gbrain jobs stats` needs a local engine and cannot run on a thin client.');+ expect(calls).toEqual([]);});});diff --git a/test/think-embed-question-wiring.serial.test.ts b/test/think-embed-question-wiring.serial.test.tsindex 7d833fb649..b2167f60e1 100644--- a/test/think-embed-question-wiring.serial.test.ts+++ b/test/think-embed-question-wiring.serial.test.ts@@ -77,7 +77,7 @@ describe('#3734 — CRAG think escalation wires embedQuestion (source pin)', ()// embedQuestion (same cheap-pin pattern as the repo's other residual// source-text guards).test('ops/search.ts CRAG runThink call passes embedQuestion', () => {- // test-reads-source-ok: the CRAG escalation runThink site is unreachable hermetically (needs a full engine, a weak search result, and search.crag_escalate_think), so the #3734 wiring pin reads the call site itself.+ // test-reads-source-ok[structural]: the CRAG escalation runThink site is unreachable hermetically (needs a full engine, a weak search result, and search.crag_escalate_think), so the #3734 wiring pin reads the call site itself.const src = readFileSync(join(import.meta.dir, '../src/core/ops/search.ts'), 'utf8');const callSite = src.slice(src.indexOf('escalate_to_think = true'));const runThinkBlock = callSite.slice(callSite.indexOf('runThink(ctx.engine'), callSite.indexOf('});'));diff --git a/test/tool-catalog.test.ts b/test/tool-catalog.test.tsindex 7bf75ad34a..f0db6a17bf 100644--- a/test/tool-catalog.test.ts+++ b/test/tool-catalog.test.ts@@ -6,7 +6,7 @@*/import { describe, test, expect } from 'bun:test';-import { readFileSync, existsSync } from 'fs';+import { readFileSync } from 'fs';import { join } from 'path';import { renderToolCatalogMarkdown, firstSentence } from '../src/mcp/tool-catalog.ts';@@ -77,11 +77,4 @@ describe('freshness guard', () => {expect(committed).toBe(renderToolCatalogMarkdown() + '\n');});- test('check script exists and is wired into package.json + the verify chain', () => {- expect(existsSync(join(REPO_ROOT, 'scripts', 'check-tool-catalog-fresh.sh'))).toBe(true);- const pkg = JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf-8'));- expect(pkg.scripts['check:tool-catalog']).toBe('bash scripts/check-tool-catalog-fresh.sh');- const verify = readFileSync(join(REPO_ROOT, 'scripts', 'run-verify-parallel.sh'), 'utf-8');- expect(verify).toContain('"check:tool-catalog"');- });});diff --git a/test/transcription.test.ts b/test/transcription.test.tsindex f69e8d31d6..8e4bd4c113 100644--- a/test/transcription.test.ts+++ b/test/transcription.test.ts@@ -11,15 +11,6 @@ writeFileSync(TMP_TXT, 'not audio');writeFileSync(TMP_MP3, 'fake mp3 data');describe('transcription', () => {- test('module exports transcribe function', async () => {- const mod = await import('../src/core/transcription.ts');- expect(typeof mod.transcribe).toBe('function');- });-- test('TranscriptionResult interface shape', async () => {- const mod = await import('../src/core/transcription.ts');- expect(mod.transcribe).toBeDefined();- });test('rejects unsupported audio format', async () => {const { transcribe } = await import('../src/core/transcription.ts');@@ -50,15 +41,6 @@ describe('transcription', () => {}});- test('detects provider from env vars', async () => {- // This tests the provider detection logic indirectly- const mod = await import('../src/core/transcription.ts');- // If GROQ_API_KEY is set, Groq should be preferred- // If only OPENAI_API_KEY, OpenAI should be used- // We just verify the function is callable- expect(typeof mod.transcribe).toBe('function');- });-test('supported audio extensions are comprehensive', () => {// Verify common audio formats are supportedconst expected = ['.mp3', '.wav', '.m4a', '.ogg', '.flac', '.mp4', '.webm'];diff --git a/test/e2e/transcripts-ingest-pglite.test.ts b/test/transcripts-ingest-pglite.test.tssimilarity index 97%rename from test/e2e/transcripts-ingest-pglite.test.tsrename to test/transcripts-ingest-pglite.test.tsindex b251b152be..a73634aa4a 100644--- a/test/e2e/transcripts-ingest-pglite.test.ts+++ b/test/transcripts-ingest-pglite.test.ts@@ -8,24 +8,28 @@* clean-scan semantics, and the putRawData zero-row parity fix.** R3/R4: engine in beforeAll, disconnect in afterAll; state reset per test.+ *+ * Lane: unit. Run: `bun test test/transcripts-ingest-pglite.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { copyFileSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { resetPgliteState } from '../helpers/reset-pglite.ts';-import { runTranscriptsIngest } from '../../src/core/transcripts/ingest.ts';-import { runIngestFacts } from '../../src/core/transcripts/ingest-facts.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { runTranscriptsIngest } from '../src/core/transcripts/ingest.ts';+import { runIngestFacts } from '../src/core/transcripts/ingest-facts.ts';import {buildStatusRows,discoverTranscriptFiles,indexImportedSessions,-} from '../../src/core/transcripts/discover.ts';-import type { HarnessRoot } from '../../src/core/transcripts/detect.ts';-import { MESSAGE_CHAR_CAP } from '../../src/core/transcripts/render.ts';-import { buildTranscriptSlug } from '../../src/core/transcripts/types.ts';-import { buildHermesFixture } from '../fixtures/transcripts/hermes-fixture-builder.ts';+} from '../src/core/transcripts/discover.ts';+import type { HarnessRoot } from '../src/core/transcripts/detect.ts';+import { MESSAGE_CHAR_CAP } from '../src/core/transcripts/render.ts';+import { buildTranscriptSlug } from '../src/core/transcripts/types.ts';+import { buildHermesFixture } from './fixtures/transcripts/hermes-fixture-builder.ts';const CODEX_SLUG = buildTranscriptSlug('codex', '2026-08-02T09:00:00.000Z', {sessionId: 'rollout-1', // payload.id — the per-thread id (#4981)@@ -34,32 +38,28 @@ const AGENT_SLUG = buildTranscriptSlug('openclaw', '2026-08-03T14:00:00.000Z', {sessionId: 'agent-fixture-session-1',});-const CODEX_FIXTURE = join(import.meta.dir, '..', 'fixtures', 'transcripts', 'codex-rollout.jsonl');-const AGENT_FIXTURE = join(import.meta.dir, '..', 'fixtures', 'transcripts', 'agent-session.jsonl');+const CODEX_FIXTURE = join(import.meta.dir, 'fixtures', 'transcripts', 'codex-rollout.jsonl');+const AGENT_FIXTURE = join(import.meta.dir, 'fixtures', 'transcripts', 'agent-session.jsonl');const CLAUDE_CODE_FIXTURE = join(import.meta.dir,- '..','fixtures','conversation-formats','claude-code.jsonl',);const CHATGPT_FIXTURE = join(import.meta.dir,- '..','fixtures','transcripts','chatgpt-conversations.json',);const CLAUDE_EXPORT_FIXTURE = join(import.meta.dir,- '..','fixtures','transcripts','claude-export.json',);const GROK_FIXTURE = join(import.meta.dir,- '..','fixtures','transcripts','grok-session',diff --git a/test/e2e/upgrade-bun-link-arc.serial.test.ts b/test/upgrade-bun-link-arc.serial.test.tssimilarity index 97%rename from test/e2e/upgrade-bun-link-arc.serial.test.tsrename to test/upgrade-bun-link-arc.serial.test.tsindex 67db2c28e2..898eef1681 100644--- a/test/e2e/upgrade-bun-link-arc.serial.test.ts+++ b/test/upgrade-bun-link-arc.serial.test.ts@@ -48,7 +48,11 @@* child runs. The real repo is never touched.** Serial: test 1 mutates process.argv[1] file-wide (restored in afterEach);- * run-e2e.sh runs each e2e file in its own bun process regardless.+ * the serial lane runs each file in its own bun process.+ *+ * Lane: serial. Run: `bash scripts/run-serial-tests.sh test/upgrade-bun-link-arc.serial.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test, expect, afterEach, afterAll } from 'bun:test';@@ -57,11 +61,11 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSyncimport { join } from 'node:path';import { tmpdir } from 'node:os';-import { detectInstallMethod } from '../../src/commands/upgrade.ts';-import { migrations } from '../../src/commands/migrations/index.ts';-import { VERSION } from '../../src/version.ts';+import { detectInstallMethod } from '../src/commands/upgrade.ts';+import { migrations } from '../src/commands/migrations/index.ts';+import { VERSION } from '../src/version.ts';-const REPO_ROOT = join(import.meta.dir, '..', '..');+const REPO_ROOT = join(import.meta.dir, '..');const CLI_PATH = join(REPO_ROOT, 'src', 'cli.ts');const REAL_UPGRADE_TS = join(REPO_ROOT, 'src', 'commands', 'upgrade.ts');diff --git a/test/upgrade-checkpoint.serial.test.ts b/test/upgrade-checkpoint.serial.test.tsdeleted file mode 100644index ef8adfa21f..0000000000--- a/test/upgrade-checkpoint.serial.test.ts+++ /dev/null@@ -1,214 +0,0 @@-import { describe, expect, test, beforeEach, afterEach } from 'bun:test';-import { mkdtempSync, rmSync, existsSync, writeFileSync } from 'node:fs';-import { join } from 'node:path';-import { tmpdir } from 'node:os';-import {- computeBrainId,- loadCheckpoint,- writeCheckpoint,- clearCheckpoint,- validateCheckpoint,- markStepComplete,- markStepFailed,- ALL_UPGRADE_STEPS,- type UpgradeCheckpoint,-} from '../src/core/upgrade-checkpoint.ts';--let tmpHome: string;-let originalHome: string | undefined;--beforeEach(() => {- tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-upgrade-checkpoint-test-'));- originalHome = process.env.GBRAIN_HOME;- process.env.GBRAIN_HOME = tmpHome;-});--afterEach(() => {- if (originalHome === undefined) delete process.env.GBRAIN_HOME;- else process.env.GBRAIN_HOME = originalHome;- if (existsSync(tmpHome)) rmSync(tmpHome, { recursive: true, force: true });-});--describe('computeBrainId — X2 multi-tenant safety', () => {- test('strips userinfo before hashing — same hash for cred-rotated URL', () => {- const a = computeBrainId('postgresql://user:passA@host:5432/db');- const b = computeBrainId('postgresql://user:passB@host:5432/db');- expect(a).toBe(b);- });-- test('different DBs hash differently', () => {- const a = computeBrainId('postgresql://u:p@host:5432/db_a');- const b = computeBrainId('postgresql://u:p@host:5432/db_b');- expect(a).not.toBe(b);- });-- test('returns a stable 16-char hex string', () => {- const id = computeBrainId('postgresql://u:p@host:5432/db');- expect(id).toMatch(/^[0-9a-f]{16}$/);- });-- test('no URL → still returns a hash (PGLite path)', () => {- const id = computeBrainId(undefined);- expect(id).toMatch(/^[0-9a-f]{16}$/);- });-- test('null URL → same hash as undefined', () => {- const a = computeBrainId(null);- const b = computeBrainId(undefined);- expect(a).toBe(b);- });-});--describe('writeCheckpoint + loadCheckpoint round-trip', () => {- test('writes and reads a complete checkpoint', () => {- const cp: UpgradeCheckpoint = {- brain_id: 'abc123',- started_at: '2026-05-08T00:00:00.000Z',- from_version: '0.30.0',- to_version: '0.30.1',- completed_steps: ['pull', 'install'],- };- writeCheckpoint(cp);- const loaded = loadCheckpoint();- expect(loaded).toEqual(cp);- });-- test('loadCheckpoint returns null when no file', () => {- expect(loadCheckpoint()).toBeNull();- });-- test('loadCheckpoint returns null for malformed JSON', () => {- const cp: UpgradeCheckpoint = {- brain_id: 'abc',- started_at: '2026-05-08T00:00:00.000Z',- from_version: '0.30.0',- to_version: '0.30.1',- completed_steps: [],- };- writeCheckpoint(cp);- // Corrupt the file. gbrainPath resolves to GBRAIN_HOME/.gbrain/<file>.- const path = join(tmpHome, '.gbrain', 'upgrade-checkpoint.json');- writeFileSync(path, 'not json {{');- expect(loadCheckpoint()).toBeNull();- });-- test('clearCheckpoint removes the file', () => {- const cp: UpgradeCheckpoint = {- brain_id: 'abc',- started_at: '2026-05-08T00:00:00.000Z',- from_version: '0.30.0',- to_version: '0.30.1',- completed_steps: [],- };- writeCheckpoint(cp);- expect(loadCheckpoint()).not.toBeNull();- clearCheckpoint();- expect(loadCheckpoint()).toBeNull();- });-});--describe('validateCheckpoint — F4 fall-through + X2 mismatch', () => {- test('F4: no checkpoint → falls through to full upgrade', () => {- const r = validateCheckpoint('any-brain-id');- expect(r.valid).toBe(false);- expect(r.reason).toBe('no_checkpoint');- });-- test('X2: brain mismatch → reason=brain_mismatch', () => {- const cp: UpgradeCheckpoint = {- brain_id: 'brain-A',- started_at: '2026-05-08T00:00:00.000Z',- from_version: '0.30.0',- to_version: '0.30.1',- completed_steps: ['pull'],- };- writeCheckpoint(cp);- const r = validateCheckpoint('brain-B');- expect(r.valid).toBe(false);- expect(r.reason).toBe('brain_mismatch');- expect(r.checkpoint?.brain_id).toBe('brain-A');- });-- test('partial completion → resumeAt = next un-completed step', () => {- const cp: UpgradeCheckpoint = {- brain_id: 'brain-A',- started_at: '2026-05-08T00:00:00.000Z',- from_version: '0.30.0',- to_version: '0.30.1',- completed_steps: ['pull', 'install'],- };- writeCheckpoint(cp);- const r = validateCheckpoint('brain-A');- expect(r.valid).toBe(true);- expect(r.resumeAt).toBe('schema');- expect(r.checkpoint?.brain_id).toBe('brain-A');- });-- test('all steps complete → reason=all_complete', () => {- const cp: UpgradeCheckpoint = {- brain_id: 'brain-A',- started_at: '2026-05-08T00:00:00.000Z',- from_version: '0.30.0',- to_version: '0.30.1',- completed_steps: [...ALL_UPGRADE_STEPS],- };- writeCheckpoint(cp);- const r = validateCheckpoint('brain-A');- expect(r.valid).toBe(false);- expect(r.reason).toBe('all_complete');- });-- test('first step pending → resumeAt = first step', () => {- const cp: UpgradeCheckpoint = {- brain_id: 'brain-A',- started_at: '2026-05-08T00:00:00.000Z',- from_version: '0.30.0',- to_version: '0.30.1',- completed_steps: [],- };- writeCheckpoint(cp);- const r = validateCheckpoint('brain-A');- expect(r.valid).toBe(true);- expect(r.resumeAt).toBe(ALL_UPGRADE_STEPS[0]);- });-});--describe('markStepComplete + markStepFailed', () => {- const base: UpgradeCheckpoint = {- brain_id: 'a',- started_at: '2026-05-08T00:00:00.000Z',- from_version: '0.30.0',- to_version: '0.30.1',- completed_steps: [],- };-- test('markStepComplete appends new step', () => {- const cp = markStepComplete({ ...base }, 'pull');- expect(cp.completed_steps).toEqual(['pull']);- });-- test('markStepComplete is idempotent', () => {- let cp = markStepComplete({ ...base }, 'pull');- cp = markStepComplete(cp, 'pull');- expect(cp.completed_steps).toEqual(['pull']);- });-- test('markStepComplete clears prior failed_step', () => {- const cp: UpgradeCheckpoint = {- ...base,- failed_step: 'pull',- failed_step_error: { message: 'broken' },- };- const out = markStepComplete(cp, 'pull');- expect(out.failed_step).toBeUndefined();- expect(out.failed_step_error).toBeUndefined();- });-- test('markStepFailed sets failed_step + error info', () => {- const err = Object.assign(new Error('timeout'), { code: '57014' });- const cp = markStepFailed({ ...base }, 'schema', err);- expect(cp.failed_step).toBe('schema');- expect(cp.failed_step_error?.message).toBe('timeout');- expect(cp.failed_step_error?.code).toBe('57014');- });-});diff --git a/test/upgrade-skill-publish-prompt-race.test.ts b/test/upgrade-skill-publish-prompt-race.test.tsindex f124b2bd84..5994d990ea 100644--- a/test/upgrade-skill-publish-prompt-race.test.ts+++ b/test/upgrade-skill-publish-prompt-race.test.ts@@ -21,7 +21,7 @@ import { readFileSync } from 'node:fs';import { join } from 'node:path';describe('gbrain upgrade — skill-publish prompt wiring (#4318 residual)', () => {- // test-reads-source-ok: the prompt is inline inside a large, side-effecting,+ // test-reads-source-ok[structural]: the prompt is inline inside a large, side-effecting,// non-exported runUpgrade() with no injectable stdin — resolve/close// ordering is only observable in source text, not an executable boundary.const src = readFileSync(join(import.meta.dir, '../src/commands/upgrade.ts'), 'utf8');diff --git a/test/upgrade.serial.test.ts b/test/upgrade.serial.test.tsindex e4a317eb1b..1dc0bbe5cd 100644--- a/test/upgrade.serial.test.ts+++ b/test/upgrade.serial.test.ts@@ -1,4 +1,4 @@-import { describe, test, expect } from 'bun:test';+import { describe, test, expect, spyOn } from 'bun:test';import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs';import { dirname, join } from 'path';import { tmpdir } from 'os';@@ -8,8 +8,9 @@ import { formatMarker } from '../src/core/self-upgrade.ts';import type { BinarySelfUpdateResult } from '../src/core/binary-self-update.ts';import { VERSION } from '../src/version.ts';-// We can't easily mock process.execPath in bun, so we test the upgrade-// command's --help output and the detection logic via subprocess+// Install-method detection runs in-process where it spawns nothing (argv[1] /+// execPath patched); PATH-shimmed paths (clawhub, bun-link, bun update) run+// runUpgrade in a subprocess, because Bun snapshots PATH at process start.describe('upgrade command', () => {test('--help prints usage and exits 0', async () => {@@ -38,99 +39,58 @@ describe('upgrade command', () => {});});-describe('detectInstallMethod heuristic (source analysis)', () => {- // Read the source and verify the detection order is correct- const { readFileSync } = require('fs');- const source = readFileSync(- new URL('../src/commands/upgrade.ts', import.meta.url),- 'utf-8',- );-- test('checks node_modules before binary', () => {- const nodeModulesIdx = source.indexOf('node_modules');- const binaryIdx = source.indexOf("endsWith('/gbrain')");- expect(nodeModulesIdx).toBeLessThan(binaryIdx);- });-- test('checks binary before clawhub', () => {- const binaryIdx = source.indexOf("endsWith('/gbrain')");- const clawhubIdx = source.indexOf("clawhub --version");- expect(binaryIdx).toBeLessThan(clawhubIdx);- });-- test('uses clawhub --version, not which clawhub', () => {- expect(source).toContain("clawhub --version");- expect(source).not.toContain('which clawhub');- });-- test('has timeout on upgrade execSync calls', () => {- // Count timeout occurrences in execSync calls- const timeoutMatches = source.match(/timeout:\s*\d+/g) || [];- expect(timeoutMatches.length).toBeGreaterThanOrEqual(2); // bun + clawhub detection at minimum- });-- test('return type includes bun-link variant (v0.28.5 cluster D)', () => {- expect(source).toContain("'bun' | 'bun-link' | 'binary' | 'clawhub' | 'unknown'");- });-- test('does not reference npm in case labels or messages', () => {- // Should not have case 'npm' or 'Upgrading via npm'- expect(source).not.toContain("case 'npm'");- expect(source).not.toContain('via npm');- expect(source).not.toContain('npm upgrade');- });-- // v0.28.5 cluster D: 3-signal layered detection.- test('bun-link signal walks .git/config for garrytan/gbrain match', () => {- expect(source).toContain('function detectBunLink');- expect(source).toContain('GBRAIN_GITHUB_REPO');- expect(source).toContain('toLowerCase()');- });-- test('detectBunLink does not gate on isSymbolicLink (bun resolves argv[1])', () => {- // v0.28.5 gated on lstatSync(argv1).isSymbolicLink() which always- // returned false because bun resolves symlinks before setting argv[1].- // The function body between "function detectBunLink" and the next- // top-level function must not contain isSymbolicLink.- const fnStart = source.indexOf('function detectBunLink');- const fnEnd = source.indexOf('\nfunction ', fnStart + 1);- const fnBody = source.slice(fnStart, fnEnd > -1 ? fnEnd : undefined);- expect(fnBody).not.toContain('isSymbolicLink');- expect(fnBody).not.toContain('lstatSync');- });-- test('detectBunLink returns repoRoot, not a string literal', () => {- expect(source).toContain("{ repoRoot: string } | null");- expect(source).toContain('repoRoot: dir');- });+describe('detectInstallMethod — package-install classification (in-process)', () => {+ // The node_modules branch spawns nothing, so argv[1] / execPath are patched+ // in-process (serial file). The bun-link, clawhub and cwd contracts need+ // PATH shims and live in the subprocess suite below.+ const originalArgv1 = process.argv[1];+ const originalExecPath = process.execPath;++ function detectFrom(pkg: Record<string, unknown>, entry: string, execPath?: string) {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-upgrade-detect-'));+ const pkgDir = join(root, 'node_modules', 'gbrain');+ const argv1 = join(pkgDir, entry);+ mkdirSync(dirname(argv1), { recursive: true });+ writeFileSync(join(pkgDir, 'package.json'), JSON.stringify(pkg));+ writeFileSync(argv1, '');+ const warn = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ process.argv[1] = argv1;+ if (execPath) Object.defineProperty(process, 'execPath', { value: execPath, configurable: true, writable: true });+ const method = upgradeModule.detectInstallMethod();+ return { method, warnings: warn.mock.calls.map(c => c.join(' ')).join('\n') };+ } finally {+ warn.mockRestore();+ process.argv[1] = originalArgv1;+ Object.defineProperty(process, 'execPath', { value: originalExecPath, configurable: true, writable: true });+ rmSync(root, { recursive: true, force: true });+ }+ }- test('bun-link upgrade uses execFileSync for shell-injection safety', () => {- // execFileSync with array args bypasses the shell (same pattern as- // dry-fix.ts:172). execSync with template strings is vulnerable to- // paths containing shell metacharacters.- expect(source).toContain("execFileSync('git', ['-C', linkInfo.repoRoot, 'pull', '--ff-only']");- expect(source).toContain("execFileSync('bun', ['install']");+ test('canonical by repository.url: bun, no squatter warning', () => {+ const r = detectFrom({ name: 'gbrain', repository: { url: 'git+https://github.com/GarryTan/GBrain.git' } }, 'dist/cli.js');+ expect(r.method).toBe('bun');+ expect(r.warnings).toBe('');});- test('bun global upgrade passes cwd to bun update', () => {- expect(source).toContain('const bunGlobalRoot = resolveBunGlobalRoot()');- expect(source).toContain("execFileSync('bun', ['update', 'gbrain'], { cwd: bunGlobalRoot");+ test('canonical by shipped src/cli.ts marker when repository is absent', () => {+ const r = detectFrom({ name: 'gbrain' }, 'src/cli.ts');+ expect(r.method).toBe('bun');+ expect(r.warnings).toBe('');});- test('classifyBunInstall checks repository.url AND src/cli.ts marker', () => {- // Codex feedback: repository.url alone is spoofable by future squatter- // updates; the source-marker fallback (src/cli.ts presence) is- // belt-and-suspenders.- expect(source).toContain('function classifyBunInstall');- expect(source).toContain('pkg.repository');- expect(source).toContain("'src', 'cli.ts'");+ test('npm squatter (no repository, no source) warns with clone + release recovery (#658)', () => {+ const r = detectFrom({ name: 'gbrain', version: '1.3.0' }, 'dist/cli.js');+ expect(r.method).toBe('bun');+ expect(r.warnings).toContain('WARNING');+ expect(r.warnings).toContain('git clone https://github.com/garrytan/gbrain.git');+ expect(r.warnings).toContain('https://github.com/garrytan/gbrain/releases');+ expect(r.warnings).toContain('#658');});- test('squatter recovery message names both source-clone AND release-binary paths', () => {- expect(source).toContain('printSquatterRecovery');- expect(source).toContain('git clone');- expect(source).toContain('releases');- expect(source).toContain('#658');+ test('node_modules is checked before the compiled-binary execPath name', () => {+ const r = detectFrom({ name: 'gbrain', repository: 'github:garrytan/gbrain' }, 'dist/cli.js', '/opt/bin/gbrain');+ expect(r.method).toBe('bun');});});@@ -266,14 +226,28 @@ describe('runUpgrade target verification (#4366)', () => {observedVersion: string;targetVersion?: string;binaryResult?: BinarySelfUpdateResult;- }): Promise<{ home: string; exitCode: number; stderr: string }> {+ /** Body of the PATH `clawhub` shim (default: exit 0 for everything). */+ clawhub?: string;+ /** Driver directory relative to the fake HOME (default: HOME itself). */+ driverDir?: string;+ /** Shim `git` and `bun` as recorders appending `<cwd>|<args>` to HOME/calls.log. */+ recordGitAndBun?: boolean;+ /** Lay out extra install-shape files under HOME before the spawn. */+ setup?: (home: string) => void;+ }): Promise<{ home: string; exitCode: number; stdout: string; stderr: string }> {const home = mkdtempSync(join(tmpdir(), 'gbrain-upgrade-target-'));const bin = join(home, 'bin');mkdirSync(bin);- writeFileSync(join(bin, 'clawhub'), '#!/bin/sh\nexit 0\n');+ writeFileSync(join(bin, 'clawhub'), `#!/bin/sh\n${opts.clawhub ?? 'exit 0'}\n`);writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\necho "gbrain ${opts.observedVersion}"\n`);chmodSync(join(bin, 'clawhub'), 0o755);chmodSync(join(bin, 'gbrain'), 0o755);+ if (opts.recordGitAndBun) {+ for (const tool of ['git', 'bun']) {+ writeFileSync(join(bin, tool), `#!/bin/sh\necho "$(pwd)|$*" >> "${join(home, 'calls.log')}"\nexit 0\n`);+ chmodSync(join(bin, tool), 0o755);+ }+ }mkdirSync(join(home, '.gbrain'), { recursive: true });writeFileSync(@@ -283,7 +257,10 @@ describe('runUpgrade target verification (#4366)', () => {// The driver lives OUTSIDE the repo so detectInstallMethod() cannot see a// node_modules/.git ancestor and falls through to the clawhub shim.- const driverPath = join(home, 'driver.ts');+ const driverDir = join(home, opts.driverDir ?? '');+ mkdirSync(driverDir, { recursive: true });+ opts.setup?.(home);+ const driverPath = join(driverDir, 'driver.ts');const mockPrelude = opts.binaryResult? `import { mock } from 'bun:test';\n` +`mock.module('${repoRoot}src/core/binary-self-update.ts', () => ({\n` +@@ -297,7 +274,7 @@ describe('runUpgrade target verification (#4366)', () => {`const t = process.env.TEST_TARGET_VERSION;\n` +`await runUpgrade(['--swap-only'], t ? { targetVersion: t } : {});\n`,);- let bunExec = 'bun';+ let bunExec = process.execPath;if (opts.binaryResult) {bunExec = join(home, 'exec', 'gbrain');mkdirSync(dirname(bunExec));@@ -312,6 +289,7 @@ describe('runUpgrade target verification (#4366)', () => {PATH: `${bin}:${process.env.PATH}`,};delete env.TEST_TARGET_VERSION;+ delete env.BUN_INSTALL;if (opts.targetVersion) env.TEST_TARGET_VERSION = opts.targetVersion;const proc = Bun.spawn([bunExec, 'run', driverPath], {@@ -320,9 +298,9 @@ describe('runUpgrade target verification (#4366)', () => {stdout: 'pipe',stderr: 'pipe',});- const stderr = await new Response(proc.stderr).text();+ const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);const exitCode = await proc.exited;- return { home, exitCode, stderr };+ return { home, exitCode, stdout, stderr };}test('mismatch exits nonzero, keeps the pending-upgrade cache, and records verify-target', async () => {@@ -401,4 +379,84 @@ describe('runUpgrade target verification (#4366)', () => {}});}++ // ── install-method detection + upgrade commands (PATH-shimmed) ──────────++ test('clawhub is detected by running `clawhub --version`, not by PATH presence', async () => {+ // The shim is ON PATH but fails `--version`: a `which clawhub` probe would+ // pick it; the real probe falls through to 'unknown'.+ const { home, stdout, stderr } = await runUpgradeAgainstFakeInstall({+ observedVersion: OLD,+ clawhub: '[ "$1" = "--version" ] && exit 1\nexit 0',+ });+ try {+ expect(stdout).toContain('Detected install method: unknown');+ expect(stderr).toContain('Could not detect installation method.');+ expect(`${stdout}${stderr}`).not.toMatch(/\bnpm\b/);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });++ test('a hung `clawhub --version` probe times out instead of wedging upgrade', async () => {+ const started = Date.now();+ const { home, stdout } = await runUpgradeAgainstFakeInstall({+ observedVersion: OLD,+ clawhub: '[ "$1" = "--version" ] && exec sleep 60\nexit 0',+ });+ try {+ expect(stdout).toContain('Detected install method: unknown');+ expect(Date.now() - started).toBeLessThan(30_000);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ }, 60_000);++ test('bun-link: case-insensitive .git/config marker; git pull + bun install run at the repo root without a shell', async () => {+ // The checkout path carries shell metacharacters: a template-string+ // execSync would run the `touch`; execFileSync passes it through intact.+ const marker = `INJECTED-${process.pid}-${Date.now()}`;+ const repoDir = `clone $(touch ${marker})`;+ const { home, stdout } = await runUpgradeAgainstFakeInstall({+ observedVersion: OLD,+ driverDir: join(repoDir, 'src'),+ recordGitAndBun: true,+ setup: (h) => {+ mkdirSync(join(h, repoDir, '.git'), { recursive: true });+ writeFileSync(join(h, repoDir, '.git', 'config'), '[remote "origin"]\n\turl = https://github.com/GarryTan/GBrain.git\n');+ },+ });+ try {+ const root = join(home, repoDir);+ expect(stdout).toContain('Detected install method: bun-link');+ const calls = readFileSync(join(home, 'calls.log'), 'utf-8').trim().split('\n');+ expect(calls[0]!.split('|')[1]).toBe(`-C ${root} pull --ff-only`);+ expect(calls[1]).toBe(`${realpathSync(root)}|install`);+ for (const dir of [home, repoRoot, join(root, 'src')]) {+ expect(existsSync(join(dir, marker))).toBe(false);+ }+ } finally {+ rmSync(join(repoRoot, marker), { force: true });+ rmSync(home, { recursive: true, force: true });+ }+ });++ test('bun global install: `bun update gbrain` runs in the bun global root', async () => {+ const { home, stdout } = await runUpgradeAgainstFakeInstall({+ observedVersion: OLD,+ driverDir: join('global', 'node_modules', 'gbrain', 'src'),+ recordGitAndBun: true,+ setup: (h) => {+ writeFileSync(join(h, 'global', 'package.json'), '{}');+ writeFileSync(join(h, 'global', 'node_modules', 'gbrain', 'package.json'), JSON.stringify({ name: 'gbrain', repository: 'github:garrytan/gbrain' }));+ },+ });+ try {+ expect(stdout).toContain('Detected install method: bun');+ const calls = readFileSync(join(home, 'calls.log'), 'utf-8').trim().split('\n');+ expect(calls).toEqual([`${realpathSync(join(home, 'global'))}|update gbrain`]);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });});diff --git a/test/e2e/v0_28_5-fix-wave.test.ts b/test/v0_28_5-fix-wave.serial.test.tssimilarity index 94%rename from test/e2e/v0_28_5-fix-wave.test.tsrename to test/v0_28_5-fix-wave.serial.test.tsindex a57945837d..b2e1a70368 100644--- a/test/e2e/v0_28_5-fix-wave.test.ts+++ b/test/v0_28_5-fix-wave.serial.test.ts@@ -31,12 +31,16 @@* is the PGLite-side equivalent specifically for the wedge classes the* v0.28.5 wave fixed.*- * Run: bun test test/e2e/v0_28_5-fix-wave.test.ts+ * Run: bun test test/v0_28_5-fix-wave.serial.test.ts+ *+ * Lane: serial. Run: `bash scripts/run-serial-tests.sh test/v0_28_5-fix-wave.serial.test.ts`. Moved from test/e2e/+ * by the 2026-09 lane-move pilot (PGLite-only, no DATABASE_URL); see+ * docs/TESTING.md "Lane-move pilot".*/import { describe, test, expect } from 'bun:test';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { LATEST_VERSION } from '../../src/core/migrate.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { LATEST_VERSION } from '../src/core/migrate.ts';// Cold-path opt-out: asserts hasPendingMigrations === true on a FRESH brain// before initSchema — a restored snapshot already carries the config.version@@ -46,7 +50,7 @@ delete process.env.GBRAIN_PGLITE_SNAPSHOT;import {readContentChunksEmbeddingDim,embeddingMismatchMessage,-} from '../../src/core/embedding-dim-check.ts';+} from '../src/core/embedding-dim-check.ts';describe('v0.28.5 cluster A — PGLite upgrade wedge regression', () => {test('pre-v0.20 brain (missing v0.20+v0.26.3+v0.27 columns) re-runs initSchema cleanly', async () => {@@ -134,7 +138,7 @@ describe('v0.28.5 cluster A — PGLite upgrade wedge regression', () => {}, 60000);test('hasPendingMigrations correctly reports state across the upgrade lifecycle', async () => {- const { hasPendingMigrations } = await import('../../src/core/migrate.ts');+ const { hasPendingMigrations } = await import('../src/core/migrate.ts');const engine = new PGLiteEngine();await engine.connect({});try {@@ -163,7 +167,7 @@ describe('v0.28.5 cluster B — embedding dim corruption regression', () => {// The wedge: v0.27 silently created vector(1536) regardless of the// --embedding-dimensions flag. v0.28.5 (#641) plumbs the dim through// `getPGLiteSchema(dims)` so the column is templated correctly.- const { configureGateway } = await import('../../src/core/ai/gateway.ts');+ const { configureGateway } = await import('../src/core/ai/gateway.ts');configureGateway({embedding_model: 'openai:text-embedding-3-small',embedding_dimensions: 768,@@ -188,7 +192,7 @@ describe('v0.28.5 cluster B — embedding dim corruption regression', () => {// Codex finding #8: dims > 2000 cannot be HNSW-indexed in pgvector.// The schema templating path must skip the HNSW CREATE INDEX while// still creating the underlying `vector(N)` column.- const { configureGateway } = await import('../../src/core/ai/gateway.ts');+ const { configureGateway } = await import('../src/core/ai/gateway.ts');configureGateway({embedding_model: 'voyage:voyage-4-large',embedding_dimensions: 2048,@@ -231,7 +235,7 @@ describe('v0.28.5 A4 — existing-brain dim mismatch loud failure', () => {// to 1536 so the test still exercises the "existing brain at 1536d"// path it was designed for. This mirrors how a real v0.18-vintage brain// would look post-upgrade.- const { configureGateway, resetGateway } = await import('../../src/core/ai/gateway.ts');+ const { configureGateway, resetGateway } = await import('../src/core/ai/gateway.ts');resetGateway();configureGateway({embedding_model: 'openai:text-embedding-3-large',diff --git a/test/v0_37_fix_wave.serial.test.ts b/test/v0_37_fix_wave.serial.test.tsindex 6ab5fc414e..222b9a3716 100644--- a/test/v0_37_fix_wave.serial.test.ts+++ b/test/v0_37_fix_wave.serial.test.ts@@ -245,12 +245,6 @@ describe('v0.37 Lane C.3 — Voyage key reaches buildGatewayConfig', () => {}});- test('GBrainConfig type includes voyage_api_key field (TS compile guard)', async () => {- const { type } = await import('../src/core/config.ts').then(m => ({ type: undefined }));- // The type-level assertion happens at compile time. If this file- // compiles, the field exists. Body of the test is a runtime no-op.- expect(true).toBe(true);- });});// Lane D.1 — engine-kind branching already covered in test/embedding-dim-check.test.ts@@ -297,11 +291,6 @@ describe('v0.37 deferred TODO shipped — gbrain reinit-pglite', () => {expect(selfHelpMatch![1]).toContain(`'reinit-pglite'`);});- test('reinit-pglite module exports runReinitPglite', async () => {- const mod = await import('../src/commands/reinit-pglite.ts');- expect(typeof mod.runReinitPglite).toBe('function');- });-test('embeddingMismatchMessage PGLite branch recommends `gbrain reinit-pglite`', async () => {const { embeddingMismatchMessage } = await import('../src/core/embedding-dim-check.ts');const msg = embeddingMismatchMessage({diff --git a/test/voyage-response-cap.test.ts b/test/voyage-response-cap.test.tsdeleted file mode 100644index c873ed2231..0000000000--- a/test/voyage-response-cap.test.ts+++ /dev/null@@ -1,98 +0,0 @@-/**- * v0.31.8 — voyage adapter Content-Length pre-check + per-item cap (D2 + D10).- *- * Pre-fix: voyageCompatFetch in src/core/ai/gateway.ts called- * `await resp.clone().json()` BEFORE iterating embeddings. A malicious or- * compromised Voyage response of arbitrary size was fully parsed into the- * JS heap before any cap could fire. The fix adds two layers:- *- * Layer 1 (PRIMARY): Content-Length header pre-check, fires BEFORE- * `resp.clone().json()` so the JSON.parse OOM vector is gated.- * Layer 2 (defense-in-depth): per-embedding base64 length check inside- * the iteration; catches the rare case where Layer 1 was skipped- * because the response uses chunked encoding (no Content-Length).- *- * The cap is 256 MB — sized as "unambiguously not legitimate" (the- * realistic upper bound is voyage-3-large × 16K embeddings ≈ 200 MB raw).- *- * Tests are structural source-string assertions (matches the doctor.test.ts- * style) because voyageCompatFetch is a closed-over helper inside the- * recipe instantiation path and isn't exported. Behavioral coverage of the- * voyage adapter lives in the existing E2E tests that hit a live Voyage- * endpoint; these regression guards pin the SHAPE so a silent revert- * (e.g. moving the cap below the resp.clone().json() call) fails loudly.- */--import { describe, test, expect } from 'bun:test';--describe('v0.31.8 — voyage Content-Length pre-check + per-item cap', () => {- test('MAX_VOYAGE_RESPONSE_BYTES constant is declared at 256 MB (D2 sizing)', async () => {- const source = await Bun.file(new URL('../src/core/ai/gateway.ts', import.meta.url)).text();- // 256 * 1024 * 1024 == 268435456. Either form is acceptable; assert- // both so a silent re-tighten to 64 MB or 128 MB fails this test.- expect(source).toContain('MAX_VOYAGE_RESPONSE_BYTES');- expect(source).toMatch(/MAX_VOYAGE_RESPONSE_BYTES\s*=\s*256\s*\*\s*1024\s*\*\s*1024/);- });-- test('Layer 1: Content-Length pre-check fires BEFORE resp.clone().json() (D10 OOM defense)', async () => {- const source = await Bun.file(new URL('../src/core/ai/gateway.ts', import.meta.url)).text();- // Anchor relative to the post-fetch handler block. The function declaration- // contains an OUTBOUND request body section earlier; we want to verify- // the INBOUND ordering (everything after `await fetch(input, init)`).- const fetchCallIdx = source.indexOf('const resp = await fetch(input, init);');- expect(fetchCallIdx).toBeGreaterThan(0);- const inboundBlock = source.slice(fetchCallIdx, fetchCallIdx + 6000);-- // Pre-check string. Use the actual code shape from gateway.ts so the test- // doesn't pin to comment text.- const preCheckIdx = inboundBlock.indexOf("resp.headers.get('content-length')");- // Use the full lvalue assignment so the match doesn't accidentally hit- // comment text that mentions `await resp.clone().json()` for context.- const jsonParseIdx = inboundBlock.indexOf('const json: any = await resp.clone().json()');- expect(preCheckIdx).toBeGreaterThan(0);- expect(jsonParseIdx).toBeGreaterThan(0);- // The pre-check MUST appear before the JSON parse — otherwise the OOM- // defense is theatrical (the original codex OV8 finding). This is the- // critical structural invariant for D10.- expect(preCheckIdx).toBeLessThan(jsonParseIdx);- });-- test('Layer 1 throws on Content-Length over the cap (not silent return)', async () => {- const source = await Bun.file(new URL('../src/core/ai/gateway.ts', import.meta.url)).text();- // The cap check must throw a VoyageResponseTooLargeError so the inbound- // try/catch at the bottom of voyageCompatFetch rethrows it (instead of- // the pre-fix bare `catch {}` that swallowed `throw new Error(...)` and- // returned the original response — making the cap theatrical).- expect(source).toMatch(/exceeds[^`]*MAX_VOYAGE_RESPONSE_BYTES[^`]*bytes/);- expect(source).toMatch(/throw new VoyageResponseTooLargeError\([\s\S]{0,200}Voyage response Content-Length/);- });-- test('Layer 2: per-embedding base64 cap fires inside the json.data iteration', async () => {- const source = await Bun.file(new URL('../src/core/ai/gateway.ts', import.meta.url)).text();- // Defense-in-depth: even when Content-Length header is missing- // (chunked encoding), each embedding string is bounded.- expect(source).toMatch(/item\.embedding\.length\s*\*\s*0\.75/);- expect(source).toMatch(/throw new VoyageResponseTooLargeError\([\s\S]{0,200}Voyage embedding base64/);- });-- test('inbound try/catch rethrows VoyageResponseTooLargeError (Codex P3 follow-up)', async () => {- const source = await Bun.file(new URL('../src/core/ai/gateway.ts', import.meta.url)).text();- // Critical structural invariant after the Codex P3 fix: the catch- // around the inbound JSON-rewrite block MUST rethrow OOM-cap errors.- // Pre-fix, a bare `catch {}` swallowed the throw and returned the- // original (oversized) response, making Layer 2 ineffective. The- // tagged class + instanceof check restores fail-loud behavior.- expect(source).toContain('VoyageResponseTooLargeError');- expect(source).toMatch(/if\s*\(\s*err\s+instanceof\s+VoyageResponseTooLargeError\s*\)\s*throw\s+err/);- });-- test('comment thread documents both layers + the cap-sizing decision', async () => {- const source = await Bun.file(new URL('../src/core/ai/gateway.ts', import.meta.url)).text();- // Anti-regression: the comment thread is part of the contract. If a- // refactor strips them, future maintainers won't know why the order- // matters or why the cap is 256 MB.- expect(source).toContain('Layer 1');- expect(source).toContain('Layer 2');- expect(source).toMatch(/16K embeddings/);- });-});diff --git a/test/whoknows.test.ts b/test/whoknows.test.tsindex b6319d2af1..3003778405 100644--- a/test/whoknows.test.ts+++ b/test/whoknows.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from 'bun:test';-import { rankCandidates, runWhoknows, findExperts, type WhoknowsResult } from '../src/commands/whoknows.ts';+import { rankCandidates, type WhoknowsResult } from '../src/commands/whoknows.ts';import type { PageType } from '../src/core/types.ts';/**@@ -122,13 +122,6 @@ describe('whoknows / rankCandidates — locked shadow paths (ENG-D3)', () => {]);expect(ranked.map((r) => r.slug)).toEqual(['alice', 'bob', 'zoe']);});-- // Case 10: contract shape — public exports exist and have expected types- it('public surface: rankCandidates / findExperts / runWhoknows are functions', () => {- expect(typeof rankCandidates).toBe('function');- expect(typeof findExperts).toBe('function');- expect(typeof runWhoknows).toBe('function');- });});describe('whoknows / rankCandidates — ranking sanity', () => {diff --git a/test/worker-lock-renewal-shape.test.ts b/test/worker-lock-renewal-shape.test.tsindex 1a77b1c67b..9f297dab38 100644--- a/test/worker-lock-renewal-shape.test.ts+++ b/test/worker-lock-renewal-shape.test.ts@@ -117,10 +117,6 @@ describe('A: launchJob wires the pure tick function', () => {expect(launchJobBody.length).toBeGreaterThan(0);});- test('launchJob calls runLockRenewalTick (the extracted pure function)', () => {- expect(launchJobBody).toMatch(/runLockRenewalTick\s*\(/);- });-test('launchJob constructs the LockRenewalState via the documented helper', () => {// resolveLockRenewalKnobs reads the env knobs (D2). If it disappears// from launchJob, operators can't tune via env vars.