Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge capy/gbra47-test-ci-wave (S0 receipts) into gbra47/lane-a

garrytane337eabb17b3
diff --cc docs/architecture/key-files/engines-1.md
index 3538856a65,d818f1e4b5..3b9ee7812e
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@@ -29,10 -29,10 +29,10 @@@ Current behavior and load-bearing invar
- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration instead of a `getAllSlugs()→getPage(slug)` N+1 (which would silently default to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. `traversePathsDetailed(slug, opts?)` returns `{ paths: GraphPath[], truncated }` — the final SELECT of the path-enumerating recursive CTE is bounded at `TRAVERSE_PATH_ROW_CAP + 1` rows on both engines (the probe row signals overflow; `ORDER BY depth` means the deepest edges are dropped, so a truncated result is still the complete shallow neighbourhood; the cap counts raw rows before the in-memory edge dedup, so `paths.length` alone cannot reveal truncation) and `traversePaths` is its `.paths` projection. Each `GraphPath` carries `from_source_id`/`to_source_id` and the edge dedup keys on page ids; each `traverseGraph` `GraphNode` carries `source_id` (DISTINCT per page), so the same slug in two sources stays two edges or nodes. `resolveSlugWithAliasDetailed(slug, sourceOrSources)` returns `{ canonical_slug, source_id } | null` — the winning alias row AND its owning source under the same scope/precedence rules (`ORDER BY array_position(scope, source_id), id`; null when nothing matches or the `slug_aliases` table does not exist yet); `resolveSlugWithAlias` is its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read to `source_id`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence and offsetting `row_num` past the canonical page's current MAX(row_num) (all rows incl. expired — the partial `idx_facts_fence_key` only excludes NULL; NULL stays NULL) so overlapping fence rows never collide; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. `softDeletePages(slugs, {sourceId}): Promise<string[]>` is the batch soft-delete twin, mirroring `deletePages`' contract exactly (required `sourceId`, `> DELETE_BATCH_SIZE` throws, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): one `UPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING slug` round-trip returning only the slugs that actually flipped active→soft-deleted — the `deleted_at IS NULL` predicate is load-bearing so a re-run never refreshes an already-soft-deleted row's 72h purge clock — and NOTHING cascades (chunks/links/timeline stay behind the read-side `deleted_at` filters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives via `putPage`'s upsert; `deletePage`/`deletePages` remain the purge/teardown primitives). `getStats(opts?)` / `getHealth(opts?)` take an optional `{sourceId?, sourceIds?}` scope (same shape as `sourceScopeOpts` output): omitted = brain-wide; scoped = EVERY counter/coverage/degree confines to the grant, including derived-table counts via their page joins, and link-derived numbers count only edges with BOTH endpoints in scope — so an excluded source's numbers can't be recovered by subtraction. Consumer is the remote-caller ladder in `src/core/ops/admin.ts`; `getHealth` is a one-line delegation to `src/core/engine-sql/health.ts`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, so a new index on `pages` cannot flip ranking on tied scores.
- - `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`).
+ - `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `src/core/engine-sql/bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`).
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The runner (ordering, retry, verify, repair-handler hooks and the static helper imports engine-live paths require) has a plain ratchet ceiling; migrations no longer live in this file.
-- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.serial.test.ts` (real `bun add -g`-shaped hoisted layout).
+- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.test.ts` (real `bun add -g`-shaped hoisted layout).
- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The methods of every migrated storage domain (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh PGLite adapter over `this.db` on every access, so transaction clones run inside their transaction); PGLite-only code stays under `src/core/pglite-engine/`. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; one implementation in `engine-sql/links.ts`) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` retries a failed in-memory `PGlite.create()` once, cold, only while no database is attached. The retry omits the snapshot and clears its loaded flag so `initSchema()` replays the schema. Recovery warns on stderr; exhausted recovery retains both error diagnostics. Post-open setup errors instead close the existing database, preserving close-poison and ownership rules. The doctor scratch probe is a separate disk-backed path and does not use this retry. Remaining initialization failures use the existing classifier and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown; it presents like a macOS WASM bug but is not one), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, per the engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` awaits mandatory resident-consumer stops, closes admission on tracked query/exec/transaction handles, drains admitted statements and best-effort background work, then awaits CHECKPOINT and close before kernel release. A deadline reports `pglite_closing` while actual shutdown continues with ownership retained; a failed close poisons reconnect until process exit. The out-of-band watchdog remains available for event-loop wedges. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying PGLITE_SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (see its entry) with the PGLite dialect hooks; no-op on fresh installs and current brains (this is what keeps an upgrade from wedging on a forward-referenced column). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode`: PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and links the upstream tracking issue; `unknown` is platform-gated). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` (in `engine-sql/pages.ts`) bind `slug = ANY($1::text[])`, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); one SQL copy in `src/core/engine-sql/chunks.ts`, shared with PostgresEngine. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and the chunk upsert (`engine-sql/chunks.ts` `upsertChunksOnce`, behind `_upsertChunksOnce`), line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass. `getRawData` pushes `p.deleted_at IS NULL` into its `where[]` unless `opts.includeDeleted` — parity twin of the Postgres `alive` fragment; see the postgres-engine.ts entry. Outermost `transaction()` calls run `PgliteCheckpointGuard` (`src/core/pglite-engine/checkpoint-guard.ts`) before BEGIN: when WAL since the last redo point passes half the automatic-checkpoint distance (256 MB with the default 1 GB `max_wal_size`) it issues a top-level `CHECKPOINT` (each probe is queued with its own transaction, so concurrent callers see their predecessors' WAL, and the whole guarded operation is admitted once into the datastore's shutdown drain), because PGLite runs the automatic checkpoint inline inside the WAL write that crosses the trigger and that nested checkpoint spins forever (#5449/#5284). Savepoint transactions never checkpoint; the direct read-only vector-search transaction and other direct driver transactions are not guarded. A failed WAL probe proceeds with a once-per-process warning; a failed `CHECKPOINT` refuses before BEGIN with a `GBrainError` naming `gbrain pglite-repair`. Tests: `test/pglite-checkpoint-guard.test.ts`; the large-store harness `scripts/pglite-checkpoint-harness/supervisor.ts` (external supervisor, WAL-bound assertion) runs outside CI.
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers every BrainEngine method whose SQL has not moved to `src/core/engine-sql/` (rows in `scripts/engine-sql-baseline.tsv`); each storage feature lands as a parity twin in both engines (search arms, graph traversal caps, source-scoped stats and health, page lifecycle and soft delete, chunk writes, statement-cache and WAL-checkpoint lifecycle); refactor wave 1 moves shared SQL to `src/core/engine-sql/`.
diff --cc scripts/lib/test-env.sh
index 665e4ac498,ca796cbb81..7ef8b81e0d
--- a/scripts/lib/test-env.sh
+++ b/scripts/lib/test-env.sh
@@@ -105,15 -105,87 +105,100 @@@ ensure_default_pglite_snapshot()
echo "[$label] default PGLite snapshot active: $GBRAIN_TEST_DEFAULT_SNAPSHOT" >&2
}
+# ──────────────────────────────────────────────────────────────────────────
+# Coverage wait multiplier: bun's lcov instrumentation slows the code under
+# test while test deadlines stay wall-clock, so a coverage lane (COVERAGE_DIR
+# set) exports GBRAIN_TEST_WAIT_MULTIPLIER=2 unless the caller chose a value.
+# test/helpers/wait-for.ts scales every waitFor deadline by it and keeps the
+# result below bun's 60s per-test timeout. The bun preload keeps GBRAIN_TEST_*
+# and run-e2e.sh's env scrub keep-lists the name. Runs when this file is
+# sourced, so every runner that sources it gets the same default.
+# ──────────────────────────────────────────────────────────────────────────
+if [ -n "${COVERAGE_DIR:-}" ] && [ -z "${GBRAIN_TEST_WAIT_MULTIPLIER:-}" ]; then
+ export GBRAIN_TEST_WAIT_MULTIPLIER=2
+fi
++
+ # ──────────────────────────────────────────────────────────────────────────
+ # Executed-test receipts (X2). With GBRAIN_TEST_RECEIPT_DIR set, every bun
+ # invocation a runner makes records one receipt in that directory:
+ # <id>.receipt key=value lines: lane, kind (primary|rerun|rescue),
+ # shard/of, arm, sha, run_id, run_attempt, started, and
+ # exit= once the invocation returns
+ # <id>.files the test files assigned to the invocation
+ # <id>.junit.xml Bun's native JUnit report (--reporter=junit)
+ # scripts/ci-executed-counts.ts reads them: an assigned file with no valid
+ # JUnit from any attempt is `incomplete`, and a later attempt (rerun/rescue)
+ # supersedes an earlier one for the files it re-ran.
+ #
+ # receipts_init captures the directory and lane, then UNSETS both variables so
+ # test processes (and the nested runners some tests start) never inherit
+ # them; a runner that starts another runner passes
+ # GBRAIN_TEST_RECEIPT_DIR="$TEST_RECEIPT_DIR" explicitly.
+ # GBRAIN_TEST_RECEIPT_DIR receipt directory (unset = receipts off)
+ # GBRAIN_TEST_RECEIPT_LANE overrides the runner's default lane name
+ # ──────────────────────────────────────────────────────────────────────────
+ receipts_init() {
+ TEST_RECEIPT_LANE="${GBRAIN_TEST_RECEIPT_LANE:-$1}"
+ TEST_RECEIPT_DIR="${GBRAIN_TEST_RECEIPT_DIR:-}"
+ unset GBRAIN_TEST_RECEIPT_DIR GBRAIN_TEST_RECEIPT_LANE
+ RECEIPT_ID=""
+ RECEIPT_ARGS=()
+ [ -n "$TEST_RECEIPT_DIR" ] || return 0
+ case "$TEST_RECEIPT_DIR" in /*) ;; *) TEST_RECEIPT_DIR="$PWD/$TEST_RECEIPT_DIR" ;; esac
+ mkdir -p "$TEST_RECEIPT_DIR" || {
+ echo "[receipts] cannot create $TEST_RECEIPT_DIR; receipts are required when GBRAIN_TEST_RECEIPT_DIR is set" >&2
+ return 1
+ }
+ TEST_RECEIPT_SHA="${GITHUB_SHA:-$(git rev-parse HEAD 2>/dev/null || echo unknown)}"
+ }
+
+ # receipt_begin <kind> <tag> <shard> <of> <arm> [file...]
+ # Sets RECEIPT_ID and RECEIPT_ARGS (the bun reporter flags; empty when
+ # receipts are off). <tag> must be unique per invocation within the lane.
+ receipt_begin() {
+ local kind="$1" tag="$2" shard="$3" of="$4" arm="$5" id n=1
+ shift 5
+ RECEIPT_ID=""
+ RECEIPT_ARGS=()
+ [ -n "${TEST_RECEIPT_DIR:-}" ] || return 0
+ id="${TEST_RECEIPT_LANE}--${tag}--${kind}"
+ while [ -e "$TEST_RECEIPT_DIR/$id.receipt" ]; do
+ n=$((n + 1))
+ id="${TEST_RECEIPT_LANE}--${tag}--${kind}-$n"
+ done
+ {
+ echo "version=1"
+ echo "lane=$TEST_RECEIPT_LANE"
+ echo "kind=$kind"
+ echo "tag=$tag"
+ echo "shard=$shard"
+ echo "of=$of"
+ echo "arm=$arm"
+ echo "sha=$TEST_RECEIPT_SHA"
+ echo "root=$PWD"
+ echo "run_id=${GITHUB_RUN_ID:-}"
+ echo "run_attempt=${GITHUB_RUN_ATTEMPT:-}"
+ echo "job=${GITHUB_JOB:-}"
+ echo "started=$(date +%s)"
+ } > "$TEST_RECEIPT_DIR/$id.receipt"
+ if [ "$#" -gt 0 ]; then printf '%s\n' "$@" > "$TEST_RECEIPT_DIR/$id.files"; else : > "$TEST_RECEIPT_DIR/$id.files"; fi
+ RECEIPT_ID="$id"
+ RECEIPT_ARGS=(--reporter=junit "--reporter-outfile=$TEST_RECEIPT_DIR/$id.junit.xml")
+ }
+
+ # receipt_end <exit-code>: records how the invocation returned. A receipt
+ # without exit= was interrupted before its runner saw the result.
+ receipt_end() {
+ [ -n "${TEST_RECEIPT_DIR:-}" ] && [ -n "${RECEIPT_ID:-}" ] || return 0
+ echo "exit=$1" >> "$TEST_RECEIPT_DIR/$RECEIPT_ID.receipt"
+ }
+
+ # receipt_empty <tag> <shard> <of>: this invocation was assigned no files.
+ # Keeps an empty shard from reading as a missing one.
+ receipt_empty() {
+ receipt_begin primary "$1" "$2" "$3" ""
+ [ -n "${RECEIPT_ID:-}" ] || return 0
+ echo "empty=1" >> "$TEST_RECEIPT_DIR/$RECEIPT_ID.receipt"
+ receipt_end 0
+ RECEIPT_ARGS=()
+ }
diff --cc scripts/run-e2e.sh
index 78c6a4e6db,13a3b2a485..5fef6c59ce
--- a/scripts/run-e2e.sh
+++ b/scripts/run-e2e.sh
@@@ -151,7 -157,7 +157,8 @@@ for _e2e_var in $(env | grep -oE '^(CON
GBRAIN_TEST_DB) ;; # explicit schema-reset opt-in for service hosts; schema-drift still requires a test-shaped DB name
GBRAIN_PGBOUNCER_URL|GBRAIN_PGBOUNCER_DIRECT_URL|GBRAIN_CI_REQUIRE_PGBOUNCER) ;; # explicit pooler test target and execution requirement
GBRAIN_PGBOUNCER_E2E_URL|GBRAIN_PGBOUNCER_E2E_DB) ;; # backend-matrix pooled target (scripts/e2e-backend-matrix.txt)
+ GBRAIN_TEST_WAIT_MULTIPLIER) ;; # coverage deadline multiplier read by test/helpers/wait-for.ts — keep
+ GBRAIN_TEST_REQUIRE_COMPILE) ;; # bootstrap-compiled-binary opt-in: a failed compile fails instead of skipping
GBRAIN_E2E_FILE_TIMEOUT) ;; # per-file cap override — read AFTER this scrub, so it must survive it
GBRAIN_E2E_ALLOW_DB) ;; # #3485 name-floor opt-in — the guard's own error
# message tells operators to set it; stripping it
diff --cc scripts/serial-files.tsv
index 80f4f02269,0000000000..730cd477d9
mode 100644,000000..100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@@ -1,344 -1,0 +1,345 @@@
+# Every *.serial.test.ts file outside test/e2e, with the reason it cannot share a bun process.
+# class: R1 (process.env mutation) | R2 (mock.module) | global-state (other process-wide state) | exclusive (EXCLUSIVE_FILES in scripts/run-serial-tests.sh).
+# Before adding a row, run: bash scripts/check-test-isolation.sh --as-parallel <file> (docs/TESTING.md#when-to-quarantine-instead-of-fix)
+path class reason
+test/admin-grant-outcome.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; binds local servers/ports
+test/advisor-backup-coverage.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_BACKUP_CHECK)
+test/agent-error-surfaces.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/agent-harness-seed.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/agent-injection-http-view.serial.test.ts global-state global-state: binds local servers/ports
+test/agent-install-backup.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; spyOn fs.renameSync, PGLiteEngine.prototype.connect, console.log
+test/agent-install-follow-setup.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/agent-journey-recovery.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/agent-journey-tier2.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/agent-journey-upgrade.serial.test.ts global-state global-state: binds local servers/ports
+test/agent-journey.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/agent-operator-gate-fixes.serial.test.ts global-state global-state: binds local servers/ports
+test/agent-recovery-consent-journeys.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/ai/gateway-ledger-records.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests, __setEmbedTransportForTests, __setRerankTransportForTests; configureGateway changes the process-wide AI gateway
+test/ai/gateway-model-sources.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
+test/ai/header-transport.serial.test.ts global-state global-state: process-wide test seams __setRerankTransportForTests; configureGateway changes the process-wide AI gateway
+test/ai/no-batch-cap-suppression.serial.test.ts global-state global-state: process-wide test seams __setTestRecipesForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
+test/ambient-recall-hooks.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_HOOKS)
+test/ambient-writeback-lifecycle.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/apply-migrations-safety.serial.test.ts R2 R2: mock.module(dynamic specifier) replaces modules for every file in the process
+test/attendance-repair-cli.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; binds local servers/ports
+test/audit-parser-probe.serial.test.ts R1 R1: mutates process.env (GBRAIN_AUDIT_DIR)
+test/audit-slug-fallback.serial.test.ts R1 R1: mutates process.env (GBRAIN_AUDIT_DIR)
+test/audit-synopsis.serial.test.ts R1 R1: mutates process.env (GBRAIN_AUDIT_DIR)
+test/auth-rescope-token.serial.test.ts global-state global-state: binds local servers/ports
+test/autopilot-cycle-connector.serial.test.ts R2 R2: mock.module(../src/core/cycle.ts) replaces modules for every file in the process
+test/autopilot-fanout-clamp.serial.test.ts R1 R1: mutates process.env (GBRAIN_AUDIT_DIR)
+test/autopilot-launchd-lifecycle.serial.test.ts exclusive exclusive: launchd/cron lifecycle arc: install → self-disable → reinstall → uninstall ordering against (PATH-shimmed) launchctl; the arc asserts machine-level sequencing and is the flake-class canary.
+test/backfill-concurrency-clamp.serial.test.ts R1 R1: mutates process.env (GBRAIN_DIRECT_POOL_SIZE)
+test/backup-cli.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_BACKUP_CHECK)
+test/backup-coverage.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_BRAIN_ID)
+test/backup-fsync.serial.test.ts global-state global-state: spyOn fs.fsyncSync, fs.openSync, privacy.protectNewBackupPath, childProcess.execFile
+test/backup-invalidation.serial.test.ts R1 R1: mutates process.env (HOME, GBRAIN_HOME, GBRAIN_GIT_ALLOW_FILE_TRANSPORT, GBRAIN_ALLOW_UNVERIFIED_REMOTE (+2 more))
+test/backup-portability-native.serial.test.ts R1 R1: mutates process.env (SystemRoot)
+test/backup-status-file.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_BACKUP_CHECK_DAYS, GBRAIN_BACKUP_CHECK, GBRAIN_FORCE_BACKUP_NAG (+2 more))
+test/backup-verification.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/binary-self-update-compiled.serial.test.ts global-state global-state: compile smoke gated by GBRAIN_SELFUPDATE_COMPILE_SMOKE
+test/bootstrap-dispatcher.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, CODEX_HOME, HOME, CLAUDE_CONFIG_DIR)
+test/bootstrap-harness-lifecycle.serial.test.ts global-state global-state: patches process stdout/stderr/console
+test/bootstrap-harness.serial.test.ts global-state global-state: patches process stdout/stderr/console
+test/bootstrap-hook-under-serve.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_SOURCE, GBRAIN_DATABASE_URL, DATABASE_URL (+3 more))
+test/bootstrap-interview.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/bootstrap-opencode-door.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, XDG_CONFIG_HOME)
+test/bootstrap-plugin-lane.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, CODEX_HOME, CLAUDE_CONFIG_DIR, HOME)
+test/bootstrap-seat.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/bootstrap-status.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GB_FAKE_RECORD, PATH, GB_FAKE_GH_ANSWER)
+test/bootstrap-subcommand-help.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/bootstrap-uninstall.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/bootstrap-verify.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/brain-durability-hook.serial.test.ts exclusive exclusive: hardenBrainRepo({installCron:true}) executes REAL launchctl/crontab (src/core/brain-repo-durability.ts) — a concurrent or killed run could strand a real scheduled job on the machine.
+test/brain-flag-routing.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/brain-registry.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/brain-repo-durability.serial.test.ts exclusive exclusive: hardenBrainRepo's own scaffolding commit fires the just-installed post-commit hook (background push) which races the synchronous push-probe on the same bare remote ("cannot lock ref" → needs_attention non-empty). The race is intra-call; pooled CPU contention widens the window past what the assertions tolerate (observed on a 4-vCPU CI runner, never locally). Sequential lane restores master-era timing until the probe learns to retry ref-lock contention.
+test/brainstorm/checkpoint.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/check-update-refresh.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/checkpoint-harvest.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, CLAUDE_CONFIG_DIR)
+test/cli-dispatch-lifecycle.serial.test.ts R2 R2: mock.module(../src/core/engine-factory.ts, ../src/commands/orphans.ts, ../src/commands/salience.ts, ../src/commands/serve.ts (+4 more)) replaces modules for every file in the process
+test/code-callers-pin.serial.test.ts global-state global-state: spyOn console.log, console.error, process.exit; process.chdir changes the shared cwd
+test/code-def-refs-pin.serial.test.ts global-state global-state: spyOn console.log, console.error, process.exit; process.chdir changes the shared cwd
+test/company-brain-connect-cli.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/company-brain-recovery.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/config-db-plane.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_DATABASE_URL, DATABASE_URL)
+test/connection-manager.serial.test.ts R1 R1: mutates process.env (GBRAIN_DISABLE_DIRECT_POOL, GBRAIN_DIRECT_POOL_SIZE, GBRAIN_DIRECT_DATABASE_URL)
+test/connectors-credentials.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/consent-table.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/context-engine-checkpoint.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_MEMORABLE_CONFIG, MEMORABLE_BIN, GBRAIN_MEMORABLE)
+test/context-pack-wb-lane.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/contextual-retrieval-doctor.serial.test.ts R1 R1: mutates process.env (GBRAIN_AUDIT_DIR)
+test/contextual-synopsis-model.serial.test.ts global-state global-state: process-wide test seams __setGenerateTextTransportForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
+test/core/audit-week-file.serial.test.ts R1 R1: mutates process.env (GBRAIN_AUDIT_DIR)
+test/core/cycle.serial.test.ts R2 R2: mock.module(../../src/commands/lint.ts, ../../src/commands/backlinks.ts, ../../src/commands/sync.ts, ../../src/commands/extract.ts (+3 more)) replaces modules for every file in the process
+test/core/remediation-checkpoint.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/creds-vault.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/cross-modal-hybrid-integration.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway
+test/cycle-lock-release-diagnostic.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/cycle-lock-steal.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_CYCLE_LOCK_REFRESH_MS)
+test/cycle-patterns-completed-outcome.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts, ../src/core/cycle/synthesize.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the process
+test/cycle-patterns-evidence-gate.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts, ../src/core/cycle/synthesize.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the process
+test/cycle-pglite-lock-ordering.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/cycle-start-recovery-throw.serial.test.ts R2 R2: mock.module(../src/core/minions/queue.ts) replaces modules for every file in the process
+test/cycle/cycle-sync-uncommitted-warn.serial.test.ts R2 R2: mock.module(../../src/commands/sync.ts) replaces modules for every file in the process
+test/cycle/global-freshness-postcondition.serial.test.ts R2 R2: mock.module(../../src/commands/embed.ts, ../../src/core/ai/gateway.ts, ../../src/core/cycle/inline-drain.ts) replaces modules for every file in the process
+test/db-repair.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_DATABASE_URL, DATABASE_URL, GBRAIN_BRAIN_ID (+1 more))
+test/decide/cli.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/decide/conflict-proposals.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
+test/decide/conflict-relink-handoff.serial.test.ts global-state global-state: process-wide test seams __setDecideTransportForTests, __setEmbedTransportForTests, __resetDecideStoreForTests; configureGateway changes the process-wide AI gateway
+test/decide/conflict-sweep.serial.test.ts global-state global-state: process-wide test seams __setDecideTransportForTests, __setEmbedTransportForTests, __resetDecideStoreForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
+test/decide/eval-flags.serial.test.ts R1 R1: mutates process.env (GBRAIN_DECIDE_SLOTS)
+test/decide/evidence-copack-calibration.serial.test.ts global-state global-state: process-wide test seams __setDecideTransportForTests, __resetDecideStoreForTests; configureGateway changes the process-wide AI gateway; spyOn console.log, console.error
+test/decide/grounding-slot.serial.test.ts global-state global-state: process-wide test seams __setDecideTransportForTests, __resetDecideStoreForTests; configureGateway changes the process-wide AI gateway
+test/decide/judge-agreement-cli.serial.test.ts R1 R1: mutates process.env (TYPESAFE_API_KEY, JEV_TYPESAFE_API_KEY)
+test/decide/quickstart-doc.serial.test.ts R2 R2: mock.module(../../src/core/interaction.ts) replaces modules for every file in the process
+test/decide/retrieval-search.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/decide/retrieval-think.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/decide/search-slots.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/decide/status-no-entity.serial.test.ts global-state global-state: patches process stdout/stderr/console
+test/decide/triage-slot.serial.test.ts global-state global-state: process-wide test seams __setDecideTransportForTests, __setChatTransportForTests, __resetDecideStoreForTests; configureGateway changes the process-wide AI gateway
+test/decide/turn-context-s6.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/decide/writepath-datasets.serial.test.ts global-state global-state: process-wide test seams __setDecideTransportForTests, __resetDecideStoreForTests; configureGateway changes the process-wide AI gateway; spyOn console.log, console.error, process.stdout.write
+test/decide/writepath-phase.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests, __setDecideTransportForTests, __resetDecideStoreForTests; configureGateway changes the process-wide AI gateway
+test/dispatch-response-meta.serial.test.ts R2 R2: mock.module(../src/core/search/hybrid.ts) replaces modules for every file in the process
+test/dispatch-vector-incomplete.serial.test.ts R2 R2: mock.module(../src/core/search/hybrid.ts) replaces modules for every file in the process
+test/doctor-autopilot-fanout-concurrency.serial.test.ts R1 R1: mutates process.env (GBRAIN_AUDIT_DIR)
+test/doctor-backup-coverage.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_BACKUP_CHECK)
+test/doctor-connection-classified.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/doctor-early-stop-golden.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, HOME, GBRAIN_AUDIT_DIR, GBRAIN_SYNC_FAILURES_DIR (+3 more))
+test/doctor-engine-fit.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/doctor-eval-drift-branches.serial.test.ts R2 R2: mock.module(../src/core/eval/drift-watch.ts) replaces modules for every file in the process
+test/doctor-keyless.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway
+test/doctor-mode-matrix.serial.test.ts R1 R1: mutates process.env (HOME, GBRAIN_HOME, GBRAIN_AUDIT_DIR, GBRAIN_SYNC_FAILURES_DIR (+1 more))
+test/doctor-remediation-plan-observational.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/doctor-remote.serial.test.ts global-state global-state: binds local servers/ports
+test/doctor-report-remote.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/dream-drain-failure-summary.serial.test.ts R2 R2: mock.module(../src/core/cycle/extract-atoms-drain.ts) replaces modules for every file in the process
+test/dream-owner-id-threading.serial.test.ts R2 R2: mock.module(../src/core/cycle.ts) replaces modules for every file in the process
+test/dream-postgres.serial.test.ts global-state global-state: spyOn process.exit, console.error
+test/dream-synthesize-chunking.serial.test.ts R1 R1: mutates process.env (ANTHROPIC_API_KEY)
+test/embed-backfill-cli-admission.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; patches process stdout/stderr/console
+test/embed-exit-code-3037.serial.test.ts global-state global-state: binds local servers/ports
+test/embed-input-type-wire.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway
+test/embed-lock-skipped.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/embed-null-signature-warning-5527.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; spyOn console.error
+test/embed-oversize-heal-drain.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/embed-partial-failure-3037.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/embed-quarantine.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/embed-stale-chunkless-pages.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway
+test/embed-stale-dry-run-restamp-5289.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway
+test/embed-stale-signature-pagination.serial.test.ts R1 R1: mutates process.env (GBRAIN_EMBED_CONCURRENCY)
+test/embed-stale-unavailable-snapshot.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway
+test/embed.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/embedding-completion-atomic.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests, __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway
+test/embedding-identity-companions.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; process-wide test seams __setEmbedTransportForTests, __setRerankTransportForTests; configureGateway changes the process-wide AI gateway; spyOn globalThis.fetch
+test/embedding-migration-settle.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; spyOn console.log, console.error
+test/embedding-recovery.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway
+test/embedding-rejection-refund.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway
+test/embedding-truth-predicates.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/embedding-zero-norm-4616.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway
+test/eval-brainbench-decide.serial.test.ts R1 R1: mutates process.env (GBRAIN_DECIDE_SLOTS)
+test/eval-longmemeval-decide.serial.test.ts R1 R1: mutates process.env (GBRAIN_DECIDE_SLOTS)
+test/eval-retrieval-quality-decide.serial.test.ts R1 R1: mutates process.env (GBRAIN_DECIDE_SLOTS)
++test/eval-run-all-outcome.serial.test.ts R2 R2: mock.module(../src/commands/eval-brainbench.ts) replaces modules for every file in the process; spyOn process.stderr.write
+test/eval-takes-quality-runner.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the process
+test/extract-conversation-facts-diagnostics.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests, __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; spyOn console.log, process.exit, concurrency.resolveWorkersWithClamp, console.error (+2 more)
+test/extract-cross-source-links-db.serial.test.ts R1 R1: mutates process.env (bracket or computed key)
+test/extract-endpoint-revision.serial.test.ts global-state global-state: spyOn console.error, process.exit
+test/extract-facts-embed-unavailable.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the process
+test/extract-facts-embed-warn.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the process
+test/extract-include-frontmatter-config.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/facts-backstop-outcome.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, OPENAI_API_KEY, ANTHROPIC_API_KEY)
+test/facts-context-injection.serial.test.ts global-state global-state: process-wide test seams __resetHotMemoryCacheForTests
+test/facts-valid-from-context.serial.test.ts R2 R2: mock.module(../src/core/facts/extract.ts) replaces modules for every file in the process
+test/filing-rules-resolution.serial.test.ts R1 R1: mutates process.env (HOME, GBRAIN_HOME, GBRAIN_GIT_ALLOW_FILE_TRANSPORT)
+test/fix-wave-3-connector-loops.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests; configureGateway changes the process-wide AI gateway
+test/fix-wave-3-managed-embedding.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway
+test/fix-wave-5-mounted.serial.test.ts global-state global-state: binds local servers/ports
+test/foreground-chat-gateway-init.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, OPENAI_API_KEY)
+test/fresh-init-db-extract.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; patches process stdout/stderr/console
+test/fresh-install-pglite.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, VOYAGE_API_KEY, OPENAI_API_KEY)
+test/friction-diff.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_FRICTION_RUN_ID)
+test/fts-language-cache-isolation.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/fts-language-migration.serial.test.ts R1 R1: mutates process.env (bracket or computed key)
+test/fts-language-schema-replay.serial.test.ts R1 R1: mutates process.env (GBRAIN_PGLITE_SNAPSHOT)
+test/fts-language.serial.test.ts R1 R1: mutates process.env (bracket or computed key)
+test/gateway-reconfigure-clobber.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/git-remote-durable.serial.test.ts R1 R1: mutates process.env (GBRAIN_GIT_ALLOW_FILE_TRANSPORT)
+test/git-remote-pull-file-transport.serial.test.ts R1 R1: mutates process.env (GBRAIN_GIT_ALLOW_FILE_TRANSPORT)
+test/google-connect-cmd.serial.test.ts global-state global-state: spyOn console.error; patches process stdout/stderr/console
+test/google-loops-recovery.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
+test/graph-query-thin-client-source-flag.serial.test.ts R2 R2: mock.module(../src/core/config.ts, ../src/core/mcp-client.ts) replaces modules for every file in the process
+test/guarded-http-tls.serial.test.ts global-state global-state: binds local servers/ports
+test/harness-delivery-recovery.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/hook-backup-notice.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_BACKUP_CHECK)
+test/hook-command.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_HOOKS, GBRAIN_HOOK_LANE, GBRAIN_SOURCE (+3 more))
+test/hook-writeback-stop.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_SOURCE)
+test/hybrid-adaptive-dedup-cache-plane.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/hybrid-cache-hit-limit-honors-mode.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/hybrid-cache-scope-poison.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/hybrid-cached-hit-budget-meta.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/hybrid-degraded-cache-meta.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/hybrid-exclude-private-cache-fold.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/hybrid-meta.serial.test.ts R1 R1: mutates process.env (OPENAI_API_KEY)
+test/hybrid-pool-floor.serial.test.ts R1 R1: mutates process.env (OPENAI_API_KEY)
+test/hybrid-reranker-skipped.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_AUDIT_DIR, VOYAGE_API_KEY)
+test/hybrid-salvage.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/hybrid-search-lite.serial.test.ts R1 R1: mutates process.env (OPENAI_API_KEY)
+test/hybrid-search-single-mode-read.serial.test.ts R2 R2: mock.module(../src/core/search/mode.ts) replaces modules for every file in the process
+test/hybrid-since-relative.serial.test.ts R1 R1: mutates process.env (OPENAI_API_KEY)
+test/hybrid-types-cache-skip.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/import-cancellation.serial.test.ts R2 R2: mock.module(../src/core/postgres-engine.ts) replaces modules for every file in the process
+test/import-configured-root-guard.serial.test.ts global-state global-state: spyOn engine.executeRaw
+test/import-connection-budget.serial.test.ts R2 R2: mock.module(../src/core/postgres-engine.ts) replaces modules for every file in the process
+test/import-signature-stamp.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway
+test/import-source-cr-mode.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway
+test/internal-breadth-callers.serial.test.ts R2 R2: mock.module(../src/core/search/hybrid.ts) replaces modules for every file in the process
+test/jobs-child-readiness.serial.test.ts global-state global-state: spyOn console.error
+test/jobs-embed-background-dryrun.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/jobs-embed-background-parity.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/jobs-embed-stall-wiring.serial.test.ts R2 R2: mock.module(../src/commands/embed.ts) replaces modules for every file in the process
+test/jobs-gateway-refresh.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, ANTHROPIC_API_KEY, OPENAI_API_KEY)
+test/jobs-list-get-json.serial.test.ts global-state global-state: patches process stdout/stderr/console
+test/jobs-stats-backpressure.serial.test.ts global-state global-state: patches process stdout/stderr/console
+test/jobs-stats-divergence.serial.test.ts global-state global-state: patches process stdout/stderr/console
+test/jobs-stats-private-queue.serial.test.ts global-state global-state: patches process stdout/stderr/console
+test/keyword-relaxed-fusion.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/link-reads-thin-client-5827.serial.test.ts R2 R2: mock.module(../src/core/config.ts, ../src/core/mcp-client.ts) replaces modules for every file in the process
+test/llm-intent-hybrid-integration.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests; configureGateway changes the process-wide AI gateway
+test/loops-close-fact.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
+test/loops-extract-run.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the process
+test/managed-connector-routing.serial.test.ts global-state global-state: spyOn globalThis.fetch
+test/managed-unsupported-preflight.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the process
+test/mcp-admin-cli.serial.test.ts global-state global-state: spyOn console.log, globalThis.fetch
+test/mcp-backup-nag.serial.test.ts R2 R2: mock.module(../src/core/search/hybrid.ts, ../src/core/search/projection-readiness.ts) replaces modules for every file in the process
+test/memorable-relay.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, MEMORABLE_BIN, GBRAIN_MEMORABLE_CONFIG, GBRAIN_MEMORABLE)
+test/memory-safety-wave.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; binds local servers/ports
+test/migrate-embeddings-ann-deferred-5088.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/migrate-embeddings-boundary.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/migrate-embeddings-dry-run-split-5226.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; spyOn console.log, console.error
+test/migrate-embeddings-flow.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/migrate-embeddings-hardening.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_EMBEDDING_MODEL, GBRAIN_EMBEDDING_DIMENSIONS, GBRAIN_EMBED_LOCK_HEARTBEAT_MS (+3 more))
+test/migrate-embeddings-op-contract.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_EMBEDDING_MODEL, GBRAIN_EMBEDDING_DIMENSIONS)
+test/migrate-embeddings-recovery-cli.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; process-wide test seams __setEmbedTransportForTests
+test/migrate-engine-completeness.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, DATABASE_URL, GBRAIN_DATABASE_URL)
+test/migrate-engine-page-copy-failure.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, DATABASE_URL, GBRAIN_DATABASE_URL)
+test/migrate-engine-pagination.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, DATABASE_URL, GBRAIN_DATABASE_URL)
+test/migrate-quiet-replay.serial.test.ts R1 R1: mutates process.env (GBRAIN_MIGRATE_VERBOSE, GBRAIN_PGLITE_SNAPSHOT)
+test/migration-in-process.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/migration-v0-29-1.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/migrations-fresh-install-audit.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/minions/delegated-execution.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests
+test/model-config.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_MODEL, OPENAI_API_KEY)
+test/models-newer-hint.serial.test.ts R1 R1: mutates process.env (GBRAIN_MODEL)
+test/models-per-task-extract-atoms.serial.test.ts global-state global-state: patches process stdout/stderr/console
+test/models-probe-max-output-tokens.serial.test.ts global-state global-state: binds local servers/ports
+test/native-base-url-fold.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, OPENAI_BASE_URL)
+test/oauth-client-setup.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/observational-startup.serial.test.ts R2 R2: mock.module(../src/cli/commands/repair.ts) replaces modules for every file in the process
+test/openai-latest.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_MODEL_DISCOVERY)
+test/openclaw-context-engine-native.serial.test.ts global-state global-state: binds local servers/ports
+test/ops-run-onboard-scope-gate.serial.test.ts R2 R2: mock.module(../src/core/onboard/checks.ts, ../src/core/remediation/index.ts, ../src/core/onboard/render.ts) replaces modules for every file in the process
+test/page-summary-length.serial.test.ts R1 R1: mutates process.env (GBRAIN_AUDIT_DIR)
+test/pending-write-exit.serial.test.ts global-state global-state: binds local servers/ports
+test/persistence-image-import.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/persistence-publication-native.serial.test.ts global-state global-state: platform-gated (darwin) machine integration
+test/persistence-reconnect.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/persistence-skill-bundles.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/persistence-sync-company.serial.test.ts global-state global-state: spyOn globalThis.fetch
+test/persistence-sync-failures.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; patches process stdout/stderr/console
+test/persistence-sync-options.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; process-wide test seams __setPackLocatorForTests; spyOn globalThis.setInterval
+test/pglite-engine-disconnect.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/pglite-in-memory-create-retry.serial.test.ts R2 R2: mock.module(@electric-sql/pglite) replaces modules for every file in the process
+test/pglite-reconnect.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/pglite-repair-command.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; patches process stdout/stderr/console
+test/pglite-snapshot-timezone.serial.test.ts R1 R1: mutates process.env (GBRAIN_PGLITE_SNAPSHOT)
+test/pglite-wal-repair.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; patches process stdout/stderr/console
+test/projections-drain-cli.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/put-page-push-reporting.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/query-cache-knobs-hash.serial.test.ts R1 R1: mutates process.env (GBRAIN_FTS_LANGUAGE)
+test/query-image-date-readiness.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the process
+test/query-image-flag.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the process
+test/query-image-mode-limit.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the process
+test/query-op-limit-mode-4356.serial.test.ts R2 R2: mock.module(../src/core/search/hybrid.ts) replaces modules for every file in the process
+test/readiness-embedding-enablement.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/recall-budget-policy-thin.serial.test.ts R2 R2: mock.module(../src/core/config.ts, ../src/core/mcp-client.ts) replaces modules for every file in the process
+test/recall-thin-client-fallback.serial.test.ts R2 R2: mock.module(../src/core/config.ts, ../src/core/mcp-client.ts) replaces modules for every file in the process
+test/reconcile-owner-journey.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; binds local servers/ports
+test/reindex-code-max-cost.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway
+test/reindex-code-model-source.serial.test.ts R1 R1: mutates process.env (GBRAIN_NO_CODE_MODEL_NUDGE)
+test/reindex-code-nudge.serial.test.ts R1 R1: mutates process.env (GBRAIN_NO_CODE_MODEL_NUDGE)
+test/reindex-search-vector.serial.test.ts R1 R1: mutates process.env (bracket or computed key)
+test/reindex-trace-transparency.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/remediation-run-extras.serial.test.ts R2 R2: mock.module(../src/core/minions/queue.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the process
+test/remediation-run-loop.serial.test.ts R2 R2: mock.module(../src/core/minions/queue.ts, ../src/core/minions/wait-for-completion.ts, ../src/core/remediation-checkpoint.ts, ../src/core/ai/gateway.ts) replaces modules for every file in the process
+test/remote-privacy-journeys.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; configureGateway changes the process-wide AI gateway; binds local servers/ports
+test/repair-contextual-mode-5621.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/rerank-no-key.serial.test.ts global-state global-state: process-wide test seams __setRerankTransportForTests; configureGateway changes the process-wide AI gateway
+test/schema-cli-database-path.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/schema-engine-isolation.serial.test.ts global-state global-state: spyOn engine.getConfig, engine.searchKeyword, engine.searchVector
+test/schema-pack-load-active.serial.test.ts global-state global-state: process-wide test seams __setPackLocatorForTests
+test/search-multimodal-no-embed.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway
+test/search-telemetry-cache-wiring.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/search/autocut-integration.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway
+test/search/crag-escalation-limit.serial.test.ts R2 R2: mock.module(dynamic specifier) replaces modules for every file in the process
+test/search/hybrid-reranker-integration.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_AUDIT_DIR)
+test/search/operation-expansion-contract.serial.test.ts global-state global-state: spyOn hybrid.hybridSearchCached, console.log
+test/search/output-redaction.serial.test.ts R2 R2: mock.module(../../src/core/eval-capture.ts, ../../src/core/search/hybrid.ts, ../../src/core/ai/gateway.ts, ../../src/core/think/index.ts) replaces modules for every file in the process
+test/search/relational-rerank-pin-hybrid.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/seed-pglite.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/self-upgrade-checkonly.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/serve-http-mcp-dispatch-context.serial.test.ts R2 R2: mock.module(../src/mcp/dispatch.ts) replaces modules for every file in the process
+test/serve-http-run-teardown.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/serve-idle-sweep-source.serial.test.ts R2 R2: mock.module(../src/core/sweep.ts) replaces modules for every file in the process
+test/serve-source-guard.serial.test.ts R1 R1: mutates process.env (GBRAIN_SOURCE)
+test/serve-status-mode.serial.test.ts global-state global-state: binds local servers/ports
+test/serve-sync-embed-drain.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; process-wide test seams __setEmbedTransportForTests, __resetDelegatedSyncForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
+test/serve-sync-ipc-killswitch.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; patches process stdout/stderr/console
+test/serve-sync-runner.serial.test.ts global-state global-state: process-wide test seams __resetDelegatedSyncForTests
+test/session-seat-capture.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_SEAT)
+test/shared-skills-export.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/shared-skills-init.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/shared-skills-migration-cli.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
+test/shared-skills-optimizer.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests; spyOn fs.readFileSync, fs.lstatSync, fs.realpathSync
+test/shared-skills-restore.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/skillopt/cycle-phase-caps.serial.test.ts R2 R2: mock.module(../../src/core/skillopt/orchestrator.ts, ../../src/core/repo-root.ts) replaces modules for every file in the process
+test/skillopt/models-four-paths.serial.test.ts R2 R2: mock.module(../../src/core/skillopt/orchestrator.ts, ../../src/core/repo-root.ts) replaces modules for every file in the process
+test/skillopt/models-plan.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
+test/skillopt/run-skillopt-op.serial.test.ts R2 R2: mock.module(../../src/core/skillopt/orchestrator.ts, ../../src/core/repo-root.ts) replaces modules for every file in the process
+test/sources-push-cli.serial.test.ts R1 R1: mutates process.env (HOME, GBRAIN_HOME, GBRAIN_GIT_ALLOW_FILE_TRANSPORT)
+test/stdio-stderr-redirect.serial.test.ts global-state global-state: patches process stdout/stderr/console
+test/subagent-put-page-rejection.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests; configureGateway changes the process-wide AI gateway; spyOn putPage.handler
+test/sync-cost-gate.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
+test/sync-default-write-guard.serial.test.ts global-state global-state: spyOn console.error, console.log, process.exit
+test/sync-delete-trailing-hyphen.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/sync-failure-ledger.serial.test.ts R1 R1: mutates process.env (HOME, GBRAIN_SYNC_AUTOSKIP_AFTER)
+test/sync-index-matches-tree.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/sync-pull-failed-anchor.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/sync-rename-reconcile.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/sync-resumable-import.serial.test.ts R1 R1: mutates process.env (GBRAIN_SYNC_CHECKPOINT_EVERY, GBRAIN_MAX_CONNECTIONS)
+test/sync-run-ordering.serial.test.ts R1 R1: mutates process.env (GBRAIN_SYNC_CHECKPOINT_EVERY, GBRAIN_SYNC_STALL_ABORT_SECONDS, GBRAIN_SYNC_CHECKPOINT_SECONDS)
+test/sync-soft-delete.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/takes-vector-lifecycle-5885.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway
+test/thin-client-write-errors.serial.test.ts global-state global-state: binds local servers/ports
+test/think-cli-source-flag.serial.test.ts R2 R2: mock.module(../src/core/think/index.ts, ../src/core/config.ts, ../src/core/source-resolver.ts) replaces modules for every file in the process
+test/think-embed-question-wiring.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts, ../src/core/think/index.ts) replaces modules for every file in the process
+test/think-extractive.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests, __setEmbedTransportForTests, __setUsageLogPathForTests
+test/think-gather-adaptive-return.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process
+test/think-gather-autocut.serial.test.ts R2 R2: mock.module(../src/core/search/hybrid.ts) replaces modules for every file in the process
+test/think-temporal-window.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests
+test/unified-multimodal.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway
+test/unsupported-embedding-identity.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; process-wide test seams __setEmbedTransportForTests, __setRerankTransportForTests; configureGateway changes the process-wide AI gateway
+test/upgrade-bun-link-arc.serial.test.ts global-state global-state: patches process stdout/stderr/console
+test/upgrade-no-autopilot.serial.test.ts R2 R2: mock.module(dynamic specifier) replaces modules for every file in the process
+test/upgrade-zero-provider-calls.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; configureGateway changes the process-wide AI gateway; binds local servers/ports
+test/upgrade.serial.test.ts R2 R2: mock.module(${repoRoot}src/core/binary-self-update.ts) replaces modules for every file in the process
+test/v0_28_5-fix-wave.serial.test.ts R1 R1: mutates process.env (GBRAIN_PGLITE_SNAPSHOT)
+test/v0_37_fix_wave.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_EMBEDDING_MODEL, GBRAIN_EMBEDDING_DIMENSIONS, OPENAI_API_KEY (+4 more))
+test/v0_37_gap_fill.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_NON_INTERACTIVE)
+test/worker-lock-renewal-e2e.serial.test.ts R1 R1: mutates process.env (GBRAIN_AUDIT_DIR)
+test/worker-registry.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/workspace-push.serial.test.ts R1 R1: mutates process.env (HOME, GBRAIN_HOME, GBRAIN_GIT_ALLOW_FILE_TRANSPORT, PATH (+1 more))
+test/writeback-nudge.serial.test.ts global-state global-state: patches process stdout/stderr/console
+test/writeback-review-fixes.serial.test.ts global-state global-state: process-wide test seams __resetCheckpointHarvestForTests; patches process stdout/stderr/console
diff --cc scripts/structural-suites.tsv
index dd4ca25c0f,33e1c99208..d2736c9529
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@@ -144,10 -139,10 +139,10 @@@ test/eval-brainbench-e2e.slow.test.ts -
test/eval-brainbench-e2e.slow.test.ts privacy guard violation branches (negative path) 1 exec-scan
test/eval-brainbench-e2e.slow.test.ts render-brainbench-delta.ts (the CI step-summary block) 2 exec-scan
test/eval-brainbench-e2e.slow.test.ts run-all once-per-sweep semantics (decision 16) 1 exec-scan
-test/eval-capture-db-plane.serial.test.ts eval.capture set on the DB plane reaches the runtime gate (#1475) 9 source-surface-helper
+test/eval-capture-db-plane.test.ts eval.capture set on the DB plane reaches the runtime gate (#1475) 9 source-surface-helper
test/eval-synthesize-concepts-routing.test.ts dispatch-layer source pins (routing can’t regress silently) 2 readFileSync,source-surface-helper
test/eval-synthesize-concepts-routing.test.ts subprocess smoke — end-to-end routing 1 source-surface-helper
- test/eval-takes-bootstrap.test.ts corpus integrity 4 readFileSync
+ test/eval-takes-bootstrap.test.ts corpus integrity 5 readFileSync
test/exit-classification.test.ts consumer wire-up — helper used by all 3 sites (no inline filters left) 5 doctor-source-helper,readFileSync,source-surface-helper
test/exit-codes.test.ts exit code table 5 readFileSync
test/export-publication.test.ts (file-level) 6 readFileSync