Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.45.16.0 fix: W0 verified-bug hotfix wave — cycle-lock fencing, queue reaper integrity, 10x test suite (code-smell series) (#4127)

Garry Tan83a4a94c38a3
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index bf78157faf..13d9591552 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.45.15.0 -->
+<!-- gbrain-runbook-stamp: 0.45.16.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5af9e88841..8718d7c5a2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,26 @@
All notable changes to GBrain will be documented in this file.
+## [0.45.16.0] - 2026-08-14
+
+**Fix wave W0: the verified-bug hotfix pass of the code-smell series.** A 10-auditor sweep of the codebase produced 122 findings; the top claims were adversarially verified, and this release fixes every verified live bug — the ones that survived the skeptic pass. Long-running brains get the biggest wins: background cycles can no longer silently run twice, dead background jobs no longer strand their parents, and image search no longer silently degrades after re-embedding. Developers get a test suite that runs 10x faster.
+
+### Fixed
+
+- **The background-cycle lock is now actually refreshed while a cycle runs.** Long phases (synthesis, pattern extraction, consolidation — up to 35-minute waits) previously outlived the 5-minute lock TTL with no heartbeat, so a second cycle could start against the same brain and both would write concurrently — duplicated LLM spend and racy writes on Postgres/Supabase brains. A dedicated refresher now heartbeats the lock, every refresh and release is fenced to the exact acquisition (a recycled PID or a superseded run can never touch a successor's lock — including the PGLite file lock, which is no longer rewritten after a detected steal), and a run that loses its lock stops at the next phase boundary with a structured `lock_stolen` report instead of compounding. The job supervisor treats a fenced miss as certain loss and exits for a clean restart.
+- **Background jobs that die from repeated stalls now notify and unblock their waiting parents.** Previously an aggregator parent whose child was dead-lettered by the stall sweep waited forever; a self-healing sweep also releases parents stranded before the upgrade.
+- **Retried jobs no longer burn their wall-clock budget while waiting in backoff.** Every automatic re-run path — and every parent-unblock path — resets the per-attempt clock, so exponential-backoff retries and long-waiting aggregators aren't dead-lettered before executing a line.
+- **Re-embedding no longer flips image chunks to text.** `gbrain embed --stale` (including the autopilot path) preserved every chunk field except `modality`, silently zeroing image retrieval until the next full import. One shared carry list now serves every re-embed path.
+- **A failed first sync no longer kills the MCP server.** Import preflight failures (missing embedding credentials, unreadable target) now surface as normal tool errors instead of terminating the serving process mid-call.
+- **`gbrain lint --fix` reports the true fix count** (it previously scanned everything twice and reported "0 auto-fixed" after fixing issues) and walks the tree once.
+- **The PGLite repair and re-init confirmation prompts can no longer hang forever** on closed or piped stdin: EOF declines safely, and prompts write to stderr so `--json` output stays clean.
+
+### Changed
+
+- **`bun run test` is ~10x faster** (measured: a full parallel suite run dropped from ~82 to ~8 minutes). The PGLite schema snapshot is now default-on for the everyday test loop, rebuilt automatically when migrations or the pinned embedding shape change, concurrency-safe across parallel shards and workspaces, and refused on any shape mismatch so a wrong fixture can never poison the suite.
+- **CI guards now prove they can fail.** A guard registry classifies all 45 check scripts; self-tested scanner guards run against known-bad fixtures on every verify (the registry tracks fixture coverage for the rest), so a guard whose pattern rots into a permanently-green no-op fails the build instead of masquerading as coverage. Two such rotted patterns were found and fixed in the process, along with three guards that were wired into a registry nobody ran.
+
+To take advantage of v0.45.16.0: upgrade and restart any long-running `gbrain serve`, autopilot, or jobs supervisor/worker daemon so the fenced lock refresh and job-reaper fixes take effect. If you run image search, run `gbrain backfill modality` once after upgrading to restore any image chunks a prior re-embed flipped to text (`gbrain doctor` surfaces the affected count and the exact command). No schema migration and no config changes are required.
## [0.45.15.0] - 2026-08-14
**The queue that drains itself: three background-jobs fixes reported from a downstream agent deployment (upstream issues #2, #3, #4).** A brain whose autopilot cycle stalled mid-run could accumulate byte-identical queued cycles forever while every long job queued before an upgrade died minutes in — and the operator diagnosing it couldn't even find the worker entry point, because `gbrain jobs --help` printed a one-line stub. All three failure modes are closed, and the queue now tells you when it's holding work back.
diff --git a/CLAUDE.md b/CLAUDE.md
index 648b69ccac..7f794457de 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -70,7 +70,11 @@ Per-file detail is in `docs/architecture/KEY_FILES.md`.
- **Engine-live paths avoid runtime dynamic `import()` for helper dependencies.** In
`src/core/pglite-engine.ts`, `src/core/postgres-engine.ts`, and
`src/core/migrate.ts`, dependencies previously reached through runtime dynamic
- imports use static top-level imports. The only current dynamic-`import()` exceptions
+ imports use static top-level imports. Besides the snapshot loader's lazy
+ `require()` cluster in `pglite-engine.ts:tryLoadSnapshot` (fs/crypto/
+ migrate/pglite-schema + one gateway shape lookup — lazy so production
+ builds without the test-fixture path don't eager-load; the guard now
+ matches `require()` calls too), the only dynamic-`import()` exceptions
are the four `ai/gateway.ts` lookups in both engines'
`initSchema()` and `_upsertChunksOnce()` methods; each remains lazy inside a
local `try/catch` because the gateway has a large provider/config closure and,
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 85c29a5b7a..3b84625b9f 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -92,11 +92,11 @@ The canonical reference for test tiers, isolation rules, timing, and the E2E
lifecycle is [`docs/TESTING.md`](docs/TESTING.md). The short version:
```bash
-# Inner edit loop (~85s on a Mac dev box)
-bun run test # parallel 4-shard fan-out (memory-adaptive) + serial post-pass
+# Inner edit loop (~8min full suite on a Mac dev box; single files in seconds)
+bun run test # parallel 4-shard fan-out (memory-adaptive) + serial post-pass; PGLite snapshot default-on
bun test test/markdown.test.ts # specific unit test
-# Pre-push gate (19+ parallel checks + typecheck)
+# Pre-push gate (40+ parallel checks + typecheck)
bun run verify
# Pre-merge sanity (everything CI runs)
@@ -115,7 +115,7 @@ DATABASE_URL=postgresql://postgres:postgres@localhost:5434/gbrain_test bun run t
DATABASE_URL=postgresql://... bun run test:e2e
```
-Use `bun run verify` before pushing. It runs 19+ guard checks in parallel
+Use `bun run verify` before pushing. It runs 40+ guard checks in parallel
(`scripts/run-verify-parallel.sh`), including: banned fork-name leaks
(`scripts/check-privacy.sh`), `JSON.stringify(x)::jsonb` interpolation
patterns (`scripts/check-jsonb-pattern.sh`), `\r` progress bleed to stdout
@@ -124,8 +124,14 @@ patterns (`scripts/check-jsonb-pattern.sh`), `\r` progress bleed to stdout
loop" below), silent fallback to recursive chunking in the compiled binary
(`scripts/check-wasm-embedded.sh`), stale admin-dashboard build artifacts
(`scripts/check-admin-build.sh`), resolver drift on bundled skills
-(`bun run check:resolver`), and typecheck. `bun run check:all` runs the full
-historical sweep including the trailing-newline and exports-count checks.
+(`bun run check:resolver`), and typecheck. The guard REGISTRY is
+`scripts/guards-manifest.tsv`, and `scripts/guard-self-test.sh` (also in
+`verify`) proves each self-tested scanner guard (`selftest=yes` in the
+manifest; coverage ratchets up from the `todo` rows) can actually fail by
+running it against known-bad fixtures — a new `scripts/check-*` guard must be
+registered in the manifest or the build fails. There is no `check:all` script; the
+trailing-newline, exports-count, and no-legacy-getconnection checks run in
+`verify` with everything else.
### Writing tests that survive the parallel loop
diff --git a/TODOS.md b/TODOS.md
index 798a1b4cc6..c6f6c5762d 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,34 @@
# TODOS
+## Code-smell fix-wave deferrals (filed at W0; plan: ~/.claude/plans/system-instruction-you-are-working-encapsulated-eclipse.md)
+
+Each was individually decided as a deferral in the CEO/eng reviews of the
+fix-wave plan; the wave series (W0.5–W9, 3.4, 3.6) tracks its own scope there.
+
+- [ ] **Full engine staged merge** (~10 domains onto shared query modules +
+ Dialect record). **Priority: P2.** Gated on the W9 two-slice pilot criteria
+ (structure+params+results parity on chronicle AND the searchKeyword/CJK
+ hard seam; ≥40% domain LOC cut; Dialect ≤~6 fields; query-builder extension
+ ≤~150 lines). The terminal fix for the engine-divergence/JSONB class —
+ blast radius is the production hot path, hence pilot-gated. Blocked by: W9.
+- [ ] **gateway.ts file split** behind a re-export facade (~121 import sites
+ unmoved). **Priority: P3.** After W8's behavior changes so the split is
+ pure motion; needs the CLAUDE.md engine-dynamic-import exemption-path
+ chasers + check-engine-dynamic-import.sh + build:llms.
+- [ ] **BrainEngine 149-method interface → domain repos** (65 methods have
+ 0-1 callers; 3 already deleted in W3). **Priority: P3.** Shape informed by
+ the W9 pilot's query-module seam.
+- [ ] **Legacy Anthropic-SDK subagent loop deletion.** **Priority: P2.** One
+ release after W8 flips `agent.use_gateway_loop` default ON (flag stays as
+ the revert path for that release).
+- [ ] **Deeper test-suite speedup** beyond the W0 snapshot default-on (which
+ already cut the full parallel suite ~4,900s → ~490s). **Priority: P3.**
+ Revisit with post-W0 timing data; diminishing returns until measured.
+- [ ] **PGLite schema build-time derivation** from SCHEMA_SQL via a named
+ transform list. **Priority: P3.** Only if W3's schema drift TEST proves
+ annoying in practice — the test alone kills the drift bug class (Codex
+ D4.8/D5.23: fresh-schema equivalence ≠ upgrade correctness; old-shape
+ bootstrap fixtures + replay coverage stay regardless).
## Jobs fix-wave follow-ups (filed v0.45.15.0 — upstream issues #2/#3/#4)
- [ ] **P2 — `jobs submit --max-pending` public flag.** maxPending stays an
@@ -1840,18 +1869,14 @@ single canonical `src/core/model-pricing.ts` with `canonicalLookup`.
operator pipes directly into `crontab -e` instead of copy-paste-massage.
~80 LOC. Mirrors `gbrain sync --break-lock` argv shape.
-- **TODO-OPS-2 (P2)**: Lock-loss detection — extend `DbLockHandle.refresh()`
- to throw `LockLostError` on 0 rows affected. Codex caught during the
- v0.41.19.0 plan review: `refresh()` runs `UPDATE ... WHERE holder_pid = pid`
- with no rows-affected check (`db-lock.ts:108-114`, `:151-156`). If the
- TTL expired and another worker took over, the original keeps writing
- silently. v0.41.19.0 ships TTL=5min + active in-phase refresh via
- `buildYieldDuringPhase` which makes the race window much narrower, but
- an `await chat()` call that exceeds the 5min wallclock window can still
- hit it. Fix: `RETURNING id` on the UPDATE + check `rows.length === 0` →
- throw tagged `LockLostError`. Phases catch + abort cleanly (write partial
- progress, return `status: 'fail'` with reason `'lock_lost'`). Behavioral
- contract change with phase-abort fallout; needs its own design pass.
+- [x] **TODO-OPS-2 (P2)**: Lock-loss detection — CLOSED by the W0 fix-wave
+ (code-smell series). `refresh()` now runs a FENCED update (id + holder_pid +
+ epoch-rendered `acquired_at`) with `RETURNING id`, returns `false` on 0
+ rows, and runCycle's steal controller aborts the run at the next boundary
+ with a structured `reason: 'lock_stolen'` partial report (LockStolenError;
+ raced awaits cover the 5 long phases). The supervisor exits LOCK_LOST
+ immediately on a fenced miss. Pinned by `test/db-lock-fencing.test.ts` +
+ `test/cycle-lock-steal.serial.test.ts`.
## v0.41.20.0 status + doctor-categories wave follow-ups (v0.42+)
diff --git a/VERSION b/VERSION
index 4650acc694..f0e272f2b4 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.45.15.0
+0.45.16.0
\ No newline at end of file
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 6a72b85a44..5f5cebfdae 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -7,17 +7,76 @@ only.
### Test command tiers
-Seven test command tiers, each with a clear scope:
+Six test command tiers, each with a clear scope:
| Command | What it runs | Wallclock | When to use |
|---|---|---|---|
-| `bun run test` | Parallel unit-test fast loop. Sharded fan-out via `scripts/run-unit-parallel.sh` (default 4 shards — CPU-detected, clamped to a max of 8; 4 matches CI's fan-out and avoids PGLite WASM-init contention), then a serial pass over `*.serial.test.ts`. Excludes `*.slow.test.ts` and `test/e2e/*`. No pre-checks, no typecheck. Memory-safe by default: total concurrency (shards × intra-shard files) is capped to available memory at `GBRAIN_TEST_MEM_PER_FILE_MB` (default 1536 — a PGLite WASM instance) per concurrent file, and two phantom-failure classes are automatically re-run serially (the rescue pass): failures carrying the WASM out-of-memory signature, and shards killed externally (SIGTERM/SIGKILL well before the shard timeout — sibling workspaces' process cleanup, memory jetsam). Phantoms pass serially and the run goes green with an `oom_rescued` note; real failures fail again serially and stay red. Knobs: `GBRAIN_TEST_NO_MEM_ADAPT=1`, `GBRAIN_TEST_NO_OOM_FALLBACK=1`, `GBRAIN_TEST_MAX_CONCURRENCY` (intra-shard, default 4), `GBRAIN_TEST_SHARD_TIMEOUT` / `GBRAIN_TEST_SHARD_KILL_AFTER`, plus `--shards N` / `--max-concurrency N` / `--dry-run` script args. | a few minutes on a Mac dev box | Inner edit loop. Default. |
+| `bun run test` | Parallel unit-test fast loop. Sharded fan-out via `scripts/run-unit-parallel.sh` (default 4 shards — CPU-detected, clamped to a max of 8; 4 matches CI's fan-out and avoids PGLite WASM-init contention), then a serial pass over `*.serial.test.ts`. Excludes `*.slow.test.ts` and `test/e2e/*`. No pre-checks, no typecheck. Builds/refreshes the PGLite schema snapshot BEFORE the shard fan-out and exports `GBRAIN_PGLITE_SNAPSHOT` so PGLite-booting files restore a baked schema instead of replaying every migration (~10x wallclock on a full run; see "PGLite schema snapshot" below). Opt out: `GBRAIN_NO_SNAPSHOT=1`. Memory-safe by default: total concurrency (shards × intra-shard files) is capped to available memory at `GBRAIN_TEST_MEM_PER_FILE_MB` (default 1536 — a PGLite WASM instance) per concurrent file, and two phantom-failure classes are automatically re-run serially (the rescue pass): failures carrying the WASM out-of-memory signature, and shards killed externally (SIGTERM/SIGKILL well before the shard timeout — sibling workspaces' process cleanup, memory jetsam). Phantoms pass serially and the run goes green with an `oom_rescued` note; real failures fail again serially and stay red. Knobs: `GBRAIN_TEST_NO_MEM_ADAPT=1`, `GBRAIN_TEST_NO_OOM_FALLBACK=1`, `GBRAIN_TEST_MAX_CONCURRENCY` (intra-shard, default 4), `GBRAIN_TEST_SHARD_TIMEOUT` / `GBRAIN_TEST_SHARD_KILL_AFTER`, plus `--shards N` / `--max-concurrency N` / `--dry-run` script args. | a few minutes on a Mac dev box | Inner edit loop. Default. |
| `bun run verify` | CI's authoritative pre-test gate set, fanned out in parallel by `scripts/run-verify-parallel.sh`: the full `check:*` battery (privacy, jsonb, progress, source-id, test-isolation, wasm, …) plus `bun run typecheck`. The `CHECKS` array in that script is the single source of truth — CI literally calls `bun run verify` in a dedicated job. | ~16s (parallel; typecheck dominates) | Before pushing; before `/ship`. |
| `bun run test:full` | `verify && bun run test && bun run test:slow && [smart e2e]`. The local equivalent of "everything CI runs." Smart e2e: runs e2e only when `DATABASE_URL` is set; else loud skip notice to stderr. | ~3-5min depending on slow + e2e | Pre-merge sanity, before opening a PR. |
| `bun run test:slow` | Just the `*.slow.test.ts` set (intentional cold-path correctness checks). | seconds-to-minutes | When touching slow-path code. |
| `bun run test:serial` | Just the `*.serial.test.ts` set (cross-file-contention quarantine; one bun process per file for true module-registry isolation). | ~1s per quarantined file | Debugging a specific quarantined file. |
| `bun run test:e2e` | Real Postgres E2E. Requires Docker + `DATABASE_URL`. Sequential. | ~5-10min | Pre-ship; nightly. |
-| `bun run check:all` | The historical pre-check scripts (chained sequentially in package.json). Overlaps `verify` heavily but is NOT a superset — `verify`'s `CHECKS` array in `scripts/run-verify-parallel.sh` is the authoritative gate; `check:all` keeps a few local-only extras (trailing-newline, exports-count, no-legacy-getconnection). | ~10s | Local-only sweep for the extras. |
+
+There is no `check:all` script anymore — it was a second, hand-synced guard
+registry that drifted from `verify` (three checks were reachable ONLY from it,
+i.e. never ran anywhere). The `CHECKS` array in `scripts/run-verify-parallel.sh`
+is the single execution list, and it now includes the former `check:all`-only
+extras (`check:newlines`, `check:exports-count`, `check:no-legacy-getconnection`).
+The guard REGISTRY is `scripts/guards-manifest.tsv` (see "Guard registry and
+self-test" below).
+
+### PGLite schema snapshot (default-on)
+
+`scripts/build-pglite-snapshot.ts` (`bun run build:pglite-snapshot`) bakes a
+post-`initSchema()` PGLite data dir into `test/fixtures/pglite-snapshot.tar`
+plus a version file; `PGLiteEngine.initSchema()` restores the tar instead of
+replaying the embedded schema + all migrations when the env var
+`GBRAIN_PGLITE_SNAPSHOT` points at it. Both `bun run test`
+(`scripts/run-unit-parallel.sh`, before the shard fan-out) and
+`scripts/ci-local.sh` call the builder unconditionally and export the env var.
+Measured effect: a full parallel suite run drops ~10x (PGLite-booting files go
+~1.63s → ~0.91s each). Properties:
+
+- **Idempotent.** A hash short-circuit exits in ~40ms when the snapshot is
+ fresh, and REBUILDS a stale one. The hash covers `PGLITE_SCHEMA_SQL`, every
+ migration's `sql` + `sqlFor.pglite`, AND each migration `handler`'s function
+ source (`Function.prototype.toString`) — 19+ migrations carry executable
+ handler code with empty `sql` that a sql-only hash cannot see.
+- **Concurrency-safe.** Parallel shard runners / sibling workspaces serialize
+ on an atomic `mkdir` lock (`test/fixtures/.pglite-snapshot.lock`) with
+ staleness-verified takeover of a crashed builder; the tar is written first
+ and the version file last, so a crash can never leave a fresh-looking torn
+ fixture. `GBRAIN_SNAPSHOT_LOCK_TIMEOUT_MS` (default 120000) bounds the
+ waiter; an exhausted waiter facing a still-live lock proceeds unlocked as a
+ last resort (the loader gate below validates the version file, not the tar
+ bytes).
+- **Never authoritative.** The loader (`tryLoadSnapshot` in
+ `src/core/pglite-engine.ts`) verifies the schema hash AND the embedding
+ shape the snapshot was baked with (`dims=` / `model=` lines in the version
+ file) against what this process would create; any mismatch — including a
+ version file without shape lines — warns once and falls through to normal
+ cold init. A wrong fixture can never poison the suite.
+- **Opt out.** `GBRAIN_NO_SNAPSHOT=1` skips the build + env export for a run;
+ the migration-replay canary tests clear the env themselves regardless.
+
+Pinned by `test/snapshot-shape-guard.test.ts` (hash + shape refusal matrix,
+handler-source hash sensitivity).
+
+### Guard registry and self-test
+
+`scripts/guards-manifest.tsv` is THE single registry of `scripts/check-*`
+guards (currently 45), each classified `scanner` (greps/parses repo sources —
+must eventually carry fixtures), `buildfresh`, or `repostate` (build/freshness
+guards are exempt-with-reason, not fixture-tested).
+`scripts/guard-self-test.sh` (`bun run check:guard-self-test`, wired into
+`bun run verify`) proves every `selftest=yes` scanner CAN fail: it runs each
+one against known-bad (must exit non-zero) and known-good (must pass) fixture
+trees under `test/fixtures/guards/<guard>/{bad,good}/` via the
+`GBRAIN_GUARD_ROOT` env seam, and enforces manifest completeness — a new
+`scripts/check-*` script that isn't registered in the manifest fails the
+build. A guard whose pattern rots into a permanently-green no-op now fails CI
+instead of masquerading as coverage.
### Shell dispatch and Windows
@@ -90,7 +149,7 @@ Any change under `skills/` must regenerate it: `bun run scripts/generate-skills-
**This section is the canonical home of the test-isolation discipline** — CONTRIBUTING.md and other docs link here rather than restating the rules.
-The cross-file flake class is enforced statically by `scripts/check-test-isolation.sh`, wired into `bun run verify` and `bun run check:all`. Rules (non-serial unit files only; `*.serial.test.ts` and `test/e2e/*` are skipped):
+The cross-file flake class is enforced statically by `scripts/check-test-isolation.sh`, wired into `bun run verify`. Rules (non-serial unit files only; `*.serial.test.ts` and `test/e2e/*` are skipped):
| Rule | What it bans | Fix |
|---|---|---|
@@ -264,6 +323,15 @@ Unit tests and what they cover:
- `test/longmemeval-sanitize.test.ts` — sanitization parity pinning that `INJECTION_PATTERNS` from `src/core/think/sanitize.ts` is the single source of truth (adding a pattern there must cover both `<take>` framing and `<chat_session>` framing, no per-surface regex drift).
- `test/openai-compat-multimodal.test.ts` — gateway's openai-compatible multimodal path: happy-path single + multi-input embedding, unauthenticated proxy mode, dimension-mismatch guard (throws `AIConfigError` with model id + observed + expected pre-storage), default-dim fallback when recipe declares `default_dims`, HTTP 401 / 400 / malformed-JSON / non-array error paths, regression that the existing Voyage `/multimodalembeddings` recipe still routes through its dedicated path. Hermetic via the `__setEmbedTransportForTests` seam.
- `test/serve-stdio-lifecycle.test.ts` — `MCP_STDIO=1` env guard: stdin EOF does NOT trigger shutdown when the env is set, SIGTERM still does (guard scope is correct), unset env preserves the CLI lifecycle. Exercises the `ServeOptions.mcpStdio?: boolean` test seam directly so tests don't mutate `process.env`.
+- `test/db-lock-fencing.test.ts` — fenced lock identity: a `DbLockHandle` carries its acquisition fence, `refresh()` returns true while owned and false after a steal (0-row fenced UPDATE), a stolen-from handle's `release()` is a fenced no-op that leaves the successor's row intact, and `startCycleLockRefresher` aborts its controller with `LockStolenError` on a fenced miss while serializing ticks (a slow refresh never overlaps the next).
+- `test/cycle-lock-steal.serial.test.ts` — runCycle steal-abort arc end-to-end: a mid-run steal produces a structured partial report (`reason: 'lock_stolen'`), runs no further phases, and never touches the successor's lock row; a steal-free cycle completes and releases normally.
+- `test/cycle-any-abort-signal.test.ts` — `anyAbortSignal` combining: pre-aborted inputs, late aborts propagating their reason, duck-typed signal stubs (no `addEventListener`) observed via poll, and `dispose()` detaching the caller-signal listener + clearing the poll timer (the daemon leak class).
+- `test/queue-stall-parent-unblock.test.ts` — the shared `killJobs` tail: a stall-exhausted child lands `child_done(dead)` in its parent's inbox and unblocks the parent, a requeued child doesn't touch the parent, all three reapers route through the tail with their own outcome, and the idempotent stranded-parent sweep self-heals parents whose children were already dead (without unblocking parents that still have a live child).
+- `test/queue-started-at-retry.test.ts` — every automatic re-run path clears `started_at` (failJob delayed branch, stall requeue, lease release, promoteDelayed, parent re-claim) so a retried job's wall-clock budget measures execution, not backoff wait; end-to-end survival of the wall-clock sweep on a fresh attempt.
+- `test/embed-modality-preserved.test.ts` — `carryChunkMetadata` carries modality + all code-metadata fields through re-embed merges (an image chunk stays image), plus the write-side contract that omitting modality resets it to text (why the shared list is load-bearing).
+- `test/import-abort-error.test.ts` — `runImport` preflight/argv failures throw typed `ImportAbortError` instead of exiting the process; the calling process survives the abort.
+- `test/lint-fix-single-pass.test.ts` — `gbrain lint --fix` walks the tree once and `total_fixed` reports the fixes THIS run applied.
+- `test/snapshot-shape-guard.test.ts` — PGLite snapshot loader refusal matrix: shape-less version files, dims/model mismatches, and stale schema hashes are all refused; matching hash + shape loads; a migration-handler edit changes the hash.
### E2E test inventory
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 7a07155e1f..6685580fa3 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -31,7 +31,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/pglite-lock.ts` — advisory data-dir lock so two processes never open the same embedded PGLite (single-connection WASM Postgres) at once. Atomic `mkdir` of `.gbrain-lock/` + a `lock` file carrying `{pid, acquired_at, refreshed_at, command, subcommand}`. A held lock HEARTBEATS its `refreshed_at` every 30s (`.unref()`ed timer; informational). A waiting acquirer reaps a holder ONLY when its PID is dead — a LIVE holder is NEVER stolen, regardless of how stale its heartbeat is (#2348). A live `gbrain serve` holder is identified from the parsed `subcommand` and reported immediately with separate CLI-retry and MCP-tool choices; other live holders keep the bounded wait. The heartbeat runs on the JS event loop, which is blocked during long synchronous WASM imports/CHECKPOINTs, so a working `dream`/`embed` holder can look stale while alive; the old steal-on-stale-heartbeat grace let a second OS process open the same data dir and corrupt the catalog + pgvector extension (58P01 / `internal_load_library` / `type "vector" does not exist`), recoverable only by wipe+restore. A wedged-but-alive or PID-reused holder is never stolen: serve-tagged holders report immediately, while other holders time out with a message naming the PID. Each holder carries an ownership token (`<pid>:<acquired_at>`); the heartbeat and `releaseLock` verify the on-disk lock is STILL theirs before touching it. In-memory engines take no lock. There is deliberately NO same-process reentrancy or same-PID special case: a second `acquireLock` from the process that already holds the lock waits out the timeout like any other live holder (#1963 was this shape — a command double-connecting a second engine on the same data dir; the fix is to reuse the connected engine at the dispatch layer, never to soften the lock). `LockHandle.reaped` marks an acquisition that reaped a prior holder's lock (dead-PID reap or corrupt-lock-file removal — the only reaps that exist post-#2348); the WAL auto-repair gate refuses to run surgery on a reaped acquisition since a corrupt lock file cannot prove its holder is dead. A corrupt-lock reap ALSO writes a persisted marker (`<dataDir>.lock-reap.json`, read via exported `msSinceLastReap`) so the NEXT process's clean acquisition is still repair-quarantined for 10 minutes — the in-process flag alone let the reaper's successor run surgery under a possibly-live writer; dead-PID reaps (affirmative ESRCH verdict; EPERM reads as ALIVE) deliberately skip the marker so dead-holder recovery stays one-failed-command-plus-one-re-run. Heartbeat refreshes write via tmp+rename (a torn in-place write could be read mid-flight by a polling acquirer and misclassify a HEALTHY live holder as a corrupt lock). Pinned by `test/pglite-lock.test.ts`. A corrupted store surfaces a `reinit-pglite` recovery hint via `classifyPgliteInitError`'s `corrupt` verdict in `pglite-engine.ts`.
- `src/core/pglite-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (ported from electric-sql/pglite PR #994 by @yestheboxer, Apache-2.0, rejected upstream as "should be a separate tool" — gbrain is that tool). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.
- `src/core/pglite-repair.ts` — WAL-repair orchestrator wrapping the resetWal port with the safety layers that make it runnable automatically from `connect()`: `validateWalRepairTarget` (read-only, fail-closed; refuses symlinked dataDir/pg_wal/`global`/pg_control — lstat follows INTERMEDIATE symlinks, so `global/` itself must be checked or surgery would write pg_control through it into a foreign dir; tolerates the in-dir `.gbrain-lock`), rename-based backup (the ENTIRE `pg_wal/` dir + postmaster.pid renamed into a sibling `<dataDir>.wal-repair-backup-<ts>/`, only the 8KB pg_control copied — zero transient disk cost), `restoreWalBackup` (overwrite order: control first via atomic tmp+rename, then a pg_wal dir swap with the reset dir set ASIDE inside the backup — nothing is ever deleted during restore; mtime guard refuses when a foreign segment is newer than the backup; a missing/empty backup NEVER reports `restored:true`), `WalRepairError` (thrown when resetWal fails AFTER the backup — carries the receipt + the best-effort restore's REAL result so the seam's `restored` flag and the `failed-restored`/`failed-not-restored` message arms never lie), a cooldown sidecar `<dataDir>.wal-repair-attempt.json` (skip `'recently-failed'` inside `GBRAIN_PGLITE_WAL_REPAIR_COOLDOWN_SECONDS`, default 3600 — bounds the autopilot/supervisor reconnect loops) with episode-scoped backups (attempts within one corruption episode REUSE the episode's first backup — the pre-damage forensic state, honored only when the sidecar's path is a real non-symlink `<dataDir>.wal-repair-backup-*` sibling since the sidecar is user-writable JSON; retention keeps the newest 3 episodes, never pruning the open episode's), and `attemptWalRepairAndRetry` — the engine seam that NEVER throws (gates: kill-switch → reaped-lock `'possibly-live-writer'` → 10-minute reap-marker quarantine (`msSinceLastReap`, cross-process) → validation → cooldown; then repair → retry create once → restore-and-record on failure; prints a repair-start stderr line so a timeout-killed attempt is self-explaining). `inspectPgliteDataDir` is the read-only diagnosis for `gbrain doctor` + `pglite-repair --dry-run`. Imports runtime values only from `pglite-lock.ts`/`pglite-resetwal.ts`/node:fs — never from `pglite-engine.ts` (no cycle; the engine statically imports THIS file per the #3596 engine-live rule). Pinned by `test/pglite-repair.test.ts` + `test/pglite-wal-repair.serial.test.ts`.
-- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the #2348 concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`.
+- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Its confirmation prompt (and `src/commands/reinit-pglite.ts`'s) writes to stderr so `--json` stdout stays clean, refuses non-TTY stdin in-prompt (defense-in-depth behind the caller-side "Non-TTY environment requires --yes" guard), resolves `false` on EOF/close instead of parking forever on a closed or piped stdin, and cleans up its listeners; `--yes`/`-y` stays the non-interactive path. The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the #2348 concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`.
- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit]`: health checks. Checks include `jsonb_integrity` + `markdown_body_completeness` (reliability), `schema_version` (fails loudly when `version=0`, routes to `gbrain apply-migrations --yes`), `queue_health` (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via `GBRAIN_QUEUE_WAITING_THRESHOLD`, and dead-lettered subagent jobs with `last_error` matching the `prompt_too_long` classifier in last 24h), `sync_failures` (`[CODE=N, ...]` breakdown for unacked-warn + acked-ok; severity comes from the shared `decideSyncFailureSeverity` in `src/core/sync-failure-ledger.ts` so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already `auto_skipped` rows stay a visible WARN), `rls_event_trigger` (healthy `evtenabled` set is `('O','A')` only; fix hint `gbrain apply-migrations --force-retry 35`), `graph_coverage` (short-circuits to ok when `SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')` returns 0; WARN hint is `gbrain extract all`), `embedding_column_registry` (probes each declared column via Postgres `format_type(atttypid, atttypmod)` to catch dim mismatch with a paste-ready `gbrain config set embedding_columns '{...}'` hint, probes HNSW index presence via `pg_indexes`, computes default-column population via `COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)` warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via `executeRaw`), and `skill_brain_first` (walks SKILL.md via `autoDetectSkillsDirReadOnly`, calls `analyzeSkillBrainFirst()` from `src/core/skill-brain-first.ts` per file with structured `Check.issues[]`; warn states `missing_brain_first`/`brain_first_typo`, ok states `compliant_callout`/`compliant_phase`/`compliant_position`/`exempt_frontmatter`/`no_external`; snapshot+diff audit at `~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl`). `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](path).` callouts via `src/core/dry-fix.ts` (and MISSING_RULE_PATTERNS for the brain-first callout); `--fix --dry-run` previews. `--index-audit` (Postgres-only, informational, no auto-drop) reports zero-scan indexes from `pg_stat_user_indexes`. Every DB check runs under a progress phase; `markdown_body_completeness` runs under a 1s heartbeat. `runDoctor` uses `autoDetectSkillsDirReadOnly` (from `src/core/repo-root.ts`; install-path fallback so `cd ~ && gbrain doctor` finds bundled skills); `--fix` carries a D6 install-path safety gate that refuses auto-repair when `detected.source === 'install_path'` (would rewrite the bundled tree). The Lane D supervisor check at `doctor.ts:1011-1043` consumes `summarizeCrashes(events)` from `src/core/minions/handlers/supervisor-audit.ts` (warn at `>=1` real crash; ok message has `clean_exits_24h=N`; warn message has `runtime=A oom=B unknown=C legacy=D` per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with `gbrain jobs supervisor status` is pinned by source-grep wiring assertions requiring the breakdown substrings in BOTH `doctor.ts` and `jobs.ts`. `checkSyncFreshness` (exported, in `runDoctor` local + `doctorReportRemote` thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-`last_sync_at` warns ("clock skew") instead of falling through ok; env overrides `GBRAIN_SYNC_FRESHNESS_WARN_HOURS`/`GBRAIN_SYNC_FRESHNESS_FAIL_HOURS` (invalid fall back with once-per-process stderr warn via `_resolveSyncFreshnessHours`); failure messages embed `source.id` so the printed `gbrain sync --source <id>` matches. A source holding a LIVE, non-expired per-source sync lock (`inspectLock(engine, syncLockId(source.id))` from `src/core/db-lock.ts`) is reported as actively syncing (the message names the holder pid + host) and counted in `synced_recently_count`, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic `db-lock` import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a `localOnly`-gated git short-circuit (`runDoctor` passes `localOnly: true`; `doctorReportRemote` runs in the HTTP MCP server `src/commands/serve-http.ts` and keeps default `false` so that path never walks DB-supplied `local_path` via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == `last_commit` AND working tree clean via `requireCleanWorkingTree: 'ignore-untracked'` so a quiet repo with only untracked dirs is `unchanged` not SEVERE, AND `chunker_version === CURRENT`); the inline SELECT carries `last_commit + chunker_version + newest_content_at`. The REMOTE path computes lag via `lagFromContentMs(newest_content_at, lastSync, now)` from the stored column, NO git subprocess; LOCAL fall-through and the `< 0` clock-skew check stay on raw wall-clock. Three-bucket count math populates `Check.details = {unchanged_count, synced_recently_count, stale_count}` with the invariant `sum === sources.length`. `checkCycleFreshness` is DELIBERATELY NOT git-short-circuited or content-relativized (`last_commit == HEAD` can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis `last_full_cycle_at`). Pinned by `test/doctor.test.ts` (incl. IRON-RULE regression banning stale verb names, the sync_freshness boundary matrix, the D4 regression guard verifying git probes are NEVER called when `localOnly` is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). `pglite_data_dir` check: fs-only check that runs when a PGLite brain FAILS to connect (`!fastMode && !engine && config.engine === 'pglite'`, placed after `orphan_clones`, before the DB-checks gate): `computePgliteDataDirCheck(dataDir, diagnosis)` (exported pure fn, `computeWorkerOomLoopCheck` convention) maps the `inspectPgliteDataDir` verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → `fail` naming `gbrain pglite-repair --dry-run`/`--yes` or the rebuild path, live-lock/missing-dir → `warn`; all `remediation_status: 'human_only'` (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in `doctor-categories.ts` OPS_CHECK_NAMES. Pinned by `test/doctor-pglite-datadir.test.ts`. silent-failure batch (#2250/#2784/#2788): `content_hash_duplicates` (single GROUP BY over `(source_id, content_hash)` with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the `pages delete` → `purge-deleted --older-than 0` remediation); `undeclared_db_only_pages` (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo); `db_only_collector_collision` (configured recipe `output_paths` inside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync's `manageGitignore` at config-write time). All warn-level, engine-parity pinned by `test/e2e/doctor-silent-death-parity.test.ts`; units in `test/doctor-silent-death-checks.test.ts`. `graph_signals_coverage` check wired into both `runDoctor` (local) and `doctorReportRemote` (HTTP/JSON thin-client path). Reads `search.graph_signals` config first, falls back to mode default; silent `ok` when disabled. Computes inbound link coverage on the page set; warns at <10% with `gbrain extract all` fix hint; `ok` at ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases in `test/doctor.test.ts`. `subagent_provider` check (layer 3 of 3). Resolves subagent model config in runtime order (`models.subagent` > `models.default` > `models.tier.subagent` > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`. `computeWorkerOomLoopCheck(engine)` is the single authoritative OOM-loop signal, unioning supervised `summarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog` (cross-week read via `readRecentSupervisorEvents` so a Monday window can't lose Sunday) + bare-worker `minion_jobs error_text='aborted: watchdog'` count (Postgres-only; the same source `queue_health` subcheck 3 reads). Cap comes from the latest `rss_watchdog_loop` breaker alert's `max_rss_mb`, else `resolveDefaultMaxRssMb()` fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise. `computePoolReapHealthCheck(engine)` is the Postgres-only `pool_reap_health` check reading `readRecentPoolRecoveries(1)` — fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered in `buildChecks` after the `supervisor` block. The `supervisor` causeStr carries `rss=N (see worker_oom_loop)` and `queue_health`'s watchdog message cross-references `worker_oom_loop`. `DoctorReport.top_issues` + the cause-ranked render header. `worker_oom_loop` + `pool_reap_health` registered under ops in `doctor-categories.ts`. Pinned by `test/doctor-worker-oom-loop.test.ts`, `test/doctor-pool-reap-health.test.ts`. `supervisor_singleton` check (#1849), a SEPARATE check from `supervisor` (same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when a `started` supervisor event was seen in the last 24h and a live engine is available. Reads the queue-scoped DB lock row (`gbrain_cycle_locks WHERE id = supervisorLockId(queue)`) and compares the lock holder (`holder_host:holder_pid`) against the local pidfile holder via the pure `classifySupervisorSingleton`. `mismatch` → warn (a second supervisor may be running with a different `--max-rss`; message names both holders, the effective cap from the `started` event's `max_rss_mb`, and the fix `gbrain jobs supervisor stop`); `single` → ok (names holder + cap); `no_lock` → no check emitted. Best-effort try/catch (silent skip on brains without the lock table). Registered under ops in `doctor-categories.ts` as `supervisor_singleton`. Pinned by `test/supervisor-db-lock.test.ts` + `test/doctor.test.ts`. `checkBatchRetryHealth`: `batch_retry_health` check surfacing Supavisor circuit-breaker incidents. Wired into both `runDoctor` (local) and `doctorReportRemote` (thin-client). Reads last 24h. States: `ok` (zero exhausted in 24h OR <3 from a single site), `warn` (>=3 same-site OR >=5 cross-site), `fail` (>=20 sustained breaker). Surfaces bad `GBRAIN_BULK_*` env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also reads `readRecentDbDisconnects(24)` and appends `Disconnect-call audit: N call(s) in 24h (most recent caller: <frame>).` to ALL three message paths so connection-incident signal is greppable from one `gbrain doctor --json` call (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned by `test/doctor-batch-retry.test.ts` (10 cases). three checks wired into `runDoctor()` and the JSON envelope, all warn-only with paste-ready fix hints. (1) `checkSourceRoutingHealth(engine)` scans up to 200 pages on federated brains and flags pages whose `source_id` doesn't match what `resolveSourceWithTier()` would have picked for their `source_path`; single-source brains short-circuit to `ok`; the 200-page cap is total across the brain so doctor stays under 5s. (2) `checkOauthConfidentialHealth(engine)` probes registered confidential clients for `/token` reachability. (3) `checkAutopilotLockScope()` (pure, no engine) compares the resolved lock path to `$GBRAIN_HOME`; warns when set but the lock lives elsewhere, with a PID-safe inspection hint (`kill -0 <pid>` before deletion). Pinned by `test/doctor-v0_37_7_checks.test.ts`. `buildChecks(engine, args, dbSource): Promise<Check[]>` exported as a test seam. `runDoctor` is a thin wrapper: `buildChecks → computeDoctorReport → render + process.exit`. All 10 `process.exit` sites stay in the wrapper; the two early-return paths (no engine, connection failure) return partial check lists instead of inline exits (observable output identical). Pinned by `test/doctor-behavioral.test.ts` (13 cases: pure aggregation math over `computeDoctorReport`, orchestrator cases for `--fast` skip set + `--json` flag + no-engine partial path + snapshot of load-bearing check names) and `test/doctor-cli-smoke.serial.test.ts` (1 subprocess case spawning `bun run src/cli.ts doctor --json` against a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined `.serial` because PGLite write-locks don't play with parallel runners). three checks wired into `runDoctor()` and the JSON envelope: `oversized_pages` (warns on pages exceeding `content_sanity.bytes_warn`), `scraper_junk_pages` (warns on live DB pages matching any junk pattern that escaped ingest), and `content_sanity_audit_recent` (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; `--content-audit` opts into a full scan. All three warn-only with paste-ready fix hints (junk → `gbrain sources audit <id>` + `git rm` source-of-truth, oversize → split or accept). two checks wired into `runDoctor()` + the JSON envelope: `quarantined_pages` (counts pages carrying the `quarantine` marker via `engine.executeRaw` JSONB `?` existence, works on PGLite + Postgres; warn-only with a `gbrain quarantine list` hint) and `flagged_pages` (counts `content_flag` pages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned by `test/doctor.test.ts`. `home_dir_in_worktree`: filesystem check walking up from `gbrainPath()` toward `$HOME` looking for a `.git` directory (main repo) or `.git` file (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at `$HOME` so a `.git` above the user's home doesn't false-positive. Honors `GBRAIN_HOME` (appends `.gbrain` to the override). Warn (not fail) with worktree-root path + paste-ready fix pointing at `GBRAIN_HOME` override or moving the brain. `--remediation-plan [--json] [--target-score N]` prints what would run (stable `id`, `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on`); `--remediate [--yes] [--target-score N] [--max-usd N]` submits each plan step as a Minion job in dependency order, re-checking score between steps. `--target-score N` defaults to 90; refuses to start when target exceeds `maxReachableScore()` and lists what's missing. `--max-usd N` is the cron-safety guard — submission refuses when the plan's `est_total_usd_cost` exceeds the cap. JSON envelope adds a `Check.remediation` field (additive, schema_version unchanged). Pinned by tests in `test/doctor.test.ts`. 4 checks: `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` (mitigation surface; math ships later), `voice_gate_health`.
- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (the old `unnest(${arr}::text[])` array-literal path crashed Postgres with "malformed array literal" on calendar/Zoom context, gbrain#1861) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` resets both `embedding` AND `embedded_at` to NULL when chunk_text changes without a new embedding. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL on the same probe set as PGLite (extended for column-only forward-reference cases: `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`/`archived_at`/`archive_expires_at`, `timeline_entries.event_page_id`); the entire probe path runs on the DDL connection threaded from `initSchema` (closing a concurrent-bootstrap race for Supabase pooler users); closes #1018/#974/#820. `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-ownership.test.ts`. `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` no longer hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). Test seam `__resetFactsEmbeddingCastCacheForTest()` clears the per-engine cache.
- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `countCJKAwareWords(s)` (30% density threshold — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS`, `pglite-engine.ts:searchKeyword + searchKeywordChunks`.
@@ -189,14 +189,14 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/audit/pool-recovery-audit.ts` — reap/reconnect audit on the shared `audit-writer` cathedral. Events: `reap_detected` (CONNECTION_ENDED), `reconnect_other` (network/auth/health-check), `reconnect_succeeded`, `reconnect_failed`. `readRecentPoolRecoveries(hours=1)` returns `{reaps, recoveries, failures, others, events}`. Error summaries route through `redactConnectionInfo` before truncation (DSN/host/IP safe). Emitted ONLY from `PostgresEngine.reconnect(ctx?)` (the rare reap-retry path, near-zero hot-path cost); `reconnect()` classifies the threaded error via `isConnectionEndedError` (in retry-matcher.ts) so only true pooler reaps are labeled `reap_detected`. The retry callback in retry.ts threads the triggering error as `(ctx?: {error?}) => Promise<void>`. Pinned by `test/audit/pool-recovery-audit.test.ts`.
- `src/core/audit/db-disconnect-audit.ts` — JSONL audit for every call to `db.disconnect()` and `PostgresEngine.disconnect()`. Built on `audit-writer.ts`. Schema: `{ts, engine_kind: 'postgres'|'pglite'|'unknown', connection_style: 'module'|'instance'|'unknown', caller_stack, command, pid}`. `caller_stack` captured via `new Error().stack` truncated to ~20 frames so operators identify the offending caller without inflating JSONL. Privacy: stack frames carry file paths but NO SQL content / row data / user strings. File: `~/.gbrain/audit/db-disconnect-YYYY-Www.jsonl` (honors `GBRAIN_AUDIT_DIR`). `readRecentDbDisconnects(hours=24)` walks current + previous ISO week and returns `{count, most_recent_caller, files_scanned}`. Wired into `src/core/db.ts:disconnect` and `src/core/postgres-engine.ts:disconnect`, logging BEFORE the early-return branches so even no-op disconnects on never-connected engines are recorded (that case may itself be a caller-side bug). Pinned by `test/db-disconnect-audit.test.ts` (6 cases: round-trip, stack truncation, sort order, empty-dir nulls, stable feature name, EROFS best-effort).
- `src/core/facts/queue.ts:FactsQueue.drainPending` — method `drainPending({timeout?: number}): Promise<{drained, unfinished}>`. Semantically distinct from `shutdown()` (which calls `this.internalAbort.abort()` and would abort the very facts:absorb worker trying to log its post-completion event). Drain lets in-flight finish; only the wait is bounded. Default timeout `1000ms` so commands that don't enqueue facts pay one fast 0ms check before exit. `src/cli.ts` op-dispatch finally block awaits `getFactsQueue().drainPending({timeout: 1000})` BEFORE `engine.disconnect()`. Lazy-import keeps the facts-queue module off the hot path for ops that never touch it. Closes the trailing `'No database connection'` line after `gbrain capture` (post-page-write facts:absorb outlived the CLI process). Pinned by `test/facts-queue-drain-pending.test.ts` (4 cases: empty fast-path, in-flight settled without abort, unfinished count on timeout, default timeout = 1000ms).
-- `scripts/check-no-double-retry.sh` + `scripts/check-batch-audit-site.sh` — CI lint guards wired into `bun run verify`. The former greps src/ for `withRetry(...engine.{addLinksBatch|addTimelineEntriesBatch|upsertChunks})` patterns and fails the build on hit (prevents 3×3=9 retry amplification on incomplete reverts). The latter extracts every string-literal `auditSite: '...'` from src/ and validates each appears in the `BATCH_AUDIT_SITES` const in `src/core/retry.ts` (typo guard — prevents fragmented doctor output).
+- `scripts/check-no-double-retry.sh` + `scripts/check-batch-audit-site.sh` — CI lint guards wired into `bun run verify`. The former greps src/ for `withRetry(...engine.{addLinksBatch|addTimelineEntriesBatch|upsertChunks})` patterns and fails the build on hit (prevents 3×3=9 retry amplification on incomplete reverts); its single-line pattern crosses arrow-callback parens (the canonical banned shape is `withRetry(() => engine.addLinksBatch(...))` — a paren-stopping regex cannot see it), and its multi-line fallback runs under perl (always present locally and in CI). Both are proven fail-able by the guard self-test fixtures under `test/fixtures/guards/`. The latter extracts every string-literal `auditSite: '...'` from src/ and validates each appears in the `BATCH_AUDIT_SITES` const in `src/core/retry.ts` (typo guard — prevents fragmented doctor output).
- `src/core/fail-improve.ts` — Deterministic-first, LLM-fallback loop with JSONL failure logging and auto-test generation.
- `src/core/transcription.ts` — Audio transcription: Groq Whisper (default), OpenAI fallback, ffmpeg segmentation for >25MB.
- `src/core/enrichment-service.ts` — Global enrichment service: entity slug generation, tier auto-escalation, batch throttling. Write path is trust-gated (issue #160): `enrichEntity` / `enrichEntities` / `extractAndEnrich` take `EnrichmentTrustOptions { trusted?, sourceId? }`; only an explicit `trusted: true` writes authoritative `people/` / `companies/` stubs. Anything else (undefined/false — fail-closed, mirroring `OperationContext.remote`) creates the stub with the extraction quarantine markers from `src/core/extraction-review.ts` and reports `quarantined: true` in `EnrichmentResult`. The ONLY sanctioned op surface is `extract_entities` (operations.ts), which grants `trusted` solely for `ctx.remote === false` callers passing `--trusted-extraction`.
- `src/core/extraction-review.ts` — Extraction quarantine lane markers (issue #160), sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).
- `src/commands/enrich.ts` + `src/core/enrich/thin.ts` + `src/core/cycle/enrich-thin.ts` — `gbrain enrich --thin`: batch-develops stub (thin) pages via **brain-internal grounded synthesis**. gbrain's model tooling sees only brain-internal context (search / get_page / facts / backlinks), not the web, so enrich consolidates what the brain ALREADY knows about an entity (scattered across meetings, other pages, deals, facts) into one cited page via ONE `gateway.chat` call per page; web research stays the agent-driven `enrich` SKILL's job. `runEnrichCore(engine, opts, signal)` (strict per-source; multi-source iteration is the caller's job) drives `enrichOne` per candidate: `withRefreshingLock('enrich:<src>:<slug>')` → `getPage` → deterministic retrieve (hybridSearch + getBacklinks + facts + raw_data, source-scoped, sanitized via `INJECTION_PATTERNS`) → `assessGrounding` gate (skip < `MIN_CONTEXT_CHARS`, no LLM) → `buildEnrichPrompt` (grounded dossier, `[Source: slug]` citations, SKIP sentinel) → synth → `put_page` handler (`remote:false`, auto-link + write-through) stamping `enriched_at` + `enriched_by:'cli:enrich'`. Candidate selection is the SQL-native `engine.listEnrichCandidates(opts)` (`src/core/engine.ts` interface + `EnrichCandidate`/`EnrichCandidatesOpts`/`ENRICH_ORDER_SQL` in `src/core/types.ts` + pg/pglite impls): thin-filter + per-page source-correct inbound count (`to_page_id = p.id`, `mentions` excluded) + `enriched_at` recency guard + whitelisted ORDER BY + LIMIT, lightweight projection (NO bodies). Resume via `src/core/op-checkpoint.ts` (local `enrichFingerprint`); budget via `BudgetTracker` + `withBudgetTracker` (best-effort under `--workers > 1` — `runSlidingPool` aborts new claims on `BUDGET_EXHAUSTED` but does NOT cancel in-flight `gateway.chat`; pin `--workers 1` for a hard ceiling). `sanitizeContext` (thin.ts) neutralizes the `<context>…</context>` data-envelope delimiters (injection escape, mirrors the `</trajectory>` convention); the `--background` multi-source fan-out idempotency key carries the run fingerprint via exported `backgroundIdempotencyKey(sid, args)` (a bare `enrich:${sid}` would return stale completed jobs); `runEnrichCore` flags `budget_exhausted` post-hoc when `tracker.totalSpent > tracker.cap` even when the gateway swallowed the final-call throw (via read-only `BudgetTracker.cap` getter); `body()` flushes the checkpoint on `BudgetExhausted` before it propagates so resume doesn't re-charge. The opt-in `enrich_thin` cycle phase (default OFF via `cycle.enrich_thin.enabled`) trickles `max_pages_per_tick` (default 3) per source with per-source cost cap enforced as `min(per_source_cap, brain_wide_remaining)` + brain-wide total + walltime caps. Wired into `cycle.ts` (`CyclePhase`/`ALL_PHASES` between `conversation_facts_backfill` and `skillopt`/`embed`; `PHASE_SCOPE='source'`; `NEEDS_LOCK`; dispatch), `cli.ts` (`CLI_ONLY` + `CLI_ONLY_SELF_HELP` + `THIN_CLIENT_REFUSED_COMMANDS` + dispatch), `jobs.ts` (Minion `enrich` handler, strict per-source, NOT in `PROTECTED_JOB_NAMES`). DI seam `opts.synthesizeFn` keeps tests hermetic (no API key, no mock.module). Pinned by `test/enrich/thin.test.ts`, `test/enrich/idempotency.test.ts`, `test/enrich-cycle-phase.test.ts`, `test/e2e/enrich-pglite.test.ts` (grew-cited, skip, ordering, multi-source, recency, resume, budget abort + checkpoint flush, final-call overage, lock-skip, provenance), `test/e2e/engine-parity.test.ts` (`listEnrichCandidates` pg↔pglite parity).
- `src/core/data-research.ts` — Recipe validation, field extraction (MRR/ARR regex), dedup, tracker parsing, HTML stripping.
-- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it re-fetches the LIVE page via `getPage` (chunks CURRENT content, not the batch-list snapshot) and re-checks `getChunks`, narrowing (NOT fully closing — accepted residual risk, see the function's docstring) the check-then-write window: a concurrent writer landing chunks in the gap between that re-check and the `upsertChunks` call can still have them overwritten with this sweep's stale-content chunks, the same unmitigated-until-now window `embedPage`'s single-page chunkless branch already ships with. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, embeds, re-upserts via `upsertChunks`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Every embed-write path stamps `pages.embedding_signature` via `engine.setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page — but ONLY when EVERY chunk was stale this pass (a partially-stale page keeps preserved chunks of unknown provenance, so it stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` (#3391) lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent (#3037): all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the regression guard — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-helper-migration.test.ts` (asserts the helper is wired in AND the pre-migration `let nextIdx = 0` + `Promise.all(Array.from({length: numWorkers}, ...))` shapes are gone). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. The other six commands (`extract`, `lint`, `backlinks`, `reindex`, `integrity`, `pages`) adopt the same pattern in a follow-up wave. #1737: `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`.
+- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it re-fetches the LIVE page via `getPage` (chunks CURRENT content, not the batch-list snapshot) and re-checks `getChunks`, narrowing (NOT fully closing — accepted residual risk, see the function's docstring) the check-then-write window: a concurrent writer landing chunks in the gap between that re-check and the `upsertChunks` call can still have them overwritten with this sweep's stale-content chunks, the same unmitigated-until-now window `embedPage`'s single-page chunkless branch already ships with. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, embeds, re-upserts via `upsertChunks`. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). This list is load-bearing: `upsertChunks` overwrites from EXCLUDED (not COALESCE), so any re-embed path that omits a field resets it — omitting `modality` flips every image chunk to `modality='text'` and silently zeroes the image search arm (its filter is `cc.modality = 'image'`). Never hand-roll a per-path field list. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Every embed-write path stamps `pages.embedding_signature` via `engine.setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page — but ONLY when EVERY chunk was stale this pass (a partially-stale page keeps preserved chunks of unknown provenance, so it stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` (#3391) lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent (#3037): all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the regression guard — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-helper-migration.test.ts` (asserts the helper is wired in AND the pre-migration `let nextIdx = 0` + `Promise.all(Array.from({length: numWorkers}, ...))` shapes are gone). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. The other six commands (`extract`, `lint`, `backlinks`, `reindex`, `integrity`, `pages`) adopt the same pattern in a follow-up wave. #1737: `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`.
- `src/core/retrieval-upgrade-planner.ts` — `runSchemaTransition(engine, targetDim)` (exported) is the ONE atomic dimension-transition path, shared by `ze-switch` and `gbrain migrate embeddings`. In a single transaction it rebuilds ALL THREE dim-pinned text-embedding-space columns at `targetDim` — `content_chunks.embedding`, `query_cache.embedding`, `facts.embedding` — preserving each column's declared type (`vector` vs `halfvec`, probed from `information_schema`) and recreating its HNSW index with the matching opclass, gated on `hnswIndexExpected` (above the per-type dim ceiling pgvector refuses the index and exact scans remain the path). query_cache + facts are created at brain-birth width by `migrate.ts` and NO migration ever ALTERs them, so omitting either leaves it silently broken: a narrow `query_cache.embedding` makes every `store()`/`lookup()` fail inside the cache's own error-swallowing (permanent 0% hit rate), and a narrow `facts.embedding` fails every per-fact embed write (the doctor check that would warn is skipped on PGLite, the default engine). `content_chunks.embedding_image` / `embedding_multimodal` are the deliberate exception — separate multimodal models, dimensions independent of the text model. Pinned by `test/embedding-migration.test.ts` (all three widths + a real INSERT at the new width into each) and `test/e2e/migrate-embeddings-postgres.test.ts`.
- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core (#3390): `planEmbeddingMigration` (workload counts via the widened stale predicates with the TARGET signature + `includeNullSignature`, so a mid-migration re-plan counts only what remains; cost via `embedding-pricing.ts`; `null_signature_chunks` split out for #3391 visibility; reranker-on-outgoing-provider warning), `applyEmbeddingMigration` (env-override gate BEFORE any mutation → in-flight state marker `embedding_migration.state` → `runSchemaTransition` when the ACTUAL column width differs from target → DB-plane `embedding_model`/`embedding_dimensions` → `persistConfig` callback for the file plane → `invalidateStaleSignatureEmbeddings({includeNullSignature: true})` → `SemanticQueryCache.clear()`), `completeEmbeddingMigration` (clears the marker + stamps `embedding_migration.completed`; call only at zero backlog), `resolveMigrationTarget` (validates `provider:model` via `resolveRecipe`, dims via `embeddingDimsForModel` or explicit `--dim`), `migrationSignature` (matches `currentEmbeddingSignature()` shape). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Reuses `runSchemaTransition` (now exported from `retrieval-upgrade-planner.ts`) so ze-switch and the migration share ONE dimension-transition path. `reconcilePageSignatures(engine, plan)` runs after the re-embed drain and BEFORE the completion probe: it stamps the target signature on every page that has zero NULL-embedding chunks, covering pages whose chunks straddle a `listStaleChunks` batch boundary (the embed loop only stamps when `stale.length === existing.length`, so a split page is embedded correctly but never stamped — without the reconcile a >1-batch brain reports "incomplete" and the re-run re-invalidates and re-pays for those pages). Sound only because apply() invalidated everything not already in the target space; pages with a remaining NULL chunk stay unstamped so a real embed failure still surfaces. Invalidation is ordered BEFORE the config writes so a crash on a same-dim swap leaves rows merely stale (empty results) rather than new-space queries scored against old-space vectors (silently wrong). Pinned by `test/embedding-migration.test.ts` (PGLite) + `test/e2e/migrate-embeddings-postgres.test.ts` (real pgvector).
- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`, the command README/doctor promised since v0.36). Flow: plan → render (stderr when `--json` so stdout stays JSON-clean) → consent gate (TTY y/N prompt or `--yes`; non-TTY without `--yes` refuses exit 2, mirroring the reindex-code cost gate) → live probe (one embed against the TARGET model/dims BEFORE any mutation — bad key/model/dim fails with nothing changed) → `applyEmbeddingMigration` with `persistEmbeddingFileConfig` (writes `~/.gbrain/config.json` + reconfigures the in-process gateway — the gateway reads file/env, NOT the DB plane) → `runEmbedCore({stale, catchUp, singleFlight, includeNullSignature, pace})` → drain check → `completeEmbeddingMigration` or exit 1 with the resume hint (re-run the same command). When the re-embed was skipped because another backfill holds the per-source single-flight lock (`EmbedResult.lock_skipped` — the state a hard-killed run leaves behind for up to the 60-min lock TTL), the exit-1 message says so instead of misreporting embed failures, since an immediate re-run cannot resume until the lock expires. Also surfaced as the `migrate_embeddings` op (scope admin, localOnly, hidden cliHints; handler hard-refuses `ctx.remote !== false` and returns `needs_confirmation` + plan without `yes: true`). Pinned by `test/migrate-embeddings-flow.serial.test.ts` (full lifecycle incl. interrupted-run resume on PGLite) + `test/provider-sunset-doctor.serial.test.ts` (lock-skip visibility). Discovery surfaces for brains pinned to a sunsetting provider: the `provider_sunset` doctor check (every run; paste-ready command with the ACTUAL column width via `readContentChunksEmbeddingDim`; warn before the date, fail after it ONLY when embedded vectors actually exist on the dead provider — zero-vector brains stay warn so doctor-as-CI-gate keeps exiting 0; reranker exposure resolved via `resolveSearchMode`, the plane search actually reranks with, not the gateway plane; suppress via `doctor.suppress_provider_sunset`; self-host escape hatch given equal billing) and the one-shot `gbrain upgrade` banner (`ze_sunset_notice_shown`, same reranker resolution); the shutdown date lives once as `ZEROENTROPY_SUNSET_DATE` in `src/core/ai/defaults.ts`, and `checkProviderSunset(engine, now?)` takes an injectable clock so tests pin both date branches.
@@ -207,7 +207,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). No in-memory dedup pre-load — candidates buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three new `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). Race fix: `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` gains `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` for `pagesAffected` at the inline-extract call site, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` adds `'extract.stale'` to `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` adds `links_extraction_lag` to `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp regression + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite regression in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.
- Extract CLI help — `EXTRACT_HELP` in `src/commands/extract.ts` is the canonical detailed usage shared by `--help` and invalid-subcommand errors. `src/cli.ts` routes `extract --help` before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by `test/cli-help-discoverability.test.ts`.
- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against extraction-loop guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. `extract_health` doctor check reads last 7 days, warns at halt-rate > 10% AND when rollup_write_failures > 0; pre-v104 brains report `ok`. CLI: `gbrain extract status [--source-id ID] [--kind X] [--verbose] [--json]` (7-day rollup, sorted halt_rate desc + cost desc, top-5 + "more rows" hint, stable `schema_version: 1`); `gbrain extract --explain <kind>` (resolution chain pack-declared vs built-in cycle phase, prompt_template + fixture_corpus paths with `✓`/`(missing)`, last 7d rollup); `gbrain extract benchmark --pack X --kind Y` (loads pack fixture corpus through strict path validation — rejects absolute paths, `..` traversal, null bytes, AND symlinks resolving outside pack root; ships as a stub-reporter). `src/core/schema-pack/manifest-v1.ts` widens `extractable` from `z.boolean()` to `z.union([z.boolean(), ExtractableSpecSchema])` (carries `prompt_template`, `fixture_corpus`, `eval_dimensions`, `benchmark_min_recall`, plus reserved `verifier_path` — parses but refuses at runtime); `extractableSpecsFromPack` + `getExtractableSpec` + `refuseVerifierPathInV042` in `src/core/schema-pack/extractable.ts`; `gbrain schema scaffold-extractable <type> --pack <pack>` declares the type extractable, generates 5 placeholder fixtures + a prompt template stub under `packs/<pack>/{fixtures,prompts}/extract/`, refuses to overwrite without `--force`. Pinned by `test/extractable-spec-widening.test.ts` (22), `test/extract/receipt-writer.test.ts` (12, canonical PGLite block R3+R4), `test/extract/benchmark.test.ts` (17), `test/extract/status.test.ts` (15), `test/schema-pack/scaffold-extractable.test.ts` (15, privacy guards), `test/doctor-extract-health.test.ts` (8).
-- `src/commands/import.ts` — `gbrain import <path> [--source-id <id>]`: page import with the path-set checkpoint. `--source-id <id>` routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`). Pinned by `test/import-source-id.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Uses a path-set checkpoint via `src/core/import-checkpoint.ts` (the walk still applies `sortNewestFirst()` for embed-cost ordering, but checkpoint correctness no longer depends on sort order). A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. This closes three classes: parallel-import-with-slow-worker dropping the slow file on crash-resume (the slow file isn't in `completed` until its own `processFile` resolves), failed-file-bumps-counter-past-itself (failures don't add to `completed`), and sort-flip-drops-newest-N-on-cross-version-resume (order is no longer part of the checkpoint). Old positional checkpoints are detected and discarded with a stderr line on first resume (re-walking is cheap because `content_hash` short-circuits unchanged files). Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry regression). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` imported (and resurrected soft-deleted) pages incremental sync excludes (#2607). Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs, #753/#774; the resume checkpoint stays dir-relative per `resumeFilter`'s contract).- `src/core/import-checkpoint.ts` — `loadCheckpoint(brainDir)`, `saveCheckpoint(brainDir, completed)`, `resumeFilter(files, completed, brainDir)`, `clearCheckpoint()`, plus the `ImportCheckpoint` type. Path-set format `{schema_version, brainDir, completed: string[]}`. Atomic write via `.tmp` + `rename()` so a mid-write crash never leaves a partial JSON. `loadCheckpoint` returns `null` on: missing file, malformed JSON, brainDir mismatch (ran against a different brain), and the old positional format (logged to stderr before discard). `resumeFilter` returns `{toProcess, skippedCount}` — pure, no I/O, deterministic. `clearCheckpoint` is no-op-on-missing for clean-exit cleanup. Honors `GBRAIN_HOME` via `gbrainPath()` so `withEnv({GBRAIN_HOME: tmpdir})` test isolation works without monkey-patching fs. Best-effort persistence — `saveCheckpoint` logs warnings on write errors but never throws.
+- `src/commands/import.ts` — `gbrain import <path> [--source-id <id>]`: page import with the path-set checkpoint. `runImport` contains NO `process.exit`: all five preflight/argv failure sites (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target) throw the exported typed `ImportAbortError` (carries `exitCode`; the user-facing message is printed at the throw site), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`, byte-identical to the old behavior. Pinned by `test/import-abort-error.test.ts`. `--source-id <id>` routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`). Pinned by `test/import-source-id.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Uses a path-set checkpoint via `src/core/import-checkpoint.ts` (the walk still applies `sortNewestFirst()` for embed-cost ordering, but checkpoint correctness no longer depends on sort order). A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. This closes three classes: parallel-import-with-slow-worker dropping the slow file on crash-resume (the slow file isn't in `completed` until its own `processFile` resolves), failed-file-bumps-counter-past-itself (failures don't add to `completed`), and sort-flip-drops-newest-N-on-cross-version-resume (order is no longer part of the checkpoint). Old positional checkpoints are detected and discarded with a stderr line on first resume (re-walking is cheap because `content_hash` short-circuits unchanged files). Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry regression). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` imported (and resurrected soft-deleted) pages incremental sync excludes (#2607). Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs, #753/#774; the resume checkpoint stays dir-relative per `resumeFilter`'s contract).- `src/core/import-checkpoint.ts` — `loadCheckpoint(brainDir)`, `saveCheckpoint(brainDir, completed)`, `resumeFilter(files, completed, brainDir)`, `clearCheckpoint()`, plus the `ImportCheckpoint` type. Path-set format `{schema_version, brainDir, completed: string[]}`. Atomic write via `.tmp` + `rename()` so a mid-write crash never leaves a partial JSON. `loadCheckpoint` returns `null` on: missing file, malformed JSON, brainDir mismatch (ran against a different brain), and the old positional format (logged to stderr before discard). `resumeFilter` returns `{toProcess, skippedCount}` — pure, no I/O, deterministic. `clearCheckpoint` is no-op-on-missing for clean-exit cleanup. Honors `GBRAIN_HOME` via `gbrainPath()` so `withEnv({GBRAIN_HOME: tmpdir})` test isolation works without monkey-patching fs. Best-effort persistence — `saveCheckpoint` logs warnings on write errors but never throws.
- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). Foreign-edge footer always present (`X foreign edges (use --include-foreign to traverse)`) so cross-source edges never disappear silently; `--include-foreign` widens the SQL filter to walk them. Pinned by `test/graph-query.test.ts`.
- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit}`. `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.
- `src/commands/reindex-frontmatter.ts` — `gbrain reindex-frontmatter`. `reindexFrontmatterCli(engine, args)` takes the ALREADY-CONNECTED engine from cli.ts's dispatch (#1963); it must never build/connect its own engine — a second connect on the same PGLite data dir self-deadlocks on the data-dir lock (this process already holds it) and timed out 100% of the time on PGLite. Same rule applies to `runBackfillCommand(engine, args)` in `src/commands/backfill.ts` and any future command dispatched from cli.ts's engine-connected switch. Pinned by `test/reindex-frontmatter-connect.test.ts` (library path) and `test/reindex-frontmatter-pglite-spawn.serial.test.ts` (CLI dispatch seam, both commands).
@@ -225,9 +225,9 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/quarantine.ts` — `gbrain quarantine <list|clear|scan>` operator surface for the content-quality gate. `list [--json] [--include-flagged]` paginates `listPages` and reports quarantined (HIDDEN) pages, optionally also `content_flag` (FLAGGED, searchable) pages. `clear <slug> [--force] [--no-embed] [--json]` drops both markers and re-imports through the normal pipeline so the page re-chunks + re-embeds and becomes searchable; the gate re-runs on import so genuinely-junk pages re-quarantine (exit 1) unless `--force` sets `GBRAIN_NO_SANITY=1` for that one import. `scan [--limit N] [--apply] [--no-embed] [--json]` re-assesses already-ingested pages so junk predating the gate gets marked (unchanged content short-circuits normal sync, so it never re-assesses otherwise); dry-run uses the SAME effective `content_sanity` config thresholds `--apply` will use, idempotent (skips already-marked pages), `--apply` re-imports with `forceRechunk` to set markers + (for quarantine) drop chunks. Dispatched in `cli.ts`. Pinned by `test/quarantine-cli.test.ts`.
- `src/core/zombie-reap.ts` — idempotent `installSigchldHandler()` so JS-spawned children get reaped via Bun's internal `waitpid()`. Bun (like Node) only auto-reaps when a SIGCHLD listener is registered; without it, every child the worker spawns (shell jobs, embed batches, sub-agents) becomes a zombie on exit and holds connection slots. Called once at module load from `src/cli.ts` (Windows platform guard — SIGCHLD doesn't exist on Windows). Cross-file leak guard via `_uninstallSigchldHandlerForTests()`. Layer 1 of the three-layer zombie defense; Layer 2 is tini-as-PID-1 wrapping the worker subtree (via `src/core/minions/spawn-helpers.ts`); Layer 3 is the container's own tini for hard Bun crashes.
- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, stagger, handlers/shell).
-- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor.ts` `subagent_provider` check). Pinned by `test/agent-cli.test.ts`.
+- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor.ts` `subagent_provider` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`.
- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the moved-out generic abort listener now fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape was the unhandledRejection crash class during PgBouncer rotation). Gaps closed: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` + per-call `Promise.race` timeout (`GBRAIN_LOCK_RENEWAL_CALL_TIMEOUT_MS`, default `lockDuration/3`); (3) time-based abort (`Date.now() - lastSuccessfulRenewalAt >= lockDuration - GBRAIN_LOCK_RENEWAL_SAFETY_MARGIN_MS`) so we release the lock BEFORE another worker can reclaim; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims). CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe now runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress (#1801). Pinned by `test/worker-lock-renewal.test.ts` (18), `test/audit/lock-renewal-audit.test.ts` (11), `test/scripts/check-worker-lock-renewal-shape.test.ts` (5), `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3).
-- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, restarts on crash with exponential backoff, periodic health check. `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets. Worker exit classifier emits `likely_cause` on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. Consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in tini-as-PID-1 when tini is on `PATH` (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes `isTiniDetected` read-only accessor. The spawn-and-respawn loop is the shared `ChildWorkerSupervisor` core: MinionSupervisor composes it via `runSuperviseLoop()` → `new ChildWorkerSupervisor({...})` and maps `ChildSupervisorEvent` back through `emit()` SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and `process.exit` on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (`maxCrashes`) no longer permanently gives up (#1994/#2227): the core drops into degraded retry (capped backoff + a `crash_budget_degraded` health_warn) and self-heals when a respawn runs stably; permanent `process.exit(MAX_CRASHES)` fires only at the hard ceiling `resolveHardStopMaxCrashes(maxCrashes)` (default `maxCrashes × 10`, env `GBRAIN_SUPERVISOR_HARD_STOP_CRASHES`, `0` = never). Separately, `gbrain jobs supervisor status` + `gbrain doctor` detect a live supervisor through this queue lock (`inspectLock` + `isLockHolderLive`, freshness-keyed so PID reuse can't false-positive) when the `$HOME`-derived pidfile is absent, so a split-`$HOME` deployment no longer reads a healthy supervisor as "not running" (#2227). `code=0` leaves `crashCount` untouched (so a worker alternating real crashes + watchdog drains still trips `max_crashes`); `cleanRestartBudget` (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via `health_warn { reason: 'clean_restart_budget_exceeded' }` + backoff. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Progress watchdog (#1801): `healthCheck()` restarts an alive-but-wedged child via `childSupervisor.restartCurrentChild(35_000)` when a queue has claimable work, 0 live-lock active jobs, and stale completions across `wedgeRestartChecks` (default 3) consecutive checks past `wedgeRestartMinutes` (default 15, 0 disables) + a `startupGraceMs` window; bounded by `wedgeRestartLoopBudget` (default 3 / `wedgeRestartLoopWindowMs`) which switches to a one-shot `wedge_restart_loop` alert. The wedge query is the exported `queryWedgeSignals(engine, queue, handlerNames)` — name+queue-scoped, `active_healthy` = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway `registerBuiltinHandlers` worker (its new `quiet` opt). Flags `--wedge-restart-minutes` / `--wedge-restart-checks` + env `GBRAIN_WEDGE_RESTART_MINUTES` / `GBRAIN_WEDGE_RESTART_CHECKS`. The worker argv is built by the exported pure `buildWorkerArgs(opts)` (appends `--nice N` when `opts.nice_requested` is set, alongside `--concurrency`/`--queue`/`--max-rss`); the niceness apply RESULT (`nice_requested`/`nice_effective`/`nice_error`, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the `started`/`worker_spawned` audit emissions (#1815). Queue-scoped singleton (#1849): the real authority is a DB lock (`tryAcquireDbLock` from `src/core/db-lock.ts`) keyed on `supervisorLockId(queue)` = `gbrain-supervisor:<queue>` — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (an earlier revision mixed in a config-derived DB identity, which let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire — fixed). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` no longer both run with conflicting `--max-rss`; the second exits `LOCK_HELD`. The pidfile-cleanup `process.on('exit')` listener is installed BEFORE the DB-lock acquisition so the `LOCK_HELD` early-exit can't strand the pidfile this process just created. The default pidfile is now brain-scoped (`supervisor-<brainId>.pid`) so different brains under one HOME don't false-block. The lock refreshes on its own `setInterval` (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that fails past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain. `shutdown()` releases the lock so a clean restart re-acquires immediately. The `started` audit now records `max_rss_mb` so `gbrain doctor`'s `supervisor_singleton` check can surface the effective cap. Exports `supervisorLockId()` and the pure `classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'` (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by `test/supervisor.test.ts` (16 cases), `test/supervisor-tini.test.ts`, `test/supervisor-wedge.test.ts`, `test/supervisor-build-worker-args.test.ts`, and `test/supervisor-db-lock.test.ts`.
+- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, restarts on crash with exponential backoff, periodic health check. `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets. Worker exit classifier emits `likely_cause` on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. Consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in tini-as-PID-1 when tini is on `PATH` (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes `isTiniDetected` read-only accessor. The spawn-and-respawn loop is the shared `ChildWorkerSupervisor` core: MinionSupervisor composes it via `runSuperviseLoop()` → `new ChildWorkerSupervisor({...})` and maps `ChildSupervisorEvent` back through `emit()` SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and `process.exit` on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (`maxCrashes`) no longer permanently gives up (#1994/#2227): the core drops into degraded retry (capped backoff + a `crash_budget_degraded` health_warn) and self-heals when a respawn runs stably; permanent `process.exit(MAX_CRASHES)` fires only at the hard ceiling `resolveHardStopMaxCrashes(maxCrashes)` (default `maxCrashes × 10`, env `GBRAIN_SUPERVISOR_HARD_STOP_CRASHES`, `0` = never). Separately, `gbrain jobs supervisor status` + `gbrain doctor` detect a live supervisor through this queue lock (`inspectLock` + `isLockHolderLive`, freshness-keyed so PID reuse can't false-positive) when the `$HOME`-derived pidfile is absent, so a split-`$HOME` deployment no longer reads a healthy supervisor as "not running" (#2227). `code=0` leaves `crashCount` untouched (so a worker alternating real crashes + watchdog drains still trips `max_crashes`); `cleanRestartBudget` (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via `health_warn { reason: 'clean_restart_budget_exceeded' }` + backoff. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Progress watchdog (#1801): `healthCheck()` restarts an alive-but-wedged child via `childSupervisor.restartCurrentChild(35_000)` when a queue has claimable work, 0 live-lock active jobs, and stale completions across `wedgeRestartChecks` (default 3) consecutive checks past `wedgeRestartMinutes` (default 15, 0 disables) + a `startupGraceMs` window; bounded by `wedgeRestartLoopBudget` (default 3 / `wedgeRestartLoopWindowMs`) which switches to a one-shot `wedge_restart_loop` alert. The wedge query is the exported `queryWedgeSignals(engine, queue, handlerNames)` — name+queue-scoped, `active_healthy` = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway `registerBuiltinHandlers` worker (its new `quiet` opt). Flags `--wedge-restart-minutes` / `--wedge-restart-checks` + env `GBRAIN_WEDGE_RESTART_MINUTES` / `GBRAIN_WEDGE_RESTART_CHECKS`. The worker argv is built by the exported pure `buildWorkerArgs(opts)` (appends `--nice N` when `opts.nice_requested` is set, alongside `--concurrency`/`--queue`/`--max-rss`); the niceness apply RESULT (`nice_requested`/`nice_effective`/`nice_error`, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the `started`/`worker_spawned` audit emissions (#1815). Queue-scoped singleton (#1849): the real authority is a DB lock (`tryAcquireDbLock` from `src/core/db-lock.ts`) keyed on `supervisorLockId(queue)` = `gbrain-supervisor:<queue>` — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (an earlier revision mixed in a config-derived DB identity, which let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire — fixed). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` no longer both run with conflicting `--max-rss`; the second exits `LOCK_HELD`. The pidfile-cleanup `process.on('exit')` listener is installed BEFORE the DB-lock acquisition so the `LOCK_HELD` early-exit can't strand the pidfile this process just created. The default pidfile is now brain-scoped (`supervisor-<brainId>.pid`) so different brains under one HOME don't false-block. The lock refreshes on its own `setInterval` (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain, while a fenced refresh returning `false` (0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emits `health_error { reason: 'supervisor_lock_lost' }` and exits `LOCK_LOST` immediately (counting it toward the failure threshold would let two supervisors drain the same queue for up to two more refresh windows). `shutdown()` releases the lock so a clean restart re-acquires immediately. The `started` audit now records `max_rss_mb` so `gbrain doctor`'s `supervisor_singleton` check can surface the effective cap. Exports `supervisorLockId()` and the pure `classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'` (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by `test/supervisor.test.ts` (16 cases), `test/supervisor-tini.test.ts`, `test/supervisor-wedge.test.ts`, `test/supervisor-build-worker-args.test.ts`, and `test/supervisor-db-lock.test.ts`.
- `src/core/minions/child-worker-supervisor.ts` — shared spawn-and-respawn core reused by both `MinionSupervisor` (standalone `gbrain jobs supervisor` daemon) and `src/commands/autopilot.ts` (autopilot daemon), so the two consumers can't drift into parallel-loop bugs. Pure class: NO PID file, NO signal handlers, NO `process.exit`, NO health check. Lifecycle events fire via injected `onEvent: (ChildSupervisorEvent) => void`. Exit classifier: `code === 0` leaves `crashCount` UNCHANGED (preserves flap detection across mixed exit sequences); `code != 0` follows `runDuration > stableRunResetMs ? 1 : ++crashCount`. Clean-restart budget: sliding window of code=0 exits; when count exceeds `cleanRestartBudget` (default 10) inside `cleanRestartWindowMs` (default 60s), emits `health_warn { reason: 'clean_restart_budget_exceeded' }` and applies `cleanRestartBudgetBackoffMs` (default 1s). The exit classifier special-cases `WORKER_EXIT_RSS_WATCHDOG` — `likely_cause='rss_watchdog'`, and that exit does NOT bump `crashCount` (routes to its own breaker); a dedicated `_watchdogExitTimestamps` sliding window trips a loud `rss_watchdog_loop` health_warn naming the cap when N watchdog exits land inside the window, INDEPENDENT of the stable-run reset (which would otherwise hide a >5-min-run watchdog drain loop). New opts `watchdogLoopBudget` (3), `watchdogLoopWindowMs` (600000), `watchdogBackoffMs` (30000); `ChildSupervisorEvent` extended. Public read-only accessors `childAlive`, `inBackoff`, `crashCount`; `killChild(signal)` gates on liveness (`exitCode === null && signalCode === null`), NOT `.killed` — `.killed` flips true once a signal is *sent*, so the old `!this._child.killed` guard made a follow-up SIGKILL after an ignored SIGTERM a silent no-op (#1801; the bug also lived in the `shutdown()` drain). `restartCurrentChild(graceMs)` (#1801 wedge self-heal) captures the CURRENT child ref, SIGTERM→grace→SIGKILLs THAT ref (never the respawn — closes the timer-kills-fresh-worker race), and flags `_intentionalRestart` so the exit is `likelyCause='wedge_restart'`, leaves `crashCount` UNTOUCHED (never trips `max_crashes`; like `rss_watchdog`), and respawns immediately (`backoff ms:0 reason='wedge_restart'`). `awaitChildExit(timeoutMs)` short-circuits when `child.exitCode !== null || child.signalCode !== null` so fast-SIGTERM responders don't cause a 35s shutdown hang. Degraded-retry (#1994/#2227): the `run()` loop no longer fires `onMaxCrashesExceeded` at the soft `maxCrashes`; it announces `health_warn { reason: 'crash_budget_degraded' }` once per episode and keeps respawning with capped backoff (the 60s cap makes it a paced retry, not a hot loop), re-arming after a stable-run reset drops the count. Permanent give-up fires only at `hardStopMaxCrashes` (default `maxCrashes × HARD_STOP_CRASH_MULTIPLIER` = 10×; `0` disables). Test hooks `_backoffFloorMs`, `_now`. `supervisor-audit.ts` adds `rss_watchdog` as a non-clean cause + its own `CrashSummary.by_cause` bucket, and `wedge_restart` to `CLEAN_EXIT_CAUSES` (a self-heal, not a crash; denylist preserved so future causes route to `legacy`). Pinned by `test/child-worker-supervisor.test.ts` (12 cases).
- `src/core/minions/spawn-helpers.ts` — pure `detectTini()` + `buildSpawnInvocation()` consumed by both `supervisor.ts` and `autopilot.ts` (resolves the DRY violation between the two spawn sites and makes tini wrapping testable without `mock.module()`, rule R2 of `scripts/check-test-isolation.sh`). `detectTini()` calls `execFileSync('which', ['tini'])` with explicit `env: process.env` so Bun sees runtime PATH mutations. `buildSpawnInvocation(tiniPath, cmd, args)` returns `{cmd, args}` with tini prepended when present, or the bare invocation otherwise. Pinned by `test/spawn-helpers.test.ts` (5) and `test/supervisor-tini.test.ts` (4).
- `src/core/minions/niceness.ts` — OS scheduling-priority (niceness) primitives for the `--nice` flag. `parseNiceValue(raw)` whole-string parses + range-validates to POSIX `[-20, 19]` (rejects `"3.5"`/`"10abc"` that `parseInt` would silently truncate). `applyNiceness(nice, setPriority?, getPriority?)` calls `os.setPriority(0, n)` and ALWAYS re-reads `os.getPriority(0)` afterwards — in both the success and the catch paths — so a denied renice (EPERM) or an `RLIMIT_NICE` clamp records the real effective value (e.g. `0`), not null; returns `{applied, requested, effective, error?}`. `getEffectiveNiceness(pid, getPriority?)` reads an arbitrary pid's niceness (null on dead/unreadable). `formatNice(n)` → `+10`/`0`/`-5`. Applied only at the CLI layer (jobs.ts) so worker.ts/supervisor.ts stay embeddable. Pinned by `test/niceness.test.ts`.
@@ -305,14 +305,14 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/cli-options.ts` — Global CLI flag parser. `parseGlobalFlags(argv)` returns `{cliOpts, rest}` with `--quiet` / `--progress-json` / `--progress-interval=<ms>` / `--brain <id>` stripped. `--brain` is the brain-axis (which database) selector: exact-match only (`--brain-*` per-command flags pass through), value validated against the mount-id regex at parse time, missing/malformed value THROWS — never a silent host fallback. `connectEngine` in `src/cli.ts` feeds it (plus the ambient `GBRAIN_BRAIN_ID` / `.gbrain-mount` / mount-path tiers) through `resolveBrainId` → `BrainRegistry.getBrain`, which throws `UnknownBrainError` for an unregistered id; mounts get no auto-migrations and keep the host-config AI gateway. `getCliOptions()` / `setCliOptions()` expose a module-level singleton so commands reach resolved flags without parameter threading. `cliOptsToProgressOptions()` maps to reporter options. `childGlobalFlags()` returns the flag suffix to append to `execSync('gbrain ...')` calls in migration orchestrators (propagates `--brain=<id>` so children stay on the parent's brain). `OperationContext.cliOpts` extends shared-op dispatch for MCP callers. `CliOptions` gains `explain: boolean`. `parseGlobalFlags` recognizes `--explain` anywhere in argv (stripped before command dispatch). `src/cli.ts` `formatResult` for `search` + `query` cases routes to `formatResultsExplain` from `src/core/search/explain-formatter.ts` when `CliOptions.explain` is set; falls through to the existing JSON / human formatters otherwise. `maybeBackground(opName, fingerprintArgs, runDirect)` helper. Same semantics in TTY and cron (no `--no-tty-detect` flag, no surprise behavior change between contexts): when `--background` is passed, submits the op as a Minion job via `op_checkpoints` for resumability and returns the `job_id`. `--background --follow` execs `gbrain jobs follow <id>` so the user sees the same stderr stream they'd get from a direct call. PGLite degrades to inline execution with a clear stderr note ("PGLite worker pool not yet supported; running inline"). Returns a tagged union the caller dispatches on.
- `src/cli.ts` strict flag validation (#2185) + `src/core/cli-flag-registry.generated.ts` + `scripts/generate-flag-registry.ts` — pre-dispatch, pre-engine unknown-flag rejection for every command: a flag no handler consults fails loud (`unknown flag --x for 'gbrain <cmd>'`, exit 1; `--json` invocations also get a structured `{status:'error', reason:'invalid_flag'}` on stdout) instead of being silently ignored while the un-asked-for real operation runs. `validateCommandFlags(command, subArgs)` runs after the `--help` short-circuit and before any dispatch or engine connect, in two lanes mirroring dispatch order (CLI_ONLY first — `think`/`salience`/`anomalies` are both ops AND CLI_ONLY members whose handlers parse flags the op contract doesn't declare): CLI_ONLY commands validate against the generated `CLI_FLAG_REGISTRY` (per-command legal sets derived from each command's source — case block + imported modules + one level of relative imports + `EXTRA_FLAGS`; deliberately over-inclusive, help-text mentions count; regenerate via `bun run build:flag-registry`); op commands validate via `findUnknownOpFlag`, which mirrors `parseOpArgs`'s traversal (non-boolean flags consume their value token; `--key=value` inline form recognized) plus the CLI-local flags consumed outside the op contract (`json`, `explain`, `help`, `source`, `dry-run`); the CLI_ONLY token scan is the exported `findUnknownFlag(args, legal)`. In `parseOpArgs`, `json`/`dry_run` are CLI-local booleans that never consume a value token, so a trailing `--dry-run` is a real rehearsal switch feeding `makeContext`'s `ctx.dryRun`. Uppercase flag spellings are treated as unknown (every handler is case-sensitive-lowercase, so they'd be silently ignored downstream — the exact class the validator kills). Exempt by contract: `call` (arbitrary `--param` interface), `config` (arbitrary set values), `jobs submit` (handler-defined payload params); everything after a literal `--` is passthrough and never validated. A command missing from the registry fails OPEN at runtime (never bricks a command); `test/cli-flag-validation.test.ts` pins registry freshness, per-command drift, and consumption evidence — a safety flag (`--dry-run`, `--yes`, `--force`) may only be advertised if the command's source actually reads it.
- `src/core/source-id.ts` — single canonical source_id validation, dependency-free by design (imported by both engines, cycle, source-resolver, sources-ops). `SOURCE_ID_RE` (strict: 1-32 lowercase alnum, interior hyphens only, no edge hyphens); `isValidSourceId` (boolean — for tiers that silently fall back: dotfile, brain_default) vs `assertValidSourceId` (throws — for tiers that must reject loudly: explicit `--source`, `GBRAIN_SOURCE`, `cycleLockIdFor`); `ALL_SOURCES = '__all__'` sentinel (#1712 — deliberately NOT a valid id so it can never collide with a real source or leak into lock ids/path joins; `sourceScopeOpts` translates it to an unscoped read for trusted local callers and keeps it unsatisfiable for remote callers, fail-closed). `normalizeSourceInput`/`normalizeFederatedReadInput` normalize the `/admin/api/register-client` HTTP body, mirroring the CLI's `--source`/`--federated-read` flags: omitted `source` → `'default'`; omitted `federatedRead` → `undefined` so `registerClientManual` applies its own `[sourceId]` default; present-but-invalid values throw so the route returns a structured 400 (`invalid_source`) instead of failing at INSERT time. Pinned by `test/register-client-source-normalize.test.ts`.
-- `src/core/db-lock.ts` — generic `tryAcquireDbLock(engine, lockId, ttlMinutes)` over the `gbrain_cycle_locks` table. Parameterized lock id so scopes nest cleanly: `gbrain-cycle` for the broad cycle (held by `cycle.ts`) and `gbrain-sync` (`SYNC_LOCK_ID`) for `performSync`'s narrower writer window. UPSERT-with-TTL semantics survive PgBouncer transaction pooling (unlike session-scoped `pg_try_advisory_lock`); crashed holders auto-release once their TTL expires. It also does automatic same-host dead-pid takeover: when the upsert finds a held, NOT-TTL-expired lock whose holder is on this host and provably dead, it reclaims via a guarded `DELETE WHERE id=$1 AND holder_pid=$2` + one normal-upsert retry returning the standard handle (refresh/release intact). The liveness check is the exported `classifyHolderLiveness(pid, host, ageMs, opts?)` / `isHolderDeadLocally(...)` (injectable `process.kill` seam; `HOLDER_TAKEOVER_GRACE_MS = 60_000` PID-reuse guard; EPERM classified as `alive` so a live process you don't own is never stolen). TTL-expired locks stay the upsert's job; cross-host stays TTL-only. `runBreakLock` (`src/commands/sync.ts`) consumes the same predicate. Background reaper (#1972): `reapDeadHolderLocks(engine)` is the periodic sweep the contention path lacked — it deletes locks whose holder is `isHolderDeadLocally`, scoped to the `gbrain-sync:*` / `gbrain-cycle`/`gbrain-cycle:*` namespaces ONLY (election/supervisor/reindex locks keep TTL-only behavior, untouched), via `deleteLockRowExact(engine, id, pid, acquiredAt)` — a snapshot-matched delete (`date_trunc('milliseconds', acquired_at) = $3`, so the ms a JS Date keeps survives) that's TOCTOU-safe against a reused PID taking the lock between SELECT and DELETE. `cycle.ts` runs it at cycle start (before the sync phase); `gbrain doctor --fix` runs it for no-autopilot brains. `selectLockRows(engine, opts?)` + a shared row→`LockSnapshot` mapper are the single canonical reader now backing `inspectLock` + `listStaleLocks` + the reaper (was triplicated). `isLockHolderLive(snap, ttlMinutes)` (#2227) is the observability liveness predicate — freshness-keyed (`ttl_expired` plus the heartbeat steal-grace), never `process.kill`, so `gbrain jobs supervisor status` / `gbrain doctor` can report a live supervisor via its queue lock without a PID-reuse false-positive. Pinned by `test/db-lock-auto-takeover.test.ts` + `test/db-lock-reap.test.ts`.
+- `src/core/db-lock.ts` — generic `tryAcquireDbLock(engine, lockId, ttlMinutes)` over the `gbrain_cycle_locks` table. Parameterized lock id so scopes nest cleanly: `gbrain-cycle` for the broad cycle (held by `cycle.ts`) and `gbrain-sync` (`SYNC_LOCK_ID`) for `performSync`'s narrower writer window. UPSERT-with-TTL semantics survive PgBouncer transaction pooling (unlike session-scoped `pg_try_advisory_lock`); crashed holders auto-release once their TTL expires. Every handle is FENCED to its exact acquisition: `DbLockHandle.acquiredAt` captures the row's `acquired_at` as epoch-seconds text (`extract(epoch from acquired_at)::text` — GUC-independent, unlike `timestamptz::text` which varies with per-session TimeZone/DateStyle across pools) and `refresh()`/`release()`/the cleanup hook all match `(id, holder_pid, fence)`, so a recycled PID or a superseded holder can never refresh or delete a successor's row. `refresh()` returns a boolean: `true` = still owned; `false` = the fenced UPDATE matched 0 rows (stolen or force-cleared — certain loss, the caller must stop relying on mutual exclusion); transient DB errors still THROW (not evidence of a steal; the TTL is the backstop). Exports `LockStolenError` (thrown/used as an AbortSignal reason by consumers like `cycle.ts`'s refresher and the supervisor). It also does automatic same-host dead-pid takeover: when the upsert finds a held, NOT-TTL-expired lock whose holder is on this host and provably dead, it reclaims via a guarded `DELETE WHERE id=$1 AND holder_pid=$2` + one normal-upsert retry returning the standard handle (refresh/release intact). The liveness check is the exported `classifyHolderLiveness(pid, host, ageMs, opts?)` / `isHolderDeadLocally(...)` (injectable `process.kill` seam; `HOLDER_TAKEOVER_GRACE_MS = 60_000` PID-reuse guard; EPERM classified as `alive` so a live process you don't own is never stolen). TTL-expired locks stay the upsert's job; cross-host stays TTL-only. `runBreakLock` (`src/commands/sync.ts`) consumes the same predicate. Background reaper (#1972): `reapDeadHolderLocks(engine)` is the periodic sweep the contention path lacked — it deletes locks whose holder is `isHolderDeadLocally`, scoped to the `gbrain-sync:*` / `gbrain-cycle`/`gbrain-cycle:*` namespaces ONLY (election/supervisor/reindex locks keep TTL-only behavior, untouched), via `deleteLockRowExact(engine, id, pid, acquiredAt)` — a snapshot-matched delete (`date_trunc('milliseconds', acquired_at) = $3`, so the ms a JS Date keeps survives) that's TOCTOU-safe against a reused PID taking the lock between SELECT and DELETE. `cycle.ts` runs it at cycle start (before the sync phase); `gbrain doctor --fix` runs it for no-autopilot brains. `selectLockRows(engine, opts?)` + a shared row→`LockSnapshot` mapper are the single canonical reader now backing `inspectLock` + `listStaleLocks` + the reaper (was triplicated). `isLockHolderLive(snap, ttlMinutes)` (#2227) is the observability liveness predicate — freshness-keyed (`ttl_expired` plus the heartbeat steal-grace), never `process.kill`, so `gbrain jobs supervisor status` / `gbrain doctor` can report a live supervisor via its queue lock without a PID-reuse false-positive. Pinned by `test/db-lock-auto-takeover.test.ts` + `test/db-lock-reap.test.ts` + `test/db-lock-fencing.test.ts`.
- `src/core/sync-concurrency.ts` — single source of truth for the parallel-sync policy. Exports `autoConcurrency(engine, fileCount, override?)` (PGLite always serial; explicit override clamped to >=1; auto path returns `DEFAULT_PARALLEL_WORKERS=4` when `fileCount > AUTO_CONCURRENCY_FILE_THRESHOLD=100`), `shouldRunParallel(workers, fileCount, explicit)` (explicit `--workers` bypasses the >50-file floor), and `parseWorkers(s)` (rejects `'0'`, `'-3'`, `'foo'`, `'1.5'`, trailing chars). Used by `performSync`, `performFullSync`, `runImport`, and the Minion `sync` handler so the sites can't drift. `DEFAULT_PARALLEL_SOURCES = 4` is a SEPARATE constant for the per-source fan-out under `gbrain sync --all` — kept distinct from `DEFAULT_PARALLEL_WORKERS` because total live Postgres connections per wave ≈ `DEFAULT_PARALLEL_SOURCES × DEFAULT_PARALLEL_WORKERS × 2 (per-file pool)` = 32 at both defaults (each per-file worker opens its own `PostgresEngine` with `poolSize = min(2, resolvePoolSize(2))`); `sync.ts` warns when `parallel × workers × 2 > 16`. `resolveWorkersWithClamp(engine, override, commandName, fileCount)` wraps `autoConcurrency` with a per-command stderr clamp warning on PGLite (per-(command, requested) dedup via module-scoped warned-once set with `_resetWorkersClampWarningsForTest()` seam) and is the canonical surface for every bulk-command `--workers N` flag (extract-conversation-facts, extract, edges-backfill, reindex-multimodal, reindex, reindex-code); embed.ts deliberately bypasses it and keeps `GBRAIN_EMBED_CONCURRENCY || 20`. `resolveMaxConnections()` (reads `GBRAIN_MAX_CONNECTIONS`, undefined when unset) + `clampWorkersForConnectionBudget(workers, perWorkerPool, maxConnections, parentPool)` back the opt-in single-sync connection-footprint clamp so a big sync stays under a low pooler cap (`parent_pool + workers×perWorkerPool ≤ budget`); `gbrain doctor`'s `pool_budget` check (`computePoolBudgetCheck` / `checkPoolBudget` in `src/commands/doctor.ts`) warns when the budget leaves no room for a worker, pointing at `GBRAIN_POOL_SIZE=2`. Pinned by `test/pglite-workers-clamp.test.ts`.
- `src/core/worker-pool.ts` — Canonical sliding-pool + bounded-semaphore primitive (extracted from `src/commands/embed.ts` sliding-pool sites and `src/commands/eval-cross-modal.ts` `runWithLimit` semaphore). Two exports: `runSlidingPool<T>({items, workers, onItem, signal?, onError?, failureLabel?, onProgress?})` + `runWithLimit<TIn, TOut>({items, limit, fn, signal?})`. Atomicity invariant: `const idx = nextIdx++` is one synchronous JS statement (no `await` between read and write — guaranteed by the single-threaded event loop), documented in the module header AND enforced by `scripts/check-worker-pool-atomicity.sh` (wired into `bun run verify`), which rejects importing `worker_threads` in any consuming file and inserting `await` between the `nextIdx` read and write. `MUST_ABORT_ERROR_TAGS` set is seeded with `BUDGET_EXHAUSTED` from `src/core/budget/budget-tracker.ts`; tagged errors (matched via `err.tag === 'BUDGET_EXHAUSTED'` to avoid cross-module import) bypass `onError` and hard-abort the pool via `AbortController.abort()` to in-flight `onItem` — the budget cap is a structural ceiling under concurrency. `failures[]` shape is `{idx, label, error}` records (NOT full items; callers supply `failureLabel(item) => string`) for bounded memory under huge brains. Pinned by `test/worker-pool.test.ts` + `test/scripts/check-worker-pool-atomicity.test.ts`. Drives every `--workers N` bulk command.
- `src/core/embedding-dim-check.ts` — facts.embedding dim drift surface. `readFactsEmbeddingDim(engine): Promise<FactsColumnDimResult>` covers both `vector(N)` and `halfvec(N)` shapes (migration v40 falls back to `vector` on pgvector < 0.7); regex ordering is halfvec-before-vector (substring "vec" appears in "halfvec"; naive `/vector/i` would shadow). `buildFactsAlterRecipe(dims, configured, type)` emits the paste-ready `DROP INDEX IF EXISTS idx_facts_embedding_hnsw; ALTER TABLE facts ALTER COLUMN embedding TYPE halfvec(N) USING embedding::halfvec(N); CREATE INDEX idx_facts_embedding_hnsw ON facts USING hnsw (embedding halfvec_cosine_ops) WHERE ...` flow (NOT bare REINDEX, which doesn't rewrite the index after a column-type change). `assertFactsEmbeddingDimMatchesConfig(engine)` is the preflight — throws `FactsEmbeddingDimMismatchError` (tagged `tag: 'FACTS_EMBEDDING_DIM_MISMATCH'` for parity with the worker-pool MUST_ABORT semantics) when configured dim ≠ column width; cached per-engine via `WeakMap`; PGLite engines silently skip. Doctor check `facts_embedding_width_consistency` (registered after `embedding_width_consistency`) reuses the same helpers with an identical ALTER recipe. Pinned by `test/embedding-dim-check-facts.test.ts`.
- `src/core/sort-newest-first.ts` — single source of truth for the descending-lex sort that `gbrain import` and `gbrain sync` both apply. Mutates in place (Array.prototype.sort semantics), returns the same array reference for fluent chaining. Empty/single-element inputs short-circuit. Future ordering changes flip one line here instead of touching two CLI commands. Pinned by `test/sort-newest-first.test.ts` (descending order, mixed prefixes, empty, single-element, in-place-mutation contract).
-- `src/core/cycle.ts` — brain maintenance cycle primitive (9 phases). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order: lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite. `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive (synthesize/patterns renew the cycle-lock TTL during long waits). Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (#1586: threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out (#2194/#2227): `PHASE_SCOPE` partitions `ALL_PHASES` into `GLOBAL_PHASES` (brain-wide: embed/orphans/purge/resolve_symbol_edges/grade_takes/calibration_profile/synthesize_concepts/skillopt) and `NON_GLOBAL_PHASES` (source + mixed). Per-source `autopilot-cycle` jobs run only `NON_GLOBAL_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `GLOBAL_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (no longer a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). Future phase wrappers (sync, extract, embed, orphans, extract_facts, resolve_symbol_edges, recompute_emotional_weight) land as additional describes in the same file. with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops fixes. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) replaces the per-hash loop (7K individual queries) with one batched SQL roundtrip returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Shorter cycle lock TTL + active in-phase refresh: `LOCK_TTL_MINUTES = 5` (was 30); `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock 6x faster while a healthy long-running cycle keeps it alive (residual: a single `await chat()` past 5 min can expire the lock mid-await — TODO-OPS-2). (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/cycle/cycle-lock-ttl.test.ts` (regression pin on `LOCK_TTL_MINUTES === 5`), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (#2163: the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (the cycle's 9th phase, for soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). #1737: the cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run.
+- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; their in-flight work runs to its own bounded timeout because their opts can't carry a signal yet). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (#1586: threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out (#2194/#2227): `PHASE_SCOPE` partitions `ALL_PHASES` into `GLOBAL_PHASES` (brain-wide: embed/orphans/purge/resolve_symbol_edges/grade_takes/calibration_profile/synthesize_concepts/skillopt) and `NON_GLOBAL_PHASES` (source + mixed). Per-source `autopilot-cycle` jobs run only `NON_GLOBAL_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `GLOBAL_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (no longer a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). Future phase wrappers (sync, extract, embed, orphans, extract_facts, resolve_symbol_edges, recompute_emotional_weight) land as additional describes in the same file. with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops fixes. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) replaces the per-hash loop (7K individual queries) with one batched SQL roundtrip returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/cycle/cycle-lock-ttl.test.ts` (regression pin on `LOCK_TTL_MINUTES === 5`), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (#2163: the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). #1737: the cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run.
- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline. Reads `dream.synthesize.session_corpus_dir`, runs a cheap Haiku verdict (cached in `dream_verdicts`), then fans out one Sonnet subagent per worth-processing transcript with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace — #2415 — and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped (#1586): cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written ONLY on success. Idempotency key `dream:synth:<file_path>:<content_hash>`. `--dry-run` runs Haiku, skips Sonnet. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` (#2569) additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance` and `JudgeClient` are exported; `judgeSignificance` takes a `verdictModel` param loaded from `dream.synthesize.verdict_model` via `loadSynthConfig`. `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Per-chunk idempotency keys `dream:synth:<filePath>:<hash16>:c<i>of<n>`; single-chunk transcripts preserve the legacy `dream:synth:<filePath>:<hash16>` key byte-for-byte so existing brains skip with `already_synthesized_legacy_single_chunk` instead of re-spending Sonnet. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips don't write to `dream_verdicts` so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported, replacing `makeHaikuClient()`) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary (lines 395-404) a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`.
-- `scripts/check-gateway-routed-no-direct-anthropic.sh` — CI guard that fails the build if `src/core/cycle/synthesize.ts` or `src/core/think/index.ts` reintroduces a runtime `new Anthropic()` constructor call or a value-shaped `import Anthropic from '@anthropic-ai/sdk'` import. Type-only imports (`import type Anthropic from '@anthropic-ai/sdk'`) stay allowed for adapter types; comment lines (`//` or ` *` prefixes) are excluded so historical JSDoc doesn't false-fire. Mirrors `scripts/check-jsonb-pattern.sh`. Wired into `bun run verify` and `bun run check:all`. Extend `GUARDED_FILES` when migrating another file off direct SDK construction.
+- `scripts/check-gateway-routed-no-direct-anthropic.sh` — CI guard that fails the build if `src/core/cycle/synthesize.ts` or `src/core/think/index.ts` reintroduces a runtime `new Anthropic()` constructor call or a value-shaped `import Anthropic from '@anthropic-ai/sdk'` import. Type-only imports (`import type Anthropic from '@anthropic-ai/sdk'`) stay allowed for adapter types; comment lines (`//` or ` *` prefixes) are excluded so historical JSDoc doesn't false-fire. Mirrors `scripts/check-jsonb-pattern.sh`. Wired into `bun run verify`. Extend `GUARDED_FILES` when migrating another file off direct SDK construction.
- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — #2415: the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh.
- `src/core/cycle/extract-facts.ts` — extract_facts cycle phase. Fence is canonical: per-page wipe (`deleteFactsForPage`) + reinsert from `parseFactsFence` + `extractFactsFromFenceText` + `engine.insertFacts`. #1928: the per-page wipe passes `excludeSourcePrefixes: ['cli:']` so conversation facts (written by `extract-conversation-facts`, on pages with NO `## Facts` fence to recreate them from) survive the reconcile instead of being deleted-with-nothing-to-reinsert. The destructive phase no longer inherits a failed sync's full-brain walk: `slugs: []` (a real incremental no-op) is distinguished from `slugs: undefined` (full-walk intent) by presence, not length. `runPhaseExtractFacts` (cycle.ts) surfaces a `warn` (`net_fact_deletion`) when the reconcile deletes at least `NET_DELETION_WARN_FLOOR` (50) more facts than it reinserts — the exact signature of the conversation-facts wipe, which previously read as a silent `ok`. Empty-fence guard refuses when legacy rows (`row_num IS NULL AND entity_slug IS NOT NULL`) pend backfill (status: warn, hint: `gbrain apply-migrations --yes`). A phantom-redirect pre-pass runs AFTER the legacy-row guard, BEFORE the main reconcile loop: when `opts.brainDir` is set, `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun)` walks unprefixed-slug pages capped by `GBRAIN_PHANTOM_REDIRECT_LIMIT` (default 50). The pass returns `touched_canonicals` — canonical slugs whose disk fence merged with phantom rows; `runExtractFacts` UNIONs them into the main reconcile slug set so canonical's DB facts derive from the merged fence in the same cycle (handles phantom-had-only-on-disk-fence). `ExtractFactsResult` gains six phantom fields: `phantomsScanned`, `phantomsRedirected`, `phantomsAmbiguous`, `phantomsSkippedDrift`, `phantomsLockBusy`, `phantomsMorePending`. Three bubble to `CycleReport.totals` (`phantoms_redirected`, `phantoms_ambiguous`, `phantoms_skipped_drift`).
- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`. `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.
@@ -334,7 +334,9 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (the #1939 wedge: `title: 2024-06-01` parsed as a `Date`, `title: 1458` as a number, and the throw blocked the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics).
- `scripts/check-jsonb-pattern.sh` — CI grep guard. Fails the build if anyone reintroduces (a) the `${JSON.stringify(x)}::jsonb` interpolation pattern (postgres.js v3 double-encodes it), or (b) `max_stalled INTEGER NOT NULL DEFAULT 1` in any schema source file (must be DEFAULT 5 to preserve SIGKILL-rescue). It also invokes `scripts/check-jsonb-params.mjs` and propagates its exit code. Wired into `bun test`.
- `scripts/check-jsonb-params.mjs` — AST-lite CI guard for the POSITIONAL jsonb double-encode form the template grep above misses: an `executeRaw`/`executeRawDirect`/`.unsafe()` call whose balanced arg span binds `JSON.stringify(x)` into a bare `$N::jsonb` cast (the #2339 class). Walks each call's balanced span respecting strings/templates/comments, handles generic-typed calls (`executeRaw<T>(`), and allows the sanctioned forms (`$N::text::jsonb`, `$N::text[]`, `executeRawJsonb`, `sql.json`, an inline `jsonb-guard-ok` comment). PGLite's native `db.query` is deliberately not scanned (it parses text→jsonb, so the bug can't occur there). Heuristic by design (whole-span correlation; can't see a `JSON.stringify` assigned to a variable before the call) — the real backstop is the DATABASE_URL-gated e2e parity tests. Scan roots overridable via argv for its self-test (`test/check-jsonb-params.test.ts`).
-- `scripts/check-source-id-projection.sh` — CI grep guard for the multi-source bug class. Greps `src/core/postgres-engine.ts` + `src/core/pglite-engine.ts` for `SELECT.*FROM pages` projections matching the `rowToPage` feeder shape (id + slug + type + title) and fails if `source_id` is missing. `Page.source_id` is required at the type level; a projection dropping the column produces `Page` rows with `source_id: undefined` while TypeScript's `: string` lies about it. Wired into `bun run verify` + `bun run check:all`.
+- `scripts/check-source-id-projection.sh` — CI grep guard for the multi-source bug class. Greps `src/core/postgres-engine.ts` + `src/core/pglite-engine.ts` for `SELECT.*FROM pages` projections matching the `rowToPage` feeder shape (id + slug + type + title) and fails if `source_id` is missing. `Page.source_id` is required at the type level; a projection dropping the column produces `Page` rows with `source_id: undefined` while TypeScript's `: string` lies about it. Wired into `bun run verify`.
+- `scripts/guards-manifest.tsv` + `scripts/guard-self-test.sh` — THE single registry of `scripts/check-*` CI guards (45 guards) and its self-test harness. Every guard is classified `scanner` (greps/parses repo sources — must eventually carry fixtures), `buildfresh`, or `repostate` (exempt-with-reason, not fixture-tested). `guard-self-test.sh` (`bun run check:guard-self-test`, wired into `bun run verify`) runs each `selftest=yes` scanner against known-bad (must exit non-zero) and known-good (must pass) fixture trees under `test/fixtures/guards/<guard>/{bad,good}/` via the `GBRAIN_GUARD_ROOT` env seam, and fails the build when a new `scripts/check-*` script is missing from the manifest — so a guard whose pattern rots into a permanently-green no-op fails CI instead of masquerading as coverage. The manifest replaces the second hand-synced REGISTRY copy (package.json's `check:all` chain — deleted); it registers and classifies guards but does not itself schedule them — `run-verify-parallel.sh`'s `CHECKS` array remains the execution list, and a registered guard is not automatically wired into verify. New guard = new manifest row (+ fixtures if scanner) + a `CHECKS` entry if it should gate pushes.
+- `scripts/build-pglite-snapshot.ts` — `bun run build:pglite-snapshot`: bakes a post-`initSchema()` PGLite data dir into `test/fixtures/pglite-snapshot.tar` + a version file (schema hash line, then `dims=`/`model=` lines recording the embedding shape it was baked with). Idempotent (hash short-circuit ~40ms when fresh; rebuilds stale) and concurrency-safe (atomic `mkdir` lock at `test/fixtures/.pglite-snapshot.lock` with staleness-verified takeover — a live lock is never stolen; tar written first, version file last, so a crash can't leave a fresh-looking torn fixture; waiter bounded by `GBRAIN_SNAPSHOT_LOCK_TIMEOUT_MS`, default 120000; an exhausted waiter facing a still-live lock proceeds unlocked as a last resort — the loader's hash/shape gate validates the version file, not the tar bytes). Called by `scripts/run-unit-parallel.sh` (default-on for `bun run test`; opt out `GBRAIN_NO_SNAPSHOT=1`) and `scripts/ci-local.sh`, both of which export `GBRAIN_PGLITE_SNAPSHOT`. The loader side is `tryLoadSnapshot` + `computeSnapshotSchemaHash` (exported from `src/core/pglite-engine.ts`): the hash folds `PGLITE_SCHEMA_SQL`, every migration's `sql` + `sqlFor.pglite`, AND each migration `handler`'s function source (handler-only migrations are invisible to a sql-only hash); any hash or embedding-shape mismatch warns once and falls through to normal cold init — the snapshot is an optimization, never authoritative. Pinned by `test/snapshot-shape-guard.test.ts`.
- `docker-compose.ci.yml` + `scripts/ci-local.sh` — Local CI gate. `bun run ci:local` spins up four `pgvector/pgvector:pg16` services (postgres-1..4) + `oven/bun:1` with named volumes (`gbrain-ci-pg-data-{1..4}`, `gbrain-ci-node-modules`, `gbrain-ci-bun-cache`), runs gitleaks on host, smoke-tests `scripts/run-e2e.sh` argv handling, runs guards + typecheck, then the Tier 1 default: 4-shard parallel unit + E2E (`xargs -P4`, one Postgres per shard; unit phase keeps `DATABASE_URL` unset). `--no-shard` falls back to the legacy unsharded sequential flow (debug aid); `--diff` runs the diff-aware selector unsharded. Also runs a `pgbouncer` service (`edoburu/pgbouncer`, `POOL_MODE: transaction`, `AUTH_TYPE: plain` — pg16 stores SCRAM verifiers, so the userlist must hold the plaintext password; `IGNORE_STARTUP_PARAMETERS` whitelists gbrain's `statement_timeout`/`idle_in_transaction_session_timeout` startup params the way the Supabase pooler does) fronting postgres-1 on host port `GBRAIN_CI_PGBOUNCER_PORT` (default 6543); every E2E invocation exports `GBRAIN_PGBOUNCER_URL` (pooled; dedicated `gbrain_pgbouncer` database so it never races the `gbrain_test` TRUNCATE fixtures) + `GBRAIN_PGBOUNCER_DIRECT_URL`, consumed by `test/e2e/pgbouncer-teardown.test.ts` — the transaction-mode teardown bug class (#1972/#2015/#2084) reproduced in the local gate instead of only in production. `--no-pull` skips upstream pulls; `--clean` nukes named volumes. Postgres host port defaults to 5434; override with `GBRAIN_CI_PG_PORT=NNNN`. Stronger gate than PR CI's 2-file Tier 1 set.
- `scripts/select-e2e.ts` + `scripts/e2e-test-map.ts` — Diff-aware E2E test selector. Reads three git sources (committed `origin/master...HEAD`, working-tree `HEAD`, and `git ls-files --others --exclude-standard` for untracked NOT-gitignored files), classifies as EMPTY / DOC_ONLY / SRC. Fail-closed: EMPTY → all files; DOC_ONLY (every path matches the README/CLAUDE/AGENTS/CHANGELOG/TODOS allowlist) → empty stdout; SRC → escape-hatch paths (schema, package.json, skills/) trigger all, else the hand-tuned `E2E_TEST_MAP` glob narrows, and an unmapped src/ change still emits ALL files (never silently nothing). Pure-function exports `selectTests`, `classify`, `matchGlob`. `bun run ci:select-e2e` prints the current selection on stdout. `test/select-e2e.test.ts` covers all 4 branches plus 3 regression guards (skills/, untracked files, unmapped src/) — 24 cases.
- `scripts/run-e2e.sh` — Sequential E2E runner. Accepts an optional argv-driven file list (used by `ci:local:diff`) and a `--dry-run-list` flag that prints the resolved file list and exits (used by `ci-local.sh`'s startup smoke-test). Falls back to `test/e2e/*.test.ts` when invoked with no args.
@@ -385,7 +387,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `skills/migrations/` — Version migration files with feature_pitch YAML frontmatter
- `src/commands/publish.ts` — Deterministic brain page publisher (code+skill pair, zero LLM calls)
- `src/commands/backlinks.ts` — Back-link checker and fixer (enforces Iron Law)
-- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates) lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. with `src/commands/sources.ts`: `gbrain lint` gains a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` becomes disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the new quarantine/flag dispositions.
+- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. with `src/commands/sources.ts`: `gbrain lint` gains a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` becomes disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the new quarantine/flag dispositions.
- `src/commands/report.ts` — Structured report saver (audit trail for maintenance/enrichment)
- `src/core/destructive-guard.ts` — three-layer protection against accidental data loss. `assessDestructiveImpact(engine, sourceId)` counts pages/chunks/embeddings/files for a source. `checkDestructiveConfirmation(impact, opts)` is the fail-closed gate (`--confirm-destructive` required when data is present; `--yes` alone is rejected). `softDeleteSource` / `restoreSource` / `listArchivedSources` / `purgeExpiredSources` drive the source-level archive lifecycle via `sources.archived BOOLEAN`, `archived_at TIMESTAMPTZ`, `archive_expires_at TIMESTAMPTZ`. Page-level analog: `BrainEngine.softDeletePage` / `restorePage` / `purgeDeletedPages` plus `pages.deleted_at TIMESTAMPTZ` and a partial purge index. The MCP `delete_page` op rewires to `softDeletePage`; ops `restore_page` (`scope: write`) and `purge_deleted_pages` (`scope: admin`, `localOnly: true`) round out the surface. Search visibility (`buildVisibilityClause` in `src/core/search/sql-ranking.ts`) hides soft-deleted pages and archived sources from `searchKeyword` / `searchKeywordChunks` / `searchVector` in both engines. The autopilot cycle's `purge` phase calls `purgeExpiredSources` + `engine.purgeDeletedPages(72)` so the 72h TTL is real.
- `src/commands/pages.ts` — `gbrain purge-deleted [--older-than HOURS|Nd] [--dry-run] [--json]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff; cascades to content_chunks/page_links/chunk_relations.
diff --git a/docs/eval/FIX_WAVE_BASELINES.md b/docs/eval/FIX_WAVE_BASELINES.md
new file mode 100644
index 0000000000..5fb12a8d2d
--- /dev/null
+++ b/docs/eval/FIX_WAVE_BASELINES.md
@@ -0,0 +1,61 @@
+# Fix-wave series baselines (W0 → W9)
+
+Recorded per wave so the series' "10x better for 2x effort" claim is measured,
+not vibed (fix-wave plan D4.13). Update this file in each wave's PR; keep the
+prior rows — the deltas ARE the receipt.
+
+## How to refresh
+
+```bash
+wc -l src/commands/doctor.ts src/core/pglite-engine.ts src/core/postgres-engine.ts \
+ src/core/operations.ts src/core/migrate.ts src/commands/sync.ts \
+ src/core/ai/gateway.ts src/cli.ts src/core/engine.ts \
+ src/core/search/hybrid.ts src/core/search/mode.ts src/core/cycle.ts
+ls scripts/check-* | wc -l # guard count
+bash scripts/guard-self-test.sh # self-tested count + harness runtime
+bun run test > /tmp/suite.txt 2>&1; echo $? # wall-clock from the run banner
+```
+
+Retrieval-quality canary (MANDATORY before W1, and after W1/W3/W9): run
+`gbrain eval gate` against a NON-PRODUCTION brain (the production PGLite brain
+is single-writer and usually held by a live `gbrain serve`; eval runs never
+touch `~/.gbrain` per the eval discipline — results land in
+`<repo>/.gbrain-evals/eval-results.jsonl`). Record the gate verdict + headline
+metrics here per run.
+
+## W0 (2026-08-14, branch garrytan/code-smell-fix-wave @ post-hotfix)
+
+God-file line counts (the audit's structural targets, BEFORE the registry waves):
+
+| File | Lines |
+|---|---|
+| src/commands/doctor.ts | 10,057 |
+| src/core/operations.ts | 7,459 |
+| src/core/pglite-engine.ts | 6,874 |
+| src/core/postgres-engine.ts | 6,847 |
+| src/core/migrate.ts | 6,201 |
+| src/commands/sync.ts | 5,991 |
+| src/core/ai/gateway.ts | 4,049 |
+| src/cli.ts | 3,301 |
+| src/core/cycle.ts | 2,933 |
+| src/core/search/hybrid.ts | 2,453 |
+| src/core/engine.ts | 2,320 |
+| src/core/search/mode.ts | 1,232 |
+
+Guards: 47 scripts/check-* files; 3 self-tested (harness <1s, budget 30s);
+single registry established (guards-manifest.tsv; `check:all` deleted; 3
+previously-unreachable guards wired into verify).
+
+Test infra: PGLite snapshot default-on for `bun run test`. Per-PGLite-file:
+1.63s cold → 0.91s snapshotted (measured on test/db-lock-fencing.test.ts).
+Full-suite wall-clock (post-snapshot): recorded in the W0 ship notes — see
+the run banner of the W0 PR's `bun run test` evidence.
+
+Retrieval canary: NOT RUN at W0 (production brain locked by live serve; W0
+touches no search paths). REQUIRED before W1 lands.
+
+Verified-bug status at W0 ship: cycle-lock refresh + fencing (TODO-OPS-2
+closed), stall-death parent unblock, started_at ×4, modality carry, import
+typed aborts, lint single-pass, prompt EOF safety, guard self-test harness,
+snapshot default-on. W0a superseded by master's WP1/D7 (port-ledger in the
+plan file).
diff --git a/llms-full.txt b/llms-full.txt
index 3e1344dcab..697632b0b4 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -225,7 +225,11 @@ Per-file detail is in `docs/architecture/KEY_FILES.md`.
- **Engine-live paths avoid runtime dynamic `import()` for helper dependencies.** In
`src/core/pglite-engine.ts`, `src/core/postgres-engine.ts`, and
`src/core/migrate.ts`, dependencies previously reached through runtime dynamic
- imports use static top-level imports. The only current dynamic-`import()` exceptions
+ imports use static top-level imports. Besides the snapshot loader's lazy
+ `require()` cluster in `pglite-engine.ts:tryLoadSnapshot` (fs/crypto/
+ migrate/pglite-schema + one gateway shape lookup — lazy so production
+ builds without the test-fixture path don't eager-load; the guard now
+ matches `require()` calls too), the only dynamic-`import()` exceptions
are the four `ai/gateway.ts` lookups in both engines'
`initSchema()` and `_upsertChunksOnce()` methods; each remains lazy inside a
local `try/catch` because the gateway has a large provider/config closure and,
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index f7356369b0..956cadf656 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.45.15.0",
+ "version": "0.45.16.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 78a098890f..67306640fb 100644
--- a/package.json
+++ b/package.json
@@ -50,7 +50,6 @@
"check:admin-scope-drift": "bash scripts/check-admin-scope-drift.sh",
"check:cli-exec": "bash scripts/check-cli-executable.sh",
"check:engine-dynamic-import": "bash scripts/check-engine-dynamic-import.sh",
- "check:all": "bash scripts/check-privacy.sh && bash scripts/check-proposal-pii.sh && bash scripts/check-test-real-names.sh && bash scripts/check-jsonb-pattern.sh && bash scripts/check-source-id-projection.sh && bash scripts/check-source-config-leak.sh && bash scripts/check-progress-to-stdout.sh && bash scripts/check-no-tracked-symlinks.sh && bash scripts/check-no-legacy-getconnection.sh && bash scripts/check-test-isolation.sh && bash scripts/check-trailing-newline.sh && bash scripts/check-wasm-embedded.sh && bash scripts/check-pglite-embedded.sh && bash scripts/check-exports-count.sh && bash scripts/check-admin-build.sh && bash scripts/check-admin-scope-drift.sh && bash scripts/check-cli-executable.sh && bash scripts/check-skill-brain-first.sh && bash scripts/check-operations-filter-bypass.sh && bash scripts/check-gateway-routed-no-direct-anthropic.sh && bash scripts/check-worker-pool-atomicity.sh && bash scripts/check-key-files-current-state.sh && bash scripts/check-no-double-retry.sh && bash scripts/check-batch-audit-site.sh && bash scripts/check-engine-dynamic-import.sh",
"check:gateway-routed": "bash scripts/check-gateway-routed-no-direct-anthropic.sh",
"check:worker-pool-atomicity": "bash scripts/check-worker-pool-atomicity.sh",
"check:doc-history": "bash scripts/check-key-files-current-state.sh",
@@ -97,7 +96,9 @@
"prepublish:clawhub": "bun run build:all",
"publish:clawhub": "clawhub package publish . --family bundle-plugin",
"check:skill-refs": "bun scripts/check-skill-refs.mjs",
- "gate:skills": "bash scripts/skills-commit-gate.sh"
+ "gate:skills": "bash scripts/skills-commit-gate.sh",
+ "check:guard-self-test": "bash scripts/guard-self-test.sh",
+ "check:no-legacy-getconnection": "bash scripts/check-no-legacy-getconnection.sh"
},
"openclaw": {
"compat": {
@@ -155,7 +156,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.45.15.0",
+ "version": "0.45.16.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/scripts/build-pglite-snapshot.ts b/scripts/build-pglite-snapshot.ts
index 12da70fd3c..576a2c682f 100644
--- a/scripts/build-pglite-snapshot.ts
+++ b/scripts/build-pglite-snapshot.ts
@@ -18,10 +18,14 @@
//
// Re-run whenever you touch src/core/migrate.ts or src/schema.sql.
-import { writeFileSync, mkdirSync } from "node:fs";
-import { dirname } from "node:path";
+import { writeFileSync, mkdirSync, existsSync, readFileSync, rmdirSync, rmSync, mkdtempSync, statSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { tmpdir } from "node:os";
import * as crypto from "node:crypto";
+import { configureGateway, getEmbeddingDimensions, getEmbeddingModel } from "../src/core/ai/gateway.ts";
+import { LEGACY_EMBEDDING_CONFIG } from "../test/helpers/legacy-embedding-config.ts";
+
import { PGLiteEngine, computeSnapshotSchemaHash } from "../src/core/pglite-engine.ts";
import { MIGRATIONS } from "../src/core/migrate.ts";
import { PGLITE_SCHEMA_SQL } from "../src/core/pglite-schema.ts";
@@ -33,9 +37,84 @@ function computeSchemaHash(): string {
async function main() {
const fixturePath = "test/fixtures/pglite-snapshot.tar";
const versionPath = "test/fixtures/pglite-snapshot.version";
+ const lockPath = "test/fixtures/.pglite-snapshot.lock";
mkdirSync(dirname(fixturePath), { recursive: true });
+ // W0 fix-wave: build under the EXACT embedding shape the test suite pins.
+ // bunfig.toml preloads test/helpers/legacy-embedding-preload.ts, which
+ // configures the gateway to the shared LEGACY_EMBEDDING_CONFIG (OpenAI
+ // 1536-d) for every `bun test` file — so the snapshot's baked vector(dims)
+ // columns MUST match that shape, not the builder machine's ambient config
+ // (nor the shipped 1280-d default an unconfigured gateway falls back to).
+ // Set in main(), not module scope: ESM hoists imports, so module-scope
+ // placement implied an ordering it never had — config reads are lazy.
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: { ...process.env } });
+
const schemaHash = computeSchemaHash();
+
+ // W0 fix-wave (Tier-1 #16): idempotent short-circuit. Runners now call this
+ // script UNCONDITIONALLY (build-if-missing left stale-but-present snapshots
+ // permanently on the warn+slow path); a fresh snapshot exits in ~ms.
+ const isFresh = () => {
+ if (!existsSync(fixturePath) || !existsSync(versionPath)) return false;
+ const lines = readFileSync(versionPath, "utf-8").trim().split("\n");
+ return lines[0] === schemaHash
+ && lines[1] === `dims=${getEmbeddingDimensions()}`
+ && lines[2] === `model=${getEmbeddingModel()}`;
+ };
+ if (isFresh()) {
+ console.log(`[build-pglite-snapshot] up to date (hash ${schemaHash.slice(0, 16)}...) — nothing to do`);
+ return;
+ }
+
+ // GBRAIN_HOME isolation is only needed once we actually BUILD (the engine
+ // boot reads config). Red-team catch: creating it before the isFresh()
+ // short-circuit leaked one temp dir per invocation on the COMMON path
+ // (this script runs on every `bun run test`).
+ const hermeticHome = mkdtempSync(join(tmpdir(), "gbrain-snapshot-hermetic-"));
+ process.env.GBRAIN_HOME = hermeticHome;
+
+ // W0 fix-wave (D5.8): concurrency lock. Parallel shard runners / concurrent
+ // Conductor workspaces invoking this simultaneously must not tear the tar.
+ // mkdir is atomic; the loser polls until the winner finishes, then
+ // re-checks freshness and exits.
+ let ownLock = false;
+ try {
+ mkdirSync(lockPath);
+ ownLock = true;
+ } catch {
+ console.log(`[build-pglite-snapshot] another builder holds ${lockPath}; waiting...`);
+ const timeoutMs = Number(process.env.GBRAIN_SNAPSHOT_LOCK_TIMEOUT_MS) || 120_000;
+ const deadline = Date.now() + timeoutMs;
+ while (existsSync(lockPath) && Date.now() < deadline) {
+ await new Promise(r => setTimeout(r, 250));
+ }
+ if (isFresh()) {
+ console.log(`[build-pglite-snapshot] concurrent builder finished; snapshot fresh`);
+ return;
+ }
+ // Stale lock (crashed builder) or still-stale snapshot: TAKE OVER.
+ // W0 ship-review catch: mkdirSync on a still-existing dir always throws
+ // EEXIST — the original retry could never acquire, so a single crashed
+ // builder left every future rebuild waiting the full deadline and then
+ // proceeding UNLOCKED forever (the stale dir was never removed).
+ // Red-team refinement: verify STALENESS (lock dir mtime older than the
+ // full wait window) before the rmdir — two exhausted waiters would
+ // otherwise each rmdir+mkdir and the second would steal the first's
+ // just-created LIVE lock, re-opening the torn-tar window.
+ try {
+ if (existsSync(lockPath)) {
+ const ageMs = Date.now() - statSync(lockPath).mtimeMs;
+ if (ageMs > timeoutMs) {
+ console.log(`[build-pglite-snapshot] stale lock (age ${Math.round(ageMs / 1000)}s > ${Math.round(timeoutMs / 1000)}s) — taking over`);
+ rmdirSync(lockPath);
+ }
+ }
+ mkdirSync(lockPath);
+ ownLock = true;
+ } catch { /* lock is LIVE (fresh mtime) or takeover raced; proceed unlocked as last resort */ }
+ }
+ try {
console.log(`[build-pglite-snapshot] schema hash: ${schemaHash.slice(0, 16)}...`);
console.log(`[build-pglite-snapshot] booting PGLite (in-memory)...`);
const engine = new PGLiteEngine();
@@ -53,12 +132,21 @@ async function main() {
const dump = await engine.db.dumpDataDir("none");
const buffer = Buffer.from(await dump.arrayBuffer());
+ // Write tar first, version LAST — the version file is the commit point, so
+ // a crash between the writes leaves a stale-hash (ignored) snapshot, never
+ // a fresh-looking torn one. Lines 2-3 record the embedding shape the
+ // snapshot was baked with; the loader refuses a shape-mismatched snapshot
+ // (the W0 1280-vs-1536 incident class).
writeFileSync(fixturePath, buffer);
- writeFileSync(versionPath, schemaHash + "\n");
+ writeFileSync(versionPath, `${schemaHash}\ndims=${getEmbeddingDimensions()}\nmodel=${getEmbeddingModel()}\n`);
await engine.disconnect();
console.log(`[build-pglite-snapshot] wrote ${fixturePath} (${buffer.length} bytes)`);
console.log(`[build-pglite-snapshot] wrote ${versionPath}`);
+ } finally {
+ if (ownLock) { try { rmdirSync(lockPath); } catch { /* best effort */ } }
+ try { rmSync(hermeticHome, { recursive: true, force: true }); } catch { /* best effort */ }
+ }
}
await main();
diff --git a/scripts/check-admin-scope-drift.sh b/scripts/check-admin-scope-drift.sh
index 0dad2899fc..0d54c4a61c 100755
--- a/scripts/check-admin-scope-drift.sh
+++ b/scripts/check-admin-scope-drift.sh
@@ -4,7 +4,7 @@
# scopes to admin/src/ so we can't import the source list directly; instead
# this script extracts both lists and diffs them.
#
-# Wired into `bun run verify` and `bun run check:all`.
+# Wired into `bun run verify` (single guard registry: scripts/guards-manifest.tsv).
#
# Exits 0 on match, 1 on drift, 2 on internal error (file missing, parse fail).
#
diff --git a/scripts/check-engine-dynamic-import.ts b/scripts/check-engine-dynamic-import.ts
index ea0da71379..da658f4b26 100644
--- a/scripts/check-engine-dynamic-import.ts
+++ b/scripts/check-engine-dynamic-import.ts
@@ -49,7 +49,16 @@ for (const file of files) {
}
function visit(node: ts.Node): void {
- if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
+ // W0 ship-review catch: match BOTH lazy-loading forms. The guard
+ // previously matched only `import(...)` call expressions, so a
+ // `require(...)` on an engine-live path passed silently and its
+ // engine-dynamic-import-ok marker was decorative.
+ const isDynamicImport = ts.isCallExpression(node)
+ && node.expression.kind === ts.SyntaxKind.ImportKeyword;
+ const isRequireCall = ts.isCallExpression(node)
+ && ts.isIdentifier(node.expression)
+ && node.expression.text === 'require';
+ if (isDynamicImport || isRequireCall) {
const { line } = sourceFile.getLineAndCharacterOfPosition(node.expression.getStart(sourceFile));
const sourceLine = lines[line] ?? '';
if (!markerLines.has(line)) {
diff --git a/scripts/check-jsonb-pattern.sh b/scripts/check-jsonb-pattern.sh
index d26acb0e29..5365379d92 100755
--- a/scripts/check-jsonb-pattern.sh
+++ b/scripts/check-jsonb-pattern.sh
@@ -17,26 +17,43 @@ set -euo pipefail
ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
cd "$ROOT"
+# W0 fix-wave (Tier-1 #11): self-test seam — the guard harness points this at
+# a known-bad fixture tree and asserts exit 1.
+SCAN_ROOT="${GBRAIN_GUARD_ROOT:-src/}"
+
# Match the interpolated form: ${JSON.stringify(...)}::jsonb
-# Using grep -P for Perl-compatible regex (lookahead-free pattern is enough here).
-PATTERN='\$\{JSON\.stringify\([^)]*\)\}::jsonb'
+#
+# W0 fix-wave (Tier-1 #11): the previous `\([^)]*\)` argument matcher could
+# not cross a nested `)` — `${JSON.stringify(obj.get())}::jsonb` was
+# invisible (the same regex-hole class that made check-no-double-retry a
+# permanently-green no-op). `[^}]*` spans nested parens but CANNOT cross the
+# interpolation's closing `}`, so a safe `${JSON.stringify(x)}::text::jsonb`
+# followed by a separate `${expr()}::jsonb` on the same line is not spanned
+# into a false positive (ship-review catch — the greedy `.*` variant was).
+PATTERN='\$\{JSON\.stringify\([^}]*\)\}::jsonb'
-if grep -rEn "$PATTERN" src/ 2>/dev/null; then
+if grep -rEn "$PATTERN" "$SCAN_ROOT" 2>/dev/null; then
echo
- echo "ERROR: Found JSON.stringify(...)::jsonb pattern in src/."
+ echo "ERROR: Found JSON.stringify(...)::jsonb pattern in $SCAN_ROOT."
echo " postgres.js v3 stringifies again, producing JSONB string literals."
echo " Use sql.json(x) instead. See feedback_postgres_jsonb_double_encode.md."
exit 1
fi
-echo "OK: no JSON.stringify(x)::jsonb interpolation pattern in src/"
+echo "OK: no JSON.stringify(x)::jsonb interpolation pattern in $SCAN_ROOT"
# v0.13.1 #219: guard against max_stalled DEFAULT 1 regressing in any schema
# source file. DEFAULT 1 dead-lettered any SIGKILL'd job on first stall, making
# the "10/10 rescued" claim false for out-of-the-box users. Default is 5 now.
MAX_STALLED_PATTERN='max_stalled\s+INTEGER\s+NOT\s+NULL\s+DEFAULT\s+1\b'
-if grep -rEn "$MAX_STALLED_PATTERN" src/schema.sql src/core/migrate.ts src/core/pglite-schema.ts src/core/schema-embedded.ts 2>/dev/null; then
+# Schema files are fixed paths; under a fixture root (self-test) they don't
+# exist — skip rather than fail on the missing-file grep.
+SCHEMA_FILES=()
+for f in src/schema.sql src/core/migrate.ts src/core/pglite-schema.ts src/core/schema-embedded.ts; do
+ [ -f "$f" ] && SCHEMA_FILES+=("$f")
+done
+if [ "${#SCHEMA_FILES[@]}" -gt 0 ] && grep -rEn "$MAX_STALLED_PATTERN" "${SCHEMA_FILES[@]}" 2>/dev/null; then
echo
echo "ERROR: max_stalled DEFAULT 1 reintroduced in schema."
echo " Must be DEFAULT 5 to preserve SIGKILL-rescue guarantee. See #219."
@@ -51,10 +68,11 @@ echo "OK: max_stalled defaults are 5 in all schema sources"
# [JSON.stringify(x)]) — which is the exact shape that double-encoded the
# op_checkpoints pin and aborted every sync in #2339. The AST-lite scanner below
# catches it. `set -e` propagates its non-zero exit.
+# Under a fixture root, scan that root; the AST-lite scanner takes roots as argv.
if command -v node >/dev/null 2>&1; then
- node scripts/check-jsonb-params.mjs
+ node scripts/check-jsonb-params.mjs ${GBRAIN_GUARD_ROOT:+"$GBRAIN_GUARD_ROOT"}
elif command -v bun >/dev/null 2>&1; then
- bun scripts/check-jsonb-params.mjs
+ bun scripts/check-jsonb-params.mjs ${GBRAIN_GUARD_ROOT:+"$GBRAIN_GUARD_ROOT"}
else
echo "WARN: neither node nor bun on PATH; skipping check-jsonb-params.mjs" >&2
fi
diff --git a/scripts/check-no-double-retry.sh b/scripts/check-no-double-retry.sh
index 23755056df..e10da8fd78 100755
--- a/scripts/check-no-double-retry.sh
+++ b/scripts/check-no-double-retry.sh
@@ -19,16 +19,24 @@ set -euo pipefail
ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
cd "$ROOT"
+# W0 fix-wave (Tier-1 #11): self-test seam. The guard harness points this at
+# a known-bad fixture tree and asserts exit 1 — the guard can no longer rot
+# into a permanently-green no-op unnoticed.
+SCAN_ROOT="${GBRAIN_GUARD_ROOT:-src/}"
+
# Match: withRetry(...) wrapping any of the 3 engine batch methods.
-# The greedy `.*` between `withRetry(` and `engine.` covers both the
-# arrow-fn form and any direct invocation. (gbrain-allow-direct-insert: doc comment)
-# Multi-line wraps are caught by `grep -E` per file (line-wise) for the
-# common single-line case; multi-line wraps still get caught by a separate
-# multi-line pass below.
-PATTERN='withRetry\([^)]*engine\.(addLinksBatch|addTimelineEntriesBatch|upsertChunks)'
+#
+# W0 fix-wave (Tier-1 #11): the previous pattern used `[^)]*` between
+# `withRetry(` and `engine.`, which can never cross the `)` in `() =>` — so
+# the CANONICAL banned shape (an arrow function wrapping the engine batch
+# call) was invisible and the guard had been permanently green since it
+# shipped. `.*` (line-bounded by grep) covers the arrow form, async arrows,
+# and any argument shape. (Spelled without the literal call token here —
+# check-system-of-record scans scripts/ comments too: the prose-bleed class.)
+PATTERN='withRetry\(.*engine\.(addLinksBatch|addTimelineEntriesBatch|upsertChunks)'
# Single-line scan (covers ~95% of real cases).
-if grep -rEn "$PATTERN" src/ --include='*.ts' 2>/dev/null; then
+if grep -rEn "$PATTERN" "$SCAN_ROOT" --include='*.ts' 2>/dev/null; then
echo
echo "ERROR: Found withRetry(...engine.{addLinksBatch|addTimelineEntriesBatch|upsertChunks})"
echo " pattern in src/."
@@ -47,17 +55,26 @@ if grep -rEn "$PATTERN" src/ --include='*.ts' 2>/dev/null; then
exit 1
fi
-# Multi-line scan: a withRetry( on one line and the engine call on the next
-# few. Bounded to 3-line window so we don't flag distant unrelated calls.
-# Uses pcregrep if available, else falls back to a simple awk window.
-if command -v pcregrep >/dev/null 2>&1; then
- if pcregrep -r -M -n --include='\.ts$' \
- 'withRetry\([^)]*\n\s*\(?[^)]*=>\s*engine\.(addLinksBatch|addTimelineEntriesBatch|upsertChunks)' \
- src/ 2>/dev/null; then
- echo
- echo "ERROR: Multi-line withRetry(...engine.batch...) wrap found in src/. See above."
- exit 1
- fi
+# Multi-line scan: a withRetry( on one line and the engine call within the
+# next 3 lines. W0 fix-wave (Tier-1 #11): the previous pass was gated on
+# pcregrep, which is not installed on dev machines OR CI — it never ran.
+# perl is always available; same 3-line window, always on.
+#
+# Ship-review catch: perl must ALWAYS exit 0 and let OUTPUT PRESENCE decide.
+# An exit-1-from-clean-batches design breaks under `set -o pipefail` the
+# moment src/ outgrows one xargs batch (xargs exits 123, overriding grep's
+# verdict) — a silently missed violation, the same permanently-green class
+# this guard was just cured of.
+MULTILINE_MATCHES=$(find "$SCAN_ROOT" -name '*.ts' -type f -print0 2>/dev/null | xargs -0 perl -0777 -ne '
+ if (/withRetry\([^\n]*\n(?:[^\n]*\n){0,2}?[^\n]*engine\.(?:addLinksBatch|addTimelineEntriesBatch|upsertChunks)/) {
+ print "$ARGV: multi-line withRetry wrap around an engine batch call\n";
+ }
+' 2>/dev/null || true)
+if [ -n "$MULTILINE_MATCHES" ]; then
+ echo "$MULTILINE_MATCHES"
+ echo
+ echo "ERROR: Multi-line withRetry(...engine.batch...) wrap found in $SCAN_ROOT. See above."
+ exit 1
fi
-echo "OK: no withRetry(...engine.batch...) double-retry patterns in src/"
+echo "OK: no withRetry(...engine.batch...) double-retry patterns in $SCAN_ROOT"
diff --git a/scripts/check-pg-url-redaction.sh b/scripts/check-pg-url-redaction.sh
index b36cbdb5f9..52dd1e1dd2 100755
--- a/scripts/check-pg-url-redaction.sh
+++ b/scripts/check-pg-url-redaction.sh
@@ -10,7 +10,7 @@
# - new logging APIs that may show up later (the regex matches the URL,
# not the consumer; any leak will trip)
#
-# Wired into bun run check:all and bun run verify.
+# Wired into bun run verify (single guard registry: scripts/guards-manifest.tsv).
#
# Exit codes: 0 = clean, 1 = found at least one suspect line.
set -euo pipefail
diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh
index 1a76706946..84fb078a66 100755
--- a/scripts/ci-local.sh
+++ b/scripts/ci-local.sh
@@ -236,12 +236,12 @@ bash scripts/check-progress-to-stdout.sh
bash scripts/check-trailing-newline.sh
bash scripts/check-wasm-embedded.sh
bun run typecheck
-echo \"[runner] Tier 3: building PGLite snapshot fixture (cached across reruns)\"
-if [ ! -f test/fixtures/pglite-snapshot.tar ] || [ ! -f test/fixtures/pglite-snapshot.version ]; then
- bun run build:pglite-snapshot
-else
- echo \"[runner] snapshot fixture exists; engine will validate hash at load time\"
-fi
+echo \"[runner] Tier 3: PGLite snapshot fixture (idempotent; rebuilds on hash drift)\"
+# W0 fix-wave (Tier-1 #16): unconditional call — the build script self-
+# short-circuits on a fresh hash and rebuilds STALE snapshots (the old
+# if-missing guard left a stale-but-present snapshot permanently on the
+# warn+slow path). Concurrency-safe via the script's mkdir lock (D5.8).
+bun run build:pglite-snapshot
export GBRAIN_PGLITE_SNAPSHOT=test/fixtures/pglite-snapshot.tar
echo \"[runner] resolving E2E file selection (--diff aware)\"
${DIFF_E2E_PREP}
diff --git a/scripts/guard-self-test.sh b/scripts/guard-self-test.sh
new file mode 100755
index 0000000000..ad858df979
--- /dev/null
+++ b/scripts/guard-self-test.sh
@@ -0,0 +1,94 @@
+#!/usr/bin/env bash
+# W0 fix-wave (Tier-1 #11 / D5.14): guard self-test harness.
+#
+# The audit found scripts/check-no-double-retry.sh had been PERMANENTLY GREEN
+# since it shipped: its regex could not match the canonical banned shape, and
+# its multi-line fallback was gated on pcregrep, which is installed nowhere.
+# A guard that cannot fail is worse than no guard — it reads as coverage.
+#
+# This harness makes that class structurally impossible for scanner guards:
+# every guard marked `selftest yes` in scripts/guards-manifest.tsv is run
+# against test/fixtures/guards/<guard>/bad (MUST exit non-zero) and
+# .../good (MUST exit 0), via the GBRAIN_GUARD_ROOT override each guard
+# honors. Adding a self-test to a `todo` scanner = flip the manifest flag +
+# drop two fixture files.
+#
+# Also prints total harness wall-clock (guard-runtime budget line, D4.5):
+# fails if the self-test pass exceeds the budget, so guard sprawl shows up
+# here before it shows up as slow `bun run verify`.
+#
+# Usage: scripts/guard-self-test.sh
+# Exit: 0 = every self-tested guard fails on bad + passes on good.
+
+set -uo pipefail
+
+ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
+cd "$ROOT"
+
+MANIFEST="scripts/guards-manifest.tsv"
+FIXTURES="test/fixtures/guards"
+BUDGET_SECONDS=30
+START=$(date +%s)
+failures=0
+tested=0
+
+if [ ! -f "$MANIFEST" ]; then
+ echo "ERROR: $MANIFEST missing — the guard registry is load-bearing."
+ exit 1
+fi
+
+run_guard() {
+ local guard="$1" fixture_root="$2"
+ case "$guard" in
+ *.mjs) GBRAIN_GUARD_ROOT="$fixture_root" node "scripts/$guard" "$fixture_root" >/dev/null 2>&1 ;;
+ *) GBRAIN_GUARD_ROOT="$fixture_root" bash "scripts/$guard" >/dev/null 2>&1 ;;
+ esac
+}
+
+while IFS=$'\t' read -r guard klass selftest _notes; do
+ case "$guard" in ''|'#'*) continue ;; esac
+ [ "$selftest" = "yes" ] || continue
+ tested=$((tested + 1))
+
+ bad="$FIXTURES/$guard/bad"
+ good="$FIXTURES/$guard/good"
+ if [ ! -d "$bad" ] || [ ! -d "$good" ]; then
+ echo "FAIL $guard: manifest says selftest=yes but fixtures missing under $FIXTURES/$guard/{bad,good}"
+ failures=$((failures + 1))
+ continue
+ fi
+
+ if run_guard "$guard" "$bad"; then
+ echo "FAIL $guard: did NOT flag the known-bad fixture — the guard is a no-op (the check-no-double-retry class)"
+ failures=$((failures + 1))
+ elif ! run_guard "$guard" "$good"; then
+ echo "FAIL $guard: flagged the known-good fixture — false positive"
+ failures=$((failures + 1))
+ else
+ echo "ok $guard (bad→fail, good→pass)"
+ fi
+done < "$MANIFEST"
+
+# Manifest completeness: every scripts/check-* guard must have a manifest row
+# (new guards can't silently skip classification).
+for f in scripts/check-*.sh scripts/check-*.mjs; do
+ base="$(basename "$f")"
+ # The .ts companion of check-engine-dynamic-import is an implementation file.
+ if ! grep -q "^${base} " "$MANIFEST"; then
+ echo "FAIL $base: no row in $MANIFEST — classify it (scanner|buildfresh|repostate)"
+ failures=$((failures + 1))
+ fi
+done
+
+ELAPSED=$(( $(date +%s) - START ))
+echo "guard self-test: $tested guard(s) self-tested, ${ELAPSED}s (budget ${BUDGET_SECONDS}s)"
+if [ "$ELAPSED" -gt "$BUDGET_SECONDS" ]; then
+ echo "FAIL guard self-test exceeded the ${BUDGET_SECONDS}s runtime budget — trim fixtures or parallelize before adding more"
+ failures=$((failures + 1))
+fi
+
+if [ "$failures" -gt 0 ]; then
+ echo "ERROR: $failures guard self-test failure(s)."
+ exit 1
+fi
+echo "OK: all self-tested guards catch their bad fixtures and pass their good ones"
diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsv
new file mode 100644
index 0000000000..7b0f0585b5
--- /dev/null
+++ b/scripts/guards-manifest.tsv
@@ -0,0 +1,62 @@
+# CI guard registry (W0 fix-wave, Tier-1 #11 / D5.14).
+# THE single registry of scripts/check-* guards. package.json's `check:all`
+# (a second, stale, hand-synced copy) was deleted; scripts/run-verify-parallel.sh
+# executes guards, and scripts/guard-self-test.sh consumes THIS file to
+# self-test every scanner guard against known-bad/known-good fixtures under
+# test/fixtures/guards/<guard>/{bad,good}/ (env: GBRAIN_GUARD_ROOT).
+#
+# class: scanner = greps/parses repo sources; MUST eventually carry fixtures
+# (selftest yes|todo). A scanner guard with selftest=todo is
+# tracked debt — the class that produced two permanently-
+# green guards (check-no-double-retry, pcregrep-gated pass).
+# buildfresh = runs builds/regenerators and diffs outputs; self-tests
+# don't apply (the build IS the test). exempt.
+# repostate = checks repo/file state (modes, symlinks, VERSION stamps);
+# exempt with reason.
+#
+# guard class selftest notes
+check-no-double-retry.sh scanner yes regex hole fixed in W0 (could not match `() =>`); perl multi-line pass replaces never-installed pcregrep
+check-jsonb-pattern.sh scanner yes nested-paren hole fixed in W0; safe ::text::jsonb spelling stays unflagged
+check-jsonb-params.mjs scanner yes positional $N::jsonb AST-lite scanner; argv/env root override
+check-batch-audit-site.sh scanner todo
+check-bun-test-timeout.sh scanner todo
+check-fixture-privacy.sh scanner todo
+check-no-legacy-getconnection.sh scanner todo was reachable from neither verify nor CI pre-W0 (check:all only)
+check-no-pii-in-agent-voice.sh scanner todo
+check-operations-filter-bypass.sh scanner todo
+check-pagetype-exhaustive.sh scanner todo
+check-pg-url-redaction.sh scanner todo
+check-privacy.sh scanner todo
+check-progress-to-stdout.sh scanner todo
+check-proposal-pii.sh scanner todo
+check-search-path.sh scanner todo
+check-skill-brain-first.sh scanner todo
+check-skill-refs.mjs scanner todo
+check-source-config-leak.sh scanner todo
+check-source-id-projection.sh scanner todo
+check-source-scope-onboard.sh scanner todo
+check-synthetic-corpus-privacy.sh scanner todo
+check-system-of-record.sh scanner todo
+check-test-real-names.sh scanner todo
+check-worker-lock-renewal-shape.sh scanner todo
+check-worker-pool-atomicity.sh scanner todo
+check-gateway-routed-no-direct-anthropic.sh scanner todo
+check-engine-dynamic-import.sh scanner todo .ts companion is its implementation, not a separate guard
+check-key-files-current-state.sh scanner todo
+check-exports-count.sh scanner todo was reachable from neither verify nor CI pre-W0 (check:all only)
+check-trailing-newline.sh scanner todo was reachable from neither verify nor CI pre-W0 (check:all only)
+check-test-isolation.sh scanner todo allowlist data file: check-test-isolation.allowlist
+check-admin-build.sh buildfresh exempt runs the admin build; the build is the test
+check-admin-embedded.sh buildfresh exempt embed freshness diff
+check-admin-scope-drift.sh buildfresh exempt regenerates + diffs
+check-bootstrap-templates.sh buildfresh exempt regenerates template tree + diffs
+check-eval-glossary-fresh.sh buildfresh exempt regenerates + diffs
+check-fuzz-purity.sh buildfresh exempt executes fuzz corpus
+check-image-decoders-embedded.sh buildfresh exempt binary embed check
+check-pglite-embedded.sh buildfresh exempt binary embed check
+check-skills-manifest-fresh.sh buildfresh exempt regenerates + diffs
+check-tool-catalog-fresh.sh buildfresh exempt regenerates + diffs
+check-wasm-embedded.sh buildfresh exempt binary embed check
+check-bootstrap-tag.sh repostate exempt VERSION stamp drift check
+check-cli-executable.sh repostate exempt file-mode check
+check-no-tracked-symlinks.sh repostate exempt git index state check
diff --git a/scripts/run-unit-parallel.sh b/scripts/run-unit-parallel.sh
index ff4fd68676..02e4644435 100755
--- a/scripts/run-unit-parallel.sh
+++ b/scripts/run-unit-parallel.sh
@@ -46,6 +46,25 @@ set -uo pipefail
cd "$(dirname "$0")/.."
+# ──────────────────────────────────────────────────────────────────────────
+# W0 fix-wave (Tier-1 #16): PGLite schema snapshot, DEFAULT-ON for the plain
+# `bun run test` loop. 500+ test files each cold-boot PGLite + replay 126
+# migrations without it; the fixture was previously enabled ONLY inside
+# scripts/ci-local.sh, so the everyday loop paid the full cost. The build
+# script is idempotent (hash short-circuit) and concurrency-safe (mkdir
+# lock, D5.8), and its hash folds handler-migration source (D5.13), so an
+# unconditional call here is cheap and always current. Runs BEFORE the shard
+# fan-out — shards inherit a finished fixture. Opt out: GBRAIN_NO_SNAPSHOT=1
+# (the migration-replay canary tests clear the env themselves regardless).
+# ──────────────────────────────────────────────────────────────────────────
+if [ "${GBRAIN_NO_SNAPSHOT:-0}" != "1" ]; then
+ if bun run build:pglite-snapshot >/dev/null 2>&1; then
+ export GBRAIN_PGLITE_SNAPSHOT=test/fixtures/pglite-snapshot.tar
+ else
+ echo "[run-unit-parallel] snapshot build failed (non-fatal) — tests run with cold init" >&2
+ fi
+fi
+
# ──────────────────────────────────────────────────────────────────────────
# CPU detection: Apple Silicon perf cores → Mac total physical → nproc → 4.
# Returns a single positive integer.
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index 9377c80114..322fbded2b 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -72,6 +72,14 @@ CHECKS=(
"check:bootstrap-tag"
"check:bootstrap-templates"
"check:skill-refs"
+ # W0 fix-wave (Tier-1 #11): guard self-tests — every scanner guard proves it
+ # can fail (bad fixture → exit 1) before it counts as coverage. Registry:
+ # scripts/guards-manifest.tsv (package.json's stale `check:all` copy deleted).
+ "check:guard-self-test"
+ # Previously reachable ONLY from the deleted check:all (i.e. never run):
+ "check:newlines"
+ "check:exports-count"
+ "check:no-legacy-getconnection"
"typecheck"
)
diff --git a/src/cli.ts b/src/cli.ts
index 833b4b7447..caa797432f 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -2352,16 +2352,26 @@ async function handleCliOnly(command: string, args: string[]) {
try {
switch (command) {
case 'import': {
- const { runImport } = await import('./commands/import.ts');
+ const { runImport, ImportAbortError } = await import('./commands/import.ts');
// v0.41 (Codex r2 #3 fix): honor errors counter for exit code.
// runImport's per-file catch already records failures, but the
// CLI was discarding the result so the process exited 0 even
// when files failed (e.g. content-sanity hard-block throws,
// size-cap throws, parse errors). Surface non-zero on errors > 0
// so wrappers (sync, CI scripts, `&& gbrain doctor`) propagate.
- const importResult = await runImport(engine, args);
- if (importResult.errors > 0) {
- setCliExitVerdict(1);
+ try {
+ const importResult = await runImport(engine, args);
+ if (importResult.errors > 0) {
+ setCliExitVerdict(1);
+ }
+ } catch (e) {
+ // W0 (Tier-1 #5): runImport throws typed aborts instead of
+ // process.exit(1) so in-process callers (sync_brain MCP op,
+ // autopilot, minion handler) survive a preflight failure. The CLI
+ // keeps the exact pre-fix behavior: message already printed at the
+ // throw site, exit non-zero here.
+ if (e instanceof ImportAbortError) process.exit(e.exitCode);
+ throw e;
}
break;
}
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index adc67cc9f9..f392d178fd 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -1,6 +1,7 @@
import type { BrainEngine } from '../core/engine.ts';
import { embedBatch, currentEmbeddingSignature } from '../core/embedding.ts';
import type { ChunkInput } from '../core/types.ts';
+import { carryChunkMetadata } from '../core/embed-stale.ts';
import { chunkText } from '../core/chunkers/recursive.ts';
import { createProgress, type ProgressReporter } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
@@ -784,9 +785,11 @@ async function embedPage(
}
/**
- * Carry code-chunk metadata (language, symbol_name, symbol_type, line range,
- * parent scope, doc comment, qualified name) from a loaded Chunk back into a
- * ChunkInput destined for upsertChunks.
+ * Carry per-chunk metadata — modality (the W0 fix: its omission flipped
+ * image chunks to text) plus the code fields (language, symbol_name,
+ * symbol_type, line range, parent scope, doc comment, qualified name) — from
+ * a loaded Chunk back into a ChunkInput destined for upsertChunks. The
+ * shared carryChunkMetadata list (core/embed-stale.ts) is authoritative.
*
* Issue #769: every re-embed used to strip these fields, and upsertChunks
* overwrites (does not COALESCE) the metadata columns from EXCLUDED, so
@@ -795,17 +798,13 @@ async function embedPage(
* (embedPage, embedAll non-stale, embedAllStale) in lock-step.
*/
function preserveCodeMetadata(loaded: any, base: ChunkInput): ChunkInput {
- return {
- ...base,
- language: loaded.language ?? undefined,
- symbol_name: loaded.symbol_name ?? undefined,
- symbol_type: loaded.symbol_type ?? undefined,
- start_line: loaded.start_line ?? undefined,
- end_line: loaded.end_line ?? undefined,
- parent_symbol_path: loaded.parent_symbol_path ?? undefined,
- doc_comment: loaded.doc_comment ?? undefined,
- symbol_name_qualified: loaded.symbol_name_qualified ?? undefined,
- };
+ // W0 fix-wave (Tier-1 #3, CONFIRMED): delegate to the single shared carry
+ // list. This local copy was missing `modality`, so every CLI re-embed path
+ // (embedPage, embedAll, embedAllStale) flipped image chunks to
+ // modality='text' — upsertChunks overwrites from EXCLUDED — silently
+ // zeroing image retrieval until the next full import. The minion twin in
+ // core/embed-stale.ts carried it correctly; one list now serves both.
+ return carryChunkMetadata(loaded, base);
}
async function embedAll(
diff --git a/src/commands/import.ts b/src/commands/import.ts
index f3021a0160..f5022d41b1 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -64,6 +64,27 @@ function defaultWorkers(): number {
return Math.min(byPool, byCpu, byMem);
}
+/**
+ * W0 fix-wave (Tier-1 #5): typed abort for runImport's preflight/argv
+ * failures. Pre-fix these five sites called process.exit(1) directly —
+ * correct for the CLI, but runImport is ALSO invoked in-process by the
+ * sync_brain MCP op (via performFullSync), the autopilot daemon, and the
+ * minion sync handler, so a first sync with unconfigured embedding
+ * credentials TERMINATED the MCP server / daemon / worker mid-call. The
+ * user-facing messages are printed BEFORE the throw (byte-identical CLI
+ * output); the CLI dispatch site maps this error back to exit(exitCode).
+ */
+export class ImportAbortError extends Error {
+ readonly exitCode: number;
+ /** True: the user-facing message was already printed at the throw site. */
+ readonly alreadyReported = true;
+ constructor(reason: string, exitCode = 1) {
+ super(`import aborted: ${reason}`);
+ this.name = 'ImportAbortError';
+ this.exitCode = exitCode;
+ }
+}
+
/** Bug 9 — surface per-file failures so callers (performFullSync) can gate state advances. */
export interface RunImportResult {
imported: number;
@@ -129,7 +150,7 @@ export async function runImport(
} catch (e) {
console.error(`\n${e instanceof Error ? e.message : e}`);
console.error('Tip: run `gbrain import <dir> --no-embed` to import without embedding now.');
- process.exit(1);
+ throw new ImportAbortError('embedding disabled (deferred-setup sentinel)');
}
// v0.41.6.0 D1: preflight embedding credentials. Closes the bug class
@@ -147,7 +168,7 @@ export async function runImport(
console.error(e.userMessage);
console.error('');
}
- process.exit(1);
+ throw new ImportAbortError('embedding credentials missing');
}
throw e;
}
@@ -221,7 +242,7 @@ export async function runImport(
workerCount = parseWorkers(workersArg ?? undefined) ?? 1;
} catch (e) {
console.error(e instanceof Error ? e.message : String(e));
- process.exit(1);
+ throw new ImportAbortError('invalid --workers value');
}
// Find dir: first non-flag arg that isn't a value for --workers
const flagValues = new Set<number>();
@@ -231,7 +252,7 @@ export async function runImport(
if (!dirArg) {
console.error('Usage: gbrain import <dir> [--no-embed] [--workers N] [--fresh] [--source-id <id>] [--include-gitignored] [--json]');
- process.exit(1);
+ throw new ImportAbortError('no import directory given');
}
// #1728: capture the import target ONCE as an absolute real path. Every
// downstream consumer of `dir` (collection, checkpoint load/save, resume
@@ -244,7 +265,7 @@ export async function runImport(
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.error(`Import target is not readable: ${dirArg} (${msg})`);
- process.exit(1);
+ throw new ImportAbortError(`import target not readable: ${dirArg}`);
}
// v0.31.2: collect under the right strategy. Pre-fix this called
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index e5b2ef7b83..7acbe2f238 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -1937,10 +1937,11 @@ export async function registerBuiltinHandlers(
});
worker.register('import', async (job) => {
- // import.ts Core extraction deferred to v0.12.0 (import has parallel
- // workers + checkpointing). Keep the CLI wrapper call but note the
- // worker-kill risk is bounded: import's only process.exit fires on
- // a missing dir arg, which this handler always passes.
+ // import.ts Core extraction deferred (import has parallel workers +
+ // checkpointing; the typed-API split lands in W7 of the fix-wave).
+ // W0 (Tier-1 #5): runImport no longer contains ANY process.exit — all
+ // five preflight sites throw typed ImportAbortError, which this
+ // handler's catch converts to a normal failJob. No worker-kill risk.
const { runImport } = await import('./import.ts');
const importArgs: string[] = [];
if (job.data.dir) importArgs.push(String(job.data.dir));
diff --git a/src/commands/lint.ts b/src/commands/lint.ts
index 94a784b0ec..db8e5e5981 100644
--- a/src/commands/lint.ts
+++ b/src/commands/lint.ts
@@ -441,6 +441,24 @@ export interface LintOpts {
* single-file targets.
*/
exclude?: string[];
+ /**
+ * W0 fix-wave (Tier-1 #14): per-page hook fired for every page WITH
+ * issues, after this run's fix attempt for that page — fixedCount is the
+ * number of fixes just applied (0 when --fix is off or nothing was
+ * fixable). The CLI passes a printer so human detail and the aggregate
+ * counts come from ONE scan — pre-fix, runLint ran its own full
+ * read+lint+fix loop and THEN called runLintCore for the summary, linting
+ * every page twice and reporting "0 auto-fixed" because the second pass
+ * saw already-fixed files.
+ */
+ onPageIssues?: (relPath: string, issues: LintIssue[], fixedCount: number) => void;
+ /** Companion to onPageIssues: per-page progress tick (CLI progress bar). */
+ onPageScanned?: () => void;
+ /**
+ * Fired once with the collected page count before scanning starts, so the
+ * CLI can size its progress bar without walking the tree a second time.
+ */
+ onPagesCollected?: (count: number) => void;
}
export interface LintResult {
@@ -468,6 +486,7 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
const isSingleFile = statSync(opts.target).isFile();
const pages = isSingleFile ? [opts.target] : collectPages(opts.target, opts.exclude ?? []);
+ opts.onPagesCollected?.(pages.length);
// Resolve content-sanity config once for this lint run (D1: lift DB
// config when reachable). Caller can pre-pass via opts.contentSanity
@@ -490,21 +509,25 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
await new Promise<void>((resolve) => setImmediate(resolve));
}
const content = readFileSync(page, 'utf-8');
- const issues = lintContent(content, isSingleFile ? page : relative(opts.target, page), lintOpts);
+ const relPath = isSingleFile ? page : relative(opts.target, page);
+ const issues = lintContent(content, relPath, lintOpts);
+ opts.onPageScanned?.();
if (issues.length === 0) continue;
pagesWithIssues++;
totalIssues += issues.length;
+ let fixCount = 0;
if (opts.fix && issues.some(i => i.fixable)) {
const fixed = fixContent(content);
if (fixed !== content) {
- const fixCount = issues.filter(i => i.fixable).length;
+ fixCount = issues.filter(i => i.fixable).length;
totalFixed += fixCount;
if (!opts.dryRun) {
writeFileSync(page, fixed);
}
}
}
+ opts.onPageIssues?.(relPath, issues, fixCount);
}
return {
@@ -547,57 +570,41 @@ export async function runLint(args: string[]) {
process.exit(1);
}
- // Single file or directory — print human detail as we go, then rely on
- // Core for the aggregate numbers at the end.
- const isSingleFile = statSync(target).isFile();
- const pages = isSingleFile ? [target] : collectPages(target, extraExcludes);
-
+ // W0 fix-wave (Tier-1 #14): ONE scan. Pre-fix this function ran its own
+ // full read+lint+fix loop for human output and THEN called runLintCore for
+ // the summary — every page linted twice, and with --fix the second pass
+ // saw already-fixed files so the summary reported "0 auto-fixed" after
+ // fixing N. Human detail now streams from runLintCore's per-page hooks
+ // and the counts come from the same single pass.
// Progress on stderr. Stdout keeps the per-issue human output it always had.
+ // Ship-review perf catch: the tree is walked ONCE — runLintCore reports the
+ // collected count via onPagesCollected (pre-fix the CLI ran its own
+ // collectPages just to size the progress bar, a second full readdir/stat
+ // walk on every directory lint).
const { createProgress } = await import('../core/progress.ts');
const { getCliOptions, cliOptsToProgressOptions } = await import('../core/cli-options.ts');
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
- progress.start('lint.pages', pages.length);
- // v0.41 (D1): resolve content-sanity config once for this lint run.
- // Mirrors runLintCore. The two paths must agree because runLint
- // prints human details inline; runLintCore at end computes the
- // aggregate. Sharing the resolved opts keeps both surfaces seeing
- // the same rule firings.
- const contentSanity = await resolveLintContentSanity();
- const lintContentOpts: LintContentOpts = { contentSanity };
-
- for (const page of pages) {
- const content = readFileSync(page, 'utf-8');
- const relPath = isSingleFile ? page : relative(target, page);
- const issues = lintContent(content, relPath, lintContentOpts);
- progress.tick(1);
- if (issues.length === 0) continue;
-
- console.log(`\n${relPath}:`);
- for (const issue of issues) {
- const fixLabel = issue.fixable ? ' [fixable]' : '';
- console.log(` L${issue.line} ${issue.rule}: ${issue.message}${fixLabel}`);
- }
-
- if (doFix && issues.some(i => i.fixable)) {
- const fixed = fixContent(content);
- if (fixed !== content) {
- const fixCount = issues.filter(i => i.fixable).length;
- if (!dryRun) {
- writeFileSync(page, fixed);
- }
- console.log(` ${dryRun ? '(dry run) ' : ''}Fixed ${fixCount} issue(s)`);
+ const result = await runLintCore({
+ target,
+ fix: doFix,
+ dryRun,
+ exclude: extraExcludes,
+ onPagesCollected: (count) => progress.start('lint.pages', count),
+ onPageScanned: () => progress.tick(1),
+ onPageIssues: (relPath, issues, fixedCount) => {
+ console.log(`\n${relPath}:`);
+ for (const issue of issues) {
+ const fixLabel = issue.fixable ? ' [fixable]' : '';
+ console.log(` L${issue.line} ${issue.rule}: ${issue.message}${fixLabel}`);
}
- }
- }
+ if (fixedCount > 0) {
+ console.log(` ${dryRun ? '(dry run) ' : ''}Fixed ${fixedCount} issue(s)`);
+ }
+ },
+ });
progress.finish();
-
- // Re-run core for the aggregate counts (cheap; re-parses contents but
- // produces canonical numbers for the summary line).
- // Pass contentSanity through so runLintCore skips its own resolve
- // (we already resolved once for the human-detail loop above).
- const result = await runLintCore({ target, fix: doFix, dryRun, contentSanity, exclude: extraExcludes });
console.log(`\n${result.pages_scanned} pages scanned. ${result.total_issues} issue(s) in ${result.pages_with_issues} page(s).`);
if (doFix) {
console.log(`${dryRun ? '(dry run) ' : ''}${result.total_fixed} auto-fixed.`);
diff --git a/src/commands/pglite-repair.ts b/src/commands/pglite-repair.ts
index 7a7d4a954d..14f80d4ae1 100644
--- a/src/commands/pglite-repair.ts
+++ b/src/commands/pglite-repair.ts
@@ -101,9 +101,15 @@ function emitError(jsonOutput: boolean, code: string, message: string): void {
}
async function promptYesNo(question: string): Promise<boolean> {
+ // W0 fix-wave (Tier-1 #15): non-interactive stdin (CI, pipes, spawned
+ // agents) must resolve to the safe default instead of hanging forever —
+ // this prompt had no TTY guard and no close/EOF handler, so a piped or
+ // closed stdin parked the process permanently.
+ if (!process.stdin.isTTY) return false;
// Prompt on stderr: stdout stays clean for --json payloads.
const rl = createInterface({ input: process.stdin, output: process.stderr });
return new Promise((resolve) => {
+ rl.on('close', () => resolve(false)); // EOF (^D) = decline, never hang
rl.question(`${question} [y/N] `, (answer) => {
rl.close();
resolve(/^y(es)?$/i.test(answer.trim()));
diff --git a/src/commands/reinit-pglite.ts b/src/commands/reinit-pglite.ts
index ec214d8a5f..0b2a5a76f7 100644
--- a/src/commands/reinit-pglite.ts
+++ b/src/commands/reinit-pglite.ts
@@ -331,18 +331,29 @@ function fail(jsonOutput: boolean, reason: string, message: string): never {
}
async function promptYesNo(question: string): Promise<boolean> {
- // Minimal TTY prompt — no external deps. Bun's process.stdin reads
- // a single line synchronously via the async iterator.
- process.stdout.write(`${question} (y/N): `);
+ // W0 fix-wave (Tier-1 #15): non-interactive stdin (CI, pipes, spawned
+ // agents) resolves to the safe default instead of hanging — this prompt
+ // had no TTY guard and no end/EOF path, so a closed stdin parked the
+ // process permanently. This command wipes the store; decline-by-default
+ // is the only safe non-interactive answer (--yes stays the escape hatch).
+ if (!process.stdin.isTTY) return false;
+ // Prompt on stderr so stdout stays clean for --json payloads.
+ process.stderr.write(`${question} (y/N): `);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const stdin = process.stdin as any;
stdin.setEncoding?.('utf8');
return new Promise<boolean>((resolve) => {
+ const cleanup = () => {
+ stdin.off?.('data', onData);
+ stdin.off?.('end', onEnd);
+ };
+ const onEnd = () => { cleanup(); resolve(false); }; // EOF = decline
const onData = (chunk: string) => {
const answer = chunk.trim().toLowerCase();
- stdin.off?.('data', onData);
+ cleanup();
resolve(answer === 'y' || answer === 'yes');
};
stdin.on?.('data', onData);
+ stdin.on?.('end', onEnd);
});
}
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 0b73596edd..808357c90b 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -49,7 +49,7 @@ import { gbrainPath } from './config.ts';
import type { BrainEngine } from './engine.ts';
import { createProgress, type ProgressReporter } from './progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from './cli-options.ts';
-import { tryAcquireDbLock, reapDeadHolderLocks, type DbLockHandle } from './db-lock.ts';
+import { tryAcquireDbLock, reapDeadHolderLocks, LockStolenError, type DbLockHandle } from './db-lock.ts';
import { assertValidSourceId } from './source-id.ts';
// ─── Types ─────────────────────────────────────────────────────────
@@ -572,7 +572,14 @@ const getLockFilePathDefault = () => gbrainPath('cycle.lock');
export interface LockHandle {
release: () => Promise<void>;
- refresh: () => Promise<void>;
+ /**
+ * W0 fix-wave: returns true while this holder still owns the lock. The
+ * DB-backed handle runs a fenced UPDATE (db-lock.ts, D5.10) and returns
+ * false after a steal; the file-lock handle rewrites its file and always
+ * returns true (single-host, pid-checked at acquire). Callers that ignore
+ * the boolean keep their old behavior.
+ */
+ refresh: () => Promise<boolean>;
}
/**
@@ -690,6 +697,7 @@ function acquireFileLock(lockPath = getLockFilePathDefault()): LockHandle | null
} catch {
/* non-fatal — a next-run stale check will notice */
}
+ return true;
},
release: async () => {
try {
@@ -726,21 +734,72 @@ function acquireFileLock(lockPath = getLockFilePathDefault()): LockHandle | null
* Returns `undefined` when there's no lock AND no outer hook so phases
* short-circuit via their `if (!opts.yieldDuringPhase) return;` guard.
*/
+/**
+ * W0 fix-wave: combine abort signals (external caller signal + the internal
+ * lock-steal controller) into one REAL AbortSignal.
+ *
+ * Deliberately NOT AbortSignal.any: CycleOpts.signal has always been duck-
+ * typed in practice (test stubs pass `{ aborted: false }` and flip the flag;
+ * pre-W0 the raw object flowed straight into checkAborted, which only reads
+ * `.aborted`/`.reason`). AbortSignal.any throws ERR_INVALID_ARG_TYPE on
+ * those. Manual fan-in: real signals propagate via listener; listener-less
+ * stubs are polled at 50ms — semantically the flip is seen within a tick,
+ * and the RETURNED signal is a genuine AbortSignal so phases can hand it to
+ * fetch/timers safely.
+ *
+ * ALWAYS call dispose() when the consuming scope ends (runCycle's finally):
+ * the forward listeners live on the CALLER's signals, and long-lived callers
+ * (the autopilot daemon passes its daemon-lifetime shutdown signal into
+ * every cycle tick) would otherwise accumulate one listener + captured
+ * controller per invocation forever (ship-review perf catch).
+ */
+export function anyAbortSignal(signals: AbortSignal[]): { signal: AbortSignal; dispose: () => void } {
+ const c = new AbortController();
+ const cleanups: Array<() => void> = [];
+ const forward = (s: AbortSignal) => { if (!c.signal.aborted) c.abort(s.reason); };
+ for (const s of signals) {
+ if (!s) continue;
+ if (s.aborted) { forward(s); break; }
+ if (typeof (s as Partial<AbortSignal>).addEventListener === 'function') {
+ const listener = () => forward(s);
+ s.addEventListener('abort', listener, { once: true });
+ cleanups.push(() => s.removeEventListener('abort', listener));
+ } else {
+ const t = setInterval(() => { if (s.aborted) { forward(s); clearInterval(t); } }, 50);
+ (t as unknown as { unref?: () => void }).unref?.();
+ c.signal.addEventListener('abort', () => clearInterval(t), { once: true });
+ cleanups.push(() => clearInterval(t));
+ }
+ }
+ return {
+ signal: c.signal,
+ dispose: () => { for (const fn of cleanups) { try { fn(); } catch { /* best effort */ } } },
+ };
+}
+
export function buildYieldDuringPhase(
lock: LockHandle | null,
outer?: () => Promise<void>,
+ onStolen?: (err: LockStolenError) => void,
): (() => Promise<void>) | undefined {
if (!lock && !outer) return undefined;
return async () => {
if (lock) {
try {
- await lock.refresh();
+ const stillOwned = await lock.refresh();
+ if (stillOwned === false) {
+ // W0 (D5.10/D5.11): the fenced refresh proved the lock is gone.
+ // Don't throw mid-LLM-call — signal the cycle's steal controller
+ // so the run stops at the next boundary / raced await instead of
+ // compounding writes against a concurrent successor.
+ console.error('[cycle] lock refresh matched 0 rows — lock stolen; signaling cycle abort');
+ onStolen?.(new LockStolenError('cycle-lock'));
+ }
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
- // Non-fatal: a refresh error doesn't crash the phase. If the
- // lock truly expired and was stolen, the next acquire by another
- // worker has already happened — let this run wind down rather
- // than throw mid-phase.
+ // Non-fatal: a TRANSIENT refresh error doesn't crash the phase (it
+ // is not evidence of a steal; the TTL is the backstop and the next
+ // tick retries).
console.error(`[cycle] lock refresh failed (non-fatal): ${msg}`);
}
}
@@ -750,6 +809,68 @@ export function buildYieldDuringPhase(
};
}
+/**
+ * W0 fix-wave (Tier-1 #1 + D5.11): runCycle-owned serialized lock refresher.
+ *
+ * Production callers never set `CycleOpts.yieldDuringPhase`, so before this
+ * timer the cycle lock was refreshed only by phases that happened to receive
+ * a wrapped hook — with a 5-min TTL against 35-min subagent waits, the lock
+ * was effectively NEVER refreshed in production (verified in the 2026-08-14
+ * audit). This interval owns the CYCLE lock only; Minion job-lock renewal
+ * stays on the yieldDuringPhase/yieldBetweenPhases hooks (the cycle.ts:618
+ * decision — a background timer must not replace the phase-boundary hook).
+ *
+ * Serialized: at most one refresh in flight (a slow refresh never overlaps
+ * the next tick). On a fenced refresh returning false, aborts `controller`
+ * with a LockStolenError; a thrown (transient) refresh error is logged and
+ * retried next tick — the TTL is the backstop.
+ */
+export function startCycleLockRefresher(
+ lock: LockHandle,
+ controller: AbortController,
+ lockId: string,
+ intervalMs: number = resolveCycleLockRefreshMs(),
+): () => void {
+ let inFlight = false;
+ const timer = setInterval(() => {
+ if (inFlight || controller.signal.aborted) return;
+ inFlight = true;
+ void (async () => {
+ try {
+ const stillOwned = await lock.refresh();
+ if (stillOwned === false && !controller.signal.aborted) {
+ controller.abort(new LockStolenError(lockId));
+ }
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ console.error(`[cycle] background lock refresh failed (non-fatal, retrying next tick): ${msg}`);
+ } finally {
+ inFlight = false;
+ }
+ })();
+ }, intervalMs);
+ // Don't let the refresher pin the event loop open past real work.
+ (timer as unknown as { unref?: () => void }).unref?.();
+ return () => clearInterval(timer);
+}
+
+/** Refresh 6x per TTL window (~50s at the 5-min TTL), matching withRefreshingLock's cadence. */
+const CYCLE_LOCK_REFRESH_INTERVAL_MS = Math.max(15_000, LOCK_TTL_MS / 6);
+
+/**
+ * GBRAIN_CYCLE_LOCK_REFRESH_MS: env-only escape hatch (incident tuning +
+ * deterministic tests), same posture as the GBRAIN_SYNC_* knobs. Floor of
+ * 10ms guards against a zero/NaN wedging the event loop.
+ */
+function resolveCycleLockRefreshMs(): number {
+ const raw = process.env.GBRAIN_CYCLE_LOCK_REFRESH_MS;
+ if (raw) {
+ const n = Number(raw);
+ if (Number.isFinite(n) && n >= 10) return n;
+ }
+ return CYCLE_LOCK_REFRESH_INTERVAL_MS;
+}
+
// ─── Helpers ───────────────────────────────────────────────────────
function makeErrorFromException(e: unknown, fallbackClass = 'InternalError'): PhaseError {
@@ -1712,8 +1833,18 @@ export async function runCycle(
lock = pgliteFileLock
? {
refresh: async () => {
- await dbLock!.refresh();
- await pgliteFileLock!.refresh();
+ // W0 (D5.10): the DB row is the authoritative multi-writer
+ // identity; the file refresh is best-effort freshness. Propagate
+ // the fenced result so steal detection reaches the refresher.
+ // Red-team catch: NEVER rewrite the file half after the fence
+ // reports loss — the unconditional rewrite let the losing
+ // holder clobber the successor's file lock (our pid back in the
+ // file) on the very tick it detected the steal, after which our
+ // pid-checked file release would DELETE the successor's only
+ // host-local protection mid-run.
+ const stillOwned = await dbLock!.refresh();
+ if (stillOwned) await pgliteFileLock!.refresh();
+ return stillOwned;
},
release: async () => {
try {
@@ -1745,6 +1876,51 @@ export async function runCycle(
}
}
+ // W0 fix-wave (Tier-1 #1 + D5.11): lock-steal detection and propagation.
+ //
+ // refresher (50s tick) ──fenced UPDATE──▶ 0 rows? ──▶ stolen.abort(LockStolenError)
+ // │ │
+ // └── yieldDuringPhase hooks also report steals ────────┤
+ // ▼
+ // cycleSignal = any(opts.signal, stolen.signal) → checkAborted() at every
+ // phase boundary; raceStolen() additionally races the 5 long-phase awaits
+ // (their opts can't carry a signal yet — full threading lands in W6).
+ //
+ // External aborts (opts.signal) keep today's throw-out semantics; ONLY a
+ // steal is caught below and returned as a structured partial report.
+ const externalSignal = opts.signal;
+ const stolen: AbortController | null = lock ? new AbortController() : null;
+ const combinedSignal = stolen && externalSignal
+ ? anyAbortSignal([externalSignal, stolen.signal])
+ : null;
+ const cycleSignal: AbortSignal | undefined = combinedSignal
+ ? combinedSignal.signal
+ : (stolen?.signal ?? externalSignal);
+ const stopRefresher: (() => void) | undefined = lock && stolen
+ ? startCycleLockRefresher(lock, stolen, cycleLockIdFor(opts.sourceId))
+ : undefined;
+ const onStolen = stolen ? (e: LockStolenError) => { if (!stolen.signal.aborted) stolen.abort(e); } : undefined;
+ const raceStolen = !stolen
+ ? <T,>(p: Promise<T>): Promise<T> => p
+ : <T,>(p: Promise<T>): Promise<T> => {
+ if (stolen.signal.aborted) return Promise.reject(stolen.signal.reason);
+ let onAbort!: () => void;
+ const abortP = new Promise<never>((_, rej) => {
+ onAbort = () => rej(stolen.signal.reason);
+ stolen.signal.addEventListener('abort', onAbort, { once: true });
+ });
+ return Promise.race([p, abortP]).finally(() => {
+ stolen.signal.removeEventListener('abort', onAbort);
+ }) as Promise<T>;
+ };
+ let lockStolenAbort = false;
+ // Raced variant for the 5 long phases (synthesize / extract_atoms / patterns
+ // / synthesize_concepts / consolidate): their opts can't carry a signal yet
+ // (W6), so a steal must be able to stop the WAIT even though the phase's
+ // in-flight work runs to its own bounded timeout. Steal-free cycles behave
+ // byte-identically to timePhase.
+ const racedTimePhase = <T,>(fn: () => Promise<T>) => raceStolen(timePhase(fn));
+
// #1972: reap dead-holder sync/cycle locks at cycle start — before the sync
// phase needs them — so a crashed sync's stranded lock self-heals THIS tick
// instead of waiting out its TTL. Best-effort, namespace-scoped + host-scoped;
@@ -1766,12 +1942,12 @@ export async function runCycle(
try {
// ── Phase 1: lint ────────────────────────────────────────────
if (phases.includes('lint')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (brainDir === null) {
phaseResults.push(skipNoBrainDir('lint'));
} else {
progress.start('cycle.lint');
- const { result, duration_ms } = await timePhase(() => runPhaseLint(brainDir, dryRun, engine, opts.signal));
+ const { result, duration_ms } = await timePhase(() => runPhaseLint(brainDir, dryRun, engine, cycleSignal));
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
@@ -1781,7 +1957,7 @@ export async function runCycle(
// ── Phase 2: backlinks ──────────────────────────────────────
if (phases.includes('backlinks')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (brainDir === null) {
phaseResults.push(skipNoBrainDir('backlinks'));
} else {
@@ -1806,7 +1982,7 @@ export async function runCycle(
let syncAttempted = false;
let synthesizeWrittenSlugs: string[] | undefined;
if (phases.includes('sync')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'sync',
@@ -1820,7 +1996,13 @@ export async function runCycle(
} else {
progress.start('cycle.sync');
syncAttempted = true; // sync ran its work; undefined pagesAffected now means failure
- const { result, duration_ms } = await timePhase(() => runPhaseSync(engine, brainDir, dryRun, pull, phases.includes('extract')));
+ // Red-team catch: sync is production's LONGEST phase (resumable
+ // imports can run hours) and was the one long await outside steal
+ // coverage. Raced like the other five: an abandoned wait is safe —
+ // sync checkpoints its progress, holds its own per-source lock (the
+ // successor's sync phase skips with lock-busy), and its stall
+ // watchdog bounds the dangling import. Signal threading lands in W6.
+ const { result, duration_ms } = await racedTimePhase(() => runPhaseSync(engine, brainDir, dryRun, pull, phases.includes('extract')));
result.duration_ms = duration_ms;
// Capture changed slugs for incremental extract.
syncPagesAffected = (result as SyncPhaseResult).pagesAffected;
@@ -1845,10 +2027,13 @@ export async function runCycle(
} else {
progress.start('cycle.synthesize');
const { runPhaseSynthesize } = await import('./cycle/synthesize.ts');
- const { result, duration_ms } = await timePhase(() => runPhaseSynthesize(engine, {
+ const { result, duration_ms } = await racedTimePhase(() => runPhaseSynthesize(engine, {
brainDir,
dryRun,
- yieldDuringPhase: opts.yieldDuringPhase,
+ // W0 (Tier-1 #1): wrap the caller hook so this phase ALSO refreshes
+ // the cycle lock (pre-fix these sites passed the raw — in production
+ // always-undefined — hook, so long phases never refreshed).
+ yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),
inputFile: opts.synthInputFile,
date: opts.synthDate,
from: opts.synthFrom,
@@ -1873,7 +2058,7 @@ export async function runCycle(
// ── Phase 5: extract (now picks up synthesize output) ───────
if (phases.includes('extract')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'extract',
@@ -1889,7 +2074,7 @@ export async function runCycle(
// If sync didn't run (phases exclude it) or failed, syncPagesAffected
// is undefined → extract falls back to full walk (safe default).
progress.start('cycle.extract');
- const { result, duration_ms } = await timePhase(() => runPhaseExtract(engine, brainDir, dryRun, syncPagesAffected, opts.signal, cycleSourceId));
+ const { result, duration_ms } = await timePhase(() => runPhaseExtract(engine, brainDir, dryRun, syncPagesAffected, cycleSignal, cycleSourceId));
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
@@ -1905,7 +2090,7 @@ export async function runCycle(
// refuses to run while v0.31 legacy facts are pending the
// v0_32_2 backfill (Codex R2-#7).
if (phases.includes('extract_facts')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'extract_facts',
@@ -1938,7 +2123,7 @@ export async function runCycle(
const syncRanButFailed = syncAttempted && syncPagesAffected === undefined;
const xfSlugs = syncRanButFailed ? [] : syncPagesAffected;
const { result, duration_ms } = await timePhase(() =>
- runPhaseExtractFacts(engine, brainDir, xfSourceId, dryRun, xfSlugs, opts.signal));
+ runPhaseExtractFacts(engine, brainDir, xfSourceId, dryRun, xfSlugs, cycleSignal));
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
@@ -1959,7 +2144,7 @@ export async function runCycle(
// resolved active pack's `phases:` list ONLY; not the extends chain
// or borrow_from targets.
if (phases.includes('extract_atoms')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'extract_atoms',
@@ -1995,13 +2180,13 @@ export async function runCycle(
...(synthesizeWrittenSlugs ?? []),
]
: undefined;
- const { result, duration_ms } = await timePhase(() => runPhaseExtractAtoms(engine, {
+ const { result, duration_ms } = await racedTimePhase(() => runPhaseExtractAtoms(engine, {
brainDir: brainDir ?? undefined,
sourceId: xaSourceId,
dryRun,
affectedSlugs: xaAffectedSlugs,
// v0.41.19.0 (T3): closure refreshes cycle lock + fires outer hook.
- yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase),
+ yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),
// v0.41.19.0 (T4): pass same reporter (not a child — cycle.ts
// owns start/finish; phase only ticks).
progress,
@@ -2019,7 +2204,7 @@ export async function runCycle(
// BATCH_SIZE * 10 chunks per invocation so a 60s watchdog tick stays
// responsive even on a 100K-chunk brain.
if (phases.includes('resolve_symbol_edges')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'resolve_symbol_edges',
@@ -2057,10 +2242,13 @@ export async function runCycle(
} else {
progress.start('cycle.patterns');
const { runPhasePatterns } = await import('./cycle/patterns.ts');
- const { result, duration_ms } = await timePhase(() => runPhasePatterns(engine, {
+ const { result, duration_ms } = await racedTimePhase(() => runPhasePatterns(engine, {
brainDir,
dryRun,
- yieldDuringPhase: opts.yieldDuringPhase,
+ // W0 (Tier-1 #1): wrap the caller hook so this phase ALSO refreshes
+ // the cycle lock (pre-fix these sites passed the raw — in production
+ // always-undefined — hook, so long phases never refreshed).
+ yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),
once: opts.onceForPhase === 'patterns',
deadlineAtMs: opts.deadlineAtMs ?? null,
// #1586: scope pattern writes to the cycle's resolved source, same as
@@ -2083,7 +2271,7 @@ export async function runCycle(
// resolved active pack manifest; no-op when this phase isn't
// declared. Real body in T6 — synthesize-concepts.ts is a stub today.
if (phases.includes('synthesize_concepts')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'synthesize_concepts',
@@ -2107,11 +2295,11 @@ export async function runCycle(
} else {
progress.start('cycle.synthesize_concepts');
const { runPhaseSynthesizeConcepts } = await import('./cycle/synthesize-concepts.ts');
- const { result, duration_ms } = await timePhase(() => runPhaseSynthesizeConcepts(engine, {
+ const { result, duration_ms } = await racedTimePhase(() => runPhaseSynthesizeConcepts(engine, {
brainDir: brainDir ?? undefined,
dryRun,
// v0.41.19.0 (T3): closure refreshes cycle lock + fires outer hook.
- yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase),
+ yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),
// v0.41.19.0 (T4): pass same reporter (not a child).
progress,
}));
@@ -2127,7 +2315,7 @@ export async function runCycle(
// every page touched in this cycle. Incremental mode uses union(sync,
// synthesize); full mode walks every page in the brain.
if (phases.includes('recompute_emotional_weight')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'recompute_emotional_weight',
@@ -2167,7 +2355,7 @@ export async function runCycle(
// per cluster, INSERT into takes(kind='fact'), mark facts as
// consolidated_into. Never DELETE — facts are the audit trail.
if (phases.includes('consolidate')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'consolidate',
@@ -2179,10 +2367,13 @@ export async function runCycle(
} else {
progress.start('cycle.consolidate');
const { runPhaseConsolidate } = await import('./cycle/phases/consolidate.ts');
- const { result, duration_ms } = await timePhase(() => runPhaseConsolidate(engine, {
+ const { result, duration_ms } = await racedTimePhase(() => runPhaseConsolidate(engine, {
dryRun,
- yieldDuringPhase: opts.yieldDuringPhase,
- signal: opts.signal,
+ // W0 (Tier-1 #1): wrap the caller hook so this phase ALSO refreshes
+ // the cycle lock (pre-fix these sites passed the raw — in production
+ // always-undefined — hook, so long phases never refreshed).
+ yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),
+ signal: cycleSignal,
}));
result.duration_ms = duration_ms;
phaseResults.push(result);
@@ -2218,7 +2409,7 @@ export async function runCycle(
} as never;
if (phases.includes('propose_takes')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
progress.start('cycle.propose_takes');
const { runPhaseProposeTakes } = await import('./cycle/propose-takes.ts');
const { result, duration_ms } = await timePhase(() => runPhaseProposeTakes(calibrationCtx, { repoPath: brainDir ?? undefined }) as Promise<PhaseResult>);
@@ -2229,7 +2420,7 @@ export async function runCycle(
}
if (phases.includes('grade_takes')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
progress.start('cycle.grade_takes');
const { runPhaseGradeTakes } = await import('./cycle/grade-takes.ts');
const { result, duration_ms } = await timePhase(() => runPhaseGradeTakes(calibrationCtx, {}) as Promise<PhaseResult>);
@@ -2240,7 +2431,7 @@ export async function runCycle(
}
if (phases.includes('calibration_profile')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
progress.start('cycle.calibration_profile');
const { runPhaseCalibrationProfile } = await import('./cycle/calibration-profile.ts');
const { result, duration_ms } = await timePhase(() => runPhaseCalibrationProfile(calibrationCtx, {}) as Promise<PhaseResult>);
@@ -2270,7 +2461,7 @@ export async function runCycle(
// reports/drift-<date> page, mutates no takes regardless of
// dream.drift.auto_update.
if (phases.includes('drift')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'drift',
@@ -2315,7 +2506,7 @@ export async function runCycle(
// tracker passed in from the phase wrapper (NOT nested-wrapped in
// core — would REPLACE not stack).
if (phases.includes('conversation_facts_backfill')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'conversation_facts_backfill',
@@ -2330,7 +2521,7 @@ export async function runCycle(
const { result, duration_ms } = await timePhase(() =>
runPhaseConversationFactsBackfill(engine, {
dryRun,
- signal: opts.signal,
+ signal: cycleSignal,
once: opts.onceForPhase === 'conversation_facts_backfill',
}),
);
@@ -2347,7 +2538,7 @@ export async function runCycle(
// cost AND walltime caps; budget tracker created in the phase wrapper and
// passed into the core (NOT nested-wrapped — would REPLACE not stack).
if (phases.includes('enrich_thin')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'enrich_thin',
@@ -2362,7 +2553,7 @@ export async function runCycle(
const { result, duration_ms } = await timePhase(() =>
runPhaseEnrichThin(engine, {
dryRun,
- signal: opts.signal,
+ signal: cycleSignal,
once: opts.onceForPhase === 'enrich_thin',
}),
);
@@ -2379,7 +2570,7 @@ export async function runCycle(
// safety (D16): the phase ALWAYS runs in --no-mutate mode — proposed
// bests land at skills/<name>/skillopt/best.md for review.
if (phases.includes('skillopt')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'skillopt' as never,
@@ -2396,7 +2587,7 @@ export async function runCycle(
engine,
dryRun,
once: opts.onceForPhase === 'skillopt',
- ...(opts.signal ? { signal: opts.signal } : {}),
+ ...(cycleSignal ? { signal: cycleSignal } : {}),
}),
);
result.duration_ms = duration_ms;
@@ -2408,7 +2599,7 @@ export async function runCycle(
// ── Phase 8: embed ──────────────────────────────────────────
if (phases.includes('embed')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'embed',
@@ -2419,7 +2610,7 @@ export async function runCycle(
});
} else {
progress.start('cycle.embed');
- const { result, duration_ms } = await timePhase(() => runPhaseEmbed(engine, dryRun, opts.signal));
+ const { result, duration_ms } = await timePhase(() => runPhaseEmbed(engine, dryRun, cycleSignal));
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
@@ -2429,7 +2620,7 @@ export async function runCycle(
// ── Phase 9: orphans ────────────────────────────────────────
if (phases.includes('orphans')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'orphans',
@@ -2455,7 +2646,7 @@ export async function runCycle(
// (T15) and the disk-derived candidate set surfaced by `gbrain schema
// review-candidates`.
if (phases.includes('schema-suggest')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'schema-suggest',
@@ -2499,7 +2690,7 @@ export async function runCycle(
// 72h recovery window. Runs last so the rest of the cycle sees the
// recoverable set; the purge then drops what's truly expired.
if (phases.includes('purge')) {
- checkAborted(opts.signal);
+ checkAborted(cycleSignal);
if (!engine) {
phaseResults.push({
phase: 'purge',
@@ -2517,9 +2708,31 @@ export async function runCycle(
}
await safeYield(opts.yieldBetweenPhases);
}
+ } catch (e) {
+ // W0 (Tier-1 #1): a lock steal aborts the run at the next boundary/raced
+ // await. Completed phases' DB writes are durable (persisted-and-resumable
+ // per D5.6); report a structured partial instead of throwing so daemon
+ // callers (jobs.ts / autopilot) don't have to classify an exception.
+ // External aborts (cycleSignal) keep the existing throw-out contract.
+ const stolenFired = stolen?.signal.aborted === true
+ && stolen.signal.reason instanceof LockStolenError
+ && externalSignal?.aborted !== true;
+ if (stolenFired) {
+ lockStolenAbort = true;
+ console.error(`[cycle] aborting: ${stolen!.signal.reason.message} — ${phaseResults.length} phase(s) completed before the steal; their writes are durable`);
+ } else {
+ throw e;
+ }
} finally {
+ stopRefresher?.();
+ // Detach the combined-signal forwarders from the CALLER's signal — the
+ // autopilot daemon reuses one shutdown signal across every tick, and
+ // undisposed listeners accumulate for the daemon's lifetime.
+ combinedSignal?.dispose();
if (lock) {
try {
+ // Safe after a steal: release() is fenced on (id, pid, acquired_at),
+ // so it can never delete the successor's row (deletes 0 rows).
await lock.release();
} catch (e) {
// #1470: best-effort, but never silent — a swallowed release failure
@@ -2541,7 +2754,7 @@ export async function runCycle(
// a cancelled run as a completed full cycle, which makes the next tick skip
// work it never actually did. Treat an aborted signal as a non-success run:
// skip the freshness stamp and report status 'partial' with reason 'aborted'.
- const aborted = opts.signal?.aborted === true;
+ const aborted = cycleSignal?.aborted === true;
// #1972 (Decision 7A gating): attribute force-evicts. The minion worker
// force-evicts a job 30s after abort and logs "handler ignored abort signal";
@@ -2614,7 +2827,7 @@ export async function runCycle(
timestamp,
duration_ms,
status: effectiveStatus,
- ...(aborted ? { reason: 'aborted' } : stampWriteFailed ? { reason: 'stamp_write_failed' } : {}),
+ ...(lockStolenAbort ? { reason: 'lock_stolen' } : aborted ? { reason: 'aborted' } : stampWriteFailed ? { reason: 'stamp_write_failed' } : {}),
...(stampWriteFailed ? { stamp_write_failed: stampWriteFailed } : {}),
...(reapedLocks ? { reaped_dead_holder_locks: reapedLocks } : {}),
brain_dir: opts.brainDir,
diff --git a/src/core/db-lock.ts b/src/core/db-lock.ts
index 0ac27bc667..656f3e91b6 100644
--- a/src/core/db-lock.ts
+++ b/src/core/db-lock.ts
@@ -26,8 +26,38 @@ import type { BrainEngine } from './engine.ts';
export interface DbLockHandle {
id: string;
+ /**
+ * Per-acquisition fencing identity (W0 fix-wave, D5.10): the row's
+ * acquired_at rendered as epoch-seconds text (GUC-independent — timestamptz::text
+ * would vary with per-session TimeZone/DateStyle across pools), captured at
+ * acquire time. refresh()
+ * and release() require an exact match, so a PID-reuse impostor (or this
+ * handle after a steal) can never refresh or delete a successor's row.
+ * `(id, holder_pid)` alone is NOT identity — PIDs recycle.
+ */
+ acquiredAt: string;
release: () => Promise<void>;
- refresh: () => Promise<void>;
+ /**
+ * Bump ttl_expires_at + last_refreshed_at. Returns true when this handle
+ * still owns the row (exactly one row matched the fenced predicate);
+ * false means the lock was stolen or released — the caller must stop
+ * relying on mutual exclusion. Transient DB errors still THROW (they are
+ * not evidence of a steal; the TTL is the backstop).
+ */
+ refresh: () => Promise<boolean>;
+}
+
+/**
+ * W0 fix-wave: thrown (or used as an AbortSignal reason) when a fenced
+ * refresh discovers the lock row no longer belongs to this acquisition.
+ */
+export class LockStolenError extends Error {
+ readonly lockId: string;
+ constructor(lockId: string) {
+ super(`lock '${lockId}' was stolen or released out from under this holder (fenced refresh matched 0 rows)`);
+ this.name = 'LockStolenError';
+ this.lockId = lockId;
+ }
}
/** Default TTL: 30 minutes, same as cycle lock. */
@@ -205,7 +235,7 @@ export async function tryAcquireDbLock(
// `gbrain sync --break-lock --max-age <s>` uses last_refreshed_at (not
// acquired_at) to identify wedged-but-alive holders without stealing
// healthy long-running holders that are actively refreshing.
- const rows: Array<{ id: string }> = await sql`
+ const rows: Array<{ id: string; fence: string }> = await sql`
INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at)
VALUES (${lockId}, ${pid}, ${host}, NOW(), NOW() + ${ttl}::interval, NOW())
ON CONFLICT (id) DO UPDATE
@@ -217,35 +247,47 @@ export async function tryAcquireDbLock(
WHERE gbrain_cycle_locks.ttl_expires_at < NOW()
AND (gbrain_cycle_locks.last_refreshed_at IS NULL
OR gbrain_cycle_locks.last_refreshed_at < NOW() - ${stealGraceSeconds} * INTERVAL '1 second')
- RETURNING id
+ RETURNING id, extract(epoch from acquired_at)::text AS fence
`;
if (rows.length === 0) return null;
+ // Fencing identity (D5.10): acquired_at is written fresh on INSERT and on
+ // every steal, so it uniquely names THIS acquisition. Rendered as
+ // extract(epoch ...)::text — GUC-INDEPENDENT (ship-review catch, 3
+ // specialists): plain timestamptz::text varies with per-session
+ // TimeZone/DateStyle, and the fence is captured on the acquire pool but
+ // compared on the direct pool; a GUC divergence would turn every fenced
+ // refresh into a false steal. Epoch text is stable across sessions and
+ // keeps microsecond precision.
+ const fence = rows[0].fence;
const deregister = registerCleanup(`db-lock:${lockId}`, async () => {
await sql`
DELETE FROM gbrain_cycle_locks
- WHERE id = ${lockId} AND holder_pid = ${pid}
+ WHERE id = ${lockId} AND holder_pid = ${pid} AND extract(epoch from acquired_at)::text = ${fence}
`;
});
return {
id: lockId,
+ acquiredAt: fence,
refresh: async () => {
// v0.41.13.0: bump BOTH ttl_expires_at AND last_refreshed_at.
// v0.42.x (#1794): route through the DIRECT session pool, not the
// transaction pool, so a Supavisor pooler exhaustion (EMAXCONNSESSION)
// can't kill the heartbeat and let the live lock get stolen.
- await engine.executeRawDirect(
+ const updated = await engine.executeRawDirect<{ id: string }>(
`UPDATE gbrain_cycle_locks
SET ttl_expires_at = NOW() + ($1)::interval,
last_refreshed_at = NOW()
- WHERE id = $2 AND holder_pid = $3`,
- [ttl, lockId, pid],
+ WHERE id = $2 AND holder_pid = $3 AND extract(epoch from acquired_at)::text = $4
+ RETURNING id`,
+ [ttl, lockId, pid, fence],
);
+ return updated.length > 0;
},
release: async () => {
deregister();
await sql`
DELETE FROM gbrain_cycle_locks
- WHERE id = ${lockId} AND holder_pid = ${pid}
+ WHERE id = ${lockId} AND holder_pid = ${pid} AND extract(epoch from acquired_at)::text = ${fence}
`;
},
};
@@ -266,32 +308,37 @@ export async function tryAcquireDbLock(
WHERE gbrain_cycle_locks.ttl_expires_at < NOW()
AND (gbrain_cycle_locks.last_refreshed_at IS NULL
OR gbrain_cycle_locks.last_refreshed_at < NOW() - $5 * INTERVAL '1 second')
- RETURNING id`,
+ RETURNING id, extract(epoch from acquired_at)::text AS fence`,
[lockId, pid, host, ttl, stealGraceSeconds],
);
if (rows.length === 0) return null;
+ // Fencing identity (D5.10) — see the postgres branch for rationale.
+ const fence = String((rows[0] as { fence: string }).fence);
const deregister = registerCleanup(`db-lock:${lockId}`, async () => {
await db.query(
- `DELETE FROM gbrain_cycle_locks WHERE id = $1 AND holder_pid = $2`,
- [lockId, pid],
+ `DELETE FROM gbrain_cycle_locks WHERE id = $1 AND holder_pid = $2 AND extract(epoch from acquired_at)::text = $3`,
+ [lockId, pid, fence],
);
});
return {
id: lockId,
+ acquiredAt: fence,
refresh: async () => {
- await db.query(
+ const res = await db.query(
`UPDATE gbrain_cycle_locks
SET ttl_expires_at = NOW() + $1::interval,
last_refreshed_at = NOW()
- WHERE id = $2 AND holder_pid = $3`,
- [ttl, lockId, pid],
+ WHERE id = $2 AND holder_pid = $3 AND extract(epoch from acquired_at)::text = $4
+ RETURNING id`,
+ [ttl, lockId, pid, fence],
);
+ return res.rows.length > 0;
},
release: async () => {
deregister();
await db.query(
- `DELETE FROM gbrain_cycle_locks WHERE id = $1 AND holder_pid = $2`,
- [lockId, pid],
+ `DELETE FROM gbrain_cycle_locks WHERE id = $1 AND holder_pid = $2 AND extract(epoch from acquired_at)::text = $3`,
+ [lockId, pid, fence],
);
},
};
@@ -852,7 +899,20 @@ export async function withRefreshingLock<T>(
const timeout = new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error('refresh_timeout')), heartbeatTimeoutMs)
);
- await Promise.race([handle.refresh(), timeout]);
+ const stillOwned = await Promise.race([handle.refresh(), timeout]);
+ if (stillOwned === false) {
+ // W0 (D5.10): the fenced refresh matched 0 rows — the lock was
+ // stolen or force-cleared. Further refreshes are pointless (and a
+ // fenced refresh can never re-take the successor's row). Stop the
+ // heartbeat and shout; the work itself keeps running (this wrapper
+ // has no cancellation seam — W7 threads one through its consumers),
+ // but mutual exclusion is GONE and the degraded-heartbeat exit
+ // message names it.
+ clearInterval(interval);
+ healthOk = false;
+ process.stderr.write(`[lock-refresh] ${lockId}: ${new LockStolenError(lockId).message} — heartbeat stopped, mutual exclusion lost\n`);
+ return;
+ }
healthOk = true;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index 94dfae7275..e61a2c3d04 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -18,12 +18,44 @@
*/
import type { BrainEngine } from './engine.ts';
-import type { ChunkInput } from './types.ts';
+import type { Chunk, ChunkInput } from './types.ts';
import { embedBatchWithBackoff, restampIfDemotedToTitleTier } from '../commands/embed.ts';
import { wrapChunkTextsForStoredMode } from './embedding-context.ts';
import { type DbPacer, createNoopPacer, observed } from './db-pacer.ts';
import { AbortError } from './abort-check.ts';
+/**
+ * W0 fix-wave (Tier-1 #3, CONFIRMED): the ONE carry-through field list for
+ * re-embed upserts. upsertChunks writes these columns as EXCLUDED.<col>
+ * (overwrite, not COALESCE), so any re-embed path that omits a field resets
+ * it — omitting `modality` flipped every image chunk to modality='text',
+ * silently zeroing the image search arm (filter `cc.modality = 'image'`).
+ * Pre-fix this list existed twice: here (correct, with modality) and in
+ * commands/embed.ts preserveCodeMetadata (missing modality — the bug). Both
+ * consumers now share THIS list; embedding_image is deliberately NOT carried
+ * (the upsert COALESCEs it, and getChunks returns the pgvector as a string
+ * which upsertChunks would mis-serialize).
+ */
+export function carryChunkMetadata(
+ loaded: Pick<Partial<Chunk>,
+ 'modality' | 'language' | 'symbol_name' | 'symbol_type' | 'start_line'
+ | 'end_line' | 'parent_symbol_path' | 'doc_comment' | 'symbol_name_qualified'>,
+ base: ChunkInput,
+): ChunkInput {
+ return {
+ ...base,
+ modality: loaded.modality ?? undefined,
+ language: loaded.language ?? undefined,
+ symbol_name: loaded.symbol_name ?? undefined,
+ symbol_type: loaded.symbol_type ?? undefined,
+ start_line: loaded.start_line ?? undefined,
+ end_line: loaded.end_line ?? undefined,
+ parent_symbol_path: loaded.parent_symbol_path ?? undefined,
+ doc_comment: loaded.doc_comment ?? undefined,
+ symbol_name_qualified: loaded.symbol_name_qualified ?? undefined,
+ };
+}
+
/** Last visited (page_id, chunk_index) for keyset-resume across runs. */
export interface StaleCursor {
afterPageId: number;
@@ -208,28 +240,12 @@ export async function embedStaleForSource(
for (let j = 0; j < stale.length; j++) {
staleIdxToEmbedding.set(stale[j].chunk_index, embeddings[j]);
}
- const merged: ChunkInput[] = existing.map((c) => ({
+ const merged: ChunkInput[] = existing.map((c) => carryChunkMetadata(c, {
chunk_index: c.chunk_index,
chunk_text: c.chunk_text,
chunk_source: c.chunk_source,
embedding: staleIdxToEmbedding.get(c.chunk_index) ?? undefined,
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
- // Carry through per-chunk metadata. upsertChunks writes these as
- // EXCLUDED.<col> (not COALESCE), so omitting them here resets image
- // rows to modality='text' (breaking the image search arm's
- // modality='image' filter) and wipes code-chunk symbol metadata on
- // every embed-stale pass. embedding_image is deliberately NOT
- // carried: the upsert COALESCEs it, and getChunks returns the
- // pgvector as a string which upsertChunks would mis-serialize.
- modality: c.modality ?? undefined,
- language: c.language ?? undefined,
- symbol_name: c.symbol_name ?? undefined,
- symbol_type: c.symbol_type ?? undefined,
- start_line: c.start_line ?? undefined,
- end_line: c.end_line ?? undefined,
- parent_symbol_path: c.parent_symbol_path ?? undefined,
- doc_comment: c.doc_comment ?? undefined,
- symbol_name_qualified: c.symbol_name_qualified ?? undefined,
}));
await observed(pacer, () => engine.upsertChunks(slug, merged, { sourceId: keySourceId }));
// v0.41.31: stamp provenance only when EVERY chunk was stale (fully
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 27c04dae0b..6d68c543d7 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -11,7 +11,7 @@
import type { BrainEngine } from '../engine.ts';
import type {
MinionJob, MinionJobInput, MinionJobStatus, InboxMessage, TokenUpdate,
- MinionQueueOpts, ChildDoneMessage, Attachment, AttachmentInput,
+ MinionQueueOpts, ChildDoneMessage, ChildOutcome, Attachment, AttachmentInput,
} from './types.ts';
import { rowToMinionJob, rowToInboxMessage, rowToAttachment } from './types.ts';
import { validateAttachment } from './attachments.ts';
@@ -570,7 +570,7 @@ export class MinionQueue {
// waiting-children whose last open child we just cancelled.
for (const parentId of parentIds) {
await tx.executeRaw(
- `UPDATE minion_jobs SET status = 'waiting', updated_at = now()
+ `UPDATE minion_jobs SET status = 'waiting', started_at = NULL, updated_at = now()
WHERE id = $1 AND status = 'waiting-children'
AND NOT EXISTS (
SELECT 1 FROM minion_jobs
@@ -807,15 +807,26 @@ export class MinionQueue {
*/
async handleTimeouts(): Promise<MinionJob[]> {
return this.engine.transaction(async (tx) => {
+ // #1737: count the timed-out run as a spent attempt (terminal, no retry).
+ // Safe against double-count: the worker sweep runs handleStalled ->
+ // handleTimeouts -> handleWallClockTimeouts sequentially and awaited, and
+ // each guards on `status = 'active'`, so the first to set status='dead'
+ // excludes the row from the later sweeps.
+ //
+ // W0 (D5.12): candidates are discovered with a plain read, PARENTS are
+ // locked first in sorted order (matching failJob's parent-before-child
+ // order), and the child UPDATE re-checks every predicate under a
+ // SKIP LOCKED subselect — see killJobs() for the shared tail.
+ const candidates = await tx.executeRaw<{ id: number; parent_job_id: number | null }>(
+ `SELECT id, parent_job_id FROM minion_jobs
+ WHERE status = 'active'
+ AND timeout_at IS NOT NULL
+ AND timeout_at < now()
+ AND lock_until > now()`
+ );
+ if (candidates.length === 0) return [];
+ await this.lockParentsOrdered(tx, candidates);
const rows = await tx.executeRaw<Record<string, unknown>>(
- // #1737: count the timed-out run as a spent attempt (terminal, no retry),
- // mirroring handleWallClockTimeouts + handleStalled. handleTimeouts is the
- // FIRST killer to fire for the long-lane handlers (timeout_ms stamped at
- // submit), so without this the job reads `attempts: 0/N (started: N)`.
- // Safe against double-count: the worker sweep runs handleStalled ->
- // handleTimeouts -> handleWallClockTimeouts sequentially and awaited, and
- // each guards on `status = 'active'`, so the first to set status='dead'
- // excludes the row from the later sweeps.
`UPDATE minion_jobs SET
status = 'dead',
error_text = 'timeout exceeded',
@@ -824,58 +835,104 @@ export class MinionQueue {
lock_until = NULL,
finished_at = now(),
updated_at = now()
- WHERE status = 'active'
- AND timeout_at IS NOT NULL
- AND timeout_at < now()
- AND lock_until > now()
- RETURNING *`
+ WHERE id IN (
+ SELECT id FROM minion_jobs
+ WHERE id = ANY($1::bigint[])
+ AND status = 'active'
+ AND timeout_at IS NOT NULL
+ AND timeout_at < now()
+ AND lock_until > now()
+ FOR UPDATE SKIP LOCKED
+ )
+ RETURNING *`,
+ [candidates.map(c => c.id)]
);
+ await this.killJobs(tx, rows, 'timeout', 'timeout exceeded');
+ return rows.map(rowToMinionJob);
+ });
+ }
- // v0.15: emit child_done(outcome='timeout') for every timed-out job that
- // had a parent. Without this, an aggregator waiting for N child_done
- // messages hangs forever when a child times out (codex iteration 3).
- // Outcome 'timeout' is distinct from 'dead' so consumers can distinguish
- // "timed out during run" from "died via max-stall".
- const parentIds = new Set<number>();
- for (const r of rows) {
- const parentJobId = r.parent_job_id as number | null;
- if (parentJobId == null) continue;
- parentIds.add(parentJobId);
- const childDone: ChildDoneMessage = {
- type: 'child_done',
- child_id: r.id as number,
- job_name: r.name as string,
- result: null,
- outcome: 'timeout',
- error: 'timeout exceeded',
- };
- await tx.executeRaw(
- `INSERT INTO minion_inbox (job_id, sender, payload)
- SELECT $1, 'minions', $2::jsonb
- WHERE EXISTS (
+ /**
+ * W0 fix-wave (Tier-1 #4, D5.12): the ONE parent-notification tail shared
+ * by every reaper that terminally kills active jobs. Pre-fix this ~45-line
+ * block was hand-copied between handleTimeouts and handleWallClockTimeouts
+ * (differing only in the error string), and handleStalled's dead-letter
+ * branch had NO copy at all — a child that died via max-stall left its
+ * aggregator parent in 'waiting-children' forever (the exact hang the v0.15
+ * comment says was fixed for timeouts).
+ *
+ * Runs inside the caller's transaction, AFTER the child transitions.
+ * Callers must have locked the parents first via lockParentsOrdered() —
+ * parents-before-children is the queue-wide lock order (failJob locks the
+ * parent before touching the child), so the reapers can never deadlock
+ * against a concurrent failJob/completeJob.
+ *
+ * Emits child_done(outcome) to each non-terminal parent's inbox, then flips
+ * any 'waiting-children' parent whose last open child we just killed back
+ * to 'waiting'.
+ */
+ private async killJobs(
+ tx: Pick<BrainEngine, 'executeRaw'>,
+ rows: Array<Record<string, unknown>>,
+ outcome: ChildOutcome,
+ errorText: string,
+ ): Promise<void> {
+ const parentIds = new Set<number>();
+ for (const r of rows) {
+ const parentJobId = r.parent_job_id as number | null;
+ if (parentJobId == null) continue;
+ parentIds.add(parentJobId);
+ const childDone: ChildDoneMessage = {
+ type: 'child_done',
+ child_id: r.id as number,
+ job_name: r.name as string,
+ result: null,
+ outcome,
+ error: errorText,
+ };
+ await tx.executeRaw(
+ `INSERT INTO minion_inbox (job_id, sender, payload)
+ SELECT $1, 'minions', $2::jsonb
+ WHERE EXISTS (
+ SELECT 1 FROM minion_jobs
+ WHERE id = $1 AND status NOT IN ('completed','failed','dead','cancelled')
+ )`,
+ [parentJobId, childDone]
+ );
+ }
+
+ // Unblock any aggregator parents whose last open child we just killed.
+ for (const parentId of [...parentIds].sort((a, b) => a - b)) {
+ await tx.executeRaw(
+ `UPDATE minion_jobs SET status = 'waiting', started_at = NULL, updated_at = now()
+ WHERE id = $1 AND status = 'waiting-children'
+ AND NOT EXISTS (
SELECT 1 FROM minion_jobs
- WHERE id = $1 AND status NOT IN ('completed','failed','dead','cancelled')
+ WHERE parent_job_id = $1
+ AND status NOT IN ('completed', 'failed', 'dead', 'cancelled')
)`,
- [parentJobId, childDone]
- );
- }
-
- // Unblock any aggregator parents whose last open child we just killed.
- for (const parentId of parentIds) {
- await tx.executeRaw(
- `UPDATE minion_jobs SET status = 'waiting', updated_at = now()
- WHERE id = $1 AND status = 'waiting-children'
- AND NOT EXISTS (
- SELECT 1 FROM minion_jobs
- WHERE parent_job_id = $1
- AND status NOT IN ('completed', 'failed', 'dead', 'cancelled')
- )`,
- [parentId]
- );
- }
+ [parentId]
+ );
+ }
+ }
- return rows.map(rowToMinionJob);
- });
+ /**
+ * W0 (D5.12): take parent row locks in ASCENDING id order before any child
+ * transition. Matches failJob's parent-first order so the three reapers and
+ * failJob can never deadlock each other on parent/child lock acquisition.
+ */
+ private async lockParentsOrdered(
+ tx: Pick<BrainEngine, 'executeRaw'>,
+ candidates: Array<{ parent_job_id: number | null }>,
+ ): Promise<void> {
+ const parentIds = [...new Set(
+ candidates.map(c => c.parent_job_id).filter((p): p is number => p != null),
+ )].sort((a, b) => a - b);
+ if (parentIds.length === 0) return;
+ await tx.executeRaw(
+ `SELECT id FROM minion_jobs WHERE id = ANY($1::bigint[]) ORDER BY id FOR UPDATE`,
+ [parentIds]
+ );
}
/**
@@ -889,6 +946,21 @@ export class MinionQueue {
*/
async handleWallClockTimeouts(lockDurationMs: number): Promise<MinionJob[]> {
return this.engine.transaction(async (tx) => {
+ // W0 (D5.12): same parents-first discover/lock/kill shape as
+ // handleTimeouts; shared tail in killJobs().
+ const candidates = await tx.executeRaw<{ id: number; parent_job_id: number | null }>(
+ `SELECT id, parent_job_id FROM minion_jobs
+ WHERE status = 'active'
+ AND started_at IS NOT NULL
+ AND EXTRACT(EPOCH FROM (now() - started_at)) * 1000 >
+ CASE
+ WHEN timeout_ms IS NOT NULL THEN timeout_ms * 2
+ ELSE $1::double precision * 2 * GREATEST(max_stalled, 1)
+ END`,
+ [lockDurationMs]
+ );
+ if (candidates.length === 0) return [];
+ await this.lockParentsOrdered(tx, candidates);
const rows = await tx.executeRaw<Record<string, unknown>>(
`UPDATE minion_jobs SET
status = 'dead',
@@ -898,54 +970,22 @@ export class MinionQueue {
lock_until = NULL,
finished_at = now(),
updated_at = now()
- WHERE status = 'active'
- AND started_at IS NOT NULL
- AND EXTRACT(EPOCH FROM (now() - started_at)) * 1000 >
- CASE
- WHEN timeout_ms IS NOT NULL THEN timeout_ms * 2
- ELSE $1::double precision * 2 * GREATEST(max_stalled, 1)
- END
+ WHERE id IN (
+ SELECT id FROM minion_jobs
+ WHERE id = ANY($2::bigint[])
+ AND status = 'active'
+ AND started_at IS NOT NULL
+ AND EXTRACT(EPOCH FROM (now() - started_at)) * 1000 >
+ CASE
+ WHEN timeout_ms IS NOT NULL THEN timeout_ms * 2
+ ELSE $1::double precision * 2 * GREATEST(max_stalled, 1)
+ END
+ FOR UPDATE SKIP LOCKED
+ )
RETURNING *`,
- [lockDurationMs]
+ [lockDurationMs, candidates.map(c => c.id)]
);
-
- const parentIds = new Set<number>();
- for (const r of rows) {
- const parentJobId = r.parent_job_id as number | null;
- if (parentJobId == null) continue;
- parentIds.add(parentJobId);
- const childDone: ChildDoneMessage = {
- type: 'child_done',
- child_id: r.id as number,
- job_name: r.name as string,
- result: null,
- outcome: 'timeout',
- error: 'wall-clock timeout exceeded',
- };
- await tx.executeRaw(
- `INSERT INTO minion_inbox (job_id, sender, payload)
- SELECT $1, 'minions', $2::jsonb
- WHERE EXISTS (
- SELECT 1 FROM minion_jobs
- WHERE id = $1 AND status NOT IN ('completed','failed','dead','cancelled')
- )`,
- [parentJobId, childDone]
- );
- }
-
- for (const parentId of parentIds) {
- await tx.executeRaw(
- `UPDATE minion_jobs SET status = 'waiting', updated_at = now()
- WHERE id = $1 AND status = 'waiting-children'
- AND NOT EXISTS (
- SELECT 1 FROM minion_jobs
- WHERE parent_job_id = $1
- AND status NOT IN ('completed', 'failed', 'dead', 'cancelled')
- )`,
- [parentId]
- );
- }
-
+ await this.killJobs(tx, rows, 'timeout', 'wall-clock timeout exceeded');
return rows.map(rowToMinionJob);
});
}
@@ -1034,7 +1074,7 @@ export class MinionQueue {
// child with on_child_fail='continue'/'ignore' doesn't strand the
// parent in waiting-children forever (v0.15 aggregator fix).
await tx.executeRaw(
- `UPDATE minion_jobs SET status = 'waiting', updated_at = now()
+ `UPDATE minion_jobs SET status = 'waiting', started_at = NULL, updated_at = now()
WHERE id = $1 AND status = 'waiting-children'
AND NOT EXISTS (
SELECT 1 FROM minion_jobs
@@ -1101,6 +1141,7 @@ export class MinionQueue {
stacktrace = COALESCE(stacktrace, '[]'::jsonb) || to_jsonb($3::text),
delay_until = CASE WHEN $1 = 'delayed' THEN now() + ($4::double precision * interval '1 millisecond') ELSE NULL END,
finished_at = CASE WHEN $1 IN ('failed', 'dead') THEN now() ELSE NULL END,
+ started_at = CASE WHEN $1 = 'delayed' THEN NULL ELSE started_at END,
lock_token = NULL, lock_until = NULL, updated_at = now()
WHERE id = $5 AND status = 'active' AND lock_token = $6
RETURNING *`,
@@ -1151,7 +1192,7 @@ export class MinionQueue {
// After dropping the dep, try to resolve the parent if all OTHER
// kids are terminal. Terminal set includes 'failed' (v0.15).
await tx.executeRaw(
- `UPDATE minion_jobs SET status = 'waiting', updated_at = now()
+ `UPDATE minion_jobs SET status = 'waiting', started_at = NULL, updated_at = now()
WHERE id = $1 AND status = 'waiting-children'
AND NOT EXISTS (
SELECT 1 FROM minion_jobs
@@ -1169,7 +1210,7 @@ export class MinionQueue {
// remain. Run the resolve check here so the last child transitioning
// via THIS code path still unblocks the parent.
await tx.executeRaw(
- `UPDATE minion_jobs SET status = 'waiting', updated_at = now()
+ `UPDATE minion_jobs SET status = 'waiting', started_at = NULL, updated_at = now()
WHERE id = $1 AND status = 'waiting-children'
AND NOT EXISTS (
SELECT 1 FROM minion_jobs
@@ -1229,6 +1270,7 @@ export class MinionQueue {
error_text = $1,
stacktrace = COALESCE(stacktrace, '[]'::jsonb) || to_jsonb($1::text),
delay_until = now() + ($2::double precision * interval '1 millisecond'),
+ started_at = NULL,
lock_token = NULL, lock_until = NULL, updated_at = now()
WHERE id = $3 AND status = 'active' AND lock_token = $4
RETURNING *`,
@@ -1304,6 +1346,7 @@ export class MinionQueue {
async promoteDelayed(): Promise<MinionJob[]> {
const rows = await this.lockRetry(() => this.engine.executeRaw<Record<string, unknown>>(
`UPDATE minion_jobs SET status = 'waiting', delay_until = NULL,
+ started_at = NULL,
lock_token = NULL, lock_until = NULL, updated_at = now()
WHERE status = 'delayed' AND delay_until <= now()
RETURNING *`
@@ -1313,40 +1356,84 @@ export class MinionQueue {
/** Detect and handle stalled jobs. Single CTE, no off-by-one. Returns affected jobs. */
async handleStalled(): Promise<{ requeued: MinionJob[]; dead: MinionJob[] }> {
- const rows = await this.engine.executeRaw<Record<string, unknown> & { action: string }>(
- `WITH stalled AS (
- SELECT id, stalled_counter, max_stalled
- FROM minion_jobs
- WHERE status = 'active' AND lock_until < now()
- FOR UPDATE SKIP LOCKED
- ),
- requeued AS (
- UPDATE minion_jobs SET
+ // W0 fix-wave (Tier-1 #4): the dead-letter branch previously emitted NO
+ // child_done and never unblocked aggregator parents — a child that died
+ // via max-stall stranded its parent in 'waiting-children' forever (the
+ // exact hang the v0.15 comment says was fixed for timeouts; there was no
+ // compensating sweep anywhere). Restructured into the parents-first
+ // discover/lock/kill shape (D5.12) with the shared killJobs() tail.
+ return this.engine.transaction(async (tx) => {
+ const candidates = await tx.executeRaw<{ id: number; parent_job_id: number | null; stalled_counter: number; max_stalled: number }>(
+ `SELECT id, parent_job_id, stalled_counter, max_stalled
+ FROM minion_jobs
+ WHERE status = 'active' AND lock_until < now()`
+ );
+ if (candidates.length === 0) return { requeued: [], dead: [] };
+ const ids = candidates.map(c => c.id);
+ // Only the dead-letter branch touches parents; lock just those, sorted.
+ await this.lockParentsOrdered(
+ tx,
+ candidates.filter(c => Number(c.stalled_counter) + 1 >= Number(c.max_stalled)),
+ );
+
+ const requeuedRows = await tx.executeRaw<Record<string, unknown>>(
+ `UPDATE minion_jobs SET
status = 'waiting', stalled_counter = stalled_counter + 1,
+ started_at = NULL,
lock_token = NULL, lock_until = NULL, updated_at = now()
- WHERE id IN (SELECT id FROM stalled WHERE stalled_counter + 1 < max_stalled)
- RETURNING *, 'requeued' as action
- ),
- dead_lettered AS (
- UPDATE minion_jobs SET
+ WHERE id IN (
+ SELECT id FROM minion_jobs
+ WHERE id = ANY($1::bigint[])
+ AND status = 'active' AND lock_until < now()
+ AND stalled_counter + 1 < max_stalled
+ FOR UPDATE SKIP LOCKED
+ )
+ RETURNING *`,
+ [ids]
+ );
+ const deadRows = await tx.executeRaw<Record<string, unknown>>(
+ `UPDATE minion_jobs SET
status = 'dead', stalled_counter = stalled_counter + 1,
attempts_made = attempts_made + 1,
error_text = 'max stalled count exceeded',
lock_token = NULL, lock_until = NULL, finished_at = now(), updated_at = now()
- WHERE id IN (SELECT id FROM stalled WHERE stalled_counter + 1 >= max_stalled)
- RETURNING *, 'dead' as action
- )
- SELECT * FROM requeued UNION ALL SELECT * FROM dead_lettered`
- );
-
- const requeued: MinionJob[] = [];
- const dead: MinionJob[] = [];
- for (const r of rows) {
- const job = rowToMinionJob(r);
- if (r.action === 'requeued') requeued.push(job);
- else dead.push(job);
- }
- return { requeued, dead };
+ WHERE id IN (
+ SELECT id FROM minion_jobs
+ WHERE id = ANY($1::bigint[])
+ AND status = 'active' AND lock_until < now()
+ AND stalled_counter + 1 >= max_stalled
+ FOR UPDATE SKIP LOCKED
+ )
+ RETURNING *`,
+ [ids]
+ );
+ // THE FIX: stall-death now notifies + unblocks parents like every
+ // other terminal kill. Outcome 'dead' (not 'timeout') so consumers can
+ // distinguish "died via max-stall" from "timed out during run".
+ await this.killJobs(tx, deadRows, 'dead', 'max stalled count exceeded');
+ return { requeued: requeuedRows.map(rowToMinionJob), dead: deadRows.map(rowToMinionJob) };
+ }).then(async (result) => {
+ // W0 ship-review (data-migration): the per-kill unblock above is
+ // forward-only — parents stranded in 'waiting-children' by PRE-upgrade
+ // stall-deaths (children already status='dead') are never revisited by
+ // any per-event unblock site. This idempotent sweep self-heals ALL
+ // stranding classes, retroactive included, once per stall tick: any
+ // waiting-children parent with zero non-terminal children flips back to
+ // 'waiting'. Cheap (single UPDATE, NOT EXISTS on an indexed FK) at the
+ // 30s sweep cadence.
+ try {
+ await this.engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'waiting', started_at = NULL, updated_at = now()
+ WHERE status = 'waiting-children'
+ AND NOT EXISTS (
+ SELECT 1 FROM minion_jobs c
+ WHERE c.parent_job_id = minion_jobs.id
+ AND c.status NOT IN ('completed', 'failed', 'dead', 'cancelled')
+ )`
+ );
+ } catch { /* best-effort backstop; the per-kill unblock is the primary path */ }
+ return result;
+ });
}
/**
@@ -1358,7 +1445,7 @@ export class MinionQueue {
*/
async resolveParent(parentId: number): Promise<MinionJob | null> {
const rows = await this.engine.executeRaw<Record<string, unknown>>(
- `UPDATE minion_jobs SET status = 'waiting', updated_at = now()
+ `UPDATE minion_jobs SET status = 'waiting', started_at = NULL, updated_at = now()
WHERE id = $1 AND status = 'waiting-children'
AND NOT EXISTS (
SELECT 1 FROM minion_jobs
diff --git a/src/core/minions/supervisor.ts b/src/core/minions/supervisor.ts
index c84043526b..658362e43d 100644
--- a/src/core/minions/supervisor.ts
+++ b/src/core/minions/supervisor.ts
@@ -839,7 +839,22 @@ export class MinionSupervisor {
private async refreshDbLock(): Promise<void> {
if (!this.dbLock || this.stopping) return;
try {
- await this.dbLock.refresh();
+ const stillOwned = await this.dbLock.refresh();
+ if (stillOwned === false) {
+ // W0 fix-wave (D5.10): the fenced refresh matched 0 rows — the lock
+ // was stolen or force-cleared. That is CERTAIN loss, not a blip:
+ // counting it toward the failure threshold (or worse, resetting the
+ // counter as a "success") would let two supervisors drain the same
+ // queue for up to two more refresh windows. Exit immediately; the
+ // process manager restarts a single clean supervisor.
+ this.emit('health_error', {
+ reason: 'supervisor_lock_lost',
+ detail: 'fenced refresh matched 0 rows (stolen or force-cleared)',
+ queue: this.opts.queue,
+ });
+ await this.shutdown('supervisor_lock_lost', ExitCodes.LOCK_LOST);
+ return;
+ }
this.lockRefreshFailures = 0;
} catch (e) {
this.lockRefreshFailures++;
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 8d19bc7610..a086bf5765 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -117,14 +117,14 @@ const PGLITE_EDGE_BATCH_MAX_BIND_PARAMS = 30_000;
// silently fall through to a normal initSchema (snapshot is just an
// optimization, never authoritative).
let _snapshotWarnLogged = false;
-function tryLoadSnapshot(snapshotPath: string): Blob | null {
+export function tryLoadSnapshot(snapshotPath: string): Blob | null {
try {
// Lazy require so production builds without these imports don't crash.
// eslint-disable-next-line @typescript-eslint/no-require-imports
- const fs = require('node:fs') as typeof import('node:fs');
- const crypto = require('node:crypto') as typeof import('node:crypto');
- const { MIGRATIONS } = require('./migrate.ts') as typeof import('./migrate.ts');
- const { PGLITE_SCHEMA_SQL } = require('./pglite-schema.ts') as typeof import('./pglite-schema.ts');
+ const fs = require('node:fs') as typeof import('node:fs'); // engine-dynamic-import-ok
+ const crypto = require('node:crypto') as typeof import('node:crypto'); // engine-dynamic-import-ok
+ const { MIGRATIONS } = require('./migrate.ts') as typeof import('./migrate.ts'); // engine-dynamic-import-ok
+ const { PGLITE_SCHEMA_SQL } = require('./pglite-schema.ts') as typeof import('./pglite-schema.ts'); // engine-dynamic-import-ok
if (!fs.existsSync(snapshotPath)) {
if (!_snapshotWarnLogged) {
@@ -144,7 +144,32 @@ function tryLoadSnapshot(snapshotPath: string): Blob | null {
return null;
}
const expectedHash = computeSnapshotSchemaHash(MIGRATIONS, PGLITE_SCHEMA_SQL, crypto);
- const actualHash = fs.readFileSync(versionPath, 'utf8').trim();
+ const versionLines = fs.readFileSync(versionPath, 'utf8').trim().split('\n');
+ const actualHash = versionLines[0] ?? '';
+
+ // W0 fix-wave: the version file's dims=/model= lines record the embedding
+ // shape the snapshot was BAKED with. A snapshot whose vector(dims) columns
+ // differ from what THIS process would create poisons every embedding
+ // write ("expected 1280 dimensions, not 1536" — the W0 incident when the
+ // fixture went default-on). Resolve our would-be shape through the same
+ // gateway-with-default fallback initSchema uses and refuse a mismatch.
+ // Version files without the shape lines (pre-W0) are treated as stale.
+ let wantDims: number | string = DEFAULT_EMBEDDING_DIMENSIONS;
+ let wantModel: string = DEFAULT_EMBEDDING_MODEL;
+ try {
+ const gw = require('./ai/gateway.ts') as typeof import('./ai/gateway.ts'); // engine-dynamic-import-ok
+ wantDims = gw.getEmbeddingDimensions();
+ wantModel = gw.getEmbeddingModel();
+ } catch { /* gateway not configured — defaults, same as initSchema */ }
+ const shapeOk = versionLines[1] === `dims=${wantDims}` && versionLines[2] === `model=${wantModel}`;
+ if (!shapeOk) {
+ if (!_snapshotWarnLogged) {
+ // eslint-disable-next-line no-console
+ console.warn(`[pglite] snapshot embedding shape mismatch (want dims=${wantDims} model=${wantModel}, have ${versionLines[1] ?? 'none'} ${versionLines[2] ?? ''}) — using normal init. Rebuild with: bun run build:pglite-snapshot`);
+ _snapshotWarnLogged = true;
+ }
+ return null;
+ }
if (expectedHash !== actualHash) {
if (!_snapshotWarnLogged) {
// eslint-disable-next-line no-console
@@ -162,7 +187,7 @@ function tryLoadSnapshot(snapshotPath: string): Blob | null {
}
export function computeSnapshotSchemaHash(
- migrations: Array<{ version: number; name: string; sql?: string; sqlFor?: { pglite?: string } }>,
+ migrations: Array<{ version: number; name: string; sql?: string; sqlFor?: { pglite?: string }; handler?: unknown }>,
schemaSQL: string,
crypto: typeof import('node:crypto'),
): string {
@@ -178,6 +203,13 @@ export function computeSnapshotSchemaHash(
hash.update(m.sql ?? '');
hash.update('\t');
hash.update(m.sqlFor?.pglite ?? '');
+ hash.update('\t');
+ // W0 fix-wave (D5.13, Codex #4): 19+ migrations carry executable
+ // `handler` code with empty/absent sql — invisible to the sql-only hash,
+ // so editing a handler reused a stale snapshot. Function.prototype
+ // .toString folds the handler SOURCE into the hash (deterministic within
+ // a checkout; this is a dev/test fixture, not a shipped artifact).
+ hash.update(typeof m.handler === 'function' ? String(m.handler) : '');
hash.update('\n');
}
return hash.digest('hex');
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 9d12b629dd..902409231b 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.45.15.0 -->
+<!-- gbrain-template-stamp: 0.45.16.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/cycle-abort.test.ts b/test/cycle-abort.test.ts
index 9c49fe52f7..798b7f8334 100644
--- a/test/cycle-abort.test.ts
+++ b/test/cycle-abort.test.ts
@@ -142,14 +142,19 @@ describe('autopilot-cycle handler contract (v0.20.5)', () => {
'utf8',
);
- // Count checkAborted calls in the runCycle function body
+ // Count checkAborted calls in the runCycle function body. W0 fix-wave:
+ // boundaries check `cycleSignal` — the combined external-caller +
+ // lock-steal signal — so a stolen lock aborts at the same seams an
+ // external abort always did.
const runCycleBody = cycleSource.slice(
cycleSource.indexOf('export async function runCycle'),
);
- const checkCalls = (runCycleBody.match(/checkAborted\(opts\.signal\)/g) || []).length;
+ const checkCalls = (runCycleBody.match(/checkAborted\(cycleSignal\)/g) || []).length;
// Should have at least 6 (one per phase)
expect(checkCalls).toBeGreaterThanOrEqual(6);
+ // And the combined signal must actually fold BOTH sources.
+ expect(runCycleBody).toContain('anyAbortSignal([externalSignal, stolen.signal])');
});
});
@@ -174,11 +179,12 @@ describe('#1972 — complete cooperative-abort coverage', () => {
const fs = await import('fs');
const src = fs.readFileSync(new URL('../src/core/cycle.ts', import.meta.url), 'utf8');
const body = src.slice(src.indexOf('export async function runCycle'));
- // Each long phase receives the signal.
- expect(body).toContain('runPhaseExtract(engine, brainDir, dryRun, syncPagesAffected, opts.signal, cycleSourceId)');
- expect(body).toMatch(/runPhaseExtractFacts\([^)]*opts\.signal\)/);
- expect(body).toContain('signal: opts.signal'); // consolidate opts
- expect(body).toContain('runPhaseLint(brainDir, dryRun, engine, opts.signal)');
+ // Each long phase receives the signal (W0: the combined cycleSignal, so
+ // phases also stop on lock-steal, not just external aborts).
+ expect(body).toContain('runPhaseExtract(engine, brainDir, dryRun, syncPagesAffected, cycleSignal, cycleSourceId)');
+ expect(body).toMatch(/runPhaseExtractFacts\([^)]*cycleSignal\)/);
+ expect(body).toContain('signal: cycleSignal'); // consolidate opts
+ expect(body).toContain('runPhaseLint(brainDir, dryRun, engine, cycleSignal)');
// Reaper runs at cycle start.
expect(body).toContain('reapDeadHolderLocks(engine)');
// Terminal guard: the success stamp is gated on !aborted, and the report
diff --git a/test/cycle-any-abort-signal.test.ts b/test/cycle-any-abort-signal.test.ts
new file mode 100644
index 0000000000..d31de68656
--- /dev/null
+++ b/test/cycle-any-abort-signal.test.ts
@@ -0,0 +1,83 @@
+/**
+ * W0 ship-review coverage — anyAbortSignal behavioral tests (the combined
+ * external-caller + lock-steal signal). Previously pinned only by a
+ * source-string contract assertion.
+ */
+
+import { test, expect } from 'bun:test';
+import { anyAbortSignal } from '../src/core/cycle.ts';
+
+test('pre-aborted input aborts the combined signal immediately with the same reason', () => {
+ const c = new AbortController();
+ const why = new Error('already done');
+ c.abort(why);
+ const combined = anyAbortSignal([c.signal, new AbortController().signal]);
+ try {
+ expect(combined.signal.aborted).toBe(true);
+ expect(combined.signal.reason).toBe(why);
+ } finally {
+ combined.dispose();
+ }
+});
+
+test('a real signal aborting later propagates reason to the combined signal', async () => {
+ const a = new AbortController();
+ const b = new AbortController();
+ const combined = anyAbortSignal([a.signal, b.signal]);
+ try {
+ expect(combined.signal.aborted).toBe(false);
+ const why = new Error('steal');
+ b.abort(why);
+ expect(combined.signal.aborted).toBe(true);
+ expect(combined.signal.reason).toBe(why);
+ } finally {
+ combined.dispose();
+ }
+});
+
+test('duck-typed stub (no addEventListener) is observed via the 50ms poll', async () => {
+ const stub = { aborted: false } as unknown as AbortSignal;
+ const real = new AbortController();
+ const combined = anyAbortSignal([stub, real.signal]);
+ try {
+ expect(combined.signal.aborted).toBe(false);
+ (stub as { aborted: boolean }).aborted = true;
+ const deadline = Date.now() + 2_000;
+ while (!combined.signal.aborted && Date.now() < deadline) {
+ await new Promise(r => setTimeout(r, 25));
+ }
+ expect(combined.signal.aborted).toBe(true);
+ } finally {
+ combined.dispose();
+ }
+});
+
+test('dispose() detaches the forward listener from the CALLER signal (the daemon leak class)', () => {
+ const daemonSignal = new AbortController();
+ // Simulate many cycle ticks against one daemon-lifetime signal.
+ for (let i = 0; i < 50; i++) {
+ const combined = anyAbortSignal([daemonSignal.signal, new AbortController().signal]);
+ combined.dispose();
+ }
+ // After dispose, aborting the daemon signal must not touch the (disposed)
+ // combined controllers — and no listener buildup means no
+ // MaxListenersExceededWarning. Behavioral proxy: a fresh combine still
+ // works and the abort propagates exactly once.
+ const last = anyAbortSignal([daemonSignal.signal]);
+ try {
+ daemonSignal.abort(new Error('shutdown'));
+ expect(last.signal.aborted).toBe(true);
+ } finally {
+ last.dispose();
+ }
+});
+
+test('dispose() clears the stub poll interval (no immortal timers)', async () => {
+ const stub = { aborted: false } as unknown as AbortSignal;
+ const combined = anyAbortSignal([stub]);
+ combined.dispose();
+ // Flip after dispose: the poll must be dead — combined never aborts.
+ (stub as { aborted: boolean }).aborted = true;
+ await new Promise(r => setTimeout(r, 150));
+ expect(combined.signal.aborted).toBe(false);
+});
diff --git a/test/cycle-lock-steal.serial.test.ts b/test/cycle-lock-steal.serial.test.ts
new file mode 100644
index 0000000000..e885dc7e65
--- /dev/null
+++ b/test/cycle-lock-steal.serial.test.ts
@@ -0,0 +1,107 @@
+/**
+ * W0 fix-wave (Tier-1 #1, D5.6 abort-determinism) — end-to-end lock-steal
+ * abort through runCycle.
+ *
+ * A cycle whose lock row is stolen mid-run must:
+ * 1. detect the steal via the background refresher (fenced refresh → false),
+ * 2. stop at the next phase boundary (no further phases run),
+ * 3. return a STRUCTURED partial report (reason 'lock_stolen') instead of
+ * throwing — completed phases' results are present (their DB writes are
+ * durable, persisted-and-resumable),
+ * 4. leave the successor's lock row intact (release is fenced).
+ *
+ * Serial: mutates GBRAIN_HOME + GBRAIN_CYCLE_LOCK_REFRESH_MS.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runCycle } from '../src/core/cycle.ts';
+
+let engine: PGLiteEngine;
+let gbrainHome: string;
+let brainDir: string;
+const PRIOR_HOME = process.env.GBRAIN_HOME;
+const PRIOR_REFRESH = process.env.GBRAIN_CYCLE_LOCK_REFRESH_MS;
+
+beforeAll(async () => {
+ // GBRAIN_HOME isolation so the PGLite file lock doesn't touch the real
+ // ~/.gbrain/cycle.lock (same pattern as cycle-pglite-lock-ordering).
+ gbrainHome = mkdtempSync(join(tmpdir(), 'gbrain-steal-home-'));
+ brainDir = mkdtempSync(join(tmpdir(), 'gbrain-steal-brain-'));
+ process.env.GBRAIN_HOME = gbrainHome;
+ // Deterministic fast refresher: 20ms tick against the 200ms in-test sleep.
+ process.env.GBRAIN_CYCLE_LOCK_REFRESH_MS = '20';
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ if (PRIOR_HOME === undefined) delete process.env.GBRAIN_HOME; else process.env.GBRAIN_HOME = PRIOR_HOME;
+ if (PRIOR_REFRESH === undefined) delete process.env.GBRAIN_CYCLE_LOCK_REFRESH_MS; else process.env.GBRAIN_CYCLE_LOCK_REFRESH_MS = PRIOR_REFRESH;
+ rmSync(gbrainHome, { recursive: true, force: true });
+ rmSync(brainDir, { recursive: true, force: true });
+});
+
+test('mid-run steal → structured partial report, no further phases, successor row intact', async () => {
+ const lockId = 'gbrain-cycle:stealtest';
+ let stole = false;
+
+ const report = await runCycle(engine, {
+ brainDir,
+ sourceId: 'stealtest',
+ phases: ['lint', 'backlinks'],
+ yieldBetweenPhases: async () => {
+ if (stole) return;
+ stole = true;
+ // Simulate a successor taking the row: new acquisition identity.
+ await engine.executeRaw(
+ `UPDATE gbrain_cycle_locks
+ SET acquired_at = acquired_at + INTERVAL '1 millisecond',
+ ttl_expires_at = NOW() + INTERVAL '5 minutes',
+ last_refreshed_at = NOW()
+ WHERE id = $1`,
+ [lockId],
+ );
+ // Give the 20ms refresher a 1.5s window (75 nominal ticks) to observe
+ // the steal — sized for shard-load timer starvation, the flake class
+ // db-lock-fencing.test.ts documents (a 200ms window ≈ 10 ticks proved
+ // too tight under a loaded suite).
+ await new Promise(r => setTimeout(r, 1_500));
+ },
+ });
+
+ expect(report.status).toBe('partial');
+ expect(report.reason).toBe('lock_stolen');
+ // lint completed before the steal; backlinks must never have started.
+ expect(report.phases.map(p => p.phase)).toEqual(['lint']);
+
+ // The fenced release must NOT have deleted the successor's row.
+ const rows = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM gbrain_cycle_locks WHERE id = $1`,
+ [lockId],
+ );
+ expect(rows.length).toBe(1);
+ // Cleanup for other suites.
+ await engine.executeRaw(`DELETE FROM gbrain_cycle_locks WHERE id = $1`, [lockId]);
+});
+
+test('steal-free cycle still completes and releases normally (regression guard)', async () => {
+ const report = await runCycle(engine, {
+ brainDir,
+ sourceId: 'stealtest2',
+ phases: ['lint', 'backlinks'],
+ });
+ expect(report.status === 'ok' || report.status === 'clean' || report.status === 'partial').toBe(true);
+ expect(report.reason).not.toBe('lock_stolen');
+ expect(report.phases.map(p => p.phase)).toEqual(['lint', 'backlinks']);
+ const rows = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM gbrain_cycle_locks WHERE id = $1`,
+ ['gbrain-cycle:stealtest2'],
+ );
+ expect(rows.length).toBe(0);
+});
diff --git a/test/cycle/yield-during-phase-refresh.test.ts b/test/cycle/yield-during-phase-refresh.test.ts
index cdf22c735b..92e80b1141 100644
--- a/test/cycle/yield-during-phase-refresh.test.ts
+++ b/test/cycle/yield-during-phase-refresh.test.ts
@@ -15,7 +15,7 @@ import type { LockHandle } from '../../src/core/cycle.ts';
function makeMockLock(): { lock: LockHandle; refreshCount: number; releaseCount: number } {
const state = { refreshCount: 0, releaseCount: 0 };
const lock: LockHandle = {
- refresh: async () => { state.refreshCount++; },
+ refresh: async () => { state.refreshCount++; return true; },
release: async () => { state.releaseCount++; },
};
return {
@@ -60,7 +60,7 @@ describe('buildYieldDuringPhase (T3 codex fix)', () => {
const outer = async () => { callOrder.push('outer'); };
const fn = buildYieldDuringPhase({
...tracker.lock,
- refresh: async () => { callOrder.push('refresh'); tracker.lock.refresh(); },
+ refresh: async () => { callOrder.push('refresh'); return tracker.lock.refresh(); },
}, outer);
await fn!();
expect(callOrder).toEqual(['refresh', 'outer']);
diff --git a/test/db-lock-fencing.test.ts b/test/db-lock-fencing.test.ts
new file mode 100644
index 0000000000..0edf7bf9e8
--- /dev/null
+++ b/test/db-lock-fencing.test.ts
@@ -0,0 +1,189 @@
+/**
+ * W0 fix-wave (Tier-1 #1, D5.10) — per-acquisition lock fencing.
+ *
+ * The refresh/release predicates require (id, holder_pid, acquired_at::text),
+ * so a handle from a PREVIOUS acquisition — a PID-reuse impostor, or this
+ * process after its row was stolen — can never refresh or delete a
+ * successor's row. Pre-fix the predicates were (id, holder_pid) only, and an
+ * expired holder could refresh a successor's lock while reporting success
+ * (Codex eng-review #1 on the fix-wave plan).
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { tryAcquireDbLock, LockStolenError } from '../src/core/db-lock.ts';
+import { startCycleLockRefresher, buildYieldDuringPhase, type LockHandle } from '../src/core/cycle.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw(`DELETE FROM gbrain_cycle_locks WHERE id LIKE 'test-fence-%'`);
+});
+
+/** Simulate a successor stealing the row: rewrite acquisition identity in place. */
+async function stealRow(lockId: string): Promise<void> {
+ await engine.executeRaw(
+ `UPDATE gbrain_cycle_locks
+ SET holder_pid = holder_pid,
+ acquired_at = acquired_at + INTERVAL '1 millisecond',
+ ttl_expires_at = NOW() + INTERVAL '5 minutes',
+ last_refreshed_at = NOW()
+ WHERE id = $1`,
+ [lockId],
+ );
+}
+
+describe('fenced refresh/release (D5.10)', () => {
+ test('handle carries its acquisition fence and refresh() returns true while owned', async () => {
+ const handle = await tryAcquireDbLock(engine, 'test-fence-own', 5);
+ expect(handle).not.toBeNull();
+ expect(typeof handle!.acquiredAt).toBe('string');
+ expect(handle!.acquiredAt.length).toBeGreaterThan(0);
+ expect(await handle!.refresh()).toBe(true);
+ // Refresh must not change the acquisition identity.
+ expect(await handle!.refresh()).toBe(true);
+ await handle!.release();
+ });
+
+ test('after a steal, the old handle refresh() returns false and cannot re-take the row', async () => {
+ const handle = await tryAcquireDbLock(engine, 'test-fence-steal', 5);
+ expect(handle).not.toBeNull();
+ await stealRow('test-fence-steal');
+
+ expect(await handle!.refresh()).toBe(false);
+ // The failed refresh must not have bumped the successor's TTL under the
+ // OLD identity — i.e. the row still exists and refresh stays false.
+ expect(await handle!.refresh()).toBe(false);
+ });
+
+ test("release() after a steal is a fenced no-op — the successor's row survives", async () => {
+ const handle = await tryAcquireDbLock(engine, 'test-fence-release', 5);
+ expect(handle).not.toBeNull();
+ await stealRow('test-fence-release');
+
+ await handle!.release(); // must NOT delete the successor's row
+ const rows = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM gbrain_cycle_locks WHERE id = $1`,
+ ['test-fence-release'],
+ );
+ expect(rows.length).toBe(1);
+ });
+
+ test('release() while still owned deletes the row (normal path unchanged)', async () => {
+ const handle = await tryAcquireDbLock(engine, 'test-fence-normal', 5);
+ expect(handle).not.toBeNull();
+ await handle!.release();
+ const rows = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM gbrain_cycle_locks WHERE id = $1`,
+ ['test-fence-normal'],
+ );
+ expect(rows.length).toBe(0);
+ });
+});
+
+describe('startCycleLockRefresher (Tier-1 #1 + D5.11)', () => {
+ const fakeLock = (impl: () => Promise<boolean>): LockHandle => ({
+ refresh: impl,
+ release: async () => {},
+ });
+
+ test('aborts the controller with LockStolenError when a fenced refresh returns false', async () => {
+ const controller = new AbortController();
+ const stop = startCycleLockRefresher(fakeLock(async () => false), controller, 'test-lock', 15);
+ try {
+ // Poll instead of a fixed sleep: under full-suite shard load, timer
+ // ticks can be starved well past the nominal interval.
+ const deadline = Date.now() + 5_000;
+ while (!controller.signal.aborted && Date.now() < deadline) {
+ await new Promise(r => setTimeout(r, 25));
+ }
+ expect(controller.signal.aborted).toBe(true);
+ expect(controller.signal.reason).toBeInstanceOf(LockStolenError);
+ } finally {
+ stop();
+ }
+ });
+
+ test('serializes refreshes — a slow refresh never overlaps the next tick', async () => {
+ let inFlight = 0;
+ let maxInFlight = 0;
+ const controller = new AbortController();
+ const stop = startCycleLockRefresher(fakeLock(async () => {
+ inFlight++;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ await new Promise(r => setTimeout(r, 60));
+ inFlight--;
+ return true;
+ }), controller, 'test-lock', 15);
+ try {
+ await new Promise(r => setTimeout(r, 250));
+ expect(maxInFlight).toBe(1);
+ expect(controller.signal.aborted).toBe(false);
+ } finally {
+ stop();
+ }
+ });
+
+ test('a THROWN refresh error is transient — logged, retried, never treated as a steal', async () => {
+ let calls = 0;
+ const controller = new AbortController();
+ const stop = startCycleLockRefresher(fakeLock(async () => {
+ calls++;
+ throw new Error('pooler blip');
+ }), controller, 'test-lock', 15);
+ try {
+ await new Promise(r => setTimeout(r, 120));
+ expect(calls).toBeGreaterThan(1); // kept retrying
+ expect(controller.signal.aborted).toBe(false);
+ } finally {
+ stop();
+ }
+ });
+
+ test('stop() halts ticking', async () => {
+ let calls = 0;
+ const controller = new AbortController();
+ const stop = startCycleLockRefresher(fakeLock(async () => { calls++; return true; }), controller, 'test-lock', 15);
+ await new Promise(r => setTimeout(r, 50));
+ stop();
+ const after = calls;
+ await new Promise(r => setTimeout(r, 60));
+ expect(calls).toBe(after);
+ });
+});
+
+describe('buildYieldDuringPhase steal reporting', () => {
+ test('invokes onStolen when refresh() returns false, still fires the outer hook', async () => {
+ let stolenErr: LockStolenError | undefined;
+ let outerRan = false;
+ const fn = buildYieldDuringPhase(
+ { refresh: async () => false, release: async () => {} },
+ async () => { outerRan = true; },
+ (e) => { stolenErr = e; },
+ );
+ await fn!();
+ expect(stolenErr).toBeInstanceOf(LockStolenError);
+ expect(outerRan).toBe(true);
+ });
+
+ test('does NOT invoke onStolen on a thrown (transient) refresh error', async () => {
+ let stolen = false;
+ const fn = buildYieldDuringPhase(
+ { refresh: async () => { throw new Error('blip'); }, release: async () => {} },
+ undefined,
+ () => { stolen = true; },
+ );
+ await fn!();
+ expect(stolen).toBe(false);
+ });
+});
diff --git a/test/embed-modality-preserved.test.ts b/test/embed-modality-preserved.test.ts
new file mode 100644
index 0000000000..06ed17e438
--- /dev/null
+++ b/test/embed-modality-preserved.test.ts
@@ -0,0 +1,90 @@
+/**
+ * W0 fix-wave (Tier-1 #3, CONFIRMED) — re-embed upserts must carry
+ * `modality`, or image chunks flip to modality='text' and the image search
+ * arm (filter cc.modality='image') silently returns nothing.
+ *
+ * Pins two layers:
+ * 1. carryChunkMetadata (the now-single shared field list) carries modality
+ * + all 8 code-metadata fields.
+ * 2. The write-side contract that makes the carry load-bearing: upsertChunks
+ * OVERWRITES modality from EXCLUDED, so a merge built via
+ * carryChunkMetadata round-trips an image chunk intact, while a merge
+ * that omits the field (the pre-fix CLI behavior) demonstrably resets it.
+ */
+
+import { test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { carryChunkMetadata } from '../src/core/embed-stale.ts';
+import type { ChunkInput } from '../src/core/types.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+test('carryChunkMetadata carries modality and all code-metadata fields', () => {
+ const loaded = {
+ modality: 'image' as const,
+ language: 'ts',
+ symbol_name: 'fn',
+ symbol_type: 'function',
+ start_line: 1,
+ end_line: 10,
+ parent_symbol_path: ['Mod'],
+ doc_comment: 'doc',
+ symbol_name_qualified: 'Mod.fn',
+ };
+ const base: ChunkInput = { chunk_index: 0, chunk_text: 'x', chunk_source: 'compiled_truth' };
+ const out = carryChunkMetadata(loaded, base);
+ expect(out.modality).toBe('image');
+ expect(out.language).toBe('ts');
+ expect(out.symbol_name_qualified).toBe('Mod.fn');
+ // Absent fields stay undefined, never null-through (DB rows can carry null
+ // at runtime; the ?? undefined in the carry normalizes them).
+ const sparse = carryChunkMetadata({}, base);
+ expect(sparse.modality).toBeUndefined();
+});
+
+test('re-embed merge via carryChunkMetadata keeps an image chunk image', async () => {
+ await engine.putPage('img-page', { type: 'note', title: 'img', compiled_truth: 'ocr text here', frontmatter: {} });
+ await engine.upsertChunks('img-page', [
+ { chunk_index: 0, chunk_text: 'ocr text here', chunk_source: 'compiled_truth', modality: 'image' },
+ ]);
+
+ // Simulate the embed --stale merge: load chunks, rebuild ChunkInputs, upsert.
+ const loaded = await engine.getChunks('img-page');
+ expect(loaded[0]!.modality).toBe('image');
+ const merged = loaded.map(c => carryChunkMetadata(c, {
+ chunk_index: c.chunk_index,
+ chunk_text: c.chunk_text,
+ chunk_source: c.chunk_source,
+ token_count: c.token_count || 1,
+ }));
+ await engine.upsertChunks('img-page', merged);
+
+ const after = await engine.getChunks('img-page');
+ expect(after[0]!.modality).toBe('image');
+});
+
+test('write-side contract: omitting modality (pre-fix behavior) resets it to text', async () => {
+ await engine.putPage('img-page-2', { type: 'note', title: 'img2', compiled_truth: 'more ocr', frontmatter: {} });
+ await engine.upsertChunks('img-page-2', [
+ { chunk_index: 0, chunk_text: 'more ocr', chunk_source: 'compiled_truth', modality: 'image' },
+ ]);
+ // The pre-fix CLI merge: field list without modality.
+ await engine.upsertChunks('img-page-2', [
+ { chunk_index: 0, chunk_text: 'more ocr', chunk_source: 'compiled_truth' },
+ ]);
+ const after = await engine.getChunks('img-page-2');
+ // This assertion documents WHY the carry is load-bearing: the upsert
+ // overwrites, so the omission class corrupts. If this ever flips to
+ // COALESCE semantics, the carry (and this test) can be revisited.
+ expect(after[0]!.modality).toBe('text');
+});
diff --git a/test/embedding-dim-check.test.ts b/test/embedding-dim-check.test.ts
index c2d2b6ba8b..badd2a82ac 100644
--- a/test/embedding-dim-check.test.ts
+++ b/test/embedding-dim-check.test.ts
@@ -12,6 +12,7 @@
import { test, expect, describe, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { withEnv } from './helpers/with-env.ts';
import {
readContentChunksEmbeddingDim,
embeddingMismatchMessage,
@@ -73,8 +74,12 @@ describe('readContentChunksEmbeddingDim', () => {
test('returns { exists: false, dims: null } on a fresh brain (no initSchema)', async () => {
// One-off engine for the fresh-brain case. Never call initSchema so
// content_chunks doesn't exist yet. Cleaned up at end of test.
+ // W0: the default-on snapshot loads a fully-migrated schema at connect,
+ // which breaks this test's truly-empty-DB premise — opt out for this boot.
const fresh = new PGLiteEngine();
- await fresh.connect({});
+ await withEnv({ GBRAIN_PGLITE_SNAPSHOT: undefined }, async () => {
+ await fresh.connect({});
+ });
try {
const result = await readContentChunksEmbeddingDim(fresh);
expect(result.exists).toBe(false);
diff --git a/test/fixtures/guards/check-jsonb-params.mjs/bad/fixture.ts b/test/fixtures/guards/check-jsonb-params.mjs/bad/fixture.ts
new file mode 100644
index 0000000000..1bd20c1797
--- /dev/null
+++ b/test/fixtures/guards/check-jsonb-params.mjs/bad/fixture.ts
@@ -0,0 +1,7 @@
+// Guard self-test fixture (known-BAD): positional $N::jsonb + JSON.stringify
+// in the same call span — the #2339 shape that aborted every sync.
+declare const engine: { executeRaw: (sql: string, params?: unknown[]) => Promise<unknown[]> };
+declare const x: Record<string, unknown>;
+export async function bad(): Promise<void> {
+ await engine.executeRaw(`UPDATE op_checkpoints SET pin = $1::jsonb WHERE id = $2`, [JSON.stringify(x), 1]);
+}
diff --git a/test/fixtures/guards/check-jsonb-params.mjs/good/fixture.ts b/test/fixtures/guards/check-jsonb-params.mjs/good/fixture.ts
new file mode 100644
index 0000000000..dbb0b10e67
--- /dev/null
+++ b/test/fixtures/guards/check-jsonb-params.mjs/good/fixture.ts
@@ -0,0 +1,6 @@
+// Guard self-test fixture (known-GOOD): the text-hop positional spelling.
+declare const engine: { executeRaw: (sql: string, params?: unknown[]) => Promise<unknown[]> };
+declare const x: Record<string, unknown>;
+export async function good(): Promise<void> {
+ await engine.executeRaw(`UPDATE op_checkpoints SET pin = $1::text::jsonb WHERE id = $2`, [JSON.stringify(x), 1]);
+}
diff --git a/test/fixtures/guards/check-jsonb-pattern.sh/bad/fixture.ts b/test/fixtures/guards/check-jsonb-pattern.sh/bad/fixture.ts
new file mode 100644
index 0000000000..c44c296d22
--- /dev/null
+++ b/test/fixtures/guards/check-jsonb-pattern.sh/bad/fixture.ts
@@ -0,0 +1,7 @@
+// Guard self-test fixture (known-BAD): template-interpolated stringify into a
+// direct ::jsonb cast, WITH nested parens (the pre-W0 regex hole).
+declare const sql: (strings: TemplateStringsArray, ...vals: unknown[]) => Promise<unknown>;
+declare const obj: { get: () => unknown };
+export async function bad(): Promise<void> {
+ await sql`UPDATE pages SET frontmatter = ${JSON.stringify(obj.get())}::jsonb WHERE id = 1`;
+}
diff --git a/test/fixtures/guards/check-jsonb-pattern.sh/good/fixture.ts b/test/fixtures/guards/check-jsonb-pattern.sh/good/fixture.ts
new file mode 100644
index 0000000000..80ce401724
--- /dev/null
+++ b/test/fixtures/guards/check-jsonb-pattern.sh/good/fixture.ts
@@ -0,0 +1,17 @@
+// Guard self-test fixture (known-GOOD): the safe text-hop spelling — binds as
+// text, the cast parses it (no direct )}::jsonb adjacency).
+declare const sql: (strings: TemplateStringsArray, ...vals: unknown[]) => Promise<unknown>;
+declare const obj: { get: () => unknown };
+export async function good(): Promise<void> {
+ await sql`UPDATE pages SET frontmatter = ${JSON.stringify(obj.get())}::text::jsonb WHERE id = 1`;
+}
+
+// Multi-interpolation line: a SAFE ::text::jsonb stringify followed by a
+// separate paren-bearing non-stringify ::jsonb interpolation on the SAME
+// line. A greedy argument matcher spans from stringify( to the second
+// interpolation's `)}::jsonb` and false-positives; the bracket-bounded
+// pattern must not (ship-review edge case, proven by repro).
+declare function getRaw(): unknown;
+export async function goodMultiInterpolation(): Promise<void> {
+ await sql`UPDATE pages SET a = ${JSON.stringify(obj.get())}::text::jsonb, b = ${getRaw()}::jsonb WHERE id = 2`;
+}
diff --git a/test/fixtures/guards/check-no-double-retry.sh/bad/fixture-multiline.ts b/test/fixtures/guards/check-no-double-retry.sh/bad/fixture-multiline.ts
new file mode 100644
index 0000000000..4e6afca0aa
--- /dev/null
+++ b/test/fixtures/guards/check-no-double-retry.sh/bad/fixture-multiline.ts
@@ -0,0 +1,12 @@
+// Guard self-test fixture (known-BAD, multi-line): withRetry( on one line and
+// the engine batch call two lines later — exercises the perl window pass
+// (the single-line grep cannot see this shape).
+declare const engine: { upsertChunks: (slug: string, chunks: unknown[]) => Promise<void> };
+declare function withRetry<T>(fn: () => Promise<T>, opts?: unknown): Promise<T>;
+declare const chunks: unknown[];
+export async function badMultiline(): Promise<void> {
+ await withRetry(
+ async () =>
+ engine.upsertChunks('slug', chunks),
+ );
+}
diff --git a/test/fixtures/guards/check-no-double-retry.sh/bad/fixture.ts b/test/fixtures/guards/check-no-double-retry.sh/bad/fixture.ts
new file mode 100644
index 0000000000..901be7eb08
--- /dev/null
+++ b/test/fixtures/guards/check-no-double-retry.sh/bad/fixture.ts
@@ -0,0 +1,9 @@
+// Guard self-test fixture (known-BAD): the CANONICAL banned shape — the exact
+// arrow-fn form the pre-W0 regex could not match ([^)]* stopped at `() =>`).
+declare const engine: { addLinksBatch: (rows: unknown[]) => Promise<void> };
+declare function withRetry<T>(fn: () => Promise<T>, opts?: unknown): Promise<T>;
+declare const rows: unknown[];
+declare const BULK_RETRY_OPTS: unknown;
+export async function bad(): Promise<void> {
+ await withRetry(() => engine.addLinksBatch(rows), BULK_RETRY_OPTS);
+}
diff --git a/test/fixtures/guards/check-no-double-retry.sh/good/fixture.ts b/test/fixtures/guards/check-no-double-retry.sh/good/fixture.ts
new file mode 100644
index 0000000000..48c786c840
--- /dev/null
+++ b/test/fixtures/guards/check-no-double-retry.sh/good/fixture.ts
@@ -0,0 +1,6 @@
+// Guard self-test fixture (known-GOOD): direct engine call, no outer retry.
+declare const engine: { addLinksBatch: (rows: unknown[], opts?: unknown) => Promise<void> };
+declare const rows: unknown[];
+export async function good(): Promise<void> {
+ await engine.addLinksBatch(rows, { auditSite: 'fixture.good' });
+}
diff --git a/test/helpers/legacy-embedding-config.ts b/test/helpers/legacy-embedding-config.ts
new file mode 100644
index 0000000000..83703f808d
--- /dev/null
+++ b/test/helpers/legacy-embedding-config.ts
@@ -0,0 +1,17 @@
+/**
+ * The pinned test-suite embedding shape (OpenAI legacy 1536-d).
+ *
+ * ONE definition, two consumers (W0 fix-wave — no hand-copied twins):
+ * - test/helpers/legacy-embedding-preload.ts (bunfig preload) pins the
+ * gateway to this shape for every `bun test` file.
+ * - scripts/build-pglite-snapshot.ts builds the snapshot fixture under the
+ * SAME shape, so the baked vector(dims) columns match what the pinned
+ * tests write. (The W0 incident: the build script ran with an
+ * unconfigured gateway → shipped-default 1280-d columns → every
+ * 1536-d-writing test failed with "expected 1280 dimensions, not 1536"
+ * the moment the snapshot became default-on.)
+ */
+export const LEGACY_EMBEDDING_CONFIG = {
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+} as const;
diff --git a/test/helpers/legacy-embedding-preload.ts b/test/helpers/legacy-embedding-preload.ts
index ca76b53034..438f44366c 100644
--- a/test/helpers/legacy-embedding-preload.ts
+++ b/test/helpers/legacy-embedding-preload.ts
@@ -25,10 +25,9 @@ import {
} from '../../src/core/ai/gateway.ts';
import { beforeEach } from 'bun:test';
-const LEGACY_CONFIG = {
- embedding_model: 'openai:text-embedding-3-large',
- embedding_dimensions: 1536,
-} as const;
+// W0 fix-wave: shared with scripts/build-pglite-snapshot.ts so the snapshot
+// fixture is baked under the exact shape this preload pins.
+import { LEGACY_EMBEDDING_CONFIG as LEGACY_CONFIG } from './legacy-embedding-config.ts';
function legacyGatewayConfig() {
return {
diff --git a/test/import-abort-error.test.ts b/test/import-abort-error.test.ts
new file mode 100644
index 0000000000..88d2232d05
--- /dev/null
+++ b/test/import-abort-error.test.ts
@@ -0,0 +1,55 @@
+/**
+ * W0 fix-wave (Tier-1 #5) — runImport must THROW a typed ImportAbortError on
+ * preflight/argv failures, never process.exit(1).
+ *
+ * runImport is invoked in-process by the sync_brain MCP op (performFullSync),
+ * the autopilot daemon, and the minion sync handler. Pre-fix, a first sync
+ * against a brain with unusable embedding credentials TERMINATED the calling
+ * process — the stdio MCP server just vanished mid-tool-call. The CLI dispatch
+ * site maps the typed error back to exit(1), keeping CLI behavior identical.
+ */
+
+import { test, expect } from 'bun:test';
+import { runImport, ImportAbortError } from '../src/commands/import.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+// The abort sites fire before any WRITE; the preamble runs a couple of
+// read-only lookups (sources, config), so the stub answers those with
+// empty sets.
+const engineStub = {
+ kind: 'pglite',
+ executeRaw: async () => [],
+ getConfig: async () => null,
+} as unknown as BrainEngine;
+
+async function expectAbort(args: string[], reasonFragment: string): Promise<void> {
+ let thrown: unknown;
+ try {
+ await runImport(engineStub, args);
+ } catch (e) {
+ thrown = e;
+ }
+ expect(thrown).toBeInstanceOf(ImportAbortError);
+ const err = thrown as ImportAbortError;
+ expect(err.exitCode).toBe(1);
+ expect(err.alreadyReported).toBe(true);
+ expect(err.message).toContain(reasonFragment);
+}
+
+test('missing dir arg → typed abort, not process death', async () => {
+ await expectAbort(['--no-embed'], 'no import directory');
+});
+
+test('invalid --workers → typed abort', async () => {
+ await expectAbort(['--no-embed', '--workers', '0', '/tmp'], 'invalid --workers');
+});
+
+test('unreadable import target → typed abort', async () => {
+ await expectAbort(['--no-embed', '/definitely/not/a/real/dir-w0-test'], 'not readable');
+});
+
+test('the calling process survives the abort (the actual Tier-1 bug)', async () => {
+ // Trivially true if we got here after three aborts above, but assert it
+ // explicitly: the process is alive and can keep dispatching.
+ expect(process.pid).toBeGreaterThan(0);
+});
diff --git a/test/lint-fix-single-pass.test.ts b/test/lint-fix-single-pass.test.ts
new file mode 100644
index 0000000000..0ab64e42d9
--- /dev/null
+++ b/test/lint-fix-single-pass.test.ts
@@ -0,0 +1,59 @@
+/**
+ * W0 fix-wave (Tier-1 #14) — `gbrain lint --fix` scans once and reports the
+ * TRUE fixed count.
+ *
+ * Pre-fix, runLint ran its own read+lint+fix loop for human detail, then
+ * called runLintCore a second time for the summary — every page linted
+ * twice, and because the first pass had already written the fixes, the
+ * summary's total_fixed counted fixes against already-fixed content: the
+ * CLI printed "0 auto-fixed" after fixing N issues.
+ */
+
+import { test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { runLintCore } from '../src/commands/lint.ts';
+
+let dir: string;
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-lint-w0-'));
+});
+
+afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+});
+
+test('single pass: total_fixed reports the fixes THIS run applied', async () => {
+ // A whole-file ```markdown wrapper is a fixable rule (code-fence-wrap).
+ writeFileSync(join(dir, 'wrapped.md'), '```markdown\n# Hello\n\nBody text.\n```\n');
+ writeFileSync(join(dir, 'clean.md'), '# Clean\n\nNothing to fix here.\n');
+
+ const scanned: string[] = [];
+ const reported: Array<{ relPath: string; fixedCount: number }> = [];
+ const result = await runLintCore({
+ target: dir,
+ fix: true,
+ contentSanity: { disabled: true } as never,
+ onPageScanned: () => scanned.push('tick'),
+ onPageIssues: (relPath, _issues, fixedCount) => reported.push({ relPath, fixedCount }),
+ });
+
+ // The bug: this was 0 after fixing. It must equal the fixes applied NOW.
+ expect(result.total_fixed).toBeGreaterThan(0);
+ // Each page scanned exactly once (2 pages, 2 ticks — not 4).
+ expect(scanned.length).toBe(2);
+ // The per-page hook carried the real fixed count for the fixed page
+ // (clean.md may still surface non-fixable advisory issues — irrelevant here).
+ const wrapped = reported.find(r => r.relPath === 'wrapped.md');
+ expect(wrapped).toBeDefined();
+ expect(wrapped!.fixedCount).toBeGreaterThan(0);
+ expect(result.total_fixed).toBe(wrapped!.fixedCount);
+ // And the fix actually landed on disk.
+ expect(readFileSync(join(dir, 'wrapped.md'), 'utf-8').startsWith('```')).toBe(false);
+
+ // Second run: nothing left to fix — counts stay honest.
+ const again = await runLintCore({ target: dir, fix: true, contentSanity: { disabled: true } as never });
+ expect(again.total_fixed).toBe(0);
+});
diff --git a/test/migrate.test.ts b/test/migrate.test.ts
index 93e312854c..a17fcdf207 100644
--- a/test/migrate.test.ts
+++ b/test/migrate.test.ts
@@ -50,8 +50,13 @@ describe('hasPendingMigrations', () => {
}, 30000);
test('returns true when version config is missing entirely (defensive default)', async () => {
+ // W0: opt out of the default-on snapshot — this test's premise is an
+ // empty PGlite with no config table at all.
+ const priorSnapshot = process.env.GBRAIN_PGLITE_SNAPSHOT;
+ delete process.env.GBRAIN_PGLITE_SNAPSHOT;
const engine = new PGLiteEngine();
await engine.connect({});
+ if (priorSnapshot !== undefined) process.env.GBRAIN_PGLITE_SNAPSHOT = priorSnapshot;
try {
// Don't call initSchema. Probe against an empty PGlite — getConfig should
// either return null (treated as version=1) or throw on missing config
diff --git a/test/queue-stall-parent-unblock.test.ts b/test/queue-stall-parent-unblock.test.ts
new file mode 100644
index 0000000000..cc51928b04
--- /dev/null
+++ b/test/queue-stall-parent-unblock.test.ts
@@ -0,0 +1,169 @@
+/**
+ * W0 fix-wave (Tier-1 #4) — a child dead-lettered via max-stall must notify
+ * and unblock its aggregator parent, exactly like timeout/failure kills do.
+ *
+ * Pre-fix, handleStalled's dead-letter branch emitted no child_done and never
+ * flipped the parent out of 'waiting-children': the parent hung forever
+ * unless it happened to carry its own timeout_ms (self-heal-proof — verified
+ * in adversarial review: resolveParent has no periodic caller and the worker
+ * only logged counts).
+ */
+
+import { test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import type { ChildDoneMessage } from '../src/core/minions/types.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM minion_inbox');
+ await engine.executeRaw('DELETE FROM minion_jobs');
+});
+
+async function jobStatus(id: number): Promise<string> {
+ const rows = await engine.executeRaw<{ status: string }>(
+ `SELECT status FROM minion_jobs WHERE id = $1`, [id],
+ );
+ return rows[0]!.status;
+}
+
+test('stall-exhausted child → child_done(dead) in parent inbox + parent unblocked', async () => {
+ const parent = await queue.add('aggregator', {});
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'waiting-children' WHERE id = $1`, [parent.id],
+ );
+ const child = await queue.add('child', {}, { parent_job_id: parent.id, max_stalled: 1 });
+
+ // Claim the child, then expire its lock so the stall sweep sees it; with
+ // max_stalled=1 the first stall dead-letters it.
+ const claimed = await queue.claim('tok-stall', 30_000, 'default', ['child', 'aggregator']);
+ expect(claimed?.id).toBe(child.id);
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET lock_until = now() - interval '1 second' WHERE id = $1`, [child.id],
+ );
+
+ const { requeued, dead } = await queue.handleStalled();
+ expect(requeued).toHaveLength(0);
+ expect(dead.map(j => j.id)).toEqual([child.id]);
+
+ // The fix, part 1: parent got child_done with outcome 'dead'.
+ const inbox = await engine.executeRaw<{ payload: unknown }>(
+ `SELECT payload FROM minion_inbox WHERE job_id = $1`, [parent.id],
+ );
+ expect(inbox).toHaveLength(1);
+ const msg = (typeof inbox[0]!.payload === 'string'
+ ? JSON.parse(inbox[0]!.payload as string)
+ : inbox[0]!.payload) as ChildDoneMessage;
+ expect(msg.type).toBe('child_done');
+ expect(msg.child_id).toBe(child.id);
+ expect(msg.outcome).toBe('dead');
+ expect(msg.error).toBe('max stalled count exceeded');
+
+ // The fix, part 2: parent flipped out of waiting-children.
+ expect(await jobStatus(parent.id)).toBe('waiting');
+});
+
+test('stall-requeued child (budget left) does NOT touch the parent', async () => {
+ const parent = await queue.add('aggregator', {});
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'waiting-children' WHERE id = $1`, [parent.id],
+ );
+ const child = await queue.add('child', {}, { parent_job_id: parent.id, max_stalled: 5 });
+ const claimed = await queue.claim('tok-stall2', 30_000, 'default', ['child', 'aggregator']);
+ expect(claimed?.id).toBe(child.id);
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET lock_until = now() - interval '1 second' WHERE id = $1`, [child.id],
+ );
+
+ const { requeued, dead } = await queue.handleStalled();
+ expect(dead).toHaveLength(0);
+ expect(requeued.map(j => j.id)).toEqual([child.id]);
+ expect(await jobStatus(child.id)).toBe('waiting');
+
+ const inbox = await engine.executeRaw<{ payload: unknown }>(
+ `SELECT payload FROM minion_inbox WHERE job_id = $1`, [parent.id],
+ );
+ expect(inbox).toHaveLength(0);
+ expect(await jobStatus(parent.id)).toBe('waiting-children');
+});
+
+test('all three reapers route through the shared kill tail with their own outcome/error (D5.5)', async () => {
+ // handleTimeouts → outcome 'timeout', error 'timeout exceeded'
+ const p1 = await queue.add('agg1', {});
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'waiting-children' WHERE id = $1`, [p1.id]);
+ const c1 = await queue.add('c1', {}, { parent_job_id: p1.id });
+ await queue.claim('t1', 30_000, 'default', ['c1', 'agg1']);
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET timeout_at = now() - interval '1 second', lock_until = now() + interval '1 minute' WHERE id = $1`, [c1.id],
+ );
+ await queue.handleTimeouts();
+
+ // handleWallClockTimeouts → outcome 'timeout', error 'wall-clock timeout exceeded'
+ const p2 = await queue.add('agg2', {});
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'waiting-children' WHERE id = $1`, [p2.id]);
+ const c2 = await queue.add('c2', {}, { parent_job_id: p2.id });
+ await queue.claim('t2', 30_000, 'default', ['c2', 'agg2']);
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET started_at = now() - interval '2 hours' WHERE id = $1`, [c2.id],
+ );
+ await queue.handleWallClockTimeouts(30_000);
+
+ const expectMsg = async (parentId: number, childId: number, outcome: string, error: string) => {
+ const inbox = await engine.executeRaw<{ payload: unknown }>(
+ `SELECT payload FROM minion_inbox WHERE job_id = $1`, [parentId],
+ );
+ expect(inbox).toHaveLength(1);
+ const msg = (typeof inbox[0]!.payload === 'string'
+ ? JSON.parse(inbox[0]!.payload as string)
+ : inbox[0]!.payload) as ChildDoneMessage;
+ expect(msg.child_id).toBe(childId);
+ expect(msg.outcome).toBe(outcome as ChildDoneMessage['outcome']);
+ expect(msg.error).toBe(error);
+ expect(await jobStatus(parentId)).toBe('waiting');
+ };
+ await expectMsg(p1.id, c1.id, 'timeout', 'timeout exceeded');
+ await expectMsg(p2.id, c2.id, 'timeout', 'wall-clock timeout exceeded');
+});
+
+test('retroactive sweep: a parent stranded BEFORE the fix (children already dead) self-heals on the next stall tick', async () => {
+ // Simulate the pre-upgrade world: child is already terminal ('dead') with
+ // NO child_done ever emitted, parent parked in waiting-children. No
+ // per-kill unblock will ever revisit this pair — only the sweep can.
+ const parent = await queue.add('agg-stranded', {});
+ const child = await queue.add('child-stranded', {}, { parent_job_id: parent.id });
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'waiting-children' WHERE id = $1`, [parent.id],
+ );
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'dead', error_text = 'max stalled count exceeded (pre-upgrade)' WHERE id = $1`, [child.id],
+ );
+
+ const { requeued, dead } = await queue.handleStalled();
+ expect(requeued).toHaveLength(0);
+ expect(dead).toHaveLength(0);
+ // The sweep healed the stranded parent even though THIS tick killed nothing.
+ expect(await jobStatus(parent.id)).toBe('waiting');
+});
+
+test('retroactive sweep does NOT unblock a parent with a live child', async () => {
+ const parent = await queue.add('agg-live', {});
+ await queue.add('child-live', {}, { parent_job_id: parent.id });
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'waiting-children' WHERE id = $1`, [parent.id],
+ );
+ await queue.handleStalled();
+ expect(await jobStatus(parent.id)).toBe('waiting-children');
+});
diff --git a/test/queue-started-at-retry.test.ts b/test/queue-started-at-retry.test.ts
new file mode 100644
index 0000000000..d37559e095
--- /dev/null
+++ b/test/queue-started-at-retry.test.ts
@@ -0,0 +1,161 @@
+/**
+ * W0 fix-wave (Tier-1 #7) — started_at is reset on every AUTOMATIC re-run
+ * path, so handleWallClockTimeouts (anchored on now() - started_at) measures
+ * per-attempt runtime, never time a job spent parked in backoff.
+ *
+ * Pre-fix, only the manual `jobs retry` path cleared started_at (its
+ * docstring documented the bug); the four automatic paths — failJob's
+ * delayed branch, handleStalled's requeue, promoteDelayed, and
+ * releaseLeaseFullJob (the 4th site, found in adversarial verification) —
+ * all preserved the FIRST claim's timestamp, so an exponential-backoff job
+ * could be dead-lettered by the wall-clock sweep before executing a single
+ * line of its retry attempt.
+ */
+
+import { test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+});
+
+async function jobStatus(id: number): Promise<string> {
+ const rows = await engine.executeRaw<{ status: string }>(
+ `SELECT status FROM minion_jobs WHERE id = $1`, [id],
+ );
+ return rows[0]!.status;
+}
+
+async function startedAtOf(id: number): Promise<string | null> {
+ const rows = await engine.executeRaw<{ started_at: string | null }>(
+ `SELECT started_at::text AS started_at FROM minion_jobs WHERE id = $1`, [id],
+ );
+ return rows[0]?.started_at ?? null;
+}
+
+async function addAndClaim(name = 'noop'): Promise<{ id: number; token: string }> {
+ const job = await queue.add(name, {});
+ const token = `tok-${Math.random().toString(36).slice(2)}`;
+ const claimed = await queue.claim(token, 30_000, 'default', [name]);
+ expect(claimed?.id).toBe(job.id);
+ expect(await startedAtOf(job.id)).not.toBeNull();
+ return { id: job.id, token };
+}
+
+test("failJob's delayed branch clears started_at (terminal branches keep it)", async () => {
+ const { id, token } = await addAndClaim();
+ const delayed = await queue.failJob(id, token, 'boom', 'delayed', 50);
+ expect(delayed?.status).toBe('delayed');
+ expect(await startedAtOf(id)).toBeNull();
+
+ // Terminal failure keeps started_at (it feeds duration accounting).
+ const { id: id2, token: token2 } = await addAndClaim();
+ const dead = await queue.failJob(id2, token2, 'boom', 'dead');
+ expect(dead?.status).toBe('dead');
+ expect(await startedAtOf(id2)).not.toBeNull();
+});
+
+test("handleStalled's requeue branch clears started_at", async () => {
+ const { id } = await addAndClaim();
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET lock_until = now() - interval '1 second' WHERE id = $1`, [id],
+ );
+ const { requeued } = await queue.handleStalled();
+ expect(requeued.map(j => j.id)).toContain(id);
+ expect(await startedAtOf(id)).toBeNull();
+});
+
+test('releaseLeaseFullJob clears started_at (lease bounce burns no wall-clock)', async () => {
+ const { id, token } = await addAndClaim();
+ const released = await queue.releaseLeaseFullJob(id, token, 'rate lease full (8/8)', 50);
+ expect(released?.status).toBe('delayed');
+ expect(await startedAtOf(id)).toBeNull();
+});
+
+test('promoteDelayed defensively clears any stale started_at', async () => {
+ const job = await queue.add('noop', {});
+ await engine.executeRaw(
+ `UPDATE minion_jobs
+ SET status = 'delayed', delay_until = now() - interval '1 second',
+ started_at = now() - interval '1 hour'
+ WHERE id = $1`, [job.id],
+ );
+ const promoted = await queue.promoteDelayed();
+ expect(promoted.map(j => j.id)).toContain(job.id);
+ expect(await startedAtOf(job.id)).toBeNull();
+});
+
+test('end-to-end: a retried job survives the wall-clock sweep on its fresh attempt', async () => {
+ const { id, token } = await addAndClaim();
+ // Simulate a long first attempt: backdate started_at far past the sweep
+ // threshold (no timeout_ms → threshold = lockDurationMs * 2 * max_stalled).
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET started_at = now() - interval '1 hour' WHERE id = $1`, [id],
+ );
+ await queue.failJob(id, token, 'first attempt failed', 'delayed', 0);
+ const promoted = await queue.promoteDelayed();
+ expect(promoted.map(j => j.id)).toContain(id);
+
+ const token2 = 'tok-second-attempt';
+ const reclaimed = await queue.claim(token2, 30_000, 'default', ['noop']);
+ expect(reclaimed?.id).toBe(id);
+
+ // Pre-fix: started_at still said now()-1h → 3.6M ms > 30_000*2*max_stalled
+ // and the very next sweep dead-lettered the fresh attempt. Post-fix the
+ // re-claim stamped a fresh started_at, so the sweep spares it.
+ const killed = await queue.handleWallClockTimeouts(30_000);
+ expect(killed.map(j => j.id)).not.toContain(id);
+
+ // Negative control — the sweep itself still works: backdate the ACTIVE
+ // attempt past the threshold and it dies.
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET started_at = now() - interval '1 hour' WHERE id = $1`, [id],
+ );
+ const killed2 = await queue.handleWallClockTimeouts(30_000);
+ expect(killed2.map(j => j.id)).toContain(id);
+});
+
+test('red-team 5th path: a re-claimed aggregator parent survives the wall-clock sweep', async () => {
+ // Parent parked in waiting-children for LONGER than the wall-clock
+ // threshold while its child runs; every unblock path (killJobs,
+ // completeJob resolve, failJob branches, cancelJob, retroactive sweep,
+ // resolveParent) must clear started_at, or claim()'s COALESCE keeps the
+ // attempt-1 anchor and the sweep dead-letters the aggregation attempt
+ // before it executes a line.
+ const parent = await queue.add('agg-wallclock', {});
+ const child = await queue.add('child-wc', {}, { parent_job_id: parent.id, max_stalled: 1 });
+ // Parent claimed long ago (attempt-1 anchor), then parked waiting-children.
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'waiting-children', started_at = now() - interval '1 hour' WHERE id = $1`, [parent.id],
+ );
+ // Child stalls to death → killJobs unblocks the parent.
+ await queue.claim('tok-wc', 30_000, 'default', ['child-wc', 'agg-wallclock']);
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET lock_until = now() - interval '1 second' WHERE id = $1`, [child.id],
+ );
+ await queue.handleStalled();
+ expect(await jobStatus(parent.id)).toBe('waiting');
+ // The fix: unblock cleared the stale anchor.
+ expect(await startedAtOf(parent.id)).toBeNull();
+
+ // Parent re-claims for its aggregation attempt → fresh anchor → survives.
+ const reclaimed = await queue.claim('tok-wc2', 30_000, 'default', ['agg-wallclock', 'child-wc']);
+ expect(reclaimed?.id).toBe(parent.id);
+ const killed = await queue.handleWallClockTimeouts(30_000);
+ expect(killed.map(j => j.id)).not.toContain(parent.id);
+});
diff --git a/test/scripts/check-engine-dynamic-import.test.ts b/test/scripts/check-engine-dynamic-import.test.ts
index aa35d46993..60ecb664d4 100644
--- a/test/scripts/check-engine-dynamic-import.test.ts
+++ b/test/scripts/check-engine-dynamic-import.test.ts
@@ -304,16 +304,21 @@ describe('check-engine-dynamic-import.sh', () => {
});
describe('engine dynamic-import guard wiring', () => {
- it('is invoked through bash by check:all', () => {
+ it('is wired into the verify registry (W0: check:all deleted; CHECKS array is THE registry)', () => {
const pkg = JSON.parse(readFileSync(PACKAGE_JSON, 'utf8')) as {
scripts: Record<string, string>;
};
expect(pkg.scripts['check:engine-dynamic-import']).toBe(
'bash scripts/check-engine-dynamic-import.sh',
);
- expect(pkg.scripts['check:all']).toContain(
- 'bash scripts/check-engine-dynamic-import.sh',
+ // The stale duplicate registry is gone for good…
+ expect(pkg.scripts['check:all']).toBeUndefined();
+ // …and the single registry carries this guard.
+ const checks = readFileSync(
+ new URL('../../scripts/run-verify-parallel.sh', import.meta.url),
+ 'utf8',
);
+ expect(checks).toContain('"check:engine-dynamic-import"');
});
it('is listed by the authoritative verify dispatcher', () => {
diff --git a/test/snapshot-shape-guard.test.ts b/test/snapshot-shape-guard.test.ts
new file mode 100644
index 0000000000..a91880c965
--- /dev/null
+++ b/test/snapshot-shape-guard.test.ts
@@ -0,0 +1,81 @@
+/**
+ * W0 ship-review coverage (GAP-2) — the snapshot loader's shape + hash guards.
+ *
+ * The fixture is default-on for every `bun run test`, so a wrong snapshot
+ * poisons the whole suite (the 1280-vs-1536 incident: 115 failures from one
+ * root cause). These tests pin the three refusal paths and the
+ * handler-aware hash (D5.13).
+ */
+
+import { test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import * as crypto from 'node:crypto';
+import { tryLoadSnapshot, computeSnapshotSchemaHash } from '../src/core/pglite-engine.ts';
+import { MIGRATIONS } from '../src/core/migrate.ts';
+import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.ts';
+import { getEmbeddingDimensions, getEmbeddingModel } from '../src/core/ai/gateway.ts';
+
+let dir: string;
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-snap-guard-'));
+});
+
+afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+});
+
+function writeFixture(versionContent: string): string {
+ const tarPath = join(dir, 'snap.tar');
+ writeFileSync(tarPath, 'not-a-real-tar-but-existence-is-what-matters');
+ writeFileSync(join(dir, 'snap.version'), versionContent);
+ return tarPath;
+}
+
+const currentHash = () => computeSnapshotSchemaHash(MIGRATIONS, PGLITE_SCHEMA_SQL, crypto);
+
+test('pre-W0 hash-only version file (no shape lines) is refused', () => {
+ const tar = writeFixture(`${currentHash()}\n`);
+ expect(tryLoadSnapshot(tar)).toBeNull();
+});
+
+test('dims mismatch is refused even with a matching hash', () => {
+ const tar = writeFixture(`${currentHash()}\ndims=99999\nmodel=${getEmbeddingModel()}\n`);
+ expect(tryLoadSnapshot(tar)).toBeNull();
+});
+
+test('model mismatch is refused even with a matching hash', () => {
+ const tar = writeFixture(`${currentHash()}\ndims=${getEmbeddingDimensions()}\nmodel=other:model\n`);
+ expect(tryLoadSnapshot(tar)).toBeNull();
+});
+
+test('stale schema hash is refused even with a matching shape', () => {
+ const tar = writeFixture(`deadbeef\ndims=${getEmbeddingDimensions()}\nmodel=${getEmbeddingModel()}\n`);
+ expect(tryLoadSnapshot(tar)).toBeNull();
+});
+
+test('matching hash + shape loads the blob', () => {
+ const tar = writeFixture(`${currentHash()}\ndims=${getEmbeddingDimensions()}\nmodel=${getEmbeddingModel()}\n`);
+ const blob = tryLoadSnapshot(tar);
+ expect(blob).not.toBeNull();
+ expect(blob!.size).toBeGreaterThan(0);
+});
+
+test('D5.13: a migration handler edit changes the hash (sql-only hashing missed 19 handler migrations)', () => {
+ const base = [
+ { version: 1, name: 'a', sql: 'CREATE TABLE t(x int)' },
+ { version: 2, name: 'b', sql: '', handler: async () => 'original' },
+ ];
+ const edited = [
+ { version: 1, name: 'a', sql: 'CREATE TABLE t(x int)' },
+ { version: 2, name: 'b', sql: '', handler: async () => 'EDITED BODY' },
+ ];
+ const h1 = computeSnapshotSchemaHash(base, 'schema', crypto);
+ const h2 = computeSnapshotSchemaHash(edited, 'schema', crypto);
+ expect(h1).not.toBe(h2);
+ // And identical handlers hash identically (determinism).
+ const h3 = computeSnapshotSchemaHash(base, 'schema', crypto);
+ expect(h1).toBe(h3);
+});
diff --git a/test/supervisor-db-lock.test.ts b/test/supervisor-db-lock.test.ts
index f7b9afbbe9..ea57798c18 100644
--- a/test/supervisor-db-lock.test.ts
+++ b/test/supervisor-db-lock.test.ts
@@ -216,6 +216,7 @@ describe('#1849 refresh-failure fails safe (F1A)', () => {
let refreshCalls = 0;
const failingLock: DbLockHandle = {
id: 'x',
+ acquiredAt: 'test-fence',
refresh: async () => { refreshCalls++; throw new Error('pooler down'); },
release: async () => {},
};
@@ -244,7 +245,8 @@ describe('#1849 refresh-failure fails safe (F1A)', () => {
let mode: 'fail' | 'ok' = 'fail';
const flakyLock: DbLockHandle = {
id: 'x',
- refresh: async () => { if (mode === 'fail') throw new Error('blip'); },
+ acquiredAt: 'test-fence',
+ refresh: async () => { if (mode === 'fail') throw new Error('blip'); return true; },
release: async () => {},
};
sup._setDbLockForTests(flakyLock);
@@ -264,3 +266,31 @@ describe('#1849 refresh-failure fails safe (F1A)', () => {
}
});
});
+
+ test('W0 (D5.10): fenced refresh returning false is CERTAIN loss — immediate LOCK_LOST, no threshold', async () => {
+ const sup = new MinionSupervisor(engine, { cliPath: '/bin/sh', healthInterval: 0, json: true });
+ const exitSpy = spyOn(process, 'exit').mockImplementation(((_code?: number) => {
+ throw new Error(`exit:${_code}`);
+ }) as never);
+
+ let refreshCalls = 0;
+ const stolenLock: DbLockHandle = {
+ id: 'x',
+ acquiredAt: 'test-fence',
+ refresh: async () => { refreshCalls++; return false; },
+ release: async () => {},
+ };
+ sup._setDbLockForTests(stolenLock);
+
+ try {
+ // FIRST tick exits — a fenced miss is proof of loss, not a blip to
+ // count toward SUPERVISOR_LOCK_REFRESH_MAX_FAILURES (pre-fix it was
+ // treated as SUCCESS and reset the failure counter while a second
+ // supervisor drained the same queue).
+ try { await sup._refreshDbLockForTests(); } catch { /* exit stub throws */ }
+ expect(exitSpy).toHaveBeenCalledWith(ExitCodes.LOCK_LOST);
+ expect(refreshCalls).toBe(1);
+ } finally {
+ exitSpy.mockRestore();
+ }
+ });