Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.46.32.0 fix: wave-k community train — 54 contributor PRs absorbed, reconciled with the v0.46.29.0 wave-g train (#4567) (#4565)
Garry Tan77bb9d8c2165
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex e040d59e24..f5fa2592e0 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.31.0",+ "version": "0.46.32.0","description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 7742a1922d..a8827cd10b 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.31.0",+ "version": "0.46.32.0","description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 85affaa518..8540a56ba1 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.46.31.0 -->+<!-- gbrain-runbook-stamp: 0.46.32.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6da330e013..fd0ebd74a7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,82 @@All notable changes to GBrain will be documented in this file.+## [0.46.32.0] - 2026-08-26++**The community train: 54 contributor PRs absorbed.** Wave K triaged all 141+open PRs against the live codebase, verified each fix still real at HEAD, and+absorbed the 54 that complement the v0.46.28.0 megawave — one commit per PR,+contributor authorship preserved via Co-authored-by trailers, fixups applied+where master had drifted. 32 community authors credited. This entry lists what+lands NET-NEW on top of v0.46.29.0–v0.46.31.0: #3617, #4400, #4411, #4414,+#4425, #4453 and issues #3729/#4416/#2036 also shipped independently in+v0.46.29.0 — this wave's implementations of those were reconciled at merge and+are not re-credited here.++### Credits+Absorbed with thanks from: @Masashi-Ono0611 (13 incl. #4459 whose+implementation was superseded mid-flight by the megawave's #3885 fix — its+e2e tests ship here), @avs-io (5), @calebhicks (4), @frxiaobei,+@alexey-metaengage, @harjothkhara (2 each), and 26 more contributors — full+per-PR attribution in the release PR body and each commit's trailers.+++### Added+- Semantic takes retrieval: `gbrain takes embed` populates take embeddings and+ `think` gains a vector retrieval arm alongside keyword takes search (#3776).+ Migration v142 resizes `takes.embedding` to the configured embedding+ dimension; any pre-existing take vectors (including manually embedded ones)+ are cleared by design and repopulate on the next `gbrain takes embed`.++**`gbrain smoke-test` no longer starts a surprise shell-enabled worker.** The+worker check now asks the native supervisor status surface, which understands+brain-scoped PID files and the queue's live database lock. A healthy managed+worker therefore passes without creating a second unmanaged process.++### Changed+- INTENTIONAL CONTRACT CHANGE: worker repair is no longer auto-fixed. A+ missing worker now produces an explicit+ `gbrain jobs supervisor start --detach` repair hint instead of silently+ launching `jobs work` with shell jobs enabled, and the smoke test exits 1+ when nothing manages workers.++### Fixed+- `gbrain takes --help` and `gbrain auth --help` print full subcommand usage+ without an engine (#3780, #4083); `think --take` records a take end-to-end+ instead of silently no-oping (#4469, fixes #2556).+- Bun 1.3.10 warm-transpiler-cache poisoning of `test/doctor.test.ts` (59-test+ cascade on any warm re-run): sync `require()` sites converted to+ `await import`. (The search cache key is unchanged in this release — this+ wave's keyword-fallback fold was already covered by v0.46.29.0's re-key.)++- Page ingest no longer aborts an entire document (or batch run) when the body+ or a chunk contains a raw NUL byte or lone UTF-16 surrogate: pages body+ columns and chunk_text are sanitized at write time in both engines, the same+ policy as links/timeline/takes free-text. (#3998)+- A live supervisor plus a legacy worker PID is reported as a duplicate+ topology that requires operator review.+- Smoke-test worker detection is hermetically covered without touching live+ processes or global PID files.+- Doctor health-score extraction uses POSIX `sed` instead of GNU-only+ `grep -P`, eliminating the macOS warning and `?/100` fallback.+- Page-retrieval metrics can no longer exceed their mathematical bounds when+ search returns multiple chunks from one page: Precision@k, Recall@k, MRR,+ nDCG@k, NamedThingBench, and the qrels correctness gate now share one+ unique-page ranking primitive that keeps only the first/best occurrence of+ each ranked page before any cutoff. Duplicate non-relevant chunks no longer+ consume page-level ranks, and qrels ground-truth duplicates count as one+ relevant page. Historical baselines that included duplicate page hits may+ decrease and should be reviewed before changing quality thresholds. (#4184)++### To take advantage of v0.46.32.0++```bash+gbrain upgrade+gbrain apply-migrations --yes # v142 resizes takes.embedding to your configured dimension+gbrain takes embed # repopulate take vectors (v142 clears them by design)+gbrain doctor # verify+```+## [0.46.31.0] - 2026-08-25Chat connectors: connect a ChatGPT or Claude account and sync its conversationdiff --git a/CLAUDE.md b/CLAUDE.mdindex f138d3847d..ebc84d1705 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -363,9 +363,10 @@ filed for held-out corpus growth, cross-vendor verification, hierarchicalarea-of-areas, embedding-based pre-router, and the run-1 vs run-2prompt-design ablation methodology.-**Operational health (v0.19.1):** smoke-test (8 post-restart health checks with auto-fix-for Bun, CLI, DB, worker, Zod CJS, gateway, API key, brain repo; user-extensible via-`~/.gbrain/smoke-tests.d/*.sh`).+**Operational health (v0.19.1):** smoke-test (8 post-restart health checks; bounded+auto-fix for Bun, CLI, and Zod CJS; read-only worker topology via native supervisor+status with duplicate detection; DB, gateway, API key, brain repo; user-extensible+via `~/.gbrain/smoke-tests.d/*.sh`).**Conventions:** `skills/conventions/` has cross-cutting rules (quality, brain-first,model-routing, test-before-bulk, cross-modal). `skills/_brain-filing-rules.md` and@@ -739,7 +740,14 @@ before considering the ship complete.Files that MUST be checked on every ship:- README.md — does it reflect new features, commands, or setup steps?-- CLAUDE.md — does it reflect new files, test files, or architecture changes?+- `docs/architecture/KEY_FILES.md` — new or changed files in `src/`, and their+ invariants, are recorded HERE. This is the on-demand layer behind the Reference+ map, and it is where per-file and per-version detail belongs.+- CLAUDE.md — only if an always-loaded rule, the Reference map, or the dispatcher+ changed. **CLAUDE.md is a map, not a log**: it is read in full at the start of every+ session, so entries are condensed or deleted as they go stale, never appended to.+ If an update adds a file inventory, a test inventory, or an "as of vX.Y.Z" note,+ it belongs in the on-demand layer above instead.- CHANGELOG.md — does it cover every commit?- TODOS.md — are completed items marked done?- docs/ — do any guides need updating?diff --git a/VERSION b/VERSIONindex a868105ff2..a2246b7a67 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.46.31.0+0.46.32.0diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 3664b47f84..cb44645fd1 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -431,6 +431,7 @@ test-shaped segment past it.Unit tests and what they cover:+- `test/facts-engine.test.ts` / `test/consolidate-valid-until.test.ts` — facts-list filtering and consolidate correctness (#4057): `unconsolidatedOnly` is applied before the 100-row limit, so newer consolidated facts cannot permanently hide older pending facts; the phase regression seeds 100 consolidated rows plus three older pending rows and requires all three to progress.- `test/markdown.test.ts` — frontmatter parsing; `splitBody` sentinel precedence, horizontal-rule preservation, `inferType` wiki subtypes.- `test/chunkers/recursive.test.ts` — chunking.- `test/parity.test.ts` — operations contract parity.@@ -561,6 +562,8 @@ Unit tests and what they cover:E2E tests live in `test/e2e/` and run against real Postgres+pgvector (require `DATABASE_URL`), except where noted as PGLite in-memory (no `DATABASE_URL` needed). One file outside the directory also rides the e2e lane: `test/phantom-redirect-engine-parity.test.ts` (Postgres arm; see the file taxonomy above).+- `test/e2e/facts-separation-postgres.test.ts` — real-Postgres parity for cross-session facts, supersession, and the pre-limit `unconsolidatedOnly` predicate used by consolidation.+- `bun run test:e2e` runs Tier 1 (mechanical, all operations, no API keys). Includes dedicated cases for the postgres-engine `addLinksBatch` / `addTimelineEntriesBatch` bind path — postgres-js's JSONB bind (`jsonb_to_recordset(($1::jsonb)->'rows')`) differs from PGLite's and gets its own coverage.- `test/e2e/search-quality.test.ts` — search quality against PGLite (no API keys, in-memory).- `test/e2e/graph-quality.test.ts` — knowledge graph pipeline (auto-link via put_page, reconciliation, traversePaths) against PGLite in-memory.diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 8b4664f213..bb69ce4fb6 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -30,7 +30,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`).- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/pglite-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full prior public surface. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` wraps `PGlite.create()` in a try/catch that classifies the failure and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown — the #223/#1670/#2575 class, historically misdiagnosed as a macOS WASM bug), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, #3596 engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` (#4143) early-nulls the handle (so no NEW statement can reach it), then runs `drainBackgroundWorkBeforeDisconnect()` so statements ALREADY in flight settle against the still-open handle — PGLite's `close()` deadlocks permanently (close's promise AND the in-flight query's promise never settle) with a statement in flight; the ordering is load-bearing (drain above the null would reopen the #1337 race). Teardown defense is layered and honestly scoped (#4284): the drain PREVENTS the known wedge; the in-loop close bound (`GBRAIN_PGLITE_CLOSE_TIMEOUT_MS`, default 5000ms, floor 1s, ceiling 2^31−1, read per call) covers ONLY a close that still yields to the event loop — armed BEFORE `close()` is called and deliberately ref'd, a timed-out close degrades to a once-per-process stderr warning naming both env knobs and teardown proceeds (an abandoned close's later rejection is swallowed; the WAL-repair path covers a zombie instance on next open); a close that WEDGES the loop (blocked or microtask-starved, the #1762 re-pump class) can never be caught by any same-loop timer and is observable/killable only by the opt-in out-of-band watchdog — a diagnostic/incident instrument, not ambient production protection: `GBRAIN_PGLITE_CLOSE_WATCHDOG_MS` (unset/0 = off; a positive value clamps UP to `max(5000, registered-sink-count×2000 + close timeout + 2000)` with a warn so a units typo never SIGKILLs a healthy slow teardown) + `GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS` (default 30000) arm the shared `process-watchdog.ts` worker around a PGLite disconnect with a live handle (armed after the early-return, before the drain; disposed in a nested finally so a `releaseLock` throw can't leak it; SIGTERM at deadline, SIGKILL at deadline+grace; lock-only teardown and postgres pool teardown are out of scope). Pinned by `test/pglite-engine-disconnect.serial.test.ts` + `test/search-telemetry-disconnect-hang.serial.test.ts` + `test/pglite-disconnect-watchdog.serial.test.ts` (spawned fixture that genuinely starves the loop) + the `#4284` structural pins in `test/fix-wave-structural.test.ts`. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and modern brains (closes the upgrade-wedge bug class #239/#243/#266/#357/#366/#374/#375/#378/#395/#396/#1018/#974/#820). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `disconnect()` uses snapshot+early-null (snapshot `_db`/`_lock`, null instance fields BEFORE any `await` so a concurrent `connect()` can't see a partial mid-close state) wrapped in try/finally guaranteeing lock-release even if `db.close()` throws; KEEPS close-then-release order (release-then-close was rejected: it would widen the window where a sibling process connects to a still-closing brain); Pinned by `test/pglite-engine-disconnect.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode` (#2084): PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and keeps the #223 link; `unknown` is platform-gated per #2674). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass.- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary regresses to the Bun-vfs ENOENT class (#1340). `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver (#4116): tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.serial.test.ts` (real `bun add -g`-shaped hoisted layout).-- `src/core/pglite-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. `gbrain sync` normally never reaches this error under a live serve — the cli.ts preflight (`src/commands/sync-delegate.ts`) probes the lock file read-only and delegates the sync through the serve's IPC socket instead. 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-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 on affirmative proof of death — ESRCH from kill-0, or a `ps`-/`proc`-read command line proving the PID was recycled by a non-gbrain program under AFFIRMATIVE same-namespace proof (on Linux the lock's recorded `pid_ns` must be readable and equal ours, `boot_id` too when recorded; legacy locks without markers are never cmdline-reaped; unreadable cmdline and same-process PID also read as alive) — a LIVE holder is NEVER stolen, regardless of how stale its heartbeat is (#2348). Every reap serializes on an atomic claim dir (`tryReapLockDir`) and re-validates the victim's ownership token while the lock is still in place, so concurrent reapers can't delete each other's freshly installed locks; a crashed claimant's dir is broken after a 30s TTL / dead PID. 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. `gbrain sync` normally never reaches this error under a live serve — the cli.ts preflight (`src/commands/sync-delegate.ts`) probes the lock file read-only and delegates the sync through the serve's IPC socket instead. 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 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, PID-recycling 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. 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`.@@ -52,7 +52,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/reindex-code.ts` — `gbrain reindex --code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks `pages WHERE type = 'code'` in 100-row batches, replays through `importCodeFile` for chunk + embed + content_hash folding. Idempotent unless `--force` bypasses the content_hash early-return. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). When `--yes` is absent and the caller is non-TTY or passed `--json`, the cost gate refuses (exit 2, no spend) via the pure exported `buildCostRefusal({json, previewMsg, preview, costUsd, model}): {stdout?, stderr?}` — JSON envelope only when `--json` is explicit, otherwise a human refusal on stderr (the spend guardrail is independent of the output format). `spend.posture=tokenmax` OR an explicit `--max-cost off`/`unlimited` makes the gate informational and proceeds (#2139); `--max-cost off` also disables the runtime BudgetTracker cap. Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE regression for the cost-preview fix), `test/reindex-cost-refusal.test.ts`.- `src/core/fts-language.ts` — Single source for the Postgres text-search configuration name used by FTS. `getFtsLanguage()` resolves `GBRAIN_FTS_LANGUAGE` (default `english`), validates against `/^[a-z][a-z0-9_]*$/` (tsvector config names can't be bound as parameters, so the value is interpolated into raw SQL — the allowlist regex is the injection guard; invalid values warn once and fall back to `english`), and caches on first read (`resetFtsLanguageCache()` is test-only). Consumed by both engines' `searchKeyword`/`searchKeywordChunks` (`websearch_to_tsquery` query side), the `configurable_fts_language` migration, and `reindex-search-vector` (write-side trigger functions). Pinned by `test/fts-language.serial.test.ts` + `test/fts-language-migration.serial.test.ts` (includes the `'; DROP TABLE pages; --` injection cases).- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language — bodies mirror the migration's and KEEP the `SET search_path = pg_catalog, public` hardening (CREATE OR REPLACE resets proconfig) — then backfills `pages` (UPDATE-to-self re-fires the trigger) and `content_chunks` (direct vector recompute) in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000) via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`, streaming phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Confirmation gate: `--yes`, or an interactive TTY [y/N]; `--json` does NOT bypass the gate (non-TTY without `--yes` refuses with a ConfirmationRequired envelope, exit 2). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts`.-- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). Six pure-function clusters live in `src/core/sync-{cost-gate,git,anchor,lock,reconcile,status-report}.ts` (see the grouped entry below) and are re-exported through this façade, so the full prior import surface is unchanged. `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; the bare no-source path uses the SAME refreshing lock (#1794 — it was previously a non-refreshing `tryAcquireDbLock`, stealable mid-run during an incident); `SyncOpts.lockId?: string` is the explicit override. The lock refresh AND its health probe route through the DIRECT session pool so Supavisor transaction-pool exhaustion (`EMAXCONNSESSION`) can't kill renewal; takeover is heartbeat-aware (it will NOT steal a holder whose `last_refreshed_at` is within `GBRAIN_LOCK_STEAL_GRACE_SECONDS`, defending an alive-but-starved holder); the import loop yields the event loop every `GBRAIN_SYNC_YIELD_EVERY` files (`setTimeout(0)`, not `setImmediate` — Bun starves the timers phase) so the refresh `setInterval` heartbeat fires mid-import. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths via `appendCompleted` (append-only delta into the `op_checkpoint_paths` child table, migration v115 — one row per path, O(delta) not the old O(N²) full-array rewrite), keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` (paths under `op:'sync'`; the pinned target under `op:'sync-target'`), and advances `last_commit`/`last_sync_at` ONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they survive `EMAXCONNSESSION`; the flush cadence is first-file then every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files OR `GBRAIN_SYNC_CHECKPOINT_SECONDS` (default 10s), with a race-safe `pendingCheckpointPaths` delta (single-flight swap, re-merge on failure) under parallel workers; a SIGTERM banks the in-flight delta via a no-retry one-shot (`appendCompletedOnce`, ordered before lock release through `registerCleanup`); and sustained flush failure aborts the run with `reason:'checkpoint_unavailable'` after `GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES` consecutive fails rather than importing work it can never bank (every partial/blocked exit logs the banked-file count). A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff — this closes the cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) replaces the old strict head-drift gate: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and no longer block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` are scoped per source (`acknowledgeFailures(sourceId)`; `--all` acks every source, single-source acks only its own) and run UNDER parallel — the #1939 failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so the old "not supported under parallel, re-run with --serial" refusal is lifted (#2139, which also removed the forcing-function that pushed recovery syncs to `--serial` and thus armed the inline cost gate); a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count, skipped_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok (sources skipped by `--missing-path skip` count as ok), 1 any error. `--missing-path <fail|skip>` (default fail) handles sources whose `local_path` does not exist on this machine — machine-specific state in a brain-wide table, so a brain registered from several machines fails every foreign source on every run; `skip` classifies them `skipped_missing_path` (⊘ line, envelope entry with `local_path`, excluded from `error_count` and the rc gate) via the exported pure helpers `parseMissingPathMode` + `partitionMissingPathSources`, pinned by `test/sync-all-missing-path.test.ts`; default `fail` stays loud because on a single-machine brain a missing path usually means an unmounted volume. (The non-TTY cost gate no longer exits 2: a worker-backed engine can auto-defer, while a runtime without a worker surface reports a manual drain instead of claiming a queued job; #2139.) The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). The sync delete loop is interleaved per-batch resolve+delete using `engine.resolveSlugsByPaths` + `engine.deletePages` from `src/core/engine.ts` (73K-delete commit: ~146K SQL round-trips → ~292, closing the cascade-staleness class where one big-delete commit jammed every other source's sync); per-batch try-catch decomposes batch DELETE failures to per-slug `deletePage` fallback, unrecoverable per-slug failures land in `failedFiles`; `pagesAffected` filters to confirmed-deleted slugs. The rename loop gets the same batched slug-resolve; a rename whose destination is un-syncable folds the source path into the delete set so the old page can't orphan (#1970). An entry-time bookmark-reachability guard distinguishes a gc'd anchor (`cat-file` fails → `performFullSync`) from a history-rewrite anchor that is merely no-longer-an-ancestor but still on disk: the latter is diffed tree-to-tree directly (`git diff lastCommit..pin` is an endpoint-tree compare, ancestry not required) so a force-push / `master`→`main` consolidation imports only the real delta instead of re-walking the whole tree forever (#1970); an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it purges file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists, sparing `put_page`/manual pages (null `source_path`) and metafiles. The stale-file decision routes through the pure, exported `planReconcileDeletes(rows, currentFiles, isSyncablePath)`: it normalizes path separators on both sides of the membership test (a Windows `path.relative` backslash path vs a git-derived forward-slash `source_path` would otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more than `MASS_RECONCILE_RATIO` (50%) of the file-backed pages the strategy manages, on a source holding more than `MASS_RECONCILE_MIN_PAGES` (20) of them, the delete is REFUSED with a loud stderr warning (that shape is almost always a path-comparison bug or the wrong repo path, not a genuine bulk deletion); `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the unguarded delete for genuinely intended bulk removals. Pinned by `test/sync-reconcile-mass-delete.test.ts`. Below the valve, stale pages are partitioned by git history via exported `listEverCommittedPaths(repoPath)` (one `git log --all --no-renames --diff-filter=A --name-only` pass; null on non-git dirs → unchanged behavior): a stale path that EVER existed in history was genuinely deleted → reconciled; a path with NO history is DB-only write-through (never committed/pushed, e.g. lost to a fresh clone) → the page is KEPT and its markdown re-exported to the working tree via `writePageThrough`, with a stderr hint to commit it (#2426 — "absent from git" is the symptom of the missing write-through commit, not evidence the content is disposable). Pinned by `test/sync-reconcile-db-only.serial.test.ts`. `resolveSlugByPathOrSourcePath` at `sync.ts:267` delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The cost gate is the shared `runInlineCostGate` (one implementation on BOTH the `--all` and single-source paths; runs at the command layer, never inside `performSync`), mode-aware via `resolveWorkerBackedSyncEmbedMode` + posture-aware `shouldBlockSync` from `src/core/embedding.ts` (#2139). The DEFERRED path (v2 on, explicitly Postgres/worker-backed, and not `--serial`; source count controls fan-out only) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog + queued-job count, NEVER exits 2). The INLINE path (v2 off, `--serial`, or PGLite/unknown engine) gates on the DELTA estimate vs `sync.cost_gate_min_usd` (default $0.50): below floor proceeds; above floor in a TTY prompts `[y/N]`; above floor in a non-TTY/`--json` session auto-defers only when a worker-backed queue is actually available. Without that worker surface it exits 0 without wedging import convergence, writes no queue row, reports `manual_drain_required` with reason `no_worker_surface`, and emits one exact `gbrain embed --stale --source <id>` command per source; a worker-backed runtime with `--no-auto-embed` reports the distinct `auto_submit_disabled` policy reason without denying queue capability; intrinsic >100-file incremental deferral reaches the same final manual outcome on no-worker runtimes; `spend.posture=tokenmax` makes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree: `estimateInlineNewTokens` routes through the shared `computeSyncDelta` (`src/core/sync-delta.ts`) — fetch-first against `origin/<branch>`, prices only the committed delta (a dirty-but-caught-up tree → $0), with a full-tree CEILING only on the fail-open rungs (chunker drift, first sync, git-unavailable) honestly labeled; `--full` adds the stale backlog (full sync sweeps it inline). Return shape carries `estimateKind: 'delta'|'ceiling'|'mixed'|'unchanged'` + `ceilingReasons`. Helpers `resolveCostGateFloorUsd(engine)` + `resolveBackfillCapUsd(engine)` resolve via `parseUsdLimit` (`off`/`unlimited` → `Infinity`; floor accepts `0` = block-on-any-spend). JSON envelopes carry `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | manual_drain_required | posture_tokenmax`) + a paste-ready `hint`; terminal single-source and `--all` envelopes carry per-source `embed_backfill` outcomes so machine readers see queued/manual/skipped state; `Infinity` floors/caps render as the string `'unlimited'` (never raw, which JSON-serializes to `null`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). Format splits on the explicit `--json` flag only (human text otherwise). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (serve-delegated sync + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). On a PGLite host brain with a live `gbrain serve`, the cli.ts pre-connect hook routes `gbrain sync` through `src/commands/sync-delegate.ts` (delegation over the resolve-IPC socket; default-deny flag gate; 1s status polls; Ctrl-C → `sync_abort`; embeds always deferred to the serve's drain) — `SyncOpts.onProgress` is the seam performSync fires at phase boundaries and checkpoint flushes so the serve-side job record carries live progress; `printSyncResult` is exported for the delegated result path. Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`. Runaway-sync protection: `resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})` resolves a wall-clock hard deadline (precedence `--no-hard-deadline` > `--hard-deadline <s>` > `--timeout <s>`(non-`--all`, which auto-arms the backstop) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none; `HARD_DEADLINE_GRACE_SEC=30`). `src/cli.ts` installs the out-of-band watchdog (see `src/core/process-watchdog.ts`) for the sync command BEFORE `connectEngine` and disposes it in the dispatch `finally`, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. `runSync` registers a SIGINT handler that aborts an interrupt `AbortController` composed via `composeAbortSignals(...)` (an `AbortSignal.any` wrapper over the defined signals) with the per-source `--timeout` signal, so Ctrl-C returns a clean `partial` and releases the lock through the normal `finally` (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). `withRefreshingLock` `unref()`s its refresh `setInterval`. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing `[gbrain phase]` breadcrumbs are the diagnosis surface. Pinned by `test/sync-hard-deadline.test.ts` (resolution precedence + `composeAbortSignals`). Monorepo subdir sources (#753/#774): `--src-subpath <dir>` (or a repo path that IS a subdir — auto-discovery via `discoverGitRoot`, i.e. `git rev-parse --show-toplevel`) splits the repo path into `gitContextRoot` (all git ops: pull/diff/rev-parse/cat-file) and `syncScopeRoot` (walk/import/delete/rename scope); scoped syncs use git-root-relative slugs + `source_path` (full sync threads `slugRoot` into `runImport`) so full and incremental agree; NAV-1/NAV-2 realpath containment rejects `../`-traversal and symlinked scopes resolving outside the repo BEFORE any git op, and a per-file realpath guard (`isPathSafe`) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); the full-sync reconcile is scope-restricted so a scoped sync never sweeps out-of-scope pages. `--exclude <glob>` (repeatable) filters scope-relative paths in both full and incremental paths; exclusion never deletes previously-imported pages (conservative, matching the #1433 metafile posture); an all-excluded run warns loudly (NAV-4). A warn-and-continue internal `git pull` failure (non-timeout class — e.g. a local-path origin rejected by `protocol.file.allow=never`) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returns `partial` with `reason: 'pull_failed'` instead of `up_to_date`: `last_commit` AND the `last_sync_at` heartbeat stay frozen (so doctor `sync_freshness` / `sources status` staleness fires), the single-source CLI exits non-zero, `sync --all` exits non-zero if any source hit it (JSON envelope carries the per-source `reason`), and the autopilot cycle's sync phase maps it to `warn`. Timeout-class partials keep their pre-existing exit-0 / phase-`ok` semantics (they converge on retry; a failing pull does not). Pinned by `test/sync-pull-failed-anchor.serial.test.ts`. `resolveSlugByPathOrSourcePath`: Resolves a slug by `pages.source_path` first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to `resolveSlugForPath(path)`. Threaded into all 4 delete/rename call sites (`performSync`'s un-syncable cleanup at ~:531, deletes at ~:603, rename oldSlug at ~:622). Without this, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (the delete path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path. #2849: above the size gate (totalChanges > 100) the deferred link/timeline extraction is DURABLY QUEUED, not just hinted — the defer branch submits an `extract` Minion job `{stale: true, sourceId?, deferred_commit: pin}` keyed `extract-stale:<sourceId|default>:<pin>` (repeat submissions toward the same drained pin coalesce; deliberately NO maxWaiting — an unscoped payload's coalesce filter matches ANY waiting extract job and would silently drop the sweep), `timeout_ms` derived from extract.ts's exported `STALE_TIME_BUDGET_MS` + headroom. The returned row is verified to be a live `{stale:true}` job (waiting/delayed/active) before the log claims "queued"; a finished row occupying the key slot (a prior sweep toward the same pin that completed before this run's pages landed — the checkpoint-resume / blocked-advance re-sync case) triggers a fresh submission under a run-unique key so those pages never strand stale. Submission is best-effort (failure falls back to the hint; pages stay stale + doctor-visible, never mis-stamped). Pinned by `test/sync-deferred-extract-queue.serial.test.ts`.+- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). Six pure-function clusters live in `src/core/sync-{cost-gate,git,anchor,lock,reconcile,status-report}.ts` (see the grouped entry below) and are re-exported through this façade, so the full prior import surface is unchanged. `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; the bare no-source path uses the SAME refreshing lock (#1794 — it was previously a non-refreshing `tryAcquireDbLock`, stealable mid-run during an incident); `SyncOpts.lockId?: string` is the explicit override. The lock refresh AND its health probe route through the DIRECT session pool so Supavisor transaction-pool exhaustion (`EMAXCONNSESSION`) can't kill renewal; takeover is heartbeat-aware (it will NOT steal a holder whose `last_refreshed_at` is within `GBRAIN_LOCK_STEAL_GRACE_SECONDS`, defending an alive-but-starved holder); the import loop yields the event loop every `GBRAIN_SYNC_YIELD_EVERY` files (`setTimeout(0)`, not `setImmediate` — Bun starves the timers phase) so the refresh `setInterval` heartbeat fires mid-import. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths via `appendCompleted` (append-only delta into the `op_checkpoint_paths` child table, migration v115 — one row per path, O(delta) not the old O(N²) full-array rewrite), keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` (paths under `op:'sync'`; the pinned target under `op:'sync-target'`), and advances `last_commit`/`last_sync_at` ONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they survive `EMAXCONNSESSION`; the flush cadence is first-file then every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files OR `GBRAIN_SYNC_CHECKPOINT_SECONDS` (default 10s), with a race-safe `pendingCheckpointPaths` delta (single-flight swap, re-merge on failure) under parallel workers; a SIGTERM banks the in-flight delta via a no-retry one-shot (`appendCompletedOnce`, ordered before lock release through `registerCleanup`); and sustained flush failure aborts the run with `reason:'checkpoint_unavailable'` after `GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES` consecutive fails rather than importing work it can never bank (every partial/blocked exit logs the banked-file count). A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff — this closes the cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) replaces the old strict head-drift gate: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and no longer block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` are scoped per source (`acknowledgeFailures(sourceId)`; `--all` acks every source, single-source acks only its own) and run UNDER parallel — the #1939 failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so the old "not supported under parallel, re-run with --serial" refusal is lifted (#2139, which also removed the forcing-function that pushed recovery syncs to `--serial` and thus armed the inline cost gate); a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count, skipped_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok (sources skipped by `--missing-path skip` count as ok), 1 any error. `--missing-path <fail|skip>` (default fail) handles sources whose `local_path` does not exist on this machine — machine-specific state in a brain-wide table, so a brain registered from several machines fails every foreign source on every run; `skip` classifies them `skipped_missing_path` (⊘ line, envelope entry with `local_path`, excluded from `error_count` and the rc gate) via the exported pure helpers `parseMissingPathMode` + `partitionMissingPathSources`, pinned by `test/sync-all-missing-path.test.ts`; default `fail` stays loud because on a single-machine brain a missing path usually means an unmounted volume. (The non-TTY cost gate no longer exits 2: a worker-backed engine can auto-defer, while a runtime without a worker surface reports a manual drain instead of claiming a queued job; #2139.) The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). The sync delete loop is interleaved per-batch resolve+delete using `engine.resolveSlugsByPaths` + `engine.deletePages` from `src/core/engine.ts` (73K-delete commit: ~146K SQL round-trips → ~292, closing the cascade-staleness class where one big-delete commit jammed every other source's sync); per-batch try-catch decomposes batch DELETE failures to per-slug `deletePage` fallback, unrecoverable per-slug failures land in `failedFiles`; `pagesAffected` filters to confirmed-deleted slugs. The rename loop gets the same batched slug-resolve; a rename whose destination is un-syncable folds the source path into the delete set so the old page can't orphan (#1970). An entry-time bookmark-reachability guard distinguishes a gc'd anchor (`cat-file` fails → `performFullSync`) from a history-rewrite anchor that is merely no-longer-an-ancestor but still on disk: the latter is diffed tree-to-tree directly (`git diff lastCommit..pin` is an endpoint-tree compare, ancestry not required) so a force-push / `master`→`main` consolidation imports only the real delta instead of re-walking the whole tree forever (#1970); an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it purges file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists, sparing `put_page`/manual pages (null `source_path`) and metafiles. The stale-file decision routes through the pure, exported `planReconcileDeletes(rows, currentFiles, isSyncablePath)`: it normalizes path separators on both sides of the membership test (a Windows `path.relative` backslash path vs a git-derived forward-slash `source_path` would otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more than `MASS_RECONCILE_RATIO` (50%) of the file-backed pages the strategy manages, on a source holding more than `MASS_RECONCILE_MIN_PAGES` (20) of them, the delete is REFUSED with a loud stderr warning (that shape is almost always a path-comparison bug or the wrong repo path, not a genuine bulk deletion); `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the unguarded delete for genuinely intended bulk removals. Pinned by `test/sync-reconcile-mass-delete.test.ts`. Below the valve, stale pages are partitioned by git history via exported `listEverCommittedPaths(repoPath)` (one `git log --all --no-renames --diff-filter=A --name-only` pass; null on non-git dirs → unchanged behavior): a stale path that EVER existed in history was genuinely deleted → reconciled; a path with NO history is DB-only write-through (never committed/pushed, e.g. lost to a fresh clone) → the page is KEPT and its markdown re-exported to the working tree via `writePageThrough`, with a stderr hint to commit it (#2426 — "absent from git" is the symptom of the missing write-through commit, not evidence the content is disposable). Pinned by `test/sync-reconcile-db-only.serial.test.ts`. `resolveSlugByPathOrSourcePath` (moved to `src/core/sync-git.ts` — see its dedicated entry below) delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping the legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The cost gate is the shared `runInlineCostGate` (one implementation on BOTH the `--all` and single-source paths; runs at the command layer, never inside `performSync`), mode-aware via `resolveWorkerBackedSyncEmbedMode` + posture-aware `shouldBlockSync` from `src/core/embedding.ts` (#2139). The DEFERRED path (v2 on, explicitly Postgres/worker-backed, and not `--serial`; source count controls fan-out only) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog + queued-job count, NEVER exits 2). The INLINE path (v2 off, `--serial`, or PGLite/unknown engine) gates on the DELTA estimate vs `sync.cost_gate_min_usd` (default $0.50): below floor proceeds; above floor in a TTY prompts `[y/N]`; above floor in a non-TTY/`--json` session auto-defers only when a worker-backed queue is actually available. Without that worker surface it exits 0 without wedging import convergence, writes no queue row, reports `manual_drain_required` with reason `no_worker_surface`, and emits one exact `gbrain embed --stale --source <id>` command per source; a worker-backed runtime with `--no-auto-embed` reports the distinct `auto_submit_disabled` policy reason without denying queue capability; intrinsic >100-file incremental deferral reaches the same final manual outcome on no-worker runtimes; `spend.posture=tokenmax` makes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree: `estimateInlineNewTokens` routes through the shared `computeSyncDelta` (`src/core/sync-delta.ts`) — fetch-first against `origin/<branch>`, prices only the committed delta (a dirty-but-caught-up tree → $0), with a full-tree CEILING only on the fail-open rungs (chunker drift, first sync, git-unavailable) honestly labeled; `--full` adds the stale backlog (full sync sweeps it inline). Return shape carries `estimateKind: 'delta'|'ceiling'|'mixed'|'unchanged'` + `ceilingReasons`. Helpers `resolveCostGateFloorUsd(engine)` + `resolveBackfillCapUsd(engine)` resolve via `parseUsdLimit` (`off`/`unlimited` → `Infinity`; floor accepts `0` = block-on-any-spend). JSON envelopes carry `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | manual_drain_required | posture_tokenmax`) + a paste-ready `hint`; terminal single-source and `--all` envelopes carry per-source `embed_backfill` outcomes so machine readers see queued/manual/skipped state; `Infinity` floors/caps render as the string `'unlimited'` (never raw, which JSON-serializes to `null`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). Format splits on the explicit `--json` flag only (human text otherwise). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (serve-delegated sync + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). On a PGLite host brain with a live `gbrain serve`, the cli.ts pre-connect hook routes `gbrain sync` through `src/commands/sync-delegate.ts` (delegation over the resolve-IPC socket; default-deny flag gate; 1s status polls; Ctrl-C → `sync_abort`; embeds always deferred to the serve's drain) — `SyncOpts.onProgress` is the seam performSync fires at phase boundaries and checkpoint flushes so the serve-side job record carries live progress; `printSyncResult` is exported for the delegated result path. Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`. Runaway-sync protection: `resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})` resolves a wall-clock hard deadline (precedence `--no-hard-deadline` > `--hard-deadline <s>` > `--timeout <s>`(non-`--all`, which auto-arms the backstop) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none; `HARD_DEADLINE_GRACE_SEC=30`). `src/cli.ts` installs the out-of-band watchdog (see `src/core/process-watchdog.ts`) for the sync command BEFORE `connectEngine` and disposes it in the dispatch `finally`, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. `runSync` registers a SIGINT handler that aborts an interrupt `AbortController` composed via `composeAbortSignals(...)` (an `AbortSignal.any` wrapper over the defined signals) with the per-source `--timeout` signal, so Ctrl-C returns a clean `partial` and releases the lock through the normal `finally` (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). `withRefreshingLock` `unref()`s its refresh `setInterval`. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing `[gbrain phase]` breadcrumbs are the diagnosis surface. Pinned by `test/sync-hard-deadline.test.ts` (resolution precedence + `composeAbortSignals`). Monorepo subdir sources (#753/#774): `--src-subpath <dir>` (or a repo path that IS a subdir — auto-discovery via `discoverGitRoot`, i.e. `git rev-parse --show-toplevel`) splits the repo path into `gitContextRoot` (all git ops: pull/diff/rev-parse/cat-file) and `syncScopeRoot` (walk/import/delete/rename scope); scoped syncs use git-root-relative slugs + `source_path` (full sync threads `slugRoot` into `runImport`) so full and incremental agree; NAV-1/NAV-2 realpath containment rejects `../`-traversal and symlinked scopes resolving outside the repo BEFORE any git op, and a per-file realpath guard (`isPathSafe`) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); the full-sync reconcile is scope-restricted so a scoped sync never sweeps out-of-scope pages. `--exclude <glob>` (repeatable) filters scope-relative paths in both full and incremental paths; exclusion never deletes previously-imported pages (conservative, matching the #1433 metafile posture); an all-excluded run warns loudly (NAV-4). A warn-and-continue internal `git pull` failure (non-timeout class — e.g. a local-path origin rejected by `protocol.file.allow=never`) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returns `partial` with `reason: 'pull_failed'` instead of `up_to_date`: `last_commit` AND the `last_sync_at` heartbeat stay frozen (so doctor `sync_freshness` / `sources status` staleness fires), the single-source CLI exits non-zero, `sync --all` exits non-zero if any source hit it (JSON envelope carries the per-source `reason`), and the autopilot cycle's sync phase maps it to `warn`. Timeout-class partials keep their pre-existing exit-0 / phase-`ok` semantics (they converge on retry; a failing pull does not). Pinned by `test/sync-pull-failed-anchor.serial.test.ts`. `resolveSlugByPathOrSourcePath` is threaded into all 4 delete/rename call sites — see its dedicated `src/core/sync-git.ts` entry below for the resolution contract. #2849: above the size gate (totalChanges > 100) the deferred link/timeline extraction is DURABLY QUEUED, not just hinted — the defer branch submits an `extract` Minion job `{stale: true, sourceId?, deferred_commit: pin}` keyed `extract-stale:<sourceId|default>:<pin>` (repeat submissions toward the same drained pin coalesce; deliberately NO maxWaiting — an unscoped payload's coalesce filter matches ANY waiting extract job and would silently drop the sweep), `timeout_ms` derived from extract.ts's exported `STALE_TIME_BUDGET_MS` + headroom. The returned row is verified to be a live `{stale:true}` job (waiting/delayed/active) before the log claims "queued"; a finished row occupying the key slot (a prior sweep toward the same pin that completed before this run's pages landed — the checkpoint-resume / blocked-advance re-sync case) triggers a fresh submission under a run-unique key so those pages never strand stale. Submission is best-effort (failure falls back to the hint; pages stay stale + doctor-visible, never mis-stamped). Pinned by `test/sync-deferred-extract-queue.serial.test.ts`.+- `src/core/sync-git.ts:resolveSlugByPathOrSourcePath` — Resolves a slug by `pages.source_path` first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to `resolveSlugForPath(path)`. Three call sites: the un-syncable cleanup (which passes `opts.sourceId`), and the bare no-`sourceId` delete and rename-source paths; when `sourceId` IS set the delete and rename loops batch through `engine.resolveSlugsByPaths` instead. The `source_path` lookup is scoped to the DEFAULT source on the bare path, matching every write that path performs (`updateSlug`, `deletePage`, the rename bookkeeping repair are all default-scoped) — an unscoped lookup could return a row from another source sharing the `source_path`, and the rename loop consumes this value directly as its cheap-move source slug. Without the helper, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (that path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path.- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`.- `src/core/utils.ts` — Shared SQL utilities extracted from postgres-engine.ts. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated; replaces bare `catch {}` blocks in `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback. `validateSourceId(id)` throws on anything outside `^[a-z0-9_-]+$`, used by the per-source disk-layout fix in patterns.ts/synthesize.ts before any `join(brainDir, '.sources', source_id, slug+'.md')` so source_id can't traverse out of brainDir. `rowToSearchResult` projects email `message_id` / `thread_id` metadata and exposes `source_subject` only when a non-empty Message-ID proves the page is an email, so generated page titles never become authoritative email subjects. `rowToPage` populates the required `Page.source_id` from the SELECT projection (`scripts/check-source-id-projection.sh` enforces every projection feeding `rowToPage` includes the column).- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect()` returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` (#1972) — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the #2084 contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`.@@ -61,7 +62,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent`'s tag reconciliation is ADD-ONLY: it only `addTag` (idempotent, ON CONFLICT DO NOTHING). The `tags` table has no provenance column and frontmatter tags are stripped from stored `pages.frontmatter` (markdown.ts:118), so a frontmatter-origin tag can't be distinguished from a DB-enrichment tag (auto-tag / dream synthesize / signal-detector) at re-import — deletion is unsafe (would wipe enrichment under `gbrain reindex --markdown`). Accepted trade-off: removing a tag from frontmatter no longer removes it from the DB on next sync (needs a `tag_source` provenance column). Pinned by `test/reindex-preserve-tags.test.ts` + `test/import-file.test.ts`. identity-based dedup pre-check at `:427-490`. Calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId})` (optional `?` so test doubles compile). Posture: SKIP when `frontmatter.id` matches (true external duplicate from overlapping ingest roots), WARN-ALWAYS on content_hash collision with different/missing `frontmatter.id` (templates and daily logs may legitimately share text), FAIL CLOSED on lookup error, bypass via `--force-rechunk`. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Pinned by `test/import-dedup-frontmatter-id.test.ts` (11 cases). `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (#2576; existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`.- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so naive walkers slipped through and inflated MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (#2404; the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files (closes #923 + #202). `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering (closes #889). The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the four canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row imported by a pre-gate release survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The `commands/sync.ts` cleanup loop guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` (#2404) so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.serial.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Closes the phantom-import bug class where syncing a worktree-with-submodules walked into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`.- `src/core/sync-failure-ledger.ts` — the bounded auto-skip sync failure ledger (issue #1939; formerly inline "Bug 9" in `sync.ts`). A LEAF module (imports only fs/path/crypto/config) so `sync.ts` can re-export it without a circular dependency. State lives in `~/.gbrain/sync-failures.jsonl`, one JSON object per line, keyed by `(source_id, path)` with a per-key `attempts` count and a 3-state machine: `open` (fresh/blocking) → `auto_skipped` (chronic, still doctor-visible) or `acknowledged` (human resolved via `gbrain sync --skip-failed` from either unresolved state). `classifyErrorCode(errorMsg)` regex classifier with 12 codes (`SLUG_MISMATCH`, `YAML_PARSE`, `YAML_DUPLICATE_KEY`, `MISSING_OPEN`, `MISSING_CLOSE`, `NESTED_QUOTES`, `EMPTY_FRONTMATTER`, `NULL_BYTES`, `INVALID_UTF8`, `STATEMENT_TIMEOUT`, `FILE_TOO_LARGE`, `SYMLINK_NOT_ALLOWED`) plus `UNKNOWN` (also recognizes `PAGE_JUNK_PATTERN` from the content-sanity gate); `summarizeFailuresByCode(failures)` returns sorted `[{code, count}]`; `MISSING_OPEN`/`MISSING_CLOSE`/`EMPTY_FRONTMATTER` regexes match the `markdown.ts` validator strings, `FILE_TOO_LARGE` covers `import-file.ts:199, 352, 401`, `SYMLINK_NOT_ALLOWED` covers `:347`. All mutations run under `withLedgerLock` (cross-process file lock) with an atomic rename write. The auto-skip threshold resolves via `resolveAutoSkipThreshold()` from `GBRAIN_SYNC_AUTOSKIP_AFTER` (default `DEFAULT_AUTOSKIP_AFTER = 3`; `0` disables the valve = pure fail-closed). Two pure decision functions are the unit-test surface: `decideGateAction({fileFailures, sentinels, attemptsByPath, threshold, skipFailed})` returns `hard_block | block | advance | advance_then_autoskip` (sentinels like `<head>` ALWAYS hard-block, even with `--skip-failed`, so a history rewrite can't auto-skip; any FRESH failure with `attempts < threshold` blocks fail-closed; only when ALL failures are chronic does it `advance_then_autoskip`), and `decideSyncFailureSeverity({entries, nowMs, failHours})` returns the `sync_failures` doctor status (`ok` when zero unresolved; `fail` when ≥10 OPEN-blocking or the oldest OPEN failure has blocked the bookmark past `failHours`; otherwise `warn` — `auto_skipped`-only rows stay WARN-visible regardless of count because the bookmark already advanced). `applySyncFailureGate(input)` is the one orchestrator BOTH sync paths (incremental + full/`runImport`) call: it records/clears ledger rows, runs `decideGateAction`, then executes effects in the crash-safe order (advance the bookmark FIRST via the injected `advance()` callback, THEN auto-skip the chronic set) so a crash can never mark a file skipped while leaving sync wedged. `isSkippablePath` rejects `<…>` sentinels. Pinned by `test/sync-failure-ledger.serial.test.ts` + `test/sync-failures.test.ts`.-- `src/core/sync-cost-gate.ts` + `sync-git.ts` + `sync-anchor.ts` + `sync-lock.ts` + `sync-reconcile.ts` + `sync-status-report.ts` — six pure-function clusters relocated out of `src/commands/sync.ts` as a pure move; the façade re-exports them, and `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps exactly these six (NOT the pre-existing `sync-*` siblings, which are ordinary deps) on the sync command's flag-scan surface. `sync-cost-gate.ts`: the inline-embed cost gate + token estimation for `gbrain sync`. `sync-git.ts`: git plumbing — invocation building, repo discovery, baseline-commit self-heal, path-containment guards. `sync-anchor.ts`: sync anchor + chunker-version state helpers (source-scoped vs legacy global-config storage). `sync-lock.ts`: the lock layer — typed lock-busy error, the rich busy message, `--break-lock` handling, the partial-result envelope (`performSync` itself stays in the façade). `sync-reconcile.ts`: full-sync reconcile planning (the mass-delete valve and ever-committed gate) + sync deadline/stall resolution. `sync-status-report.ts`: the per-source sync status report backing `gbrain sources status` and the `get_status_snapshot` op. Its queue context is engine-aware: only an explicitly worker-backed surface may promise job deferral; otherwise non-interactive cost deferral returns `manual_drain_required` with exact per-source `gbrain embed --stale --source <id>` commands and never writes or claims an embed-backfill row.+- `src/core/sync-cost-gate.ts` + `sync-git.ts` + `sync-anchor.ts` + `sync-lock.ts` + `sync-reconcile.ts` + `sync-status-report.ts` — six pure-function clusters relocated out of `src/commands/sync.ts` as a pure move; the façade re-exports them, and `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps exactly these six (NOT the pre-existing `sync-*` siblings, which are ordinary deps) on the sync command's flag-scan surface. `sync-cost-gate.ts`: the inline-embed cost gate + token estimation for `gbrain sync`. `sync-git.ts`: git plumbing — invocation building, repo discovery, baseline-commit self-heal, path-containment guards, and the delete/rename slug resolvers (`resolveSlugByPathOrSourcePath` — see its dedicated entry above — plus the #3942 verified `resolveSlugsForRemovedPaths`/`resolveRemovedPathSlug`). `sync-anchor.ts`: sync anchor + chunker-version state helpers (source-scoped vs legacy global-config storage). `sync-lock.ts`: the lock layer — typed lock-busy error, the rich busy message, `--break-lock` handling, the partial-result envelope (`performSync` itself stays in the façade). `sync-reconcile.ts`: full-sync reconcile planning (the mass-delete valve and ever-committed gate) + sync deadline/stall resolution. `sync-status-report.ts`: the per-source sync status report backing `gbrain sources status` and the `get_status_snapshot` op. Its queue context is engine-aware: only an explicitly worker-backed surface may promise job deferral; otherwise non-interactive cost deferral returns `manual_drain_required` with exact per-source `gbrain embed --stale --source <id>` commands and never writes or claims an embed-backfill row.- `src/core/sync-embed-backfill.ts` — Sync command’s engine-aware embedding-delivery seam. It derives separate worker-backed deferral and multi-source fan-out eligibility, keeps automatic-submission policy distinct from capability, invokes the shared cost gate for `--all` and single-source runs, propagates intrinsic large-sync deferral into final delivery outcomes, resolves backfill results through the centralized submitter, formats one truthful human status, and builds the single-source JSON envelope. Keeping these pieces together prevents cost-gate, queue, human, and machine surfaces from drifting while the size-ratcheted `src/commands/sync.ts` façade stays at its committed ceiling.- `src/core/storage.ts` — Pluggable storage interface (S3, Supabase Storage, local).- `src/core/storage-config.ts` — Storage tiering: `loadStorageConfig` reads `gbrain.yml`, normalizes deprecated keys (`git_tracked`/`supabase_only`) to canonical (`db_tracked`/`db_only`) with once-per-process deprecation warning, and runs `normalizeAndValidateStorageConfig` (auto-fixes missing trailing `/`, throws `StorageConfigError` on tier overlap). Path-segment matcher: `media/x/` does NOT match `media/xerox/foo`. Uses a dedicated parser for the `gbrain.yml` shape rather than gray-matter (broken on delimiter-less YAML). Also carries `DERIVE_PHASE_DB_ONLY_DEFAULTS` (`life/events/`, `atoms/`, `extracts/`, `dream-cycle-summaries/`) + `effectiveDbOnlyDirs` — the engine's derive-phase output prefixes treated as implicitly-declared db_only by the `undeclared_db_only_pages` doctor check but deliberately NOT merged into `loadStorageConfig` (a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them, the #2788 class) — and `findDbOnlyCollisions` (pure collector-output vs db_only overlap detector shared by the `db_only_collector_collision` doctor check and sync's `manageGitignore` warning). Pinned by `test/storage-config.test.ts` + `test/doctor-silent-death-checks.test.ts`.@@ -92,6 +93,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/reindex-multimodal.ts` — `gbrain reindex --multimodal [--limit N] [--dry-run] [--cost-estimate] [--no-embed] [--yes] [--json]`. Walks `content_chunks WHERE embedding_multimodal IS NULL`, batches via `embedMultimodalSafe` (partial-failure-aware), persists. Lock via `tryAcquireDbLock` (360min) so a concurrent autopilot embed phase can't race it. Cost prompt + Ctrl-C grace window in TTY. `GBRAIN_NO_REEMBED=1` bypass. Checkpoint at `~/.gbrain/reindex-multimodal-checkpoint.json` for resume. Auto-flip prompt at coverage=100% completion (TTY: interactive; non-TTY: stderr hint with a paste-ready command).- `src/core/backfill-registry.ts` — registry of idempotent data backfills. The `modality` backfill flips `modality` to `'image'` on image-asset chunks the ingest path missed; its SQL filter requires `chunk_source='image_asset'` AND `embedding_image IS NOT NULL` AND `(modality IS NULL OR modality != 'image')` — the `chunk_source` guard ensures a non-image chunk that happens to have `embedding_image` populated is never flagged. A second run finds zero rows.- `src/core/search/eval.ts` — Retrieval eval harness: P@k, R@k, MRR, nDCG@k metrics + runEval() orchestrator.+- `src/core/eval/ranked-docs.ts` (#4176) — dependency-free page-level ranking primitive shared by the retrieval eval harness, NamedThingBench, and the qrels correctness gate. `dedupeRankedKeys()` preserves the first/best occurrence of each `${source_id}::${slug}` or slug key before any cutoff, so repeated chunks neither inflate relevance gain nor consume document ranks. Precision retains its fixed-`k` denominator; Recall and nDCG are structurally bounded to `[0,1]`. Pinned across `test/eval.test.ts`, `test/retrieval-quality-harness.test.ts`, `test/bench/qrels-file.test.ts`, and `test/bench/correctness-gate.test.ts`.- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap` and `resolveHardExcludes` merge defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which let a page lose to a neighbor on ONE weak chunk while its strong chunk sat just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.- `src/core/search/title-match.ts` — pure, zero-I/O title-phrase matcher shared by the production title boost AND NamedThingBench (no drift). `isTitlePhraseMatch(query, title)` returns true when the normalized query is a contiguous token run inside the title with `>= MIN_CONTENT_TOKENS=2` non-stopword tokens, OR an exact full-title match (covers deliberate 1-word chosen names like "Helios"). Token-boundary matching (never raw substring, so "art" doesn't match "Bartholomew"); small conservative English stopword set excluded from the content-token floor (guards against promoting generic pages on stopword-y queries); NFKC normalize so CJK / width variants converge. Exports `tokenizeTitle` + `__test__` internals.@@ -109,8 +111,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/eval-cross-modal.ts` — multi-model quality gate. Three different-provider frontier models score the OUTPUT against the TASK on a 5-dim list. Verdict `pass` (exit 0) / `fail` (exit 1) / `inconclusive` (exit 2; <2/3 model successes). Reuses `src/core/ai/gateway.ts:chat()` so config/auth/aliasing comes from the gateway recipe registry — no parallel provider stack. Self-configures the gateway (`configureGateway(loadConfig() + process.env)`) since the cli.ts dispatch bypasses `connectEngine()`. Default cycles 3 in TTY, 1 in non-TTY (partial cost guardrail) via the shared `resolveCycleDefault(explicit, isTty)` in `src/core/eval/cycle-default.ts`; the cost-estimate banner appends `cycleDefaultSuffix(...)` (`for 1 cycle(s) (non-interactive default; --cycles N for more)`) when the value is the silent non-TTY fallback, so the 1-vs-3 difference isn't hidden. Receipts land at `gbrainPath('eval-receipts')/<slug>-<sha8-of-output>.json`. `--batch <jsonl> [--limit N] [--concurrent N] [--max-usd FLOAT] [--yes]` fans out cross-modal scoring across a LongMemEval-shape JSONL; mutually exclusive with `--task` (fail-fast usage error if both set); filters `kind: "by_type_summary"` rows; pre-flight cost estimate refuses if `> --max-usd` without `--yes` (default cap 5.00 USD). Semaphore-bounded fan-out via inline `runWithLimit<T>(items, limit, fn)` (exported for unit tests): max N questions in-flight × 3 model slots = ceiling of 3N parallel API calls (default `--concurrent 3` → 9). Per-question receipts land in a per-batch tempdir and are deleted at end of run; the summary receipt inlines per-question verdicts as JSON, not file paths. Exit precedence (batch-level policy, NOT inherited from aggregate.ts): ERROR > FAIL > INCONCLUSIVE > PASS. DI seam: `runEvalCrossModal(args, opts?: {runEval?: typeof runEval})` mirrors `runEvalLongMemEval(args, {client?})`; tests pass `opts.runEval` to bypass real LLM calls AND the gateway availability check. Pinned by `test/eval-cross-modal-batch.test.ts`.- `src/core/eval/cycle-default.ts` — single source of truth for the eval cycle-count default. Exports `DEFAULT_CYCLES_TTY = 3`, `DEFAULT_CYCLES_NONTTY = 1`, `resolveCycleDefault(explicit, isTty): {cycles, usedNonTtyDefault}`, and `cycleDefaultSuffix(r)` (returns ` (non-interactive default; --cycles N for more)` only when the non-TTY default was applied, else `''`). Consumed by `eval-cross-modal.ts`, `eval-takes-quality.ts` (run + regress), and `takes-quality-eval/runner.ts` (core uses only the constant — library stays TTY-agnostic; the CLI owns the TTY=3 upgrade + banner annotation). `eval-suspected-contradictions.ts` applies the same transparency to its `$5`/`$1` budget default via a `budgetUsdExplicit` flag (the budget is overwritten in-place so explicitness can't be inferred post-hoc). Not shared with `resolveWorkersWithClamp` (different domain, no engine, no dedup). Pinned by `test/eval/cycle-default.test.ts`, `test/eval-suspected-contradictions-budget-default.test.ts`.- `src/core/cross-modal-eval/json-repair.ts` — `parseModelJSON(raw)` named export with a 4-strategy fallback chain (direct parse → fence-strip → trailing-comma + single-quote + embedded-newline repair → regex nuclear option). Adversarial input throws rather than fabricating scores — the aggregator treats a throw as "this model contributed nothing this cycle" so the gate stays correct at >=2/3 successes.-- `src/core/cross-modal-eval/aggregate.ts` — pure verdict logic. Pass criterion: `(successes >= 2) AND (every dim mean >= 7) AND (every dim min across models >= 5)`. Inconclusive when <2/3 models returned parseable scores (regression guard for the v1 `Object.values({}).every(...) === true` empty-array PASS bug).-- `src/core/cross-modal-eval/runner.ts` — orchestrator. Each cycle runs `Promise.allSettled([gwChat(slotA), gwChat(slotB), gwChat(slotC)])` (bare allSettled, no rate-leases for the CLI path). Stops early on PASS or INCONCLUSIVE; runs up to 3 cycles. Default slots: `openai:gpt-5.2` / `anthropic:claude-opus-4-7` / `deepseek:deepseek-v4-pro`. `estimateCost()` prices via the canonical model-pricing table; `test/cross-modal-default-slots.test.ts` pins recipe support, pricing coverage, and three distinct providers.+- `src/core/cross-modal-eval/aggregate.ts` — pure verdict logic. Judge dimension keys are normalized with trim + lowercase before cross-model roll-up, so `CORRECTNESS` and `correctness` cannot split into separate one-model dimensions. Pass criterion: `(successes >= 2) AND (every dim mean >= 7) AND (every dim min across models >= 5)`. Inconclusive when <2/3 models returned parseable scores (regression guard for the v1 `Object.values({}).every(...) === true` empty-array PASS bug).+- `src/core/cross-modal-eval/runner.ts` — orchestrator. The judge prompt pins the exact `scores` JSON keys per dimension (`dimensionScoreKey` = the label before the em-dash) so judges cannot invent spellings; aggregate.ts's normalization is the backstop. Each cycle runs `Promise.allSettled([gwChat(slotA), gwChat(slotB), gwChat(slotC)])` (bare allSettled, no rate-leases for the CLI path). Stops early on PASS or INCONCLUSIVE; runs up to 3 cycles. Default slots: `openai:gpt-5.2` / `anthropic:claude-opus-4-7` / `deepseek:deepseek-v4-pro`. `estimateCost()` prices via the canonical model-pricing table; `test/cross-modal-default-slots.test.ts` pins recipe support, pricing coverage, and three distinct providers.- `src/core/cross-modal-eval/receipt-name.ts` — receipt filename binds (slug, SKILL.md sha-8). `findReceiptForSkill(skillPath, receiptDir)` returns `'found' | 'stale' | 'missing'`. Skillify-check surfaces the status as informational; the audit does NOT fail on missing/stale receipts.- `src/core/cross-modal-eval/receipt-write.ts` — wraps `fs.writeFileSync` with `mkdirSync({recursive:true})` ahead of every write (`gbrainPath()` does NOT auto-mkdir).- `src/commands/eval-export.ts` — streams `eval_candidates` rows as NDJSON to stdout with `schema_version: 1` prefix on every line. EPIPE-safe, progress heartbeats on stderr, stable id-desc tiebreaker so `--since` windows never dupe/miss rows.@@ -298,7 +300,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (15-name allow-list, size pinned by `test/brain-allowlist.serial.test.ts`). Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trust comes from `PROTECTED_JOB_NAMES` gating subagent submission (MCP cannot reach this field); only cycle.ts (synthesize/patterns) and direct CLI submitters set it. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param).- `src/mcp/tool-defs.ts` — `buildToolDefs(ops, opts?)` helper; the stdio MCP server, the OAuth HTTP `tools/list` (WP3 amendment 14 unified the former inline mapper onto it), and the subagent tool registry all consume it, byte-for-byte equivalence pinned by `test/mcp-tool-defs.test.ts`. Default emission is byte-identical to the pre-WP3 output; `opts.strictParams: true` (when `mcp.strict_params` resolves `'reject'`) additionally declares the `_meta`/`dry_run` passthrough keys in `properties` and closes each schema with `additionalProperties: false` (D14.1 — schema-validating clients must not strip `_meta.session_id`); both emission states pinned. Exports the recursive `paramDefToSchema(p: ParamDef)` — single source of truth for ParamDef→JSON Schema mapping shared by `buildToolDefs` and `src/core/minions/tools/brain-allowlist.ts` (subagent registry). Recursive on `items` so nested array-of-arrays preserves inner shape on the wire. Key ordering (type, description, enum, default, items) is intentional so `JSON.stringify` output stays byte-stable. `test/mcp-tool-defs.test.ts` has a `findArrayWithoutItems` walker that fails on any `type: 'array'` lacking `items.type`.- `src/core/verbs.ts` — MEMORY_VERBS v1 (Cathedral 1): the four new frozen protocol verbs (`remember`, `entity`, `synthesize`, `forget`) as first-class Operations, plus `MEMORY_VERBS_VERSION` (single source of truth, =1), `VERB_NAMES`, the hand-authored `RESPONSE_SCHEMAS` registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and `ERROR_SCHEMA`. The fifth verb is the extended `recall` op in operations.ts. RUNTIME LEAF invariant: operations.ts spreads `verbOperations` into its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it reintroduces a TDZ crash on whichever module evaluates second. Every verb error carries a populated `suggestion` + `protocol_version` (via `verbError` in operations.ts). The `forget` verb deliberately has NO cliHints (CLI_ONLY `forget` dispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.test.ts.-- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote})`: the zero-LLM sub-100ms card behind the `entity` verb. Resolution reuses the Retrieval Reflex arms (alias > exact title/slug > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs); ties break on GREATEST(updated_at, last_retrieved_at). Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints.+- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote})`: the zero-LLM sub-100ms card behind the `entity` verb. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, canonical entity types (`person`, `company`, `organization`, `entity`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints.- `src/core/verbs/usage-log.ts` — E4 observability sidecar: one JSONL line per verb call at `~/.gbrain/integrations/memory-verbs/usage.jsonl` (gbrainPath — GBRAIN_HOME honored; `brainId()` = the resolved gbrain home). LOCAL ONLY, never uploaded, stats-only (lock-free 10MB rotation may drop lines; O_APPEND line-atomic, best-effort on Windows). `logVerbUsage` is fire-and-forget (never awaited, never throws); written from the DISPATCH layer so param-validation failures count. `readVerbUsage`/`earliestVerbUsageTs` feed `gbrain protocol stats` (incl. measured TTHW vs the init-stamped `protocol_installed_at`) and the doctor `memory_verbs_usage` check.- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember` [E1]. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession [X1]: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + forgetFactInFence(old) + superseded_by link; DB path: engine insertFact supersedeId). Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented).@@ -322,7 +324,7 @@ v0.46: the `sync` handler forwards `job.data.github_item` ({repo, number, kind})- `src/core/mcp-usage.ts` — `readClientOpUsage(engine, {days})`: the ONE shared reader over `mcp_request_log` (amendment 30), consumed by `gbrain auth clients --usage` (E4), the advisor `mcp-client-fit` collector (E3), and `scripts/derive-starter-ops.ts`. Encodes the row-hygiene rules once (`normalizeLoggedOperation`): JSON-RPC method rows (`tools/list`, `initialize`, …) and `surface_change` audit rows drop; the legacy `tools/call:<name>` prefix strips to the op name, and the hygiene check re-runs on the stripped name (`tools/call:tools/list` is still not an op call). Only `status IN ('success','success_with_warnings')` rows count as usage — denied or erroring traffic cannot "use" its way into starter derivation or advisor fit findings. Windows on `created_at` (rides `idx_mcp_log_time_agent`); plain SQL through `engine.executeRaw`, both engines. D12 behavioral automation classification: `likely_automation` = >90% of calls are `context_pack`/`delta` boundary verbs (the hook lane is stdio and never logs, so there is no name convention to key on). Sees HTTP clients ONLY — stdio never writes the log. Pinned by test/mcp-usage.test.ts.- `docs/protocol/MCP_META_CHANNELS.md` — normative `_meta` conventions for MCP tool responses: one producer per top-level key, additive-forever within a key, producer isolation, and the registered-keys table (`brain_hot_memory`, `retrieval`, `warnings`). Anything the model must SEE rides a content block (mainstream harnesses don't feed `_meta` to the model); `_meta` serves structured consumers. Add a key by registering it in the table — one producer, additive-forever.- `src/mcp/rate-limit.ts` — Bounded-LRU token-bucket limiter. `buildDefaultLimiters()` returns the two-bucket pipeline: pre-auth IP (30/60s, fires BEFORE the DB lookup so brute-force load against `access_tokens` is capped) + post-auth token-id (60/60s). Tracks `lastTouchedMs` separately from `lastRefillMs` so an exhausted key can't be reset by hammering past the TTL. LRU cap bounds memory under attacker-controlled key growth. `refund(key)` returns one consumed token (capped at the limit) — the `request_tools` persist path refunds when a race-lost 0-row UPDATE (concurrent operator pin) means no write actually happened; dry-run previews never draw a token at all (the limiter meters actual writes only).-- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and `express-rate-limit` at 50 req / 15 min on `/token`. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard at `operations.ts:1391` saw a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs — RCE). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(sql, engineName, version, timeoutMs)` racing `sql\`SELECT 1\`` against the exported `HEALTH_TIMEOUT_MS = 3000` (returns the same `ProbeHealthResult` tagged-union as `probeHealth`, single timer-cleanup site, single 503 envelope); body shape `{status, version, engine}` only. Full stats moved to admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. Every OAuth/admin/audit SQL call routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the resolved write source joins the queue idempotency key so a rescoped client lands a new capture instead of deduping against its old job. confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the WP1 honest catalog: per-request filters (token scope incl. the FOV-4 `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count` (amendment 23 stopgap). Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (amendment 33/D10; the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client).+- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and `express-rate-limit` at 50 req / 15 min on `/token`. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard at `operations.ts:1391` saw a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs — RCE). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(engine, engineName, version, timeoutMs)` racing `engine.executeRaw('SELECT 1', undefined, { signal })` against the exported `HEALTH_TIMEOUT_MS = 3000`; when the timeout wins, an `AbortController` cancels the Postgres query (PGLite can only discard its eventual result) before the same tagged `ProbeHealthResult` 503 envelope is returned (single timer-cleanup site); body shape `{status, version, engine}` only. Full stats moved to admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. OAuth/admin/audit SQL outside the abortable liveness probe routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the resolved write source joins the queue idempotency key so a rescoped client lands a new capture instead of deduping against its old job. confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the WP1 honest catalog: per-request filters (token scope incl. the FOV-4 `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count` (amendment 23 stopgap). Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (amendment 33/D10; the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client).- `src/core/sql-query.ts` — engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure. `sqlQueryForEngine(engine)` returns a `SqlQuery` (`(strings, ...values) => Promise<rows[]>`) that walks the template, builds `$N` positional SQL, asserts every value is a `SqlValue` (string | number | bigint | boolean | Date | null), and routes through `engine.executeRaw(sql, params)` (Postgres via postgres.js `unsafe(sql, params)`, PGLite via `db.query(sql, params)`). Deliberately narrower than postgres.js's `sql` tag: no nested fragments, `sql.json()`, `sql.unsafe()`, `sql.begin()`, or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go through `executeRawJsonb(engine, sql, scalarParams, jsonbParams)` which composes positional `$N::jsonb` casts and passes JS **objects** through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by `test/sql-query.test.ts` on PGLite, `test/e2e/auth-permissions.test.ts:67` on Postgres). Positional binding is NOT universally immune, though: binding a `JSON.stringify(x)` **string** to a bare `$N::jsonb` via `unsafe()` double-encodes it into a jsonb string scalar on real Postgres (the #2339 class; PGLite hides it). Fixes: pass a raw object (executeRawJsonb / `sql.json`), or cast through `$N::text::jsonb`. `scripts/check-jsonb-pattern.sh` (template grep) doesn't fire on `executeRawJsonb(...)` because it passes objects; the positional `$N::jsonb` + `JSON.stringify` form is caught by `scripts/check-jsonb-params.mjs`. Consumed by `src/commands/auth.ts`, `src/commands/serve-http.ts`, `src/core/oauth-provider.ts`, `src/commands/files.ts`, `src/mcp/http-transport.ts` so all five work uniformly against PGLite and Postgres.- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`). Pinned by `test/serve-stdio-lifecycle.test.ts` (22 cases). Credit @Aragorn2046 + @seungsu-kr.- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Auth codes single-use with 10-minute TTL via atomic `DELETE...RETURNING` (closes RFC 6749 §10.5 TOCTOU); refresh rotation also `DELETE...RETURNING` (§10.4 stolen-token detection). `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); bare `catch {}` in `verifyAccessToken`/`getClient` replaced by `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`).diff --git a/docs/eval-takes-quality.md b/docs/eval-takes-quality.mdindex 215c394cd7..09c10fd33c 100644--- a/docs/eval-takes-quality.md+++ b/docs/eval-takes-quality.md@@ -31,7 +31,7 @@ receipt file from disk and re-renders it. The other modes need the brain.| `--budget-usd N` | unset | Abort before next call's projected cost would exceed cap. Models without a `pricing.ts` entry fail loud rather than silently blowing the budget. || `--source db|fs` | `db` | `fs` is reserved for v0.33+. || `--slug-prefix P` | unset | Filter takes to pages whose slug starts with P. |-| `--models a,b,c` | `openai:gpt-5.2,anthropic:claude-opus-4-7,google:gemini-2.0-flash` | Comma-separated panel. |+| `--models a,b,c` | `openai:gpt-5.2,anthropic:claude-opus-4-7,google:gemini-2.5-flash` | Comma-separated panel. || `--json` | off | Emit the full receipt to stdout. |## Receipt JSON shape (`schema_version: 1`)@@ -50,7 +50,7 @@ receipt file from disk and re-renders it. The other modes need the brain.},"prompt_sha8": "abcd1234","models_sha8": "abcd1234",- "models": ["openai:gpt-5.2", "anthropic:claude-opus-4-7", "google:gemini-2.0-flash"],+ "models": ["openai:gpt-5.2", "anthropic:claude-opus-4-7", "google:gemini-2.5-flash"],"cycles_run": 3,"successes_per_cycle": [3, 3, 2],"verdict": "pass",diff --git a/docs/eval/METRIC_GLOSSARY.md b/docs/eval/METRIC_GLOSSARY.mdindex 48be0b89b8..5f6882129b 100644--- a/docs/eval/METRIC_GLOSSARY.md+++ b/docs/eval/METRIC_GLOSSARY.md@@ -10,23 +10,23 @@ Every metric `gbrain eval *` and `gbrain search stats` reports has a plain-Engli**Key:** `precision@k`-**Plain English:** Of the top k results the engine returned, what fraction were actually relevant? High precision means few junk results in the top of the list.+**Plain English:** Of the top k unique pages the engine returned, what fraction were actually relevant? Multiple chunks from one page count once. High precision means few junk pages in the top of the list.-**Range:** 0..1, higher is better. P@10 = 0.7 means 7 of the top 10 results were on-topic.+**Range:** 0..1, higher is better. The denominator stays k even when fewer than k unique pages are returned; P@10 = 0.7 means 7 relevant pages in the top 10 slots.### Recall at k (R@k)**Key:** `recall@k`-**Plain English:** Of all the relevant results that exist in the brain, what fraction did the engine find in its top k? High recall means few missed answers.+**Plain English:** Of all the relevant pages that exist in the brain, what fraction did the engine find in its first k unique pages? Multiple chunks from one page count once. High recall means few missed answers.-**Range:** 0..1, higher is better. R@10 = 0.81 means out of every 100 questions, the right answer was in the top 10 for 81 of them.+**Range:** 0..1, higher is better. R@10 = 0.81 means 81% of all labeled relevant pages appeared in the first 10 unique results.### Mean Reciprocal Rank (MRR)**Key:** `mrr`-**Plain English:** On average, how far down the list is the FIRST relevant result? An MRR of 1.0 means the first hit is always right; an MRR of 0.5 means it's typically at rank 2.+**Plain English:** On average, how far down the unique-page list is the FIRST relevant result? Repeated chunks do not consume ranks. An MRR of 1.0 means the first page is always right; an MRR of 0.5 means it's typically at rank 2.**Range:** 0..1, higher is better. Computed as the average of 1/rank-of-first-relevant-result across all test queries.@@ -34,7 +34,7 @@ Every metric `gbrain eval *` and `gbrain search stats` reports has a plain-Engli**Key:** `ndcg@k`-**Plain English:** Like precision@k, but the engine gets MORE credit for putting good results near the top than near rank k. A perfect ordering scores 1.0; a totally random ordering scores near 0.+**Plain English:** Like precision@k, but the engine gets MORE credit for putting good pages near the top than near rank k. Each page earns gain once even if several chunks matched. A perfect ordering scores 1.0; a totally random ordering scores near 0.**Range:** 0..1, higher is better. nDCG@10 above 0.65 is the common "ship it" threshold for hybrid retrieval on technical corpora.diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex f03816898c..0f1d79bd51 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -177,9 +177,12 @@ near-duplicates may insert; dedup and supersession ride embedding similarity).One known person/company/project card. NEVER errors on a miss.-Resolution (frozen precedence): alias > exact title > slug/slug-suffix; ties-break on most-recently-touched. Multi-hit ⇒ best match's card + runners-up in-`suggestions`. Miss ⇒ `found: false` + keyword near-misses with+Resolution (frozen precedence): alias > exact slug > exact title > slug-suffix.+When multiple pages share an exact title, canonical entity types (`person`,+`company`, `organization`, `entity`) outrank note/conversation containers;+most-recently-touched breaks ties within the same match shape. A non-entity+exact-title page remains a valid fallback. Multi-hit ⇒ best match's card ++runners-up in `suggestions`. Miss ⇒ `found: false` + keyword near-misses with`create_safety` hints.Response: `{ protocol_version, found, latency_ms, card?, suggestions? }`.diff --git a/docs/takes-vs-facts.md b/docs/takes-vs-facts.mdindex 30d7b4bf6a..bf2be94082 100644--- a/docs/takes-vs-facts.md+++ b/docs/takes-vs-facts.md@@ -19,7 +19,11 @@ The epistemological layer. WHO believes WHAT, with confidence weight and time.- `holder=world kind=fact` "acme-example raised a Series C" (w=1.0)- `holder=brain kind=hunch` "alice-example has a hero/rescuer pattern" (w=0.70)-**Query surface:** `gbrain takes list`, `gbrain takes search`, `gbrain think`+**Query surface:** `gbrain takes list`, `gbrain takes search`, `gbrain takes search --semantic`, `gbrain think`++Run `gbrain takes embed` after extraction to populate the take vectors used by+semantic search and the `think` vector stream. `gbrain takes embed --dry-run`+shows the pending provider work without making calls.## Facts (hot memory — `facts` table, v0.31)diff --git a/llms-full.txt b/llms-full.txtindex 95081e2ccb..ee3f214d89 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -523,9 +523,10 @@ filed for held-out corpus growth, cross-vendor verification, hierarchicalarea-of-areas, embedding-based pre-router, and the run-1 vs run-2prompt-design ablation methodology.-**Operational health (v0.19.1):** smoke-test (8 post-restart health checks with auto-fix-for Bun, CLI, DB, worker, Zod CJS, gateway, API key, brain repo; user-extensible via-`~/.gbrain/smoke-tests.d/*.sh`).+**Operational health (v0.19.1):** smoke-test (8 post-restart health checks; bounded+auto-fix for Bun, CLI, and Zod CJS; read-only worker topology via native supervisor+status with duplicate detection; DB, gateway, API key, brain repo; user-extensible+via `~/.gbrain/smoke-tests.d/*.sh`).**Conventions:** `skills/conventions/` has cross-cutting rules (quality, brain-first,model-routing, test-before-bulk, cross-modal). `skills/_brain-filing-rules.md` and@@ -899,7 +900,14 @@ before considering the ship complete.Files that MUST be checked on every ship:- README.md — does it reflect new features, commands, or setup steps?-- CLAUDE.md — does it reflect new files, test files, or architecture changes?+- `docs/architecture/KEY_FILES.md` — new or changed files in `src/`, and their+ invariants, are recorded HERE. This is the on-demand layer behind the Reference+ map, and it is where per-file and per-version detail belongs.+- CLAUDE.md — only if an always-loaded rule, the Reference map, or the dispatcher+ changed. **CLAUDE.md is a map, not a log**: it is read in full at the start of every+ session, so entries are condensed or deleted as they go stale, never appended to.+ If an update adds a file inventory, a test inventory, or an "as of vX.Y.Z" note,+ it belongs in the on-demand layer above instead.- CHANGELOG.md — does it cover every commit?- TODOS.md — are completed items marked done?- docs/ — do any guides need updating?@@ -5047,9 +5055,12 @@ near-duplicates may insert; dedup and supersession ride embedding similarity).One known person/company/project card. NEVER errors on a miss.-Resolution (frozen precedence): alias > exact title > slug/slug-suffix; ties-break on most-recently-touched. Multi-hit ⇒ best match's card + runners-up in-`suggestions`. Miss ⇒ `found: false` + keyword near-misses with+Resolution (frozen precedence): alias > exact slug > exact title > slug-suffix.+When multiple pages share an exact title, canonical entity types (`person`,+`company`, `organization`, `entity`) outrank note/conversation containers;+most-recently-touched breaks ties within the same match shape. A non-entity+exact-title page remains a valid fallback. Multi-hit ⇒ best match's card ++runners-up in `suggestions`. Miss ⇒ `found: false` + keyword near-misses with`create_safety` hints.Response: `{ protocol_version, found, latency_ms, card?, suggestions? }`.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 606ff28095..af4d9a0ffc 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.46.31.0",+ "version": "0.46.32.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex db628de5dc..a5231ada27 100644--- a/package.json+++ b/package.json@@ -171,7 +171,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.46.31.0",+ "version": "0.46.32.0","overrides": {"@hono/node-server": "^2.0.5","fast-uri": "^3.1.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 61c35666ae..638e53273e 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.46.31.0",+ "version": "0.46.32.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 18 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 164c0ff076..6a595333ee 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.46.31.0",+ "version": "0.46.32.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 18 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex f19312e4dc..51190afb99 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.31.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.32.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex c30aa768d4..2576bfd00c 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.46.31.0",+ "version": "0.46.32.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 17 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex cbe4049115..78025e6937 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.46.31.0",+ "version": "0.46.32.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 17 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 91e6ff286f..bd688e7e0b 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.31.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.32.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex 09eefb3047..eaa1b6a582 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.31.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.32.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/plugin/skills/smoke-test/SKILL.md b/plugin/skills/smoke-test/SKILL.mdindex 4490f639ae..5914dbd02e 100644--- a/plugin/skills/smoke-test/SKILL.md+++ b/plugin/skills/smoke-test/SKILL.md@@ -3,8 +3,9 @@ name: smoke-testdescription: |Health smoke tests + auto-fix for gbrain installs (and OpenClaw serviceswhen present). Run after machine/container restarts or whenever something- seems broken. Tests critical services, auto-fixes known issues, extensible- via user-defined test scripts in ~/.gbrain/smoke-tests.d/*.sh.+ seems broken. Tests critical services, auto-fixes bounded local issues,+ and reports worker topology without starting daemons. Extensible via+ user-defined test scripts in ~/.gbrain/smoke-tests.d/*.sh.triggers:- "smoke test"- "run smoke tests"@@ -28,7 +29,8 @@ mutating: trueThis skill guarantees:- 8 core tests verify gbrain health after restart (plus OpenClaw services whenpresent; skipped otherwise)-- Known failures are auto-fixed before reporting+- Bounded local failures are auto-fixed before reporting; worker repair is+ explicit because process topology and shell-job policy are operator choices- User-extensible via `~/.gbrain/smoke-tests.d/*.sh` drop-in scripts- Results logged to `/tmp/gbrain-smoke-test.log`- Exit code = number of unfixed failures (0 = all pass)@@ -40,7 +42,7 @@ This skill guarantees:| 1 | Bun runtime | Install from bun.sh || 2 | GBrain CLI loads | Reinstall deps || 3 | GBrain database (doctor) | — |-| 4 | GBrain worker process | Start worker |+| 4 | GBrain worker process | — (native supervisor status + duplicate detection) || 5 | OpenClaw Codex plugin (Zod CJS); skips if OpenClaw absent | `npm install zod@4 --force` || 6 | OpenClaw gateway; skips if OpenClaw absent | — (may not be started yet) || 7 | Embedding API key | — (check .env) |@@ -129,7 +131,9 @@ fi|-----|---------|-------------|| `GBRAIN_SMOKE_LOG` | `/tmp/gbrain-smoke-test.log` | Log file path || `GBRAIN_DIR_OVERRIDE` | (auto-detect) | Force gbrain install path |+| `GBRAIN_BUN_PATH` | (auto-detect) | Force Bun binary path || `GBRAIN_DATABASE_URL` | (from .env) | Database connection URL |+| `GBRAIN_SMOKE_WORKER_PID_FILE` | `/tmp/gbrain-worker.pid` | Legacy bare-worker PID path || `OPENCLAW_GATEWAY_PORT` | `18789` | Gateway port to test || `GBRAIN_BRAIN_PATH` | (deployment-specific) | Brain repo path. Container deployments default to `/data/brain`; set it to your brain repo path otherwise. Test 8 skips (not fails) when unset. |diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.tsindex 4fd5e269aa..a24ba9680c 100644--- a/scripts/generate-flag-registry.ts+++ b/scripts/generate-flag-registry.ts@@ -26,6 +26,14 @@ import { readFileSync, writeFileSync, existsSync, readdirSync, statSync } from 'import { dirname, resolve as resolvePath, join } from 'path';import { fileURLToPath } from 'url';+/** Read source with CRLF normalized to LF: the parser's block-boundary and+ * comment-strip regexes are LF-anchored (`\n}\n`, `//[^\n]*`), so Windows+ * checkouts (autocrlf=true) would otherwise widen scan windows and inflate+ * the last command's flag list. Deterministic on every platform. */+function readSrc(path: string): string {+ return readFileSync(path, 'utf-8').replace(/\r\n/g, '\n');+}+const ROOT = resolvePath(dirname(fileURLToPath(import.meta.url)), '..');/** Flags that live deeper than the one-level module scan. Keep commented. */@@ -46,7 +54,11 @@ const EXTRA_FLAGS: Record<string, string[]> = {const EXCLUDED_MODULES = ['thin-client-routing.ts'];function isExcludedModule(p: string): boolean {- return EXCLUDED_MODULES.some(m => p.endsWith(`/${m}`));+ // Basename comparison is path-separator agnostic: on Windows p ends in+ // '\\thin-client-routing.ts' so endsWith('/thin-client-routing.ts') is+ // false and the skip silently no-ops, inflating every command that+ // imports the router with its flags.+ return EXCLUDED_MODULES.some(m => p.split(/[\\/]/).pop() === m);}/** Universal helper flags every command may see (parsed or short-circuited upstream). */@@ -88,7 +100,11 @@ function relativeImports(src: string, fromDir: string): string[] {* modules back in so a peel can never silently shrink a command's flag set.*/function facadeExpansion(p: string): string[] {- const rel = p.startsWith(ROOT) ? p.slice(ROOT.length + 1) : p;+ // Compare in forward-slash space: on Windows p uses '\\' separators and+ // would never match the relative-path constants below, silently skipping+ // the peeled-module expansion. Same cross-platform drift class as the+ // isExcludedModule separator check above.+ const rel = (p.startsWith(ROOT) ? p.slice(ROOT.length + 1) : p).replace(/\\/g, '/');const collect = (dir: string): string[] => {if (!existsSync(dir)) return [];const out: string[] = [];@@ -124,7 +140,7 @@ function facadeExpansion(p: string): string[] {}export function buildFlagRegistry(): Record<string, string[]> {- const cliSource = readFileSync(join(ROOT, 'src/cli.ts'), 'utf-8');+ const cliSource = readSrc(join(ROOT, 'src/cli.ts'));// CLI_ONLY membership (the single source of truth in src/cli.ts). Strip// line comments first — the set literal carries commentary whose quoted@@ -204,11 +220,11 @@ export function buildFlagRegistry(): Record<string, string[]> {// imports scan at dep depth — exactly the pre-peel walk.const surface = [modPath, ...facadeExpansion(modPath)];for (const sfPath of surface) {- const sfSrc = readFileSync(sfPath, 'utf-8');+ const sfSrc = readSrc(sfPath);depthZeroText += sfSrc;for (const f of flagsInText(sfSrc)) { flags.add(f); depthZero.add(f); }for (const dep of relativeImports(sfSrc, dirname(sfPath))) {- for (const f of flagsInText(readFileSync(dep, 'utf-8'))) flags.add(f);+ for (const f of flagsInText(readSrc(dep))) flags.add(f);}}}diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex a88664904c..4448aa94f6 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,38 +3,39 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/commands/doctor.ts 4584 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); +chat-connectors wiring+src/commands/doctor.ts 4500 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; +chat-connectors wiring; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193)src/core/operations.ts 316 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring-src/core/postgres-engine.ts 5607 ratchet lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up-src/core/pglite-engine.ts 6090 ratchet grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate-src/core/migrate.ts 687 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter)-src/commands/sync.ts 4684 ratchet grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files-src/core/ai/gateway.ts 4515 ratchet grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip)-src/cli.ts 3753 ratchet grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; +chat-connectors wiring-src/core/cycle.ts 3186 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading-src/commands/serve-http.ts 3319 ratchet grown v0.46.25.0 D2: /mcp per-request teardown (#2844); grown wave-g (#4474): resolve-IPC socket under --http via shared helper+src/core/postgres-engine.ts 5625 ratchet lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980)+src/core/pglite-engine.ts 6110 ratchet grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980)+src/core/migrate.ts 687 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482)+src/commands/sync.ts 5652 ratchet grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts)+src/core/ai/gateway.ts 4568 ratchet grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980)+src/cli.ts 3777 ratchet grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; +chat-connectors wiring; wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch+src/core/cycle.ts 3186 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k)+src/commands/serve-http.ts 3317 ratchet grown v0.46.25.0 D2: /mcp per-request teardown (#2844); grown wave-g (#4474): resolve-IPC socket under --http via shared helpersrc/commands/jobs.ts 3127 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiringsrc/core/search/hybrid.ts 2954 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying-src/core/engine.ts 2509 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count+src/core/engine.ts 2527 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980)src/commands/autopilot.ts 2648 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiringsrc/commands/extract.ts 2385 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note-src/commands/extract-conversation-facts.ts 2052 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts+src/commands/extract-conversation-facts.ts 2098 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper)src/core/import-file.ts 2181 ratchet grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence-src/core/cycle/synthesize.ts 2818 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo+src/core/cycle/synthesize.ts 2808 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source reposrc/commands/embed.ts 1901 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring-src/core/types.ts 1946 ratchet grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218)+src/core/types.ts 1955 ratchet grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867)src/commands/skillpack.ts 1360 ratchetsrc/core/minions/queue.ts 2442 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease-src/commands/init.ts 1950 ratchet grown v0.46.x keyless capability notices-src/commands/integrations.ts 1736 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit)+src/commands/init.ts 1951 ratchet grown v0.46.x keyless capability notices; +1 at megawave/wave-k merge+src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)src/core/minions/handlers/subagent.ts 1834 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop-src/commands/bootstrap.ts 2010 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness)+src/commands/bootstrap.ts 2015 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts)src/core/minions/worker.ts 1560 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wavesrc/commands/sources.ts 1790 ratchet grown v0.46.22.0 phone wave: github source kind (#4104)src/core/link-extraction.ts 1681 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737)src/core/embedding-migration.ts 1545 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers)src/core/github-source.ts 1560 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment)-src/core/bootstrap/harness.ts 1947 ratchet+src/core/bootstrap/harness.ts 1951 ratchet +4 at megawave/wave-k mergesrc/commands/hook.ts 1559 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245)src/core/chunkers/code.ts 1575 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks-src/core/config.ts 1521 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix+src/core/oauth-provider.ts 1552 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard)+src/core/config.ts 1551 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge)diff --git a/scripts/smoke-test.sh b/scripts/smoke-test.shindex 2e8e1ea54c..6f1427e871 100755--- a/scripts/smoke-test.sh+++ b/scripts/smoke-test.sh@@ -16,6 +16,7 @@ set -aset +aLOG="${GBRAIN_SMOKE_LOG:-/tmp/gbrain-smoke-test.log}"+WORKER_PID_FILE="${GBRAIN_SMOKE_WORKER_PID_FILE:-/tmp/gbrain-worker.pid}"FAILURES=0FIXES=0TOTAL=0@@ -45,7 +46,7 @@ done# Find bunBUN_PATH=""-for bp in "/root/.bun/bin/bun" "/data/.bun/bin/bun" "$(which bun 2>/dev/null)"; do+for bp in "${GBRAIN_BUN_PATH:-}" "/root/.bun/bin/bun" "/data/.bun/bin/bun" "$(which bun 2>/dev/null)"; do[ -n "$bp" ] && [ -x "$bp" ] && BUN_PATH="$bp" && breakdone@@ -95,7 +96,9 @@ fiif [ -n "$DB_URL" ] && [ -n "$GBRAIN_DIR" ] && [ -n "$BUN_PATH" ]; thenDOCTOR_OUT=$(DATABASE_URL="$DB_URL" GBRAIN_DATABASE_URL="$DB_URL" timeout 20 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" doctor 2>&1)if echo "$DOCTOR_OUT" | grep -q "Health score\|brain_score\|Health Check"; then- SCORE=$(echo "$DOCTOR_OUT" | grep -oP 'Health score: \K[0-9]+' || echo '?')+ # #4182: BSD grep (macOS) has no -P; keep this shipped smoke test POSIX-portable.+ SCORE=$(printf '%s\n' "$DOCTOR_OUT" | sed -n 's/.*Health score: \([0-9][0-9]*\).*/\1/p' | head -1)+ [ -n "$SCORE" ] || SCORE='?'pass "GBrain database (health score: $SCORE/100)"elsefail "GBrain database — doctor returned no health data"@@ -107,20 +110,24 @@ fi# ── 4. GBrain worker process ──────────────────────────────if [ -n "$GBRAIN_DIR" ] && [ -n "$BUN_PATH" ] && [ -n "$DB_URL" ]; then- if [ -f /tmp/gbrain-worker.pid ] && kill -0 "$(cat /tmp/gbrain-worker.pid)" 2>/dev/null; then- pass "GBrain worker (PID: $(cat /tmp/gbrain-worker.pid))"+ SUPERVISOR_RUNNING=0+ LEGACY_WORKER_RUNNING=0+ if DATABASE_URL="$DB_URL" GBRAIN_DATABASE_URL="$DB_URL" \+ timeout 15 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" jobs supervisor status --json >/dev/null 2>&1; then+ SUPERVISOR_RUNNING=1+ fi+ if [ -f "$WORKER_PID_FILE" ] && kill -0 "$(cat "$WORKER_PID_FILE")" 2>/dev/null; then+ LEGACY_WORKER_RUNNING=1+ fi++ if [ "$SUPERVISOR_RUNNING" -eq 1 ] && [ "$LEGACY_WORKER_RUNNING" -eq 1 ]; then+ fail "GBrain worker — duplicate supervisor + legacy worker PID $(cat "$WORKER_PID_FILE"); stop the legacy worker after verifying ownership"+ elif [ "$SUPERVISOR_RUNNING" -eq 1 ]; then+ pass "GBrain worker (supervisor-managed)"+ elif [ "$LEGACY_WORKER_RUNNING" -eq 1 ]; then+ pass "GBrain worker (PID: $(cat "$WORKER_PID_FILE"))"else- # Auto-fix: start worker- DATABASE_URL="$DB_URL" GBRAIN_DATABASE_URL="$DB_URL" GBRAIN_ALLOW_SHELL_JOBS=1 \- nohup "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" jobs work --concurrency 2 > /tmp/gbrain-worker.log 2>&1 &- echo $! > /tmp/gbrain-worker.pid- sleep 2- if kill -0 "$(cat /tmp/gbrain-worker.pid)" 2>/dev/null; then- fixed "GBrain worker started"- pass "GBrain worker (PID: $(cat /tmp/gbrain-worker.pid))"- else- fail "GBrain worker — failed to start (check /tmp/gbrain-worker.log)"- fi+ fail "GBrain worker — no live supervisor or legacy worker; start explicitly with: gbrain jobs supervisor start --detach"fielseskip "GBrain worker — prerequisites missing"diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex ede97149e7..2ca7f487b9 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -64,7 +64,7 @@ test/compile-view.test.ts compileView — source isolation + read errors 3 readFtest/config.test.ts config source correctness 2 readFileSynctest/connection-resilience.test.ts Eng-review D3 — executeRaw has no per-call retry wrapper 3 readFileSynctest/contextual-retrieval-service-pure.test.ts inline import contextual synopsis containment 1 readFileSync-test/conversation-facts-type-allowlist-drift.test.ts (file-level) 17 readFileSync+test/conversation-facts-type-allowlist-drift.test.ts (file-level) 18 readFileSynctest/cycle-abort.test.ts #1972 — complete cooperative-abort coverage 3 readFileSynctest/cycle-abort.test.ts CycleOpts.signal contract (v0.20.5) 4 readFileSynctest/cycle-abort.test.ts autopilot-cycle handler contract (v0.20.5) 3 readFileSync@@ -239,6 +239,7 @@ test/supervisor.test.ts recovery hook timeout bound (structural) 1 readFileSynctest/sync-failures.test.ts #4543 blocked output names failing files 4 bun-file,doctor-source-helpertest/sync-failures.test.ts Bug 9 — doctor surfaces sync failures 2 doctor-source-helpertest/sync-failures.test.ts Bug 9 — sync.ts CLI flag wiring 6 bun-file,doctor-source-helper+test/sync-include-hidden.test.ts sync.ts delta path threads includeHidden (#4027 merge guard) 1 readFileSynctest/sync.test.ts buildSyncManifest 9 bun-filetest/sync.test.ts isSyncable 8 bun-filetest/sync.test.ts resolveSlugByPathOrSourcePath (CJK wave v0.32.7, codex F4) 3 bun-filediff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex bbec260d09..9abe4ec295 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -166,7 +166,7 @@"skillpack-check/SKILL.md": "cb045e20a60b22774578e86f57872181a3cda73e5861add7e5750dc4de65c1fb","skillpack-harvest/SKILL.md": "775133021077f49e6b9da0cf1eafa8df87a9f311b946063db572273effb6dd15","skillpack-harvest/routing-eval.jsonl": "cb4783288e95af3132b32ecb40a54cffc095f57b36240f96a25c2d2adf5e68c6",- "smoke-test/SKILL.md": "918333adb19f0fb1369a16e2d746c51a500392e95158538aa729106c720aef54",+ "smoke-test/SKILL.md": "09b288a47cff1fc749e430f3d29cbe71d3de31c2184974d04d4fb7151c45b674","soul-audit/SKILL.md": "2788c112775be2d69c94004da88db709b775057c640b68204887719d48424e4c","strategic-reading/SKILL.md": "5be656c39c830153ec7c2f328dc8bdeac05c1412b01b3415de6b5b008926e7a2","strategic-reading/routing-eval.jsonl": "eb0fc239c93aac53cf7d856190967bb65eaf970b4fe8bd0aad1c87495fbb8ccd",diff --git a/skills/smoke-test/SKILL.md b/skills/smoke-test/SKILL.mdindex 4490f639ae..5914dbd02e 100644--- a/skills/smoke-test/SKILL.md+++ b/skills/smoke-test/SKILL.md@@ -3,8 +3,9 @@ name: smoke-testdescription: |Health smoke tests + auto-fix for gbrain installs (and OpenClaw serviceswhen present). Run after machine/container restarts or whenever something- seems broken. Tests critical services, auto-fixes known issues, extensible- via user-defined test scripts in ~/.gbrain/smoke-tests.d/*.sh.+ seems broken. Tests critical services, auto-fixes bounded local issues,+ and reports worker topology without starting daemons. Extensible via+ user-defined test scripts in ~/.gbrain/smoke-tests.d/*.sh.triggers:- "smoke test"- "run smoke tests"@@ -28,7 +29,8 @@ mutating: trueThis skill guarantees:- 8 core tests verify gbrain health after restart (plus OpenClaw services whenpresent; skipped otherwise)-- Known failures are auto-fixed before reporting+- Bounded local failures are auto-fixed before reporting; worker repair is+ explicit because process topology and shell-job policy are operator choices- User-extensible via `~/.gbrain/smoke-tests.d/*.sh` drop-in scripts- Results logged to `/tmp/gbrain-smoke-test.log`- Exit code = number of unfixed failures (0 = all pass)@@ -40,7 +42,7 @@ This skill guarantees:| 1 | Bun runtime | Install from bun.sh || 2 | GBrain CLI loads | Reinstall deps || 3 | GBrain database (doctor) | — |-| 4 | GBrain worker process | Start worker |+| 4 | GBrain worker process | — (native supervisor status + duplicate detection) || 5 | OpenClaw Codex plugin (Zod CJS); skips if OpenClaw absent | `npm install zod@4 --force` || 6 | OpenClaw gateway; skips if OpenClaw absent | — (may not be started yet) || 7 | Embedding API key | — (check .env) |@@ -129,7 +131,9 @@ fi|-----|---------|-------------|| `GBRAIN_SMOKE_LOG` | `/tmp/gbrain-smoke-test.log` | Log file path || `GBRAIN_DIR_OVERRIDE` | (auto-detect) | Force gbrain install path |+| `GBRAIN_BUN_PATH` | (auto-detect) | Force Bun binary path || `GBRAIN_DATABASE_URL` | (from .env) | Database connection URL |+| `GBRAIN_SMOKE_WORKER_PID_FILE` | `/tmp/gbrain-worker.pid` | Legacy bare-worker PID path || `OPENCLAW_GATEWAY_PORT` | `18789` | Gateway port to test || `GBRAIN_BRAIN_PATH` | (deployment-specific) | Brain repo path. Container deployments default to `/data/brain`; set it to your brain repo path otherwise. Test 8 skips (not fails) when unset. |diff --git a/src/cli.ts b/src/cli.tsindex d4d017379e..1f144402a7 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -196,6 +196,17 @@ const CLI_ONLY_SELF_HELP = new Set([// ZE interim cleanup: the retired ze-switch shim ships truthful help// (sunset refusal + canonical migration command); the generic stub hid it.'ze-switch',+ // `gbrain takes --help` printed the generic one-line stub, so the nine+ // subcommands (add/update/supersede/resolve/scorecard/calibration/revisit/+ // extract/search) were undiscoverable from the CLI — the detailed usage+ // block in runTakes (src/commands/takes.ts) was unreachable. Same holdout+ // pattern as `capture`, `sync`, and `schema` above.+ 'takes',+ // #4003: auth ships its own detailed usage (token/OAuth-client commands ++ // flags) in its `default:` switch case, hit whenever the subcommand isn't+ // one of create/list/revoke/etc — including --help. Without this entry the+ // generic short-circuit fires first and that usage block is dead code.+ 'auth',// #3686 (the #578 residue): eval / storage / reindex each ship real usage —// eval's printHelp (15 subcommands), storage's status usage, reindex's// target-flag usage — that the generic one-line stub was hiding. Their@@ -2582,6 +2593,16 @@ async function handleCliOnly(command: string, args: string[]) {return;}+ // Same pattern for `takes --help`. 'takes' is now in CLI_ONLY_SELF_HELP so+ // the generic stub stays out of the way; this pre-engine-bind branch exposes+ // the subcommand usage block without a configured brain. runTakes' help path+ // returns before touching the engine.+ if (command === 'takes' && (args.includes('--help') || args.includes('-h'))) {+ const { runTakes } = await import('./commands/takes.ts');+ await runTakes(null as never, args);+ return;+ }+// #3686 (the #578 residue): `eval --help` reaches eval.ts's printHelp// engine-free. Placed AFTER the sub-owned no-DB routes above (brainbench /// longmemeval / run-all / cross-modal / chronicle / conversation-parser /@@ -3704,6 +3725,9 @@ ADMIN--public-url URL Public issuer URL (required behind proxy/tunnel)connect <mcp-url> --token <t> Wire Claude Code to a remote gbrain (bearer token)[--install] [--json] Print the paste-ready command, or --install to run it+ auth <create|list|revoke|...> Manage legacy tokens + OAuth 2.1 clients+ auth --help Full subcommand list (register-client,+ rescope-client, revoke-client, permissions, test, ...)watch [--json] Push-based context: pipe conversation turns in,volunteered brain pages stream out (#2095)call <tool> '<json>' Raw tool invocationdiff --git a/src/commands/auth.ts b/src/commands/auth.tsindex bb74578c4f..20add07b32 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -1107,44 +1107,7 @@ export function parseAuthCreateArgs(rest: string[]): { name: string; takesHolderreturn { name: positional || '', takesHolders, ...(scopes !== undefined ? { scopes } : {}) };}-export async function runAuth(args: string[]): Promise<void> {- const [cmd, ...rest] = args;- switch (cmd) {- case 'create': {- // v0.28: optional --takes-holders world,garry,brain (default: world only)- // #4043: optional --scopes read,write (default: full access, grandfathered)- const parsed = parseAuthCreateArgs(rest);- if (parsed.error) {- console.error(`Error: ${parsed.error}`);- process.exit(1);- }- await create(parsed.name, { takesHolders: parsed.takesHolders, scopes: parsed.scopes });- return;- }- case 'list': await list(); return;- case 'revoke': {- if (rest[0] === '--id') { await revokeById(rest[1] || ''); return; }- await revoke(rest[0]);- return;- }- case 'permissions': {- // gbrain auth permissions <name> set-takes-holders world,garry- await permissions(rest[0] || '', rest[1] || '', rest[2]);- return;- }- case 'register-client': await registerClient(rest[0], rest.slice(1)); return;- case 'rescope-client': await rescopeClient(rest[0], rest.slice(1)); return;- case 'revoke-client': await revokeClient(rest[0]); return;- case 'clients': await clientsCmd(rest); return;- case 'test': {- const tokenIdx = rest.indexOf('--token');- const url = rest.find(a => !a.startsWith('--') && a !== rest[tokenIdx + 1]);- const token = tokenIdx >= 0 ? rest[tokenIdx + 1] : '';- await test(url || '', token || '');- return;- }- default:- console.log(`GBrain Token Management+const AUTH_USAGE = `GBrain Token ManagementUsage:gbrain auth create <name> [--takes-holders world,garry,brain] [--scopes read,write]@@ -1201,7 +1164,58 @@ Usage:clients (>90% context_pack/delta) are flagged.gbrain auth revoke-client <client_id> Hard-delete an OAuth 2.1 client (cascades to tokens + codes)gbrain auth test <url> --token <token> Smoke-test a remote MCP server-`);+`;++export async function runAuth(args: string[]): Promise<void> {+ // #4083 follow-up: print usage whenever --help/-h appears ANYWHERE in+ // args, before dispatching to a subcommand. Without this early return,+ // `gbrain auth create foo --help` (or revoke/register-client/... ++ // --help) actually EXECUTES the subcommand instead of showing help,+ // once `auth` joined CLI_ONLY_SELF_HELP and the generic --help+ // short-circuit in cli.ts stopped intercepting it first. Same pattern+ // as sync.ts's own `args.includes('--help') || args.includes('-h')`+ // early-return.+ if (args.includes('--help') || args.includes('-h')) {+ console.log(AUTH_USAGE);+ return;+ }+ const [cmd, ...rest] = args;+ switch (cmd) {+ case 'create': {+ // v0.28: optional --takes-holders world,garry,brain (default: world only)+ // #4043: optional --scopes read,write (default: full access, grandfathered)+ const parsed = parseAuthCreateArgs(rest);+ if (parsed.error) {+ console.error(`Error: ${parsed.error}`);+ process.exit(1);+ }+ await create(parsed.name, { takesHolders: parsed.takesHolders, scopes: parsed.scopes });+ return;+ }+ case 'list': await list(); return;+ case 'revoke': {+ if (rest[0] === '--id') { await revokeById(rest[1] || ''); return; }+ await revoke(rest[0]);+ return;+ }+ case 'permissions': {+ // gbrain auth permissions <name> set-takes-holders world,garry+ await permissions(rest[0] || '', rest[1] || '', rest[2]);+ return;+ }+ case 'register-client': await registerClient(rest[0], rest.slice(1)); return;+ case 'rescope-client': await rescopeClient(rest[0], rest.slice(1)); return;+ case 'revoke-client': await revokeClient(rest[0]); return;+ case 'clients': await clientsCmd(rest); return;+ case 'test': {+ const tokenIdx = rest.indexOf('--token');+ const url = rest.find(a => !a.startsWith('--') && a !== rest[tokenIdx + 1]);+ const token = tokenIdx >= 0 ? rest[tokenIdx + 1] : '';+ await test(url || '', token || '');+ return;+ }+ default:+ console.log(AUTH_USAGE);}}diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.tsindex 4b8b695903..1d01c06edc 100644--- a/src/commands/bootstrap.ts+++ b/src/commands/bootstrap.ts@@ -75,10 +75,12 @@ import {codexBlockOwnsName,codexPluginProvidesName,ensureHarnessHome,+ harnessDetectDeps,parseHarnessArgs,removeHarness,statusHarness,type HarnessDeps,+ type HarnessDetectOverrides,} from '../core/bootstrap/harness.ts';import { claudeUserSettingsPath, codexConfigPath, opencodeConfigDir, opencodeGlobalConfigPath, opencodeProjectConfigPath } from '../core/bootstrap/host-specs.ts';import {@@ -1625,7 +1627,7 @@ export function workspaceBrainStats(ws: string): { sources: string[]; pages: num/** `gbrain bootstrap harness` (#4043) — machine-level, no workspace, no* agent.json. Locks on the gbrain HOME (there is no workspace to lock). */-async function runHarness(rest: string[], home: string, runner: ExecRunner): Promise<number> {+async function runHarness(rest: string[], home: string, runner: ExecRunner, detect?: HarnessDetectOverrides): Promise<number> {const flags = parseHarnessArgs(rest);if (flags.error) {console.error(flags.error);@@ -1639,6 +1641,7 @@ async function runHarness(rest: string[], home: string, runner: ExecRunner): ProgbrainBin: resolveGbrainBin(),isTTY: process.stdout.isTTY === true,prompt: promptLine,+ ...harnessDetectDeps(detect),};// [X12] --status is READ-ONLY: no home mkdir, no lock — it must work (and// stay side-effect-free) even while an apply/remove holds the mutex.@@ -1866,6 +1869,8 @@ export interface RunBootstrapOpts {/** Spawn seam for the opencode `mcp list` probe (tests capture argv, cwd,* and env; the default holds a real Bun.spawn handle so timeouts kill). */probeSpawn?: OpencodeProbeSpawn;+ /** Harness-detection seam; see HarnessDetectOverrides in core/bootstrap/harness.ts. */+ harnessDetect?: HarnessDetectOverrides;}/** Dispatch. Returns the process exit code (cli.ts passes it to setCliExitVerdict). */@@ -1974,7 +1979,7 @@ export async function runBootstrap(args: string[], opts: RunBootstrapOpts = {}):code = await runUninstall(ws, rest, home, runner);break;case 'harness':- code = await runHarness(rest, home, runner);+ code = await runHarness(rest, home, runner, opts.harnessDetect);break;default:return 2; // unreachablediff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex db8689d3e0..89cdefaf5b 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -1,8 +1,5 @@import type { BrainEngine } from '../core/engine.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from '../core/embed-skip.ts';-// Leaf module (no flag surface of its own) — see that file for why this-// isn't imported from extract-conversation-facts.ts directly (#4135).-import { ALLOWED_TYPES } from '../core/facts/conversation-types.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';import * as db from '../core/db.ts';import { LATEST_VERSION, getIdleBlockers } from '../core/migrate.ts';@@ -24,6 +21,7 @@ import { computeEffectiveDate } from '../core/effective-date.ts';import { parseFrontmatter } from '../core/backfill-effective-date.ts';import { hnswIndexExpected, hnswMaxDimsForType } from '../core/vector-index.ts';import { VERSION as GBRAIN_BINARY_VERSION } from '../version.ts';+import { schemaVersionHealth } from '../core/schema-version-health.ts';import { zeroTotalContradictionsCheck } from '../core/eval-contradictions/run-health.ts';// Peeled doctor modules (containment sprint): each is a verbatim move out of// this file. doctor.ts re-exports every moved public symbol under its@@ -130,6 +128,7 @@ export {computeExtractHealthCheck,checkSyncFreshness,} from './doctor/checks/extraction-sync.ts';+export { computeConversationFormatCoverageCheck } from './doctor/checks/conversation-coverage.ts';export {checkSyncConsolidation,computePoolBudgetCheck,@@ -211,6 +210,7 @@ import {computeExtractHealthCheck,checkSyncFreshness,} from './doctor/checks/extraction-sync.ts';+import { computeConversationFormatCoverageCheck } from './doctor/checks/conversation-coverage.ts';import {checkSyncConsolidation,checkCycleFreshness,@@ -1385,70 +1385,12 @@ export async function buildChecks(}}- // 3d.3 v0.41.13.0 — conversation_format_coverage. Scans up to 200- // most-recent conversation-type pages, runs parseConversation in- // dry mode, reports per-pattern hit counts + unmatched count. Warn- // at >10% unmatched with paste-ready hint pointing at- // `gbrain conversation-parser scan <slug>` so the operator can- // triage the misses interactively.+ // 3d.3 v0.41.13.0 — conversation_format_coverage. Peeled to+ // doctor/checks/conversation-coverage.ts (#4193) so it is unit-testable;+ // summary-only conversation pages report separately instead of counting+ // as parser misses. Error handling lives inside the compute function.if (engine) {- try {- const { readConversationBodyForParsing } = await import('../core/conversation-parser/body.ts');- const { parseConversation } = await import('../core/conversation-parser/parse.ts');- // Single source of truth for the conversation-facts type allowlist (#4135).- const allowedTypes = ALLOWED_TYPES;- // PageFilters supports singular `type` only; iterate the allowed types- // and cap at ~50/each to land at ~200 total max.- const sample: import('../core/types.ts').Page[] = [];- for (const t of allowedTypes) {- const slice = await engine.listPages({ limit: 50, type: t as import('../core/types.ts').PageType });- sample.push(...slice);- }- if (sample.length === 0) {- checks.push({- name: 'conversation_format_coverage',- status: 'ok',- message: 'No conversation-type pages — coverage check not applicable',- });- } else {- const hitsByPattern: Record<string, number> = {};- let unmatched = 0;- for (const page of sample) {- const body = await readConversationBodyForParsing(engine, page);- const result = parseConversation(body, { page, noPolish: true, noFallback: true });- const id = result.matched_pattern_id ?? '_no_match';- hitsByPattern[id] = (hitsByPattern[id] ?? 0) + 1;- if (result.phase === 'no_match') unmatched++;- }- const unmatchedPct = (unmatched / sample.length) * 100;- const breakdown = Object.entries(hitsByPattern)- .sort(([, a], [, b]) => b - a)- .map(([k, v]) => `${k}=${v}`)- .join(', ');- if (unmatchedPct > 10) {- checks.push({- name: 'conversation_format_coverage',- status: 'warn',- message:- `${unmatched}/${sample.length} conversation pages (${unmatchedPct.toFixed(1)}%) match NO built-in pattern. ` +- `Breakdown: ${breakdown}. ` +- `Investigate: gbrain conversation-parser scan <slug>`,- });- } else {- checks.push({- name: 'conversation_format_coverage',- status: 'ok',- message: `${sample.length} pages: ${breakdown}`,- });- }- }- } catch (err) {- checks.push({- name: 'conversation_format_coverage',- status: 'warn',- message: `Could not check conversation format coverage: ${(err as Error)?.message ?? String(err)}`,- });- }+ checks.push(await computeConversationFormatCoverageCheck(engine));}// 3d.4 v0.41.13.0 — progressive_batch_audit_health. Reads last 7@@ -2003,76 +1945,50 @@ export async function buildChecks(try {const version = await engine.getConfig('version');schemaVersion = parseInt(version || '0', 10);+ checks.push({ name: 'schema_version', ...schemaVersionHealth(schemaVersion, LATEST_VERSION) });++ // 6b. Schema columns — gbrain#4421/#4425. The ledger counter alone can+ // lie: a PgBouncer transaction-mode pooler can swallow an ALTER TABLE+ // while the migration runner still advances config.version, leaving the+ // ledger "current" over a physically narrower table. The read-only column+ // diff below does the same live-column check `gbrain init --migrate-only`+ // already self-heals with — but a plain diagnostic run never issues DDL.if (schemaVersion > LATEST_VERSION) {- // Forward skew: another node migrated the shared DB past what this- // client knows (multi-node brain, hub + spokes on one Postgres). This- // client will read/write tables, columns, and indexes it doesn't know- // about — more dangerous than backward skew, which at least blocks on- // the next `apply-migrations`. See #2036. Takes precedence over the- // column diff below: an ahead DB is a superset of this client's- // expected columns, and "upgrade this client" is the real fix.- checks.push({- name: 'schema_version',- status: 'warn',- message: `Version ${schemaVersion} is AHEAD of this client's latest known version (${LATEST_VERSION}). ` +- `Another node migrated this DB past what this client knows — upgrade this client before writing.`,- });+ // Forward skew (schemaVersionHealth warns AHEAD above): an ahead DB is+ // a superset of this client's expected columns — the diff below would+ // only mislead. "Upgrade this client" is the real fix; skip the diff.} else if (schemaVersion >= LATEST_VERSION) {- // #4421: the ledger counter alone can lie — a PgBouncer transaction-- // mode pooler can swallow an ALTER TABLE while the migration runner- // still advances config.version, leaving the ledger "current" over a- // physically narrower table. Add a READ-ONLY column diff via- // detectMissingColumns (#4425 — the detection half of- // schema-verify.ts's verifySchema, no self-heal): when live columns- // are missing, downgrade to warn naming them with the migrate-only- // re-run hint. Diff failure is best-effort — the ledger ok stands.- // Dynamic import is deliberate: the positional source guard in- // test/doctor-schema-column-diff.test.ts pins that the diff consult- // lives INSIDE this ledger-current branch.- let columnDiffWarned = false;+ // Ledger-current branch. Dynamic import is deliberate: the positional+ // source guard in test/doctor-schema-column-diff.test.ts pins that the+ // diff consult lives INSIDE this branch (a behind DB is EXPECTED to+ // miss columns from unapplied migrations — schema_version's own warn+ // covers that already, so the diff would only mislead there too).+ progress.heartbeat('schema_columns');try {const { detectMissingColumns } = await import('../core/schema-verify.ts');- const diff = await detectMissingColumns(engine);- if (diff.missing.length > 0) {- const sample = diff.missing.slice(0, 5).map(m => `${m.table}.${m.column}`).join(', ');- const more = diff.missing.length > 5 ? ` (+${diff.missing.length - 5} more)` : '';+ const detected = await detectMissingColumns(engine);+ if (detected.missing.length === 0) {+ checks.push({ name: 'schema_columns', status: 'ok', message: `${detected.checked} column(s) verified against live schema` });+ } else {+ const cols = detected.missing.map(m => `${m.table}.${m.column}`).join(', ');checks.push({- name: 'schema_version',+ name: 'schema_columns',status: 'warn',message:- `Version ${schemaVersion} (latest: ${LATEST_VERSION}) but ${diff.missing.length} expected column(s) ` +- `are missing from the live schema: ${sample}${more}. The migration ledger advanced past a swallowed ` +- `ALTER TABLE (PgBouncer transaction-mode is the usual cause). Fix: gbrain init --migrate-only ` +- `(runs the schema self-heal); if it persists, connect directly to Postgres (not the pooler) first.`,+ `${detected.missing.length} column(s) missing despite schema_version reporting up to date: ${cols}. ` ++ `The migration ledger advanced past a swallowed ALTER TABLE (PgBouncer transaction-mode is the ` ++ `usual cause). Fix: gbrain init --migrate-only (runs the schema self-heal); if it persists, ` ++ `connect directly to Postgres (not the pooler) first.`,});- columnDiffWarned = true;}- } catch { /* read-only diff is best-effort; ledger ok stands */ }- if (!columnDiffWarned) {- checks.push({ name: 'schema_version', status: 'ok', message: `Version ${schemaVersion} (latest: ${LATEST_VERSION})` });+ } catch {+ checks.push({ name: 'schema_columns', status: 'warn', message: 'Could not verify live schema columns' });}- } else if (schemaVersion === 0) {- checks.push({- name: 'schema_version',- status: 'fail',- message: `No schema version recorded. Migrations never ran. Fix: gbrain apply-migrations --yes. ` +- `If you installed via 'bun install -g github:...', see https://github.com/garrytan/gbrain/issues/218.`,- });- } else {- checks.push({- name: 'schema_version',- status: 'warn',- message: `Version ${schemaVersion}, latest is ${LATEST_VERSION}. Fix: gbrain apply-migrations --yes`,- });}} catch {checks.push({ name: 'schema_version', status: 'warn', message: 'Could not check schema version' });}- // Note: the #4421/#4425 live-column drift diff (detectMissingColumns) is- // wired INSIDE the schema_version ledger-current branch above — one- // column-drift wiring, not a separate check.-// Note: we intentionally DO NOT fail on "schema v7+ but no preferences.json".// That's a valid fresh-install state after `gbrain init` — the migration// orchestrator writes preferences, but `init` alone doesn't run it. Thediff --git a/src/commands/doctor/checks/conversation-coverage.ts b/src/commands/doctor/checks/conversation-coverage.tsnew file mode 100644index 0000000000..de01941940--- /dev/null+++ b/src/commands/doctor/checks/conversation-coverage.ts@@ -0,0 +1,87 @@+/**+ * conversation_format_coverage check — peeled verbatim from src/commands/doctor.ts+ * (3d.3 v0.41.13.0) so it is unit-testable against PGLite, following the+ * computeExtractAtomsBacklogCheck pattern. doctor.ts re-exports it under the+ * facade rule.+ *+ * Scans up to 200 most-recent conversation-type pages (50 per allowed type),+ * runs parseConversation in dry mode, reports per-pattern hit counts ++ * unmatched count. Warn at >10% unmatched with paste-ready hint pointing at+ * `gbrain conversation-parser scan <slug>`.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import { ALLOWED_TYPES } from '../../../core/facts/conversation-types.ts';+import type { Check } from '../../doctor.ts';++export async function computeConversationFormatCoverageCheck(+ engine: BrainEngine,+): Promise<Check> {+ const name = 'conversation_format_coverage';+ try {+ const { readConversationBodyForParsing } = await import('../../../core/conversation-parser/body.ts');+ const { parseConversation } = await import('../../../core/conversation-parser/parse.ts');+ // Single source of truth for the conversation-facts type allowlist (#4135).+ const allowedTypes = ALLOWED_TYPES;+ // PageFilters supports singular `type` only; iterate the allowed types+ // and cap at ~50/each to land at ~200 total max.+ const sample: import('../../../core/types.ts').Page[] = [];+ for (const t of allowedTypes) {+ const slice = await engine.listPages({ limit: 50, type: t as import('../../../core/types.ts').PageType });+ sample.push(...slice);+ }+ if (sample.length === 0) {+ return {+ name,+ status: 'ok',+ message: 'No conversation-type pages — coverage check not applicable',+ };+ }+ const { isTranscriptClaiming } = await import('../../../core/conversation-parser/transcript-signals.ts');+ const hitsByPattern: Record<string, number> = {};+ let unmatched = 0;+ let summaryOnly = 0;+ for (const page of sample) {+ const body = await readConversationBodyForParsing(engine, page);+ const result = parseConversation(body, { page, noPolish: true, noFallback: true });+ // #4193: a no_match on a page that never claimed a transcript+ // (summary-only meeting/slack page) is not parser debt. Report it+ // separately and keep it out of the coverage denominator. Matched+ // pages and transcript-claiming misses keep today's behavior.+ if (result.phase === 'no_match' && !isTranscriptClaiming(page, body)) {+ hitsByPattern['_summary_only'] = (hitsByPattern['_summary_only'] ?? 0) + 1;+ summaryOnly++;+ continue;+ }+ const id = result.matched_pattern_id ?? '_no_match';+ hitsByPattern[id] = (hitsByPattern[id] ?? 0) + 1;+ if (result.phase === 'no_match') unmatched++;+ }+ const candidates = sample.length - summaryOnly;+ const unmatchedPct = candidates > 0 ? (unmatched / candidates) * 100 : 0;+ const breakdown = Object.entries(hitsByPattern)+ .sort(([, a], [, b]) => b - a)+ .map(([k, v]) => `${k}=${v}`)+ .join(', ');+ if (unmatchedPct > 10) {+ return {+ name,+ status: 'warn',+ message:+ `${unmatched}/${candidates} transcript-bearing conversation pages (${unmatchedPct.toFixed(1)}%) match NO built-in pattern. ` ++ `Breakdown: ${breakdown}. ` ++ `Investigate: gbrain conversation-parser scan <slug>`,+ };+ }+ return {+ name,+ status: 'ok',+ message: `${sample.length} pages: ${breakdown}`,+ };+ } catch (err) {+ return {+ name,+ status: 'warn',+ message: `Could not check conversation format coverage: ${(err as Error)?.message ?? String(err)}`,+ };+ }+}diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.tsindex 4b8d958690..81bd5fa138 100644--- a/src/commands/doctor/report-remote.ts+++ b/src/commands/doctor/report-remote.ts@@ -15,6 +15,7 @@ import { loadConfig } from '../../core/config.ts';import { loadCompletedMigrations } from '../../core/preferences.ts';import { compareVersions } from '../migrations/index.ts';import { resolveHoursEnv } from '../../core/env-number.ts';+import { schemaVersionHealth } from '../../core/schema-version-health.ts';import {type Check,type DoctorReport,@@ -109,21 +110,10 @@ export async function doctorReportRemote(try {const versionStr = await engine.getConfig('version');const version = parseInt(versionStr || '0', 10);- if (version >= LATEST_VERSION) {- checks.push({ name: 'schema_version', status: 'ok', message: `Version ${version} (latest: ${LATEST_VERSION})` });- } else if (version === 0) {- checks.push({- name: 'schema_version',- status: 'fail',- message: `No schema version recorded. Migrations never ran. Run \`gbrain apply-migrations --yes\` on the host.`,- });- } else {- checks.push({- name: 'schema_version',- status: 'warn',- message: `Version ${version}, latest is ${LATEST_VERSION}. Run \`gbrain apply-migrations --yes\` on the host.`,- });- }+ checks.push({+ name: 'schema_version',+ ...schemaVersionHealth(version, LATEST_VERSION, { remote: true }),+ });} catch {checks.push({ name: 'schema_version', status: 'warn', message: 'Could not check schema version' });}diff --git a/src/commands/eval-trajectory.ts b/src/commands/eval-trajectory.tsindex 2d2f995972..3d6eab3601 100644--- a/src/commands/eval-trajectory.ts+++ b/src/commands/eval-trajectory.ts@@ -139,6 +139,8 @@ export async function runEvalTrajectory(engine: BrainEngine, args: string[]): Prsince: parsed.since,until: parsed.until,limit: parsed.limit,+ // Fail-closed trust: local CLI must say so explicitly.+ remote: false,});const { regressions, drift_score } = computeTrajectoryStats(points);result = {diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 935c9729c3..f7929ff006 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -95,7 +95,12 @@ import { writeReceipt, shortRunId } from '../core/extract/receipt-writer.ts';import { upsertExtractRollup, classifyRunStop } from '../core/extract/rollup-writer.ts';import { ALLOWED_TYPES, type AllowedType } from '../core/facts/conversation-types.ts';import { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE } from '../core/facts/audit-sources.ts';-import { resolveEntitySlug } from '../core/entities/resolve.ts';+import {+ emptySaveTimeResolutionCounts,+ formatSaveTimeResolutionCounts,+ mergeSaveTimeResolutionCounts,+ resolveExtractedEntitiesForSave,+} from '../core/entities/resolve-on-save.ts';// Re-exported verbatim so existing importers (this file's own helpers below// and this file's tests) keep working unchanged; doctor.ts, jobs.ts,@@ -367,6 +372,10 @@ export interface ExtractConversationFactsResult {segments_processed: number;facts_extracted: number;facts_inserted: number;+ /** Entity values that reached the shipped deterministic fallback slug path. */+ fallback_slugify_count: number;+ /** Entity values kept raw after a best-effort resolution failure. */+ resolution_errors: number;budget_exhausted?: boolean;spent_usd?: number;}@@ -1053,6 +1062,7 @@ async function processPage(let newestEnd: string | null = null;let segmentsThisPage = 0;let pageInsertedTotal = 0;+ const pageResolution = emptySaveTimeResolutionCounts();for (const seg of segments) {if (state.segmentLimit > 0 && segmentsThisPage >= state.segmentLimit) break;@@ -1104,13 +1114,34 @@ async function processPage(segmentsThisPage++;state.result.facts_extracted += extracted.length;+ // This bulk path bypasses writeSingleFact and writes through insertFacts.+ // Canonicalize every extractor-provided entity via the shipped resolver+ // (alias_exact / prefix / fuzzy / slugify) while source scope is known.+ const segmentResolution = await resolveExtractedEntitiesForSave(+ state.engine,+ state.sourceId,+ extracted,+ (raw, message) => {+ process.stderr.write(+ `[extract-conversation-facts] ${page.slug} segment ${seg.startIso}..${seg.endIso} ` ++ `entity resolution failed for ${JSON.stringify(raw)}: ${message}; keeping raw value\n`,+ );+ },+ );+ const commitSegmentResolutionTelemetry = () => {+ mergeSaveTimeResolutionCounts(pageResolution, segmentResolution);+ state.result.fallback_slugify_count += segmentResolution.fallback_slugify_count;+ state.result.resolution_errors += segmentResolution.resolution_errors;+ };+if (!state.dryRun && extracted.length > 0) {// Eng-v2 C1 / E11: page-global row_num stays unique across segments.- const rows = await Promise.all(extracted.map(async (fact, i) => ({+ // entity_slug is already canonical here — resolveExtractedEntitiesForSave+ // (above) ran every fact through the shipped resolver cascade (#3729/#4052),+ // so master's per-row resolveEntitySlug mapper (#4567's independent fix for+ // the same issue) is superseded rather than layered on top.+ const rows = extracted.map((fact, i) => ({...fact,- entity_slug: fact.entity_slug- ? await resolveEntitySlug(state.engine, state.sourceId, fact.entity_slug)- : null,row_num: rowNum + i,source_markdown_slug: page.slug,source: PER_SEGMENT_SOURCE_PREFIX,@@ -1123,14 +1154,16 @@ async function processPage(: {}),context:fact.context ?? `from ${page.slug} segment ${seg.startIso}..${seg.endIso}`,- })));+ }));const ins = await state.engine.insertFacts(rows, { source_id: state.sourceId }); // gbrain-allow-direct-insert: canonical bulk extraction path for conversation pages — fences-as-system-of-record doesn't apply because conversations don't carry `## Facts` fences (the chat-log shape is the source-of-truth)pageInsertedTotal += ins.inserted;state.result.facts_inserted += ins.inserted;rowNum += extracted.length;+ commitSegmentResolutionTelemetry();} else {// dry-run: count for reporting, no DB write.rowNum += extracted.length;+ commitSegmentResolutionTelemetry();}newestEnd = seg.endIso;@@ -1176,7 +1209,8 @@ async function processPage(}process.stderr.write(- `[extract-conversation-facts] ${page.slug}: ${pageInsertedTotal} facts inserted across ${segmentsThisPage} segments\n`,+ `[extract-conversation-facts] ${page.slug}: ${pageInsertedTotal} facts inserted across ${segmentsThisPage} segments ` ++ `entity_resolution_counts=${formatSaveTimeResolutionCounts(pageResolution.counts)}\n`,);state.result.pages_processed++;@@ -1268,6 +1302,8 @@ export async function runExtractConversationFactsCore(segments_processed: 0,facts_extracted: 0,facts_inserted: 0,+ fallback_slugify_count: 0,+ resolution_errors: 0,};// F2: honor brain-wide kill-switch unless overridden.@@ -1912,6 +1948,8 @@ export async function runExtractConversationFacts(segments_processed: 0,facts_extracted: 0,facts_inserted: 0,+ fallback_slugify_count: 0,+ resolution_errors: 0,};let totalSpent = 0;let anyBudgetExhausted = false;@@ -1958,6 +1996,8 @@ export async function runExtractConversationFacts(aggregate.segments_processed += perSource.segments_processed;aggregate.facts_extracted += perSource.facts_extracted;aggregate.facts_inserted += perSource.facts_inserted;+ aggregate.fallback_slugify_count += perSource.fallback_slugify_count;+ aggregate.resolution_errors += perSource.resolution_errors;if (perSource.budget_exhausted) anyBudgetExhausted = true;if (perSource.spent_usd) totalSpent += perSource.spent_usd;@@ -2008,6 +2048,12 @@ export async function runExtractConversationFacts(if (aggregate.orphan_facts_cleaned > 0) {console.log(` Cleaned ${aggregate.orphan_facts_cleaned} orphan fact(s) from prior partial runs (D11 replay safety).`);}+ if (aggregate.fallback_slugify_count > 0) {+ console.log(` Minted ${aggregate.fallback_slugify_count} entity slug(s) via fallback_slugify.`);+ }+ if (aggregate.resolution_errors > 0) {+ console.log(` Kept ${aggregate.resolution_errors} raw entity value(s) after best-effort resolution errors.`);+ }if (anyBudgetExhausted) {console.log(` Budget cap reached. Re-run with a higher --max-cost-usd to continue.`);}@@ -2046,7 +2092,7 @@ function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));}-function isAbortError(err: unknown): boolean {+export function isAbortError(err: unknown): boolean {if (!(err instanceof Error)) return false;return err.name === 'AbortError' || /aborted|cancell?ed/i.test(err.message);}diff --git a/src/commands/features.ts b/src/commands/features.tsindex 59ecc1eed0..9b92f62a2d 100644--- a/src/commands/features.ts+++ b/src/commands/features.ts@@ -8,6 +8,7 @@import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';import { join } from 'path';import type { BrainEngine } from '../core/engine.ts';+import { heartbeatPath } from './integrations.ts';import { VERSION } from '../version.ts';// --- Types ---@@ -76,6 +77,31 @@ function saveOffers(offers: FeatureOffersFile) {} catch { /* best-effort */ }}+// Real-world check: did this integration actually get set up?+// Heartbeat files are written by Hermes during install (and by other hosts),+// so they are the source of truth for "is this wired up" — not just whether+// a secret env var happens to be exported in this shell.+function integrationHeartbeatExists(recipeId: string): boolean {+ try {+ const heartbeat = heartbeatPath(recipeId);+ if (!existsSync(heartbeat)) return false;+ const lines = readFileSync(heartbeat, 'utf-8')+ .split('\n')+ .map(l => l.trim())+ .filter(Boolean);+ return lines.some(line => {+ try {+ const evt = JSON.parse(line);+ return evt?.event === 'setup_complete';+ } catch {+ return false;+ }+ });+ } catch {+ return false;+ }+}+function shouldPitch(rec: FeatureRecommendation, offers: FeatureOffersFile, currentVersion: string): boolean {if (rec.priority === 1) return true; // always pitch data qualityconst majorMinor = currentVersion.split('.').slice(0, 2).join('.');@@ -154,9 +180,15 @@ export async function scanFeatures(engine: BrainEngine): Promise<FeatureScanResu// `every` made any recipe with alternative auth paths permanently// "unconfigured", since a ClawVisor user never sets GOOGLE_CLIENT_ID and// vice versa.- const unconfigured = RECIPE_META.filter(r =>- !r.secrets.some(s => process.env[s])- );+ // A recipe also counts as configured if a real setup heartbeat file exists+ // on disk (wired up via Hermes/another host). Env-only checks produced+ // false "not configured" reports for integrations that were actually+ // installed.+ const unconfigured = RECIPE_META.filter(r => {+ const envOk = r.secrets.some(s => !!process.env[s]);+ if (envOk) return false;+ return !integrationHeartbeatExists(r.id);+ });if (unconfigured.length > 0) {recommendations.push({id: 'no-integrations', priority: 2,diff --git a/src/commands/founder-scorecard.ts b/src/commands/founder-scorecard.tsindex 64aa99cef4..620cd70838 100644--- a/src/commands/founder-scorecard.ts+++ b/src/commands/founder-scorecard.ts@@ -305,6 +305,8 @@ export async function runFounder(engine: BrainEngine, args: string[]): Promise<vkind: 'metric',since: windowSince,until: windowUntil,+ // Fail-closed trust: local CLI must say so explicitly.+ remote: false,});let takes: Take[] = [];try {diff --git a/src/commands/import.ts b/src/commands/import.tsindex 80e15dda64..8b6dfe23d5 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -15,6 +15,7 @@ import {isImageFilePath as isImageFilePathFromSync,matchesAnyGlob,pruneDir,+ isPathPruned,SYNC_SKIP_FILES,type SyncStrategy,} from '../core/sync.ts';@@ -175,6 +176,15 @@ export async function runImport(* Threaded by performFullSync for `gbrain sync --exclude`.*/exclude?: string[];+ /**+ * #2404-class: repeatable glob patterns (same dialect as `exclude`)+ * that waive the leading-dot prune heuristic for matching paths — see+ * `isPathPruned` in core/sync.ts. Unlike `exclude`, this cannot be a+ * post-collection filter: a pruned path is never collected in the+ * first place, so it has to reach `collectSyncableFiles` itself.+ * Threaded by performFullSync for `gbrain sync --include-hidden`.+ */+ includeHidden?: string[];/*** Opt out of the git-visible fast path and walk the filesystem directly,* so markdown/code files matched by .gitignore can still be imported.@@ -377,6 +387,7 @@ export async function runImport(const malformedExcluded: string[] = [];let allFiles = collectSyncableFiles(dir, {strategy, includeGitignored,+ includeHidden: opts.includeHidden,onExcluded: (rel) => { malformedExcluded.push(rel); },});console.error(@@ -740,10 +751,16 @@ export async function runImport(// Log the ingest. #3969: skip the row when the run changed nothing// (imported=0, errors=0, chunks=0) unless --log-noop — see shouldLogIngest.+ // `sourceId ?? 'default'` mirrors the fallback `processFile` itself uses+ // when calling importFile/importImageFile — this must report the source+ // the pages actually landed in, not the unresolved CLI arg (see #3838:+ // pre-fix this field always read 'default' regardless of where+ // resolveSourceWithTier actually routed the run).if (shouldLogIngest({ imported, errors, chunksCreated }, logNoop)) {await engine.logIngest({source_type: 'directory',source_ref: dir,+ source_id: sourceId ?? 'default',pages_updated: importedSlugs,summary: `Imported ${imported} pages, ${skipped} skipped, ${chunksCreated} chunks`,});@@ -773,7 +790,13 @@ export async function runImport(// state as last time" from "new broken state." Source-scoped (#1939 #2).if (failures.length > 0) {const { recordFailures } = await import('../core/sync.ts');- recordFailures(opts.sourceId ?? 'default', failures, gitHead);+ // #3838: `opts.sourceId` is the caller-supplied value, which stays+ // undefined for a bare CLI invocation unless the resolver's+ // sole_non_default tier explicitly adopted it (see the comment above+ // this function's sourceId resolution). Use the resolved `sourceId`+ // — the same value every importFile/importImageFile call in this run+ // actually wrote to — so the ledger is keyed by the true source.+ recordFailures(sourceId ?? 'default', failures, gitHead);}// #3839: a path that failed on a prior run and succeeded (imported or@@ -785,7 +808,9 @@ export async function runImport(// is only partially clean.if (succeededPaths.length > 0) {const { clearFailures } = await import('../core/sync.ts');- clearFailures(opts.sourceId ?? 'default', succeededPaths);+ // #3838: keyed by the resolved source, matching recordFailures above —+ // a row recorded under the resolved source must clear under it too.+ clearFailures(sourceId ?? 'default', succeededPaths);}// #2114 guard: the global sync.* keys describe THE brain repo (the@@ -856,6 +881,8 @@ interface CollectOpts {* file — no rename guidance, no skipped count (structured-review finding).*/onExcluded?: (relPath: string) => void;+ /** See `RunImportOpts.includeHidden` — same repeatable-glob semantics. */+ includeHidden?: string[];}/**@@ -879,17 +906,21 @@ function isCollectibleForWalker(path: string,strategy: SyncStrategy,multimodalOn: boolean,+ includeHidden?: string[],): boolean {// #2607: apply the SAME segment-level prune gate as incremental sync's- // `classifySync` (core/sync.ts). The FS walk below prunes at descent time,+ // `classifySync` (core/sync.ts) — via the shared `isPathPruned`, so this+ // and `classifySync` cannot drift the way #923/#202 drifted before+ // `PRUNE_DIR_NAMES` existed. The FS walk below prunes at descent time,// but the git fast path enumerates via `git ls-files` and historically// filtered only by extension — so `sync --full` imported (and resurrected// previously-deleted) pages under dot-dirs / vendored trees that incremental// sync excludes. Full and incremental must agree on the exclusion set.- // (In the FS-walk route `path` is a basename, so this is the same dot-file- // check pruneDir already applied there — no behavior change on that route.)- const segments = path.split('/');- if (segments.some((seg) => !pruneDir(seg))) return false;+ // (In the FS-walk route `path` is a basename, so `includeHidden` has no+ // segment to waive there — that route's directory-level prune already ran+ // via unmodified `pruneDir` before a file entry is ever reached; see+ // `isPathPruned`'s doc comment for that scope note.)+ if (isPathPruned(path, includeHidden)) return false;// Malformed filenames (brackets / control chars — markdown-link syntax as a// literal filename) are rejected on BOTH collection routes, same as@@ -899,6 +930,7 @@ function isCollectibleForWalker(// Metafiles are directory scaffolding (READMEs / index / log / schema /// resolver), not typed brain pages — same exclusion `sync`'s `isSyncable`// applies. Guards both the FS-walk and the git-fast-path collection routes.+ const segments = path.split('/');const basename = segments[segments.length - 1] || '';if ((SYNC_SKIP_FILES as readonly string[]).includes(basename)) return false;@@ -934,6 +966,7 @@ function gitListSyncableFiles(strategy: SyncStrategy,multimodalOn: boolean,onExcluded?: (relPath: string) => void,+ includeHidden?: string[],): string[] | null {let stdout: string;try {@@ -952,7 +985,7 @@ function gitListSyncableFiles(// exclusion is reportable — other filters (strategy, prune, metafile)// are silent by design; this one hides renameable content.if (hasMalformedPathSegment(rel)) { onExcluded?.(rel); continue; }- if (!isCollectibleForWalker(rel, strategy, multimodalOn)) continue;+ if (!isCollectibleForWalker(rel, strategy, multimodalOn, includeHidden)) continue;const full = join(dir, rel);let st;try {@@ -997,7 +1030,7 @@ export function collectSyncableFiles(dir: string, opts: CollectOpts = {}): strin// PLUS untracked-not-ignored, so uncommitted source is still indexed. Non-git// dirs (or git unavailable) fall through to the FS walk below.if (!opts.includeGitignored) {- const gitFiles = gitListSyncableFiles(dir, strategy, multimodalOn, opts.onExcluded);+ const gitFiles = gitListSyncableFiles(dir, strategy, multimodalOn, opts.onExcluded, opts.includeHidden);if (gitFiles) return gitFiles;}diff --git a/src/commands/init.ts b/src/commands/init.tsindex b763edd7a8..a0b0af59b0 100644--- a/src/commands/init.ts+++ b/src/commands/init.ts@@ -1553,7 +1553,8 @@ async function initPostgres(opts: {}console.log('Running schema migration...');- await engine.initSchema();+ const { runInitSchemaWithRetry } = await import('../core/init-schema-retry.ts');+ await runInitSchemaWithRetry(engine);// v0.37.10.0 T6 (D11): post-initSchema invariant assertion guardrail.if (resolvedDim) {diff --git a/src/commands/integrations.ts b/src/commands/integrations.tsindex 197281b7b6..b2881e51e1 100644--- a/src/commands/integrations.ts+++ b/src/commands/integrations.ts@@ -518,7 +518,10 @@ function heartbeatDir(id: string): string {return gbrainPath('integrations', id);}-function heartbeatPath(id: string): string {+// Exported for features.ts's heartbeat-backed "configured" check — both+// surfaces must agree on the gbrainPath-based location (GBRAIN home+// overrides apply; a hardcoded $HOME/.gbrain would diverge).+export function heartbeatPath(id: string): string {return join(heartbeatDir(id), 'heartbeat.jsonl');}diff --git a/src/commands/migrations/in-process.ts b/src/commands/migrations/in-process.tsindex 784fea3df3..9b9ccbfc30 100644--- a/src/commands/migrations/in-process.ts+++ b/src/commands/migrations/in-process.ts@@ -80,8 +80,9 @@ export async function runMigrateOnlyCore(opts?: { timeoutMs?: number }): Promiseconst engine = await createEngine(toEngineConfig(config));try {await engine.connect(toEngineConfig(config));+ const { runInitSchemaWithRetry } = await import('../../core/init-schema-retry.ts');await withTimeout(- engine.initSchema(),+ runInitSchemaWithRetry(engine).then(() => undefined),timeoutMs,`schema init timed out after ${Math.round(timeoutMs / 1000)}s`,);diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex 938aac9c18..ca236e39ef 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -37,7 +37,6 @@ import {dcrRegistrationContext,DEFAULT_DCR_TTL_MIN_SECONDS,} from '../core/oauth-provider.ts';-import type { SqlQuery } from '../core/oauth-provider.ts';import { hasScope, ALLOWED_SCOPES_LIST, normalizeScopesInput } from '../core/scope.ts';import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';import { normalizeSourceInput, normalizeFederatedReadInput } from '../core/source-id.ts';@@ -428,26 +427,25 @@ export async function probeHealth(}/**- * Lightweight liveness probe. Races `SELECT 1` against the same timeout- * `probeHealth` uses, returns the same tagged-union result type, but the- * 200 body is intentionally bare: `{status, version, engine}` — no engine- * stats. Stats moved to `/admin/api/full-stats` (admin auth) in v0.28.10- * because `getStats()`'s six count(*) queries exceeded HEALTH_TIMEOUT_MS- * on production brains through PgBouncer, producing false 503s that- * triggered orchestrator restart cascades and advisory-lock pile-ups.+ * Races an abortable `SELECT 1` against `probeHealth`'s timeout; Postgres+ * cancels the losing query while PGLite only discards its eventual result.*/export async function probeLiveness(- sql: SqlQuery,+ engine: BrainEngine,engineName: string,version: string,timeoutMs: number = HEALTH_TIMEOUT_MS,): Promise<ProbeHealthResult> {let timer: ReturnType<typeof setTimeout> | null = null;+ const controller = new AbortController();try {await Promise.race([- sql`SELECT 1`,+ engine.executeRaw('SELECT 1', undefined, { signal: controller.signal }),new Promise<never>((_, reject) => {- timer = setTimeout(() => reject(new Error('health_timeout')), timeoutMs);+ timer = setTimeout(() => {+ controller.abort();+ reject(new Error('health_timeout'));+ }, timeoutMs);}),]);return {@@ -456,7 +454,7 @@ export async function probeLiveness(body: { status: 'ok', version, engine: engineName },};} catch (e: unknown) {- const msg = e instanceof Error ? e.message : 'unknown';+ const msg = controller.signal.aborted ? 'health_timeout' : (e instanceof Error ? e.message : 'unknown');return {ok: false,status: 503,@@ -1330,7 +1328,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption// /admin/api/full-stats (requireAdmin). See probeLiveness above for the why.// ---------------------------------------------------------------------------app.get('/health', async (_req, res) => {- const result = await probeLiveness(sql, config.engine || 'pglite', VERSION);+ const result = await probeLiveness(engine, config.engine || 'pglite', VERSION);res.status(result.status).json(result.body);});diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 095d5492d1..4ee86e915b 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -1,8 +1,10 @@-import { existsSync, readFileSync, writeFileSync, statSync, realpathSync } from 'fs';+import { existsSync, readFileSync, writeFileSync, statSync, lstatSync, realpathSync } from 'fs';import { join, relative, resolve as pathResolve } from 'path';import type { BrainEngine } from '../core/engine.ts';import { DELETE_BATCH_SIZE } from '../core/engine-constants.ts';-import { importFile, importImageFile, isImageFilePath as isImageImportPath } from '../core/import-file.ts';+import { importFile, importImageFile, isImageFilePath as isImageImportPath, MAX_FILE_SIZE } from '../core/import-file.ts';+import { parseMarkdown } from '../core/markdown.ts';+import { validateSlug } from '../core/utils.ts';import { collectSyncableFiles, shouldLogIngest } from './import.ts';import {isSyncable,@@ -11,6 +13,7 @@ import {unsyncableReason,matchesAnyGlob,resolveSlugForPath,+ isCodeFilePath,unacknowledgedSyncFailures,acknowledgeFailures,loadSyncFailures,@@ -21,13 +24,19 @@ import {summarizeFailuresByCode,isEmbeddingInfraCode,DEFAULT_SOURCE_ID,+ RENAME_SENTINEL_PREFIX,+ renameSentinelPath,+ renameReconcileErrorMessage,+ parseRenameReconcileFrom,+ clearFailures,+ restoreFailures,} from '../core/sync.ts';import {computeSyncDelta,buildDetachedWorkingTreeManifest,} from '../core/sync-delta.ts';import { CHUNKER_VERSION } from '../core/chunkers/code.ts';-import type { SyncManifest } from '../core/sync.ts';+import type { SyncManifest, SyncFailure } from '../core/sync.ts';import { createProgress } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import { loadConfig } from '../core/config.ts';@@ -89,6 +98,7 @@ import {} from '../core/sync-embed-backfill.ts';import {git,+ gitRawOutput,isPathSafe,hasOriginRemote,isDetachedHead,@@ -365,6 +375,18 @@ export interface SyncOpts {* matching the #1433 metafile posture).*/exclude?: string[];+ /**+ * Repeatable `--include-hidden <glob>` on the CLI — same glob dialect as+ * `exclude`, but waives the leading-dot part of `pruneDir`'s exclusion+ * (`.git`, `.obsidian`, and any other dot-prefixed directory) for paths+ * that match, instead of removing paths. See `isPathPruned` in+ * core/sync.ts for exactly what is and isn't waivable, and its doc+ * comment for the one gap (non-git directory imports via the FS-walk+ * fallback aren't covered). Unlike `exclude`, this has to reach the+ * collection step itself — a pruned path is never collected in the first+ * place, so there's nothing for a post-collection filter to add back.+ */+ includeHidden?: string[];/*** Include files matched by .gitignore. Git cannot report untracked ignored* changes in diffs, so sync uses the full filesystem walker when this is set.@@ -611,6 +633,597 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<}}++/**+ * Source-scoped ACTIVE slugs for the given source_paths, considering EVERY+ * matching row. `source_path` has only a non-unique index and+ * `resolveSlugsByPaths` collapses to one arbitrary row per path — through+ * that collapse a soft-deleted row could mask a live duplicate sharing the+ * same path (#3479 review), so the rename-reconcile paths query all rows+ * with an explicit `deleted_at IS NULL` instead.+ */+async function activeSlugsBySourcePath(+ engine: BrainEngine,+ paths: string[],+ sourceId: string,+ signal?: AbortSignal,+): Promise<Map<string, string[]>> {+ const out = new Map<string, string[]>();+ for (let i = 0; i < paths.length; i += DELETE_BATCH_SIZE) {+ // gate 17 (timeout responsiveness): a large rename manifest runs many+ // batches; stop between them once aborted. The partial map is safe for+ // both consumers — the rename loop's own per-iteration check returns+ // `partial` before consuming it, and a smaller map only ever degrades+ // toward skipping cheap renames, never toward moving a guessed row.+ if (signal?.aborted) break;+ const batch = paths.slice(i, i + DELETE_BATCH_SIZE);+ const rows = await engine.executeRaw<{ slug: string; source_path: string }>(+ `SELECT slug, source_path FROM pages+ WHERE source_path = ANY($1::text[]) AND source_id = $2 AND deleted_at IS NULL`,+ [batch, sourceId],+ );+ for (const r of rows) {+ const arr = out.get(r.source_path);+ if (arr) arr.push(r.slug);+ else out.set(r.source_path, [r.slug]);+ }+ }+ return out;+}++/**+ * #3583 review (data-loss blocker): every tracked working-tree file, indexed+ * by the slug it derives to. `updateSlug` never rewrites `source_path` and an+ * unchanged-content re-import is a no-write skip, so after an ordinary cheap+ * rename the LIVE row still carries its OLD path — `source_path = from`+ * therefore matches live pages, not just stale ones. A reconcile candidate is+ * only genuinely stale when NO tracked file derives to its CURRENT slug.+ *+ * Derivation mirrors the import path exactly, in both of its regimes:+ * - Ordinary paths: resolveSlugForPath. Import's anti-spoof check rejects+ * any frontmatter slug that disagrees with the path-derived one, so for+ * these files the path IS the slug authority (case folding and spaces+ * included — a naive `slug + '.md'` inversion would misclassify those).+ * - CJK-wave frontmatter fallback (#598): a markdown file whose path+ * derives NO slug (emoji / exotic-script filename) imports under its+ * frontmatter `slug:` — resolveSlugForPath cannot see that slug, so+ * resolve it the way import does end to end: parseMarkdown on the+ * content (working tree first, git index blob when the working-tree+ * copy is absent, e.g. a sparse checkout), then the same validateSlug+ * chokepoint importFromContent runs (which lowercases). Every non-code+ * file with an empty derived slug is a candidate — importFromFile has+ * no extension gate; see fallbackSlugsForFile.+ *+ * `complete` goes false when some fallback-regime file's content could not+ * be read at all: its true slug is then unknowable, so absence from the+ * index no longer PROVES staleness — callers must treat an index miss as+ * unknown and spare the row, never delete on it. That same fail-safe+ * absorbs the awkward index states: an unmerged path (no stage-0 blob →+ * cat-file throws) and an undecodable filename (utf-8 replacement mangles+ * the name → both reads miss) both land on `complete = false`, not on a+ * delete. Deliberately BROADER than the sync scope: every working-tree file+ * counts (submodule interiors never appear — ls-files lists the gitlink+ * only, and the walker never imports them — and scope/exclude-filtered+ * files still register). Over-inclusion can only delay a cleanup, never+ * delete a live page.+ *+ * Post-review fix: the listing MUST match `collectSyncableFiles`' git-aware+ * fast path (`git ls-files --cached --others --exclude-standard`, tracked+ * PLUS untracked-not-ignored — see `gitListSyncableFiles` in import.ts), not+ * a bare `git ls-files` (tracked only). A file added to the working tree but+ * not yet `git add`-ed still gets imported by `collectSyncableFiles`, so a+ * plain tracked-only listing here would treat its slug as absent from the+ * index and reconcile could hard-delete the LIVE page that import just+ * created. `--exclude-standard` keeps `.gitignore`d files out of the index+ * exactly as it keeps them out of import, so the two enumerations stay in+ * lockstep.+ *+ * Built at most once per sync run, and only when a fallback rename actually+ * has reconcile candidates. Throws on git ls-files failure: the caller's+ * catch records the `<rename:…>` sentinel (fail-closed) instead of guessing.+ */+interface TrackedSlugIndex {+ /**+ * The slugs some tracked file derives to. A SET, not a slug -> paths map:+ * liveness only ever asks "does any file still derive to this slug"+ * (`has`), so the paths were accurate but unread — state a later reader+ * would have had to re-derive the purpose of.+ */+ slugs: Set<string>;+ complete: boolean;+}++function trackedSlugIndex(gitContextRoot: string, anchorCommit?: string): TrackedSlugIndex {+ const slugs = new Set<string>();+ let complete = true;+ const addSlug = (slug: string): void => { slugs.add(slug); };+ // --cached --others --exclude-standard mirrors gitListSyncableFiles (see+ // docstring above): tracked-only would miss an unstaged new file that+ // collectSyncableFiles already imported, misclassifying its live page as+ // stale.+ const listing = gitRawOutput(gitContextRoot, ['ls-files', '--cached', '--others', '--exclude-standard', '-z']);+ for (const rel of listing.split('\u0000')) {+ if (!rel) continue;+ const slug = resolveSlugForPath(rel);+ addSlug(slug);+ // Fallback-regime candidates are every non-code file whose path derives+ // no slug. NOT just `.md`/`.mdx`: importFromFile has no extension gate —+ // an extensionless emoji-named file imports under its frontmatter slug+ // all the same, so skipping it here deleted its live row. Reads are+ // bounded by the size gates inside fallbackSlugsForFile, so a multi-GB+ // punctuation-named artifact costs one lstat, never a read.+ if (slug === '' && !isCodeFilePath(rel)) {+ try {+ const fallback = fallbackSlugsForFile(gitContextRoot, rel);+ for (const fmSlug of fallback.slugs) addSlug(fmSlug);+ if (!fallback.proofIntact) {+ complete = false;+ serr(+ ` [sync] rename reconcile: could not fully resolve the slug of ` ++ `tracked file ${rel} (unreadable, unmerged, or over the import ` ++ `size gate); staleness is unprovable this run, so reconcile will ` ++ `not delete any row missing from the index.`,+ );+ }+ } catch {+ complete = false;+ serr(+ ` [sync] rename reconcile: could not resolve the slug of tracked ` ++ `file ${rel}; staleness is unprovable this run, so reconcile will ` ++ `not delete any row missing from the index.`,+ );+ }+ }+ }+ // The anchor commit (`last_commit`, what the brain actually reflects) is+ // enumerated as ITS OWN tree, not looked up through current paths: a+ // commit that RENAMES a fallback-regime file (and drops its slug) leaves+ // the anchor's content at the OLD path, which no current-path lookup can+ // reach — the anchor-imported row was deleted while the index still+ // claimed to be complete. Registration is purely spare-side (extra+ // liveness can only delay a cleanup), so enumerating the whole anchor+ // tree is safe; reads stay bounded by the same size gates and only fire+ // for fallback-regime paths.+ if (anchorCommit && anchorCommit !== 'HEAD') {+ try {+ const epochs = attributeEpochCommits(gitContextRoot, anchorCommit);+ const historicalFilter = epochs === null || anyFilterAtAttributeEpochs(gitContextRoot, epochs);+ const anchorListing = gitRawOutput(gitContextRoot, ['ls-tree', '-r', '-z', '--name-only', anchorCommit]);+ for (const rel of anchorListing.split('\u0000')) {+ if (!rel) continue;+ if (resolveSlugForPath(rel) !== '' || isCodeFilePath(rel)) continue;+ const res = anchorBlobSlugs(gitContextRoot, anchorCommit, rel, historicalFilter);+ for (const s of res.slugs) addSlug(s);+ if (!res.proofIntact) {+ complete = false;+ serr(+ ` [sync] rename reconcile: could not resolve the slug of ${rel} at ` ++ `the sync anchor; staleness is unprovable this run, so reconcile ` ++ `will not delete any row missing from the index.`,+ );+ }+ }+ } catch {+ complete = false;+ serr(+ ` [sync] rename reconcile: could not enumerate the sync anchor tree; ` ++ `staleness is unprovable this run, so reconcile will not delete any ` ++ `row missing from the index.`,+ );+ }+ }+ return { slugs, complete };+}++/**+ * The frontmatter-slug shapes a content state can own a row under: the+ * validateSlug chokepoint importFromContent runs (lowercases), or — when+ * the current chokepoint REJECTS the slug — both raw casings, since a+ * legacy row imported under older validation rules may still carry it+ * (purely spare-side registration).+ */+function frontmatterSlugShapes(content: string, rel: string): string[] {+ const fmSlug = parseMarkdown(content, rel).slug;+ if (!fmSlug) return [];+ try {+ return [validateSlug(fmSlug)];+ } catch {+ return [fmSlug, fmSlug.toLowerCase()];+ }+}++/**+ * Size-gated read + slug extraction of one anchor-tree blob. When a+ * content filter is in effect for the path under TODAY's attributes, or+ * ANY reachable attribute epoch assigns a filter to ANYTHING+ * (`historicalFilter`, computed once per index build), the read still+ * registers what it can (spare-side) but the proof is NOT intact:+ * `cat-file --filters` reconstructs the historical blob with TODAY's+ * filter definitions, and the row's content was imported under whatever+ * filter was active — at ITS import-time anchor, under ITS path AT THAT+ * TIME. The historical side is deliberately repo-wide rather than+ * per-path: the file can have been RENAMED since the import, so its+ * import-time filter was keyed to a path no current tree names, and a+ * per-path history walk would put git's rename-detection heuristics on+ * the DELETE side of the proof. `!filter` resets, entries deleted+ * outright, and interval-only filters all land on the spare side. The+ * remaining residual is an UNVERSIONED attribute source+ * (info/attributes, core.attributesFile) whose filter entry was removed+ * since the import, or an import-time state force-pushed out of the+ * reachable history — invisible to every git surface.+ */+function anchorBlobSlugs(+ gitContextRoot: string,+ anchorCommit: string,+ rel: string,+ historicalFilter: boolean,+): { slugs: string[]; proofIntact: boolean } {+ try {+ const filtered = historicalFilter || pathHasContentFilter(gitContextRoot, rel);+ const size = Number(git(gitContextRoot, ['cat-file', '-s', `${anchorCommit}:${rel}`]));+ if (Number.isFinite(size) && size > MAX_FILE_SIZE) return { slugs: [], proofIntact: false };+ // BOTH the raw blob and the filter-converted view register (union,+ // spare-side): a smudge filter that STRIPS the slug line hides it from+ // the converted view while the raw blob still carries it. The+ // injection direction (a drifted smudge that ADDED the slug at import+ // time) is invisible to every git surface — that is what the+ // filter-presence proof downgrade below is for.+ const slugs = new Set<string>();+ const raw = git(gitContextRoot, ['cat-file', 'blob', `${anchorCommit}:${rel}`]);+ if (raw.length > MAX_FILE_SIZE) return { slugs: [], proofIntact: false };+ for (const s of frontmatterSlugShapes(raw, rel)) slugs.add(s);+ const converted = git(gitContextRoot, ['cat-file', '--filters', `${anchorCommit}:${rel}`]);+ if (converted.length <= MAX_FILE_SIZE) {+ for (const s of frontmatterSlugShapes(converted, rel)) slugs.add(s);+ }+ return { slugs: [...slugs], proofIntact: !filtered };+ } catch {+ return { slugs: [], proofIntact: false };+ }+}++/**+ * Every reachable commit that CHANGED an attributes file (root or nested+ * .gitattributes), walked from BOTH the current HEAD and the anchor (a+ * blocked past sync can have imported at a commit ahead of the anchor;+ * multiple start points cover both ancestries even after a force-push+ * moved one aside). The attribute state at any past import-time anchor is+ * the state at its nearest attribute-epoch ancestor, so checking the+ * filter attribute at every epoch covers every historical state a live+ * row can have been imported under. The anchor itself is appended so the+ * check never depends on the epoch enumeration being exhaustive for it.+ * Returns null when the enumeration fails — the caller downgrades every+ * anchor proof (spare-side).+ */+function attributeEpochCommits(gitContextRoot: string, anchorCommit: string): string[] | null {+ try {+ // A shallow clone's history is truncated: an import-time filter epoch+ // can sit below the shallow boundary where no enumeration reaches it.+ // Unprovable, not absent.+ if (git(gitContextRoot, ['rev-parse', '--is-shallow-repository']) === 'true') return null;+ // --full-history: the default path-simplified walk prunes a side line+ // whose attribute change was discarded at a merge (`-s ours` of an+ // experiment branch is TREESAME to the kept parent) — but a sync+ // anchored ON that side line imported under the pruned filter state.+ const out = git(gitContextRoot, [+ 'log', '--full-history', '--format=%H', 'HEAD', anchorCommit, '--',+ '.gitattributes', ':(glob)**/.gitattributes',+ ]);+ const epochs = out.split('\n').filter(Boolean);+ if (!epochs.includes(anchorCommit)) epochs.push(anchorCommit);+ return epochs;+ } catch {+ return null;+ }+}++/**+ * Is a `filter` attribute in effect for this path under TODAY's+ * attributes? `check-attr --all` omits genuinely-unspecified attributes+ * from its output entirely, so ANY `filter` line — whatever its value,+ * including the magic-looking `unspecified`/`unset` tokens that a literal+ * driver name can produce, and regardless of whether a driver is still+ * configured (a removed driver leaves the attribute behind and may have+ * converted content back when it was imported) — counts as filtered.+ * Explicit `-filter` lands here too: spare-side only, never delete-side.+ * Any failure counts as filtered (fail toward unprovable, never a delete).+ */+function pathHasContentFilter(gitContextRoot: string, rel: string): boolean {+ try {+ const out = gitRawOutput(gitContextRoot, ['check-attr', '--all', '-z', '--', rel]);+ if (out === '') return false;+ // -z output is a flat sequence of NUL-terminated <path> <attr> <value>+ // triplets; the attribute name sits at every 3k+1 position.+ const fields = out.split('\u0000');+ for (let i = 1; i + 1 < fields.length; i += 3) {+ if (fields[i] === 'filter') return true;+ }+ return false;+ } catch {+ return true;+ }+}++/**+ * Do the attributes files at ANY reachable attribute epoch assign a+ * content filter to ANYTHING? Deliberately repo-wide, not per-path: a+ * fallback-regime file can have been RENAMED since its import, so its+ * import-time filter was keyed to a path no current tree names — a+ * per-path history walk would put git's rename-detection heuristics on+ * the DELETE side of the proof. Text-level `filter=` detection+ * over-approximates (a commented-out assignment still counts), which is+ * purely spare-side; `-filter`/`!filter` lines assign nothing and+ * convert nothing, and git rejects `filter` inside `[attr]` macros, so+ * the token cannot be introduced without the literal `filter=` text.+ * A grep failure that is not a clean no-match counts as filtered.+ */+function anyFilterAtAttributeEpochs(gitContextRoot: string, epochs: string[]): boolean {+ for (const epoch of epochs) {+ try {+ git(gitContextRoot, [+ 'grep', '-l', '-F', 'filter=', epoch, '--',+ '.gitattributes', ':(glob)**/.gitattributes',+ ]);+ return true;+ } catch (err) {+ if ((err as { status?: unknown }).status === 1) continue;+ return true;+ }+ }+ return false;+}++/**+ * The slugs a fallback-regime file (path derives no slug) can own a row+ * under, resolved the way import resolves them — parseMarkdown for the+ * frontmatter `slug:`, then the SAME validateSlug chokepoint+ * importFromContent runs, which lowercases (a `slug: Party-Notes` row is+ * stored as `party-notes`; an index carrying the raw casing would miss it+ * and misclassify the live row as stale). A slug the current chokepoint+ * REJECTS still registers in both casings: a legacy row imported under+ * older validation rules may carry it, and extra entries are purely+ * spare-side.+ *+ * THREE current-path content states are consulted and their slugs unioned+ * (the fourth state — the sync anchor commit — is enumerated as its own+ * tree by trackedSlugIndex, since a rename moves its content to a path no+ * current-path lookup can reach):+ * - the working tree — what the next import would read; never followed+ * through a symlink (import rejects symlinks via lstat before reading,+ * and following one would read an arbitrary out-of-repo target);+ * - the git index (staging) blob — what an in-flight `git add` holds;+ * - the HEAD blob — the last committed content. An uncommitted edit+ * that removes or changes the `slug:` line must not un-prove the slug+ * the imported row still carries — and STAGING that edit changes the+ * first two states at once, so HEAD keeps proving it.+ *+ * `proofIntact` goes false when either side that might name a slug could+ * not be examined — an unreadable file (EACCES; plain working-tree absence+ * is normal, the blob covers it), a side over the import size gate (a row+ * imported while the file was under the gate stays live, and an unread+ * file must never supply a staleness proof), a smudge filter expanding the+ * blob past the gate after the raw-size check, or a path with no stage-0+ * index entry (unmerged). The caller then marks the whole index incomplete+ * and every miss is spared as unknown.+ */+function fallbackSlugsForFile(+ gitContextRoot: string,+ rel: string,+): { slugs: string[]; proofIntact: boolean } {+ const contents: string[] = [];+ let proofIntact = true;+ try {+ // `rel` comes from `git ls-files`/`git ls-tree` (trackedSlugIndex, above) —+ // paths git itself tracked, never external input — but reject any `..`+ // segment before it reaches join() rather than trust that invariant+ // silently (semgrep path-join-resolve-traversal; belt-and-braces+ // alongside the symlink guard below, which covers the OTHER+ // out-of-repo-read vector this function's own docstring calls out).+ if (rel.split('/').includes('..')) {+ proofIntact = false;+ } else {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal+ const abs = join(gitContextRoot, rel);+ const st = lstatSync(abs);+ if (!st.isSymbolicLink()) {+ if (st.size > MAX_FILE_SIZE) proofIntact = false;+ else contents.push(readFileSync(abs, 'utf-8'));+ }+ }+ // A symlink's own registrable content is its index blob (the target+ // path text, read below) — matching both git's view and import's+ // refusal to follow it.+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'ENOENT') proofIntact = false;+ }+ try {+ const blobSize = Number(git(gitContextRoot, ['cat-file', '-s', `:${rel}`]));+ if (Number.isFinite(blobSize) && blobSize > MAX_FILE_SIZE) {+ proofIntact = false;+ } else {+ // git()'s trim() can only ADD a frontmatter parse (leading+ // whitespace stripped) — spare side. Re-check the size AFTER the+ // read: a smudge filter can expand output past the raw blob size.+ const c = git(gitContextRoot, ['cat-file', '--filters', `:${rel}`]);+ if (c.length > MAX_FILE_SIZE) proofIntact = false;+ else contents.push(c);+ }+ } catch {+ // No stage-0 entry (unmerged path) or another repo oddity: the+ // committed side could not be examined.+ proofIntact = false;+ }+ // HEAD blob — the last COMMITTED content, the state sync's own imports+ // actually came from. `:${rel}` above is the STAGING index, so staging+ // an uncommitted edit that removes the slug: line changed BOTH other+ // states at once — and un-proved (deleted) the row imported from HEAD.+ try {+ const inHead = git(gitContextRoot, ['ls-tree', 'HEAD', '--', rel]);+ if (inHead !== '') {+ const headSize = Number(git(gitContextRoot, ['cat-file', '-s', `HEAD:${rel}`]));+ if (Number.isFinite(headSize) && headSize > MAX_FILE_SIZE) {+ proofIntact = false;+ } else {+ const c = git(gitContextRoot, ['cat-file', '--filters', `HEAD:${rel}`]);+ if (c.length > MAX_FILE_SIZE) proofIntact = false;+ else contents.push(c);+ }+ }+ // Absent from HEAD (a newly added file) is normal — nothing to prove.+ } catch {+ proofIntact = false;+ }+ // No frontmatter slug in a content state → that state derives nothing+ // (the import path refuses it). Residual, accepted: a row from a content+ // revision older than EVERY consulted state carries a slug this pass+ // cannot recover — it would also need drifted source_path bookkeeping to+ // ever become a reconcile candidate.+ const slugs = new Set<string>();+ for (const content of contents) {+ for (const s of frontmatterSlugShapes(content, rel)) slugs.add(s);+ }+ return { slugs: [...slugs], proofIntact };+}++/**+ * #3479 blocker 2 — find open `<rename:…>` sentinels with nothing left to+ * reconcile. A sentinel is orphaned when NO active row carries the rename's+ * OLD source_path (read back out of the sentinel's own error text) anymore:+ * the duplicate it guarded against is gone — hard-deleted, or soft-deleted+ * by the operator's `gbrain delete` — so keeping the row open only ages+ * doctor toward a permanent FAIL.+ *+ * Fail-closed on every uncertain branch: a sentinel that failed again THIS+ * run (in `excludePaths`), one whose error text doesn't parse, or a probe+ * that throws leaves the row open — only a positive "no active row has the+ * old path" clears. ANY surviving active row keeps its sentinel: the+ * duplicate is real, and the operator remedy (`gbrain delete <stale-slug>`)+ * or a converging retry is the way out, not silent bookkeeping cleanup.+ */+async function orphanedRenameSentinels(+ engine: BrainEngine,+ sourceId: string,+ excludePaths: ReadonlySet<string>,+): Promise<string[]> {+ const candidates: Array<{ path: string; from: string }> = [];+ for (const row of loadSyncFailures()) {+ if (row.source_id !== sourceId || row.state !== 'open') continue;+ if (!row.path.startsWith(RENAME_SENTINEL_PREFIX)) continue;+ if (excludePaths.has(row.path)) continue;+ const from = parseRenameReconcileFrom(row.error);+ if (from === undefined) continue;+ candidates.push({ path: row.path, from });+ }+ if (candidates.length === 0) return [];+ try {+ const active = await activeSlugsBySourcePath(+ engine, [...new Set(candidates.map(c => c.from))], sourceId,+ );+ const firstPass = candidates.filter(c => !active.has(c.from));+ if (firstPass.length === 0) return [];+ // Second probe, immediately before the verdict leaves this function: a+ // writer outside the sync lock (a raw import, restore_page) can+ // materialize an active row with the old path between probe and clear.+ // Requiring two consecutive positive "no active row" verdicts shrinks+ // that window to the clear itself. Full atomicity is unreachable here —+ // the file ledger and the DB share no transaction — and a duplicate+ // re-created AFTER the clear is out of any sentinel's reach by design:+ // the sentinel is a one-shot failure record of a specific reconcile,+ // not a continuously re-derived invariant.+ const recheck = await activeSlugsBySourcePath(+ engine, [...new Set(firstPass.map(c => c.from))], sourceId,+ );+ return firstPass.filter(c => !recheck.has(c.from)).map(c => c.path);+ } catch {+ // Probe unavailable — leave every row open rather than guess.+ return [];+ }+}++/**+ * The quiet-run half of the #3479 blocker-2 fix: the up_to_date early+ * returns never reach the failure gate, and the reviewer's exact probe was+ * a `synced` then `up_to_date` run pair that left the orphaned sentinel+ * open forever. Clears directly through the ledger; a no-op (including the+ * no-ledger-file case) costs one small file read.+ *+ * Clear-then-verify: after the clear, verifyOrRestoreClearedSentinels runs+ * the probe once more and restores any sentinel whose old path re-acquired+ * an active row in the window.+ */+async function sweepOrphanedRenameSentinels(+ engine: BrainEngine,+ sourceId: string,+ excludePaths: ReadonlySet<string> = new Set(),+): Promise<void> {+ const orphaned = await orphanedRenameSentinels(engine, sourceId, excludePaths);+ if (orphaned.length === 0) return;+ const orphanSet = new Set(orphaned);+ // Captured BEFORE the clear so a restore can reproduce the exact row.+ const clearedRows = loadSyncFailures().filter(+ r => r.source_id === sourceId && orphanSet.has(r.path),+ );+ clearFailures(sourceId, orphaned);+ serr(+ ` [sync] cleared ${orphaned.length} orphaned rename sentinel(s) — ` ++ `the stale row(s) they guarded no longer resolve.`,+ );+ await verifyOrRestoreClearedSentinels(engine, sourceId, clearedRows);+}++/**+ * The verify half of clear-then-verify (#3583), shared by every path that+ * clears `<rename:…>` sentinels on an orphan verdict (the quiet-run sweeps+ * AND both failure gates): probe once more AFTER the clear and RESTORE —+ * verbatim, via restoreFailures, so attempts / first_seen / commit survive+ * — any sentinel whose old path re-acquired an active row. A writer+ * outside the sync lock (a raw import, restore_page) landing between+ * probe and clear thereby converts from silently-lost to+ * detected-and-repaired.+ *+ * Fail-closed: when the verify probe itself is unavailable, EVERY cleared+ * row is restored — a premature restore is self-healing (the next quiet+ * run re-clears a genuinely-orphaned sentinel), a lost sentinel is not.+ * restoreFailures skips rows that are already present, so this can never+ * double-record or fight a gate that did not actually clear. A writer+ * landing after the verify probe is indistinguishable from one landing a+ * second after a legitimate clear — out of any sentinel's reach by design+ * (the sentinel is a one-shot failure record, not a continuously+ * re-derived invariant), and the file ledger and the DB share no+ * transaction that could close it.+ */+async function verifyOrRestoreClearedSentinels(+ engine: BrainEngine,+ sourceId: string,+ clearedRows: SyncFailure[],+): Promise<void> {+ if (clearedRows.length === 0) return;+ let revived: SyncFailure[];+ try {+ const froms = new Map<string, string>();+ for (const row of clearedRows) {+ const from = parseRenameReconcileFrom(row.error);+ if (from !== undefined) froms.set(row.path, from);+ }+ const active = await activeSlugsBySourcePath(+ engine, [...new Set(froms.values())], sourceId,+ );+ revived = clearedRows.filter(r => {+ const from = froms.get(r.path);+ return from !== undefined && active.has(from);+ });+ } catch {+ revived = clearedRows;+ }+ const restored = restoreFailures(sourceId, revived);+ if (restored > 0) {+ serr(+ ` [sync] restored ${restored} rename sentinel(s) — an active row ` ++ `re-acquired the old path after the clear, or verification was unavailable.`,+ );+ }+}+async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<SyncResult> {// v0.41.8.0 (D9 / #1342): phase breadcrumbs. The #1342 reporter saw// ZERO stderr output before their sync hang, which made the bug@@ -1130,8 +1743,13 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy`[sync] checkpoint target ${storedTarget.slice(0, 8)} no longer reachable ` +`(history rewritten); restarting against HEAD.`,);- await clearOpCheckpoint(engine, ckpt.paths);- await clearOpCheckpoint(engine, ckpt.target);+ // #3583 review: NOT under --dry-run — this hygiene clear is a+ // persistent write, and the real run re-detects the unreachable+ // pin and clears it itself; a preview only reports.+ if (!opts.dryRun) {+ await clearOpCheckpoint(engine, ckpt.paths);+ await clearOpCheckpoint(engine, ckpt.target);+ }}}}@@ -1201,7 +1819,10 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Syscoped && p.startsWith(syncScopeRelPath + '/') ? p.slice(syncScopeRelPath.length + 1) : p;const excluded = (p: string): boolean =>opts.exclude !== undefined && opts.exclude.length > 0 && matchesAnyGlob(scopeRel(p), opts.exclude);- const syncOpts = opts.strategy ? { strategy: opts.strategy } : undefined;+ // #4027: includeHidden must ride along wherever isSyncable() consults these+ // opts — dropping it here silently disables --include-hidden on the whole+ // delta path (and the #3974 drift counter) while the flag still parses.+ const syncOpts = { strategy: opts.strategy, includeHidden: opts.includeHidden };// Filtered working-tree counts. Renames decompose as add(to) + delete(from)// — the same decomposition the import path applies — so a rename-only dirty@@ -1265,12 +1886,25 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy// reads it), separate from the import-converged bookmark. Without this,// a cron-driven `*/15 sync` over a quiet vault leaves last_sync_at pinned// to the last real commit, so doctor falsely flags the source as stale.- if (opts.sourceId) {+ // #3583 review: NOT under --dry-run — a preview that bumps the freshness+ // heartbeat masks real staleness from doctor.+ if (opts.sourceId && !opts.dryRun) {await engine.executeRaw(`UPDATE sources SET last_sync_at = now() WHERE id = $1`,[opts.sourceId],);}+ // #3479 blocker 2: quiet runs bypass the failure gate below, and an+ // orphaned `<rename:…>` sentinel would otherwise sit open forever.+ // #3583 review: NOT under --dry-run — the sweep rewrites the failure+ // ledger, and this early return sits ABOVE the dry-run gate, so an+ // unguarded sweep here made a preview clear the operator's only wedge+ // signal. (The sibling site below already sits after the dry-run+ // return, and performFullSync's dry-run return precedes both of its+ // sweep sites.)+ if (!opts.dryRun) {+ await sweepOrphanedRenameSentinels(engine, opts.sourceId ?? DEFAULT_SOURCE_ID);+ }return {status: 'up_to_date',fromCommit: lastCommit,@@ -1288,9 +1922,13 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy`[sync] chunker_version gate: stored=${storedVersion ?? 'unset'}, current=${currentVersion}. ` +`Forcing full re-chunk pass (git HEAD unchanged but pipeline version advanced).`,);- const result = await performFullSync(engine, fullSyncRoots, headCommit, opts);- await writeChunkerVersion(engine, opts.sourceId, currentVersion);- return result;+ // #3583 gate13: NO unconditional version write here. performFullSync's+ // own gated advance writes the version exactly when the re-chunk+ // actually completed — writing it here acknowledged the version on a+ // BLOCKED run (losing the retry signal: the next run said up_to_date+ // and the failed re-walk never re-ran) and on a --dry-run PREVIEW+ // (persistent brain-state write from a preview).+ return await performFullSync(engine, fullSyncRoots, headCommit, opts);}// Diff using git diff (net result, not per-commit). v0.42.x (#1794): diff@@ -1509,8 +2147,15 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sytry {const existing = await engine.getPage(slug, pageOpts);if (existing) {- await engine.deletePage(slug, pageOpts);- slog(` Deleted un-syncable page: ${slug}`);+ // #3583 review: this loop sits ABOVE the dry-run return below, so+ // an unguarded delete made a preview under a narrower strategy+ // hard-delete previously-imported pages. A preview only reports.+ if (opts.dryRun) {+ slog(` [dry-run] would delete un-syncable page: ${slug}`);+ } else {+ await engine.deletePage(slug, pageOpts);+ slog(` Deleted un-syncable page: ${slug}`);+ }}} catch { /* ignore */ }}@@ -1556,6 +2201,9 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<SymalformedSkipped.map(sanitizePathForDisplay).join(', '),);}+ // #3479 blocker 2: this early return also bypasses the failure gate —+ // sweep orphaned `<rename:…>` sentinels here too.+ await sweepOrphanedRenameSentinels(engine, opts.sourceId ?? DEFAULT_SOURCE_ID);return {status: 'up_to_date',fromCommit: lastCommit,@@ -1918,6 +2566,66 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy// either sweep them all OR violate (source_id, slug) UNIQUE).const renameOpts = opts.sourceId ? { sourceId: opts.sourceId } : undefined;+ // #3583 review: lazily-built (at most once per run) tracked-file slug+ // index for the live-row filter in the reconcile below. A throw from the+ // index build surfaces inside the reconcile's own try/catch, where it+ // records the `<rename:…>` sentinel — fail-closed, never a guessed delete.+ // Liveness = tracked in the git index, deliberately NOT "present on+ // disk": sync's ground truth is git, and in a sparse/partial checkout a+ // tracked file is intentionally absent from the working tree — an+ // on-disk check would misclassify its live page as stale and delete it,+ // the same failure shape this filter exists to prevent.+ // Three-way verdict, not boolean: when the index is incomplete (an+ // unreadable fallback-regime file — see trackedSlugIndex), an index miss+ // proves nothing, so the row is spared as 'unknown' rather than deleted.+ let treeSlugIndex: TrackedSlugIndex | undefined;+ const slugLiveness = (s: string): 'live' | 'stale' | 'unknown' => {+ // lastCommit = the commit the brain reflects; its blob is one of the+ // consulted content states (see fallbackSlugsForFile).+ treeSlugIndex ??= trackedSlugIndex(gitContextRoot, lastCommit);+ if (treeSlugIndex.slugs.has(s)) return 'live';+ return treeSlugIndex.complete ? 'stale' : 'unknown';+ };++ // #3583 review (GATE6): the old slug of EVERY rename in this diff. A+ // row can be CARRIED by a different rename in the same diff whose+ // destination derives no slug (ordinary path → exotic path, frontmatter+ // absent): no current path, blob, or anchor state names its slug, but+ // the rename pair itself proves the content is still tracked. The+ // reconcile of rename R therefore spares candidates that are ANOTHER+ // rename's old slug; R's OWN old slug stays deletable — that is+ // exactly the duplicate the reconcile exists to remove once the+ // destination materializes. Built over the RAW manifest — not the+ // scope/exclude/resume-filtered list — so a carried row is protected+ // even when its own rename was filtered out of processing (an+ // --exclude'd or out-of-scope destination still proves the content is+ // tracked; registration is purely spare-side).+ // Each from-path maps to a SET of slugs, never one: source_path is+ // non-unique, so a DB resolve can return an UNRELATED row's slug+ // (stale bookkeeping naming the same path) and silently displace the+ // path-derived slug the carried-spare depends on — the carried row+ // then lost its protection and the GATE6 delete came back. The set+ // always holds the path-derived slug (when the path derives one)+ // PLUS every active row's slug under that source_path; registration+ // is purely spare-side, so over-inclusion only delays a cleanup.+ // Spare-side only: a resolve failure merely shrinks the DB half of the+ // set, and the path-derived entries still protect the carried row.+ let dbSlugsByFrom = new Map<string, string[]>();+ try {+ dbSlugsByFrom = await activeSlugsBySourcePath(+ engine, manifest.renamed.map(r => r.from), opts.sourceId ?? DEFAULT_SOURCE_ID,+ opts.signal,+ );+ } catch { /* see above — both consumers degrade safely */ }+ const renameOldSlugs = new Map<string, Set<string>>();+ for (const r of manifest.renamed) {+ const shapes = new Set<string>();+ const derived = resolveSlugForPath(r.from);+ if (derived !== '') shapes.add(derived);+ for (const s of dbSlugsByFrom.get(r.from) ?? []) shapes.add(s);+ renameOldSlugs.set(r.from, shapes);+ }+// T4: pre-resolve ALL `from` slugs in batches before iterating. Falls// back to per-path resolveSlugByPathOrSourcePath when sourceId is// unset (matches the delete loop's legacy posture). For large rename@@ -1933,14 +2641,29 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Syreturn await partial('timeout');}const batch = fromPaths.slice(i, i + DELETE_BATCH_SIZE);- // #3942: guarded resolver — a refused from-path gets NO entry, so the- // rename below skips updateSlug and falls back to add + reconcile.- const res = await resolveSlugsForRemovedPaths(engine, batch, sid);- for (const r of res.refused) serr(refusedRemovedPathMessage(r));- for (const [p, s] of res.slugs) fromSlugByPath.set(p, s);+ let m: Map<string, string>;+ try {+ m = await engine.resolveSlugsByPaths(batch, { sourceId: sid });+ } catch {+ m = new Map();+ }+ for (const p of batch) {+ fromSlugByPath.set(p, m.get(p) ?? resolveSlugForPath(p));+ }}}+ // Is a `<rename:…>` sentinel for this destination already open from an+ // earlier run? Read once per run: the ledger is only rewritten at the+ // gate, after this loop.+ const openRenameSentinels = new Set(+ loadSyncFailures()+ .filter(f => f.source_id === (opts.sourceId ?? DEFAULT_SOURCE_ID) && f.state === 'open')+ .map(f => f.path),+ );+ const renameSentinelAlreadyOpen = (to: string): boolean =>+ openRenameSentinels.has(renameSentinelPath(to));+for (const { from, to } of renamesToDo) {// v0.41.13.0 (T2 / D-V4-2): per-iteration abort check. Renames call// importFile() at line 1173-style sites which can be slow on big files;@@ -1949,11 +2672,10 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Syprogress.finish();return await partial('timeout');}- // #3942: a refused (foreign-origin) from-path resolves to undefined —- // never rename a page whose recorded origin is a different file.+ // T4: the batch-resolved slug for `from` (see fromSlugByPath above).const oldSlug = opts.sourceId- ? fromSlugByPath.get(from)- : await resolveRemovedPathSlug(engine, from, undefined, serr);+ ? (fromSlugByPath.get(from) ?? resolveSlugForPath(from))+ : await resolveSlugByPathOrSourcePath(engine, from, undefined);// The new path doesn't yet have a row, so resolve from path only.const newSlug = resolveSlugForPath(to);// #3056: the cheap rename is OBSERVED, not assumed. A zero-row UPDATE@@ -1962,11 +2684,40 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy// the row at the new path while the old row stayed behind live. Both// shapes now fall through to the reconcile below.let renameApplied = false;- try {- if (oldSlug !== undefined) renameApplied = (await engine.updateSlug(oldSlug, newSlug, renameOpts)) > 0;- } catch {- // Destination slug occupied or invalid — treat as add; the reconcile- // below removes the stale old row once the destination materialized.+ if (oldSlug !== '') {+ try {+ renameApplied = (await engine.updateSlug(oldSlug, newSlug, renameOpts)) > 0;+ } catch {+ // Destination slug occupied or invalid — treat as add; the+ // reconcile below removes the stale old row once the destination+ // materialized.+ }+ }+ if (renameApplied) {+ // #3583 gate13: the cheap rename moves the ROW but updateSlug never+ // rewrites source_path — and the unchanged-content reimport below is+ // a no-write skip, so the stale bookkeeping survived indefinitely+ // and the full-sync purge later read it as "source file removed"+ // and hard-deleted the LIVE renamed page. Repair the bookkeeping at+ // the moment the rename lands. Best-effort, and nothing downstream+ // covers a miss: rows renamed BEFORE this repair — and rows whose+ // repair query fails — keep the stale path and stay exposed to the+ // full-sync purge exactly as they are on master. That exposure is+ // pre-existing (verified against the merge base) and out of scope+ // here; this repair stops the shape being manufactured going+ // forward.+ try {+ // Scope EXACTLY the way updateSlug scoped the move it repairs:+ // no sourceId means the DEFAULT source, never every source — an+ // unqualified UPDATE rewrote a matching (slug, source_path) row+ // in ANOTHER source, and that source's later fallback reconcile+ // probed the rewritten path, found nothing, and advanced without+ // its rename sentinel (gate 14).+ await engine.executeRaw(+ `UPDATE pages SET source_path = $1 WHERE source_id = $2 AND slug = $3 AND source_path = $4`,+ [to, opts.sourceId ?? DEFAULT_SOURCE_ID, newSlug, from],+ );+ } catch { /* bookkeeping only — never fail the rename over it */ }}// Reimport at new path (picks up content changes). Wrapped to match the// deletes/adds loops: a malformed renamed file is recorded to failedFiles@@ -2043,22 +2794,144 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Syconst destMaterialized = importResult.status === 'imported' ||(importResult.status === 'skipped' && !importResult.error && importResult.slug === newSlug);if (destMaterialized) {+ // Hoisted above the try so the failure record can name the exact+ // row `gbrain delete` should remove when the DELETE itself failed+ // (still unknown — recorded as `?` — when the probe threw first).+ //+ // ACTIVE rows only, considering EVERY row with the old path:+ // source_path is non-unique, and a one-row resolve could hand back+ // a soft-deleted row while a live duplicate sharing the path hides+ // behind it (#3479 review). Skipping already-soft-deleted rows is+ // also what makes `gbrain delete` (a soft delete) the documented+ // operator exit from a permanent delete-failure wedge (blocker 1):+ // retrying the hard delete against a row the operator already+ // removed would just re-fail and keep the sync blocked.+ // Rows whose CURRENT slug a working-tree file still derives to are+ // LIVE, not stale, and are filtered out before any delete (#3583+ // review) — so `staleSlug` below (and the sentinel/remedy text it+ // feeds) can only ever name a genuinely-stale row.+ let staleSlug: string | undefined;try {- const staleMap = await engine.resolveSlugsByPaths([from], { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID });- const staleSlug = staleMap.get(from);- if (staleSlug !== undefined && staleSlug !== newSlug) {- await engine.deletePage(staleSlug, renameOpts);- deletedSlugs.add(staleSlug); // never hand a deleted slug to auto-embed- serr(` [sync] rename reconciled: removed stale row ${staleSlug} (${from} -> ${to} fell back to add).`);- } else if (staleSlug === undefined) {- serr(` [sync] rename fallback: no row has source_path ${from}; stale row (if any) left in place.`);+ const active = await activeSlugsBySourcePath(+ engine, [from], opts.sourceId ?? DEFAULT_SOURCE_ID,+ );+ // #3583 review (data-loss blocker): `source_path = from` also+ // matches LIVE pages — after an ordinary cheap rename the+ // surviving row keeps the OLD path (updateSlug never rewrites+ // source_path; an unchanged-content re-import writes nothing).+ // Delete only rows whose CURRENT slug no tracked file derives+ // to; spare the rest — 'live' when a tracked file still derives+ // to the slug, 'unknown' when staleness could not be proven.+ const candidates = (active.get(from) ?? []).filter(s => s !== newSlug);+ const staleSlugs: string[] = [];+ const unprovable: string[] = [];+ for (const s of candidates) {+ // Carried by ANOTHER rename in this diff (see renameOldSlugs):+ // its content is still tracked even when no slug state names+ // it anymore — never a reconcile target of THIS rename.+ let carriedByOtherRename = false;+ for (const [rFrom, rOldSlugs] of renameOldSlugs) {+ if (rFrom !== from && rOldSlugs.has(s)) { carriedByOtherRename = true; break; }+ }+ if (carriedByOtherRename) {+ serr(+ ` [sync] rename reconcile: skipping row ${s} — another rename in ` ++ `this diff still carries it (source_path ${from} is stale bookkeeping).`,+ );+ continue;+ }+ const verdict = slugLiveness(s);+ if (verdict === 'live') {+ serr(+ ` [sync] rename reconcile: skipping live row ${s} — a tracked ` ++ `file still derives to it (source_path ${from} is stale bookkeeping).`,+ );+ } else if (verdict === 'unknown') {+ // An unreadable tracked file could own this slug, so the row+ // is NOT deleted. What happens to the RENAME depends on+ // whether it was already unresolved (see the check after this+ // loop): a first unprovable run is accepted and banks+ // normally — the usual cause is a live row whose slug merely+ // could not be read (content filter, shallow clone, sparse+ // checkout, over-size file), where nothing is pending — but a+ // rename that already carries an open sentinel is not+ // retired on this evidence.+ unprovable.push(s);+ serr(+ ` [sync] rename reconcile: cannot prove row ${s} stale — an ` ++ `unreadable tracked file could still own this slug, so it is ` ++ `spared rather than deleted.`,+ );+ } else {+ // Established bookkeeping cleanup (#3056 → gate 6): a stale+ // claimant is exactly the duplicate the reconcile exists to+ // remove once the destination materialized.+ staleSlugs.push(s);+ }+ }+ if (staleSlugs.length > 0) {+ // Delete every genuinely-stale active row still carrying the+ // old path — with a non-unique source_path there can be more+ // than one, and the rename is checkpointed after this loop, so+ // a survivor would never be retried (#3479 review, the ORDER BY+ // finding).+ //+ // Post-review note: the `slugLiveness(s)` verdict above and this+ // `deletePage` are not one atomic operation — `deletePage` takes+ // only `slug`, not a row id or updated_at, so it can't express+ // "delete iff still the row I just proved stale". Under+ // `performSync`'s per-source writer lock this window is closed+ // for every normal caller (no other sync/import for this source+ // can run concurrently); it only opens for a write that bypasses+ // the lock entirely (e.g. a direct `put_page` racing this run).+ // Closing it for real needs a conditional DELETE (id/source_path/+ // updated_at) added to `BrainEngine.deletePage` on both engines —+ // out of scope for this fix; tracked as a known gap rather than+ // silently assumed safe.+ for (const s of staleSlugs) {+ staleSlug = s;+ await engine.deletePage(s, renameOpts);+ deletedSlugs.add(s); // never hand a deleted slug to auto-embed+ serr(` [sync] rename reconciled: removed stale row ${s} (${from} -> ${to} fell back to add).`);+ }+ } else if (candidates.length > 0) {+ serr(` [sync] rename fallback: every active row with source_path ${from} was spared (live or unprovable); nothing stale to reconcile.`);+ } else {+ serr(` [sync] rename fallback: no active row has source_path ${from}; nothing left to reconcile.`);+ }+ if (unprovable.length > 0 && renameSentinelAlreadyOpen(to)) {+ // Provably-stale rows above were still removed; these were not+ // provable either way. On its own that is an accepted cost (see+ // the verdict comment). But an EARLIER run already recorded a+ // `<rename:…>` sentinel for this rename, so convergence has been+ // denied before — and falling through would hand that sentinel+ // to the success path, which the gate clears before it decides.+ // Clearing a non-convergence marker requires proof of+ // convergence, and 'unprovable' is not proof.+ // Deliberately NOT named: `staleSlug` feeds the sentinel's+ // "stale row X" slot and the blocked-run remedy tells the+ // operator to `gbrain delete X`. An unprovable row may well be+ // LIVE — that is the whole reason it was spared — so naming one+ // here would tell the operator to delete a page this very code+ // just refused to delete. Clearing it also drops whatever+ // actionable slug an earlier failure had recorded. `undefined`+ // renders as `?`, which is the truth: not known.+ staleSlug = undefined;+ throw new Error(+ `staleness unprovable for ${unprovable.length} row(s) ` ++ `(${unprovable.join(', ')}): the tracked-file slug index is ` ++ `incomplete, so no index miss proves a row stale, and this ` ++ `rename was already unresolved. Fix or remove the unreadable ` ++ `tracked file and re-run.`,+ );}} catch (e: unknown) {reconcileFailed = true;failedFiles.push({- path: `<rename:${to}>`,- error: `rename reconcile failed (stale row for ${from} not removed): ` +- `${e instanceof Error ? e.message : String(e)}`,+ path: renameSentinelPath(to),+ error: renameReconcileErrorMessage(+ from, staleSlug, e instanceof Error ? e.message : String(e),+ ),});}} else {@@ -2070,7 +2943,13 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy}// Converged (cheap rename, clean reconcile, or nothing to reconcile):// clear any `<rename:…>` sentinel a previous failing run recorded.- if (!reconcileFailed && !importErrored) succeededPaths.push(`<rename:${to}>`);+ // A run that spared an UNPROVABLE row reaches here too — that is the+ // accepted cost of never deleting without proof — EXCEPT when this+ // rename already had a sentinel open, which the reconcile turns into+ // a failure above precisely so this line cannot retire it. #2683+ // residual (#4496): a failed destination import likewise cannot retire+ // the sentinel — the rename did not converge.+ if (!reconcileFailed && !importErrored) succeededPaths.push(renameSentinelPath(to));pagesAffected.push(newSlug);deletedSlugs.delete(newSlug); // #1284: rename landed on a previously-deleted slug → embeddable again// A failed reconcile OR a failed destination import must NOT checkpoint:@@ -2554,25 +3433,64 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<SyskipFailed: opts.skipFailed === true,advance,});+ // #3479 blocker 2 — self-heal for orphaned `<rename:…>` sentinels: a+ // force-push that invalidates the pinned target means the rename never+ // re-enters the diff, so the ordinary convergence path above can never+ // clear the row and doctor ages it to a permanent FAIL no CLI can fix.+ // Deliberately AFTER the gate and OUTSIDE it (#3583): the gate used to+ // clear these via succeededPaths, which cleared BEFORE advance() — a+ // throwing advance then lost the sentinel with the verify never reached.+ // Out here, a gate that throws never clears anything (fail-closed), and+ // the sweep carries the full clear-then-verify-restore semantics.+ await sweepOrphanedRenameSentinels(+ engine, opts.sourceId ?? DEFAULT_SOURCE_ID, new Set(failedFiles.map(f => f.path)),+ );if (!gate.advanced) {const codeBreakdown = formatCodeBreakdown(failedFiles);// Two sentinel classes block here: `<head>` (pin ancestry broken) and// `<rename:…>` (#3056 — a rename-reconcile delete failed and advancing- // would permanently bank the duplicate). Pick the message by which fired.+ // would permanently bank the duplicate). Pick the message by which fired —+ // and when BOTH fired, the rename detail is appended to the head message+ // rather than silently losing to it (#3479 review).+ const renameRows = failedFiles.filter(f => f.path.startsWith(RENAME_SENTINEL_PREFIX));+ // The failing rows verbatim (path + error): the error names the stale+ // slug and the old path, which the operator remedy below points at —+ // a code-count breakdown alone can't tell them which row to delete.+ const renameDetail = renameRows.map(f => ` ${f.path}: ${f.error}`).join('\n');+ // #3479 blocker 1 — the sentinel hard-blocks even --skip-failed by+ // design, so an environment where the DELETE can never succeed (RLS+ // denying DELETE, an FK RESTRICT) needs a documented exit or a cosmetic+ // duplicate becomes a total sync outage. The remedy is deliberately NOT+ // pitched at a fully read-only database: 'gbrain delete' soft-deletes+ // via UPDATE, so it unwedges exactly the environments where writes work+ // but this DELETE does not.+ const renameRemedy =+ `The next 'gbrain sync' retries the reconcile from the same diff. If the delete ` ++ `keeps failing in your environment (RLS denying DELETE, an FK RESTRICT — anywhere ` ++ `UPDATE still works), remove the stale row yourself: 'gbrain delete <stale-slug>' ` ++ `with the stale slug named above (the reconcile only names rows whose backing file ` ++ `is gone from the working tree — never a live page). A sentinel reading 'stale row ?' ` ++ `names nothing on purpose: that run could not prove ANY row stale, usually because a ` ++ `tracked file could not be read — fix or remove that file instead of deleting a page. ` ++ `The reconcile then finds nothing left to delete and the sentinel clears on the next run.`;if (gate.sentinelBlocked && failedFiles.some(f => f.path === '<head>')) {serr(`\nSync blocked: repository history changed during sync (force-push / reset).\n` +`${codeBreakdown}\n\n` +`The pinned target is no longer an ancestor of HEAD; advancing would record ` +`a commit that doesn't match the indexed tree. Re-run sync to re-pin against ` +- `current HEAD.`,+ `current HEAD.` ++ (renameRows.length > 0+ ? `\n\nA rename also left a stale duplicate that could not be removed:\n` ++ `${renameDetail}\n\n${renameRemedy}`+ : ''),);} else if (gate.sentinelBlocked) {serr(`\nSync blocked: a rename left a stale duplicate that could not be removed:\n` +- `${codeBreakdown}\n\n` +- `The next 'gbrain sync' retries the reconcile from the same diff.`,+ `${renameDetail || codeBreakdown}\n\n` ++ renameRemedy,);} else {const fileFailCount = failedFiles.filter(f => isSkippablePath(f.path)).length;@@ -2912,6 +3830,7 @@ async function performFullSync(strategy: opts.strategy ?? 'markdown',includeGitignored: opts.includeGitignored,onExcluded: (rel) => { dryRunMalformed.push(rel); },+ includeHidden: opts.includeHidden,});if (opts.exclude && opts.exclude.length > 0) {allFiles = allFiles.filter(abs => !matchesAnyGlob(relative(syncScopeRoot, abs), opts.exclude));@@ -2969,6 +3888,7 @@ async function performFullSync(strategy: opts.strategy,sourceId: opts.sourceId,exclude: opts.exclude,+ includeHidden: opts.includeHidden,includeGitignored: opts.includeGitignored,slugRoot,// issue #1939: performFullSync owns the failure ledger + bookmark via the@@ -3008,11 +3928,34 @@ async function performFullSync(skipFailed: opts.skipFailed === true,advance: advanceFull,});+ // #3479 blocker 2 — the same orphaned-`<rename:…>`-sentinel self-heal the+ // incremental path applies (a full sync is often exactly the operator's+ // reset move after a wedge). AFTER and OUTSIDE the gate (#3583): a gate+ // that throws never clears anything, and the sweep carries the full+ // clear-then-verify-restore semantics.+ await sweepOrphanedRenameSentinels(engine, fullSourceId, fullFailureSet);if (!fullGate.advanced) {const codeBreakdown = formatCodeBreakdown(result.failures);if (fullGate.sentinelBlocked) {- serr(`\nFull sync blocked: repository history changed during sync.\n${codeBreakdown}`);+ // #3479 review — say WHICH sentinel fired: a `<rename:…>` block here+ // used to print the history-changed message, pointing the operator at+ // a force-push that never happened.+ const fullRenameRows = result.failures.filter(f => f.path.startsWith(RENAME_SENTINEL_PREFIX));+ if (fullRenameRows.length > 0) {+ serr(+ `\nFull sync blocked: a rename left a stale duplicate that could not be removed:\n` ++ `${fullRenameRows.map(f => ` ${f.path}: ${f.error}`).join('\n')}\n\n` ++ `If the delete keeps failing in your environment, remove the stale row ` ++ `yourself: 'gbrain delete <stale-slug>' with the stale slug named above ` ++ `(only rows whose backing file is gone are ever named — never a live page). ` ++ `A sentinel reading 'stale row ?' names nothing on purpose: that run could not ` ++ `prove ANY row stale — fix the unreadable tracked file it reports instead. ` ++ `The sentinel then clears on the next sync.`,+ );+ } else {+ serr(`\nFull sync blocked: repository history changed during sync.\n${codeBreakdown}`);+ }} else {const fileFailCount = result.failures.filter(f => isSkippablePath(f.path)).length;// #3875: code-aware copy — provider-infra failures must not be routed@@ -3097,9 +4040,14 @@ async function performFullSync(// #774: scoped syncs store git-root-relative source_paths (slugRoot), so// relativize the walk to the same base — otherwise every page mismatches// and the mass-delete valve trips on a perfectly healthy scoped source.+ // includeHidden MUST be threaded here too: if it isn't, any page a+ // --include-hidden full sync just imported would look "gone" on the+ // very next reconcile pass (its file was never in this collection) and+ // the mass-delete valve would remove it.const currentFiles = collectSyncableFiles(syncScopeRoot, {strategy: opts.strategy ?? 'markdown',includeGitignored: opts.includeGitignored,+ includeHidden: opts.includeHidden,}).map(abs => relative(slugRoot ?? syncScopeRoot, abs));const rows = await engine.executeRaw<{ slug: string; source_path: string | null }>(@@ -3219,6 +4167,12 @@ async function performFullSync(}}+ // #3479 blocker 2 — the post-gate sweep above ran BEFORE this reconcile,+ // so a `<rename:…>` sentinel whose stale row the reconcile just removed+ // would stay open until the NEXT run. Sweep again afterwards: a full sync+ // is the operator's usual reset move, and it should converge in one run.+ await sweepOrphanedRenameSentinels(engine, fullSourceId, fullFailureSet);+// Full sync doesn't track pagesAffected, so fall back to embed --stale.// v0.37 fix wave (Lane D.3 + CDX2-8): switched to runEmbedCore for the// same reason as the incremental path — surface dim-mismatch via hint@@ -3330,6 +4284,14 @@ Options:subdirectory directly as --repo also works.--exclude <glob> Exclude files matching the glob from sync (repeatable;matched against the scope-relative path).+ --include-hidden <glob>+ Waive the leading-dot prune (.git, .obsidian, and any+ other dot-prefixed directory — but NOT node_modules/+ vendor/dist/build/venv/*.raw, which are never+ waivable) for paths matching this glob (repeatable).+ Does not reach a non-git directory's FS-walk import+ fallback; every git-tracked source (the normal case)+ is covered. Cannot combine with --all.--include-gitignored Include otherwise-syncable files matched by .gitignore.Forces a full filesystem walk so periodic syncs seeignored untracked content.@@ -3548,9 +4510,14 @@ See also:for (let i = 0; i < args.length; i++) {if (args[i] === '--exclude' && i + 1 < args.length) excludePatterns.push(args[i + 1]);}- if (syncAll && (srcSubpath || excludePatterns.length > 0)) {+ // --include-hidden is repeatable, same parsing shape as --exclude.+ const includeHiddenPatterns: string[] = [];+ for (let i = 0; i < args.length; i++) {+ if (args[i] === '--include-hidden' && i + 1 < args.length) includeHiddenPatterns.push(args[i + 1]);+ }+ if (syncAll && (srcSubpath || excludePatterns.length > 0 || includeHiddenPatterns.length > 0)) {console.error(- `--src-subpath/--exclude scope a single sync invocation; they cannot be combined with --all. ` ++ `--src-subpath/--exclude/--include-hidden scope a single sync invocation; they cannot be combined with --all. ` +`For --all runs, register the subdirectory as the source's local_path instead ` +`(gbrain sources add <id> --path <repo>/<subdir>).`,);@@ -4081,6 +5048,7 @@ See also:strategy: strategyArg, concurrency,srcSubpath,exclude: excludePatterns.length > 0 ? excludePatterns : undefined,+ includeHidden: includeHiddenPatterns.length > 0 ? includeHiddenPatterns : undefined,signal: composeAbortSignals(singleSourceInterrupt.signal, singleSourceController?.signal),};diff --git a/src/commands/takes.ts b/src/commands/takes.tsindex 13c1292e9a..b106743f60 100644--- a/src/commands/takes.ts+++ b/src/commands/takes.ts@@ -27,6 +27,10 @@ import {} from '../core/takes-write.ts';import { resolveSourceId } from '../core/source-resolver.ts';import { resolveOwnerHolder } from '../core/owner-holder.ts';+import { embedStaleTakes } from '../core/embed-takes.ts';+import { assertEmbeddingEnabled } from '../core/embedding-dim-check.ts';+import { loadConfig } from '../core/config.ts';+import { embedQuery } from '../core/embedding.ts';import {listPendingProposals,acceptProposal,@@ -161,18 +165,28 @@ async function cmdList(engine: BrainEngine, args: string[]): Promise<void> {async function cmdSearch(engine: BrainEngine, args: string[]): Promise<void> {const query = args[0];if (!query) {- console.error('Usage: gbrain takes search "<query>" [--who h] [--json]');+ console.error('Usage: gbrain takes search "<query>" [--semantic] [--limit N] [--json]');process.exit(1);}const json = flagPresent(args, '--json');+ const semantic = flagPresent(args, '--semantic');const limit = parseInt(flagValue(args, '--limit') ?? '30', 10);- const hits = await engine.searchTakes(query, { limit });+ let hits;+ if (semantic) {+ assertEmbeddingEnabled(loadConfig());+ const { validateEmbeddingCreds } = await import('../core/embed-preflight.ts');+ validateEmbeddingCreds();+ const queryEmbedding = await embedQuery(query);+ hits = await engine.searchTakesVector(queryEmbedding, { limit });+ } else {+ hits = await engine.searchTakes(query, { limit });+ }if (json) {console.log(JSON.stringify(hits, null, 2));return;}if (hits.length === 0) {- console.log(`No takes match "${query}".`);+ console.log(`No ${semantic ? 'semantic ' : ''}takes match "${query}".`);return;}for (const h of hits) {@@ -181,6 +195,38 @@ async function cmdSearch(engine: BrainEngine, args: string[]): Promise<void> {}}+async function cmdEmbed(engine: BrainEngine, args: string[]): Promise<void> {+ const dryRun = flagPresent(args, '--dry-run');+ const json = flagPresent(args, '--json');+ const batchSizeRaw = flagValue(args, '--batch-size');+ const batchSize = batchSizeRaw === undefined ? undefined : Number.parseInt(batchSizeRaw, 10);+ if (batchSize !== undefined && (!Number.isInteger(batchSize) || batchSize < 1)) {+ console.error(`Invalid --batch-size "${batchSizeRaw}". Expected a positive integer.`);+ process.exit(1);+ }++ if (!dryRun) {+ assertEmbeddingEnabled(loadConfig());+ const { validateEmbeddingCreds } = await import('../core/embed-preflight.ts');+ validateEmbeddingCreds();+ }++ const result = await embedStaleTakes(engine, { batchSize, dryRun });+ if (json) {+ console.log(JSON.stringify(result, null, 2));+ } else if (dryRun) {+ console.log(`[dry-run] Would embed ${result.would_embed} active take(s)`);+ } else {+ console.log(`Embedded ${result.embedded} take(s); ${result.total_stale - result.embedded} remain stale.`);+ if (result.failures > 0) {+ console.error(`Failed to embed ${result.failures} take(s): ${result.failure_samples[0] ?? 'unknown error'}`);+ }+ }+ if (result.failures > 0) {+ throw new Error(`takes embedding failed for ${result.failures} take(s)`);+ }+}+async function cmdAdd(engine: BrainEngine, args: string[], sourceId?: string): Promise<void> {const slug = args[0];if (!slug) {@@ -565,8 +611,10 @@ Subcommands:List takes for a pagetakes list [--json] [--who h] [--kind k] [--sort ...] [--expired]List all active takes across the brain (#2079)- takes search "<query>" [--limit N] [--json]- Keyword search across all takes+ takes search "<query>" [--semantic] [--limit N] [--json]+ Keyword search, or semantic search with --semantic+ takes embed [--dry-run] [--batch-size N] [--json]+ Embed active takes for semantic think/search retrieval (#2089)takes add <slug> --claim "..." --kind <fact|take|bet|hunch> --who <holder>[--weight 0.5] [--source "..."] [--since YYYY-MM]Append a take (markdown + DB)@@ -602,6 +650,7 @@ Common flags:// "No takes on list." — reading exactly like an empty takes table.case 'list': return cmdList(engine, rest);case 'search': return cmdSearch(engine, rest);+ case 'embed': return cmdEmbed(engine, rest);case 'add': return cmdAdd(engine, rest, await resolveTakesSourceId(engine));case 'update': return cmdUpdate(engine, rest, await resolveTakesSourceId(engine));case 'supersede': return cmdSupersede(engine, rest, await resolveTakesSourceId(engine));diff --git a/src/commands/think.ts b/src/commands/think.tsindex 210868c8cc..01e854bd7f 100644--- a/src/commands/think.ts+++ b/src/commands/think.ts@@ -10,6 +10,7 @@ import { runThink, persistSynthesis, stripGapsSection } from '../core/think/indeimport { loadConfig, isThinClient } from '../core/config.ts';import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';import { canonicalLookup } from '../core/model-pricing.ts';+import { embedQuery } from '../core/embedding.ts';function flagValue(args: string[], name: string): string | undefined {const i = args.indexOf(name);@@ -162,6 +163,11 @@ prints what would have been the input (exit 0).}result = await runThink(engine, {question, anchor, rounds, save, take, model, since, until,+ // Fail-closed trust: local CLI must say so explicitly, or trajectory+ // injection degrades to visibility='world' rows.+ remote: false,+ // #3734: activate takes' vector retrieval arm for CLI think.+ embedQuestion: (q) => embedQuery(q),// #4508: thread the validated scope (RunThinkOpts.sourceId)....(sourceId ? { sourceId } : {}),// #1698: explicit --model → hard error on an unresolvable model (no silentdiff --git a/src/core/ai/capabilities.ts b/src/core/ai/capabilities.tsindex 63cacbef97..dc79555e7c 100644--- a/src/core/ai/capabilities.ts+++ b/src/core/ai/capabilities.ts@@ -23,7 +23,7 @@* decisions don't depend on it.*/-import { resolveRecipe } from './model-resolver.ts';+import { resolveChatContextTokens, resolveRecipe } from './model-resolver.ts';import { listRecipes } from './recipes/index.ts';import { AIConfigError } from './errors.ts';@@ -131,7 +131,7 @@ export function getProviderCapabilities(modelString: string): ProviderCapabilitisupportsThinking: typeof chat.thinking_by_default === 'function'? chat.thinking_by_default(parsed.modelId): chat.thinking_by_default === true,- maxContext: chat.max_context_tokens ?? 128_000,+ maxContext: resolveChatContextTokens(modelString) ?? 128_000,};}diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 0c151f9ac2..555c205989 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -23,7 +23,7 @@import { embed as aiEmbed, embedMany, generateObject, generateText, jsonSchema } from 'ai';import { AsyncLocalStorage } from 'node:async_hooks';-import { createHash } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';import { listRecipes } from './recipes/index.ts';import { createOpenAI } from '@ai-sdk/openai';import { createGoogleGenerativeAI } from '@ai-sdk/google';@@ -52,7 +52,8 @@ import {OPENROUTER_CACHE_HEADER,openrouterRequiresExplicitPromptCache,} from './recipes/openrouter.ts';-import { resolveModel, resolveModelDetailed, resolveEffectiveChatModel, resolveEffectiveExpansionModel } from '../model-config.ts';+import { resolveModelDetailed, resolveEffectiveChatModel, resolveEffectiveExpansionModel } from '../model-config.ts';+import { snapshotConfigReader } from '../config-snapshot.ts';import { parseLlmJson } from '../llm-json.ts';import type { BrainEngine } from '../engine.ts';import { dimsProviderOptions } from './dims.ts';@@ -550,15 +551,26 @@ export async function reconfigureGatewayWithEngine(engine: BrainEngine): Promiseenv: cfg.env ?? process.env,baseUrl: resolveNativeBaseUrl('openai', cfg),});++ // The two resolutions below each walk a 5-tier precedence chain that reads+ // up to 4 config keys, plus alias expansion. Against the engine that is+ // many sequential round trips before the CLI does any work — seconds of+ // `gbrain stats`'s wall clock on a hosted brain, for reads the server+ // answered in microseconds. Take one snapshot of the config table (AFTER+ // the discovery refresh above, so tier defaults see fresh discovery) and+ // resolve every model against it. Same keys, same precedence, one round+ // trip.+ const reader = await snapshotConfigReader(engine);+// Resolve expansion (utility tier) and chat (reasoning tier). Embedding is// intentionally NOT re-resolved here — switching embedding models invalidates// the vector index. Out of scope per v0.31.12 plan ("Embedding tier knob").- const expansionDetailed = await resolveModelDetailed(engine, {+ const expansionDetailed = await resolveModelDetailed(reader, {configKey: 'models.expansion',tier: 'utility',fallback: cfg.expansion_model ?? DEFAULT_EXPANSION_MODEL,});- const chatDetailed = await resolveModelDetailed(engine, {+ const chatDetailed = await resolveModelDetailed(reader, {configKey: 'models.chat',tier: 'reasoning',fallback: cfg.chat_model ?? DEFAULT_CHAT_MODEL,@@ -2778,6 +2790,21 @@ export async function expand(query: string): Promise<string[]> {result = await _generateObjectTransport({model,schema: ExpansionSchema,+ // Name the schema. On the native-anthropic path the SDK turns the schema+ // into a tool, and without a name+description that tool carries no+ // `description` field. api.anthropic.com tolerates that; an+ // Anthropic-COMPATIBLE endpoint need not, and at least one (z.ai/GLM)+ // then ignores `tool_choice: {type:'tool'}` and answers with+ // markdown-fenced JSON as ordinary text. Measured 3/3 deterministic both+ // ways against z.ai: with a description, 3/3 tool_use; without it, 3/3+ // end_turn+text. generateObject then sees no object, `result.object` is+ // undefined, and expansion degrades to the bare query — on EVERY call,+ // with no error line, because the catch below only reports AIConfigError.+ // The two openai-compatible branches already recover via viaText(); this+ // native branch has no such fallback, so naming the schema is its only+ // guard.+ schemaName: 'query_expansions',+ schemaDescription: 'The rewritten search queries used to retrieve relevant documents.',abortSignal: withDefaultTimeout(undefined, AI_CHAT_TIMEOUT_MS),prompt: expansionPrompt,});@@ -2795,6 +2822,12 @@ export async function expand(query: string): Promise<string[]> {const result = await _generateObjectTransport({model,schema: ExpansionSchema,+ // Same schema name+description as the native branch above: an+ // Anthropic-compatible endpoint reached through this lane can hinge+ // its tool_choice compliance on the tool carrying a description+ // (the z.ai/GLM failure mode), and naming costs nothing elsewhere.+ schemaName: 'query_expansions',+ schemaDescription: 'The rewritten search queries used to retrieve relevant documents.',abortSignal: withDefaultTimeout(undefined, AI_CHAT_TIMEOUT_MS),prompt: expansionPrompt,});@@ -3069,6 +3102,23 @@ function safeStringify(value: unknown): string {}}+/**+ * Some Anthropic-compatible providers (notably z.ai/GLM) occasionally return a+ * tool-call part WITHOUT a `toolCallId`. AI SDK v6's ModelMessage schema requires+ * `toolCallId: z.string()`, so an undefined id is invisible on the turn it is+ * produced but throws "The messages do not match the ModelMessage[] schema" the+ * moment that assistant turn is replayed as history on the next tool-loop turn —+ * permanently wedging the job (observed as ~528 identical autopilot failures).+ * Synthesize a stable, unique id AT THE SOURCE (`chat()` block-normalization) so+ * the SAME id flows to both the persisted tool-call block and its matching+ * tool-result block within a turn. Also used defensively in `toModelMessages` to+ * keep any already-persisted poisoned rows from throwing on replay.+ */+function ensureToolCallId(id: unknown, toolName: string): string {+ if (typeof id === 'string' && id.length > 0) return id;+ return `glmfix-${toolName}-${randomUUID()}`;+}+export function toModelMessages(messages: ChatMessage[]): unknown[] {return messages.map((m) => {if (typeof m.content === 'string') return { role: m.role, content: m.content };@@ -3120,9 +3170,12 @@ export function toModelMessages(messages: ChatMessage[]): unknown[] {};}if (b.type === 'tool-call') {+ // ensureToolCallId here is the defensive half: rows persisted before+ // the chat()-side fix can still carry an undefined id, and replaying+ // one would throw on the ModelMessage schema.return {type: 'tool-call' as const,- toolCallId: b.toolCallId,+ toolCallId: ensureToolCallId(b.toolCallId, b.toolName),toolName: b.toolName,input: b.input,...(b.providerMetadata ? { providerOptions: b.providerMetadata } : {}),@@ -3812,7 +3865,7 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {else if (part.type === 'tool-call') {blocks.push({type: 'tool-call',- toolCallId: part.toolCallId,+ toolCallId: ensureToolCallId(part.toolCallId, part.toolName),toolName: part.toolName,input: part.input ?? part.args,...partMeta,@@ -3827,7 +3880,7 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {for (const tc of (result as any).toolCalls ?? []) {blocks.push({type: 'tool-call',- toolCallId: tc.toolCallId,+ toolCallId: ensureToolCallId(tc.toolCallId, tc.toolName),toolName: tc.toolName,input: tc.input ?? tc.args,});diff --git a/src/core/ai/model-resolver.ts b/src/core/ai/model-resolver.tsindex 1bb8129882..36ab137364 100644--- a/src/core/ai/model-resolver.ts+++ b/src/core/ai/model-resolver.ts@@ -77,6 +77,17 @@ export function resolveRecipe(modelId: string): { parsed: ParsedModelId; recipe:return { parsed, recipe };}+/**+ * Resolve the declared chat context window for a provider-qualified model.+ * Model-specific recipe metadata wins over the provider-wide default.+ * Returns undefined when the provider has no chat context declaration.+ */+export function resolveChatContextTokens(modelId: string): number | undefined {+ const { parsed, recipe } = resolveRecipe(modelId);+ const chat = recipe.touchpoints.chat;+ return chat?.model_context_tokens?.[parsed.modelId] ?? chat?.max_context_tokens;+}+type KnownTouchpointKey = 'embedding' | 'expansion' | 'chat' | 'reranker';function getTouchpoint(recipe: Recipe, touchpoint: TouchpointKind): EmbeddingTouchpoint | ExpansionTouchpoint | ChatTouchpoint | RerankerTouchpoint | undefined {diff --git a/src/core/ai/recipes/anthropic.ts b/src/core/ai/recipes/anthropic.tsindex 19f5fc3407..ed03f7bd5e 100644--- a/src/core/ai/recipes/anthropic.ts+++ b/src/core/ai/recipes/anthropic.ts@@ -34,6 +34,14 @@ export const anthropic: Recipe = {supports_tools: true,supports_subagent_loop: true,supports_prompt_cache: true,+ model_context_tokens: {+ 'claude-fable-5': 1_000_000,+ 'claude-opus-5': 1_000_000,+ 'claude-sonnet-5': 1_000_000,+ 'claude-opus-4-8': 1_000_000,+ 'claude-opus-4-7': 1_000_000,+ 'claude-opus-4-6': 1_000_000,+ },max_context_tokens: 200000,cost_per_1m_input_usd: 3.0, // sonnet-class baselinecost_per_1m_output_usd: 15.0,diff --git a/src/core/ai/recipes/google.ts b/src/core/ai/recipes/google.tsindex 3836ee5be8..ac220739f8 100644--- a/src/core/ai/recipes/google.ts+++ b/src/core/ai/recipes/google.ts@@ -59,15 +59,17 @@ export const google: Recipe = {safety_factor: 0.8,},expansion: {- models: ['gemini-2.0-flash', 'gemini-2.0-flash-lite'],- cost_per_1m_tokens_usd: 0.10,- price_last_verified: '2026-04-20',+ models: ['gemini-2.5-flash', 'gemini-2.5-flash-lite'],+ cost_per_1m_tokens_usd: 0.30,+ price_last_verified: '2026-08-02',},chat: {- // gemini-1.5-pro was retired by Google (#3510) — deliberately NOT- // listed. Default-slot guard tests validate hardcoded defaults against- // this list, so re-adding a dead model here masks dead defaults.- models: ['gemini-2.0-flash-exp', 'gemini-2.0-flash'],+ // Retired by Google and deliberately NOT listed: gemini-1.5-pro+ // (#3510) and the whole gemini-2.0 family — flash, flash-lite, and+ // flash-exp all answer 404 on generateContent. Default-slot guard+ // tests validate hardcoded defaults against this list, so re-adding a+ // dead model here masks dead defaults.+ models: ['gemini-2.5-flash', 'gemini-2.5-flash-lite'],supports_tools: true,supports_subagent_loop: true,// Per-model: implicit caching is a 2.5+ capability, and this recipe@@ -75,10 +77,10 @@ export const google: Recipe = {// list above), so a recipe-wide boolean mislabels whichever side it// picks.supports_prompt_cache: googleSupportsPromptCache,- max_context_tokens: 1000000, // Gemini 2.0 Flash+ max_context_tokens: 1000000, // Gemini 2.5 Flashcost_per_1m_input_usd: 0.30,- cost_per_1m_output_usd: 1.20,- price_last_verified: '2026-04-20',+ cost_per_1m_output_usd: 2.50,+ price_last_verified: '2026-08-02',},},setup_hint: 'Get an API key at https://aistudio.google.com/apikey, then `export GOOGLE_GENERATIVE_AI_API_KEY=...`',diff --git a/src/core/ai/types.ts b/src/core/ai/types.tsindex b9846ccb99..a8cc58cae0 100644--- a/src/core/ai/types.ts+++ b/src/core/ai/types.ts@@ -320,6 +320,8 @@ export interface ChatTouchpoint {* known to honor it.*/supports_structured_outputs?: boolean;+ /** Per-model overrides for providers whose chat models have different context windows. */+ model_context_tokens?: Record<string, number>;max_context_tokens?: number;cost_per_1m_input_usd?: number;cost_per_1m_output_usd?: number;diff --git a/src/core/batch-rows.ts b/src/core/batch-rows.tsindex 704f41bd95..bacc6bfd07 100644--- a/src/core/batch-rows.ts+++ b/src/core/batch-rows.ts@@ -87,6 +87,18 @@ export const stripNul = (s: string): string => (s.includes('\0') ? s.replace(/\0*/export const sanitizeForJsonb = (s: string): string => ensureWellFormed(stripNul(s));+/**+ * Null-safe free-prose sanitizer for plain TEXT / TEXT[] columns (title,+ * compiled_truth, timeline, chunk_text). Same NUL + lone-surrogate cleanup as+ * `sanitizeForJsonb` — a raw 0x00 in a page body otherwise aborts the INSERT+ * with `invalid byte sequence for encoding "UTF8": 0x00` (Postgres text cannot+ * store NUL), and a lone surrogate is likewise rejected. Passes null/undefined+ * through unchanged so nullable columns keep their semantics. Same policy as+ * sanitizeForJsonb: free-prose body only, NEVER identity/security fields.+ */+export const sanitizeText = <T extends string | null | undefined>(s: T): T =>+ (typeof s === 'string' ? (sanitizeForJsonb(s) as T) : s);+/** One links row, keys === the jsonb_to_recordset column list. */export interface LinkRow {from_slug: string;diff --git a/src/core/bench/correctness-gate.ts b/src/core/bench/correctness-gate.tsindex f8c4529281..7948246335 100644--- a/src/core/bench/correctness-gate.ts+++ b/src/core/bench/correctness-gate.ts@@ -18,6 +18,7 @@*/import type { BrainEngine } from '../engine.ts';+import { dedupeRankedKeys } from '../eval/ranked-docs.ts';import { hybridSearch } from '../search/hybrid.ts';import {computeExpectedTop1Hit,@@ -70,9 +71,9 @@ export interface CorrectnessResult {per_query: PerQueryResult[];}-/** Build the canonical, insertion-ordered page-key set for a SearchResult-like array. */-function toRefKeySet(results: Array<{ source_id?: string; slug: string }>): Set<string> {- return new Set(results.map(r => makeRef(r.source_id ?? 'default', r.slug)));+/** Build unique canonical `${source_id}::${slug}` keys in first/best rank order. */+function toRankedRefKeys(results: Array<{ source_id?: string; slug: string }>): string[] {+ return dedupeRankedKeys(results.map(r => makeRef(r.source_id ?? 'default', r.slug)));}async function runOneQuery(@@ -84,7 +85,7 @@ async function runOneQuery(let retrieved: string[];try {const raw = await searchFn(engine, entry.query, { limit: k });- retrieved = [...toRefKeySet(raw)];+ retrieved = toRankedRefKeys(raw);} catch (err) {return {query_id: entry.query_id,diff --git a/src/core/bench/qrels-file.ts b/src/core/bench/qrels-file.tsindex e162e7dda0..c76707e863 100644--- a/src/core/bench/qrels-file.ts+++ b/src/core/bench/qrels-file.ts@@ -24,6 +24,8 @@* Compares are on `${source_id}::${slug}` strings everywhere.*/+import { dedupeRankedKeys } from '../eval/ranked-docs.ts';+export const QRELS_FILE_SCHEMA_VERSION = 1 as const;/** Defaults when neither qrels-file nor CLI flags set them. */@@ -199,14 +201,14 @@ export function parseQrelsFile(content: string): QrelsFile {* Returns a number in [0, 1].*/export function computeRecallAtK(retrieved: string[], relevant: string[], k: number): number {- if (relevant.length === 0) return 0;+ if (k <= 0 || relevant.length === 0) return 0;const relevantSet = new Set(relevant);- const topK = retrieved.slice(0, k);+ const topK = dedupeRankedKeys(retrieved).slice(0, k);let hits = 0;for (const r of topK) {if (relevantSet.has(r)) hits++;}- return hits / relevant.length;+ return hits / relevantSet.size;}/**diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.tsindex 55ee85c597..6ec5e829a5 100644--- a/src/core/bootstrap/harness.ts+++ b/src/core/bootstrap/harness.ts@@ -312,6 +312,33 @@ function whichSafe(bin: string): string | null {}}+/** Optional overrides for the three harness-detection probes.+ *+ * Production leaves every field unset, so `resolveDeps` keeps its `Bun.which`+ * defaults. E2E tests MUST pin them: `Bun.which` resolves against the live+ * PATH and reads the real password-database HOME, so it ignores a test's+ * remapped HOME/PATH entirely. Without a pin, an otherwise hermetic test+ * silently asserts something different depending on which agent CLIs the host+ * happens to have installed — `claude` is on a developer laptop's PATH but+ * absent from a GitHub runner, so the claude lane never ran in CI, no+ * `claude mcp add` was exec'd, and no user-scope settings file was written.+ */+export interface HarnessDetectOverrides {+ claude?: () => boolean;+ codex?: () => boolean;+ opencode?: () => boolean;+}++/** Narrow the overrides to the HarnessDeps keys, omitting absent probes so+ * resolveDeps' production defaults stay in charge of anything not pinned. */+export function harnessDetectDeps(o?: HarnessDetectOverrides): Partial<HarnessDeps> {+ return {+ ...(o?.claude ? { detectClaude: o.claude } : {}),+ ...(o?.codex ? { detectCodex: o.codex } : {}),+ ...(o?.opencode ? { detectOpencode: o.opencode } : {}),+ };+}+/** Production mint: open the configured engine just long enough to insert. */async function defaultMint(opts: { name: string; scopes: string[]; sourceGrant?: string[] }): Promise<MintedLegacyToken> {const cfg = loadConfig();diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex dce2edc548..f2d3f083b2 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -42,28 +42,28 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--delete-brain', '--env', '--force', '--grant-types', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--workspace', '--yes'],'connectors': ['--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-browser', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--token', '--try-oauth', '--window-days'],'conversation-parser': ['--brain', '--help', '--json', '--source'],- 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--audit-rejects', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--date', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-jobs', '--max-rss', '--max-usd', '--mcp-even-if-plugin', '--mcp-only', '--migrate-only', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--preset', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--recency', '--refresh', '--refresh-unqualified', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--review-lower', '--rollback', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--stats', '--status', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--verbose', '--verify', '--version', '--window', '--with-calibration', '--workers', '--yes'],+ 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--audit-rejects', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--date', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-jobs', '--max-rss', '--max-usd', '--mcp-even-if-plugin', '--mcp-only', '--migrate-only', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--preset', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--recency', '--refresh', '--refresh-unqualified', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--review-lower', '--rollback', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--stats', '--status', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--verbose', '--verify', '--version', '--window', '--with-calibration', '--workers', '--yes'],'dream': ['--against', '--aliases', '--all', '--allow-regression', '--asof', '--audit-rejects', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-mention', '--by-type', '--by-type-floor', '--cancel-unmatched', '--check', '--code', '--committed-baseline', '--compare', '--compile', '--concurrent', '--cycles', '--date', '--detail', '--dim', '--dimensions', '--dir', '--drain', '--drain-implied', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--expansion', '--explain', '--fast', '--federated', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--format', '--from', '--from-db', '--from-pages', '--gold', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--install', '--json', '--judge-model', '--justification', '--keyword-only', '--lang', '--limit', '--llm', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-tokens', '--max-usd', '--mcp-only', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--name-only', '--no', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-llm', '--no-mutate', '--no-trajectory', '--once', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--path', '--pattern', '--pending', '--pglite', '--phase', '--priority', '--progress-interval', '--progress-json', '--pull', '--qrels', '--quiet', '--rebuild', '--receipt-dir', '--recency', '--reconcile-queue', '--remediate', '--repo', '--reranking', '--reset', '--resolve', '--restore-only', '--resume-from', '--retrieval-only', '--rubric-version', '--sample', '--seed', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--suite', '--suites', '--supabase', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--timeout', '--to', '--token-ttl', '--top-k', '--unsafe-bypass-dream-guard', '--update-baseline', '--verify', '--version', '--window', '--yes'],'edges-backfill': ['--all', '--all-sources', '--brain', '--concurrency', '--federated', '--help', '--json', '--max-age', '--max-chunks', '--max-cost-usd', '--no-federated', '--older-than', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--timeout', '--workers'],'embed': ['--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--check', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--name', '--no', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pglite', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--serial', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--version'],'enrich': ['--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd-per-day', '--by-mention', '--check', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--content', '--date', '--days', '--detail', '--dim', '--dir', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--judge-model', '--kind', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--name', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-federated', '--offset', '--older-than', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--reenrich-after', '--remediate', '--resume', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale', '--stats', '--stdin', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--token-ttl', '--trusted-extraction', '--types', '--url', '--version', '--walk-depth', '--with-db', '--workers', '--yes'],'eval': ['--ab-relational', '--against', '--allow-regression', '--background', '--baseline', '--batch', '--brain', '--brain-wide-max-cost-usd', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--check', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dim', '--dimensions', '--distance-min', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--explain', '--fast', '--fixtures', '--follow', '--force', '--from-capture', '--from-db', '--from-pages', '--gold', '--grounding-min', '--harness', '--help', '--http', '--include-holdout', '--input', '--json', '--judge', '--justification', '--k', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--no', '--no-cache', '--no-embed', '--no-embedding', '--no-expand', '--no-llm', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--quiet', '--receipt-dir', '--refresh-cache', '--remediate', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--strict', '--suite', '--suites', '--surface', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--version', '--with-code-intel', '--yes'],- 'export': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dir', '--explain', '--federated', '--fix', '--follow', '--full', '--help', '--json', '--lang', '--markdown', '--multimodal', '--name-status', '--near-symbol', '--no-federated', '--path', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--slug-prefix', '--source', '--source-guard', '--stale', '--strategy', '--symbol-kind', '--thin', '--timeout', '--type'],- 'extract': ['--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--catch-up', '--check', '--code', '--concurrency', '--dir', '--dry-run', '--explain', '--federated', '--follow', '--from-meetings', '--full', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--markdown', '--max-age', '--max-cost-usd', '--name-status', '--ner', '--no-federated', '--older-than', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--remediate', '--repo', '--restore-only', '--run-id', '--since', '--since-created', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--strategy', '--timeout', '--type', '--verbose', '--workers', '--yes'],+ 'export': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dir', '--explain', '--federated', '--fix', '--follow', '--full', '--help', '--include-hidden', '--json', '--lang', '--markdown', '--multimodal', '--name-status', '--near-symbol', '--no-federated', '--path', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--slug-prefix', '--source', '--source-guard', '--stale', '--strategy', '--symbol-kind', '--thin', '--timeout', '--type'],+ 'extract': ['--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--catch-up', '--check', '--code', '--concurrency', '--dir', '--dry-run', '--explain', '--federated', '--follow', '--from-meetings', '--full', '--help', '--include-frontmatter', '--include-hidden', '--infer-dates', '--json', '--kind', '--markdown', '--max-age', '--max-cost-usd', '--name-status', '--ner', '--no-federated', '--older-than', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--remediate', '--repo', '--restore-only', '--run-id', '--since', '--since-created', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--strategy', '--timeout', '--type', '--verbose', '--workers', '--yes'],'extract-conversation-facts': ['--all', '--all-sources', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--by-mention', '--check', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--dim', '--dir', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--federated', '--fix', '--follow', '--force', '--force-break-lock', '--help', '--json', '--judge-model', '--kind', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--name', '--no', '--no-embed', '--no-embedding', '--no-federated', '--older-than', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--segment-limit', '--session', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--version', '--workers', '--yes'],- 'features': ['--all', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--progress-json', '--quiet', '--rebuild', '--repo', '--run-id', '--since', '--since-created', '--slugs', '--source', '--source-id', '--stale', '--type', '--verbose', '--workers'],+ 'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--progress-json', '--quiet', '--rebuild', '--refresh', '--repo', '--run-id', '--since', '--since-created', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers'],'files': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--json', '--no-embedding', '--no-federated', '--no-pointer', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--retry-failed', '--save', '--source', '--source-guard', '--stale', '--surface', '--timeout', '--token-ttl', '--type', '--yes'],'forget': ['--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recency', '--repo', '--restore-only', '--rollup', '--salience', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stats', '--stdin', '--supersessions', '--surface', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],'founder': ['--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--mcp-only', '--no-embedding', '--since', '--source', '--surface', '--timeout', '--token-ttl', '--until'],'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--redact', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],- 'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fast', '--fix', '--force', '--from-pages', '--full', '--get', '--help', '--http', '--include-catch-all', '--json', '--name-only', '--name-status', '--no-embedding', '--no-verify', '--others', '--source', '--strategy', '--surface', '--timeout', '--token-ttl', '--uninstall', '--write-back'],+ 'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fast', '--fix', '--force', '--from-pages', '--full', '--get', '--help', '--http', '--include-catch-all', '--include-hidden', '--json', '--name-only', '--name-status', '--no-embedding', '--no-verify', '--others', '--source', '--strategy', '--surface', '--timeout', '--token-ttl', '--uninstall', '--write-back'],'graph-query': ['--brain', '--depth', '--direction', '--fast', '--force', '--from-pages', '--help', '--http', '--include-foreign', '--json', '--mcp-only', '--no-embedding', '--source', '--surface', '--timeout', '--token-ttl', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-limit', '--brain', '--budget-ms', '--cached', '--count', '--delete-brain', '--detach', '--diff-filter', '--end-of-options', '--env', '--exclude-standard', '--fast', '--force', '--from-pages', '--get', '--harness', '--help', '--http', '--jq', '--json', '--name-only', '--no-embedding', '--once', '--others', '--path', '--porcelain', '--project', '--pure', '--quiet', '--remove', '--show-current', '--show-toplevel', '--source', '--stale', '--stats', '--status', '--surface', '--timeout', '--token', '--token-ttl'],- 'import': ['--all', '--allow-noncanonical-root', '--asof', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--cached', '--check', '--code', '--compile', '--concurrency', '--dim', '--embedding-dimensions', '--embedding-model', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--fix', '--follow', '--force', '--force-rechunk', '--fresh', '--from-pages', '--full', '--help', '--http', '--include-gitignored', '--json', '--lang', '--log-noop', '--markdown', '--max-age', '--multimodal', '--name-status', '--no-embed', '--no-embedding', '--no-federated', '--older-than', '--others', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--since', '--skip-failed', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--workers'],+ 'import': ['--all', '--allow-noncanonical-root', '--asof', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--cached', '--check', '--code', '--compile', '--concurrency', '--dim', '--embedding-dimensions', '--embedding-model', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--fix', '--follow', '--force', '--force-rechunk', '--fresh', '--from-pages', '--full', '--help', '--http', '--include-gitignored', '--include-hidden', '--json', '--lang', '--log-noop', '--markdown', '--max-age', '--multimodal', '--name-status', '--no-embed', '--no-embedding', '--no-federated', '--older-than', '--others', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--since', '--skip-failed', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--workers'],'init': ['--all', '--brain', '--chat-model', '--check', '--ctx-size', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--entity', '--expansion-model', '--fast', '--flag', '--force', '--from-pages', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--judge-model', '--key', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--provenance', '--reranking', '--reset', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--token-ttl', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--embeddings', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--overwrite', '--refresh', '--reranking', '--source', '--surface', '--target', '--token-ttl'],'integrity': ['--auto', '--backend', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--fast', '--follow', '--force', '--fresh', '--from-pages', '--help', '--http', '--json', '--limit', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--stale', '--supabase', '--surface', '--timeout', '--token-ttl', '--type', '--url'],- 'jobs': ['--abbrev-ref', '--aliases', '--all', '--allow-empty', '--allow-protected', '--allow-shell-jobs', '--apply', '--asof', '--auto', '--auto-with-prompt', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--break-lock', '--budget-usd', '--budget-usd-per-day', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--cluster', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--content', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--image', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--job-id', '--job-isolation', '--json', '--kind', '--lang', '--limit', '--lock', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federate', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-max-cost', '--no-mutate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--offset', '--older-than', '--once', '--order', '--orphan', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--progress-interval', '--progress-json', '--queue', '--quiet', '--rebuild', '--recency', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--run-id', '--salience', '--save', '--segment-limit', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--sigkill-rescue', '--since', '--since-created', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--surface', '--swap-only', '--symbol-kind', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--token-ttl', '--trusted-extraction', '--type', '--types', '--uninstall', '--unsafe-bypass-dream-guard', '--url', '--user', '--verbose', '--verify', '--version', '--walk-depth', '--watch', '--wedge-rescue', '--with-db', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--aliases', '--all', '--allow-empty', '--allow-protected', '--allow-shell-jobs', '--apply', '--asof', '--auto', '--auto-with-prompt', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--break-lock', '--budget-usd', '--budget-usd-per-day', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--cluster', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--content', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--full-history', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lang', '--limit', '--lock', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federate', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-max-cost', '--no-mutate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--offset', '--older-than', '--once', '--order', '--orphan', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--progress-interval', '--progress-json', '--queue', '--quiet', '--rebuild', '--recency', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--run-id', '--salience', '--save', '--segment-limit', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--sigkill-rescue', '--since', '--since-created', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--surface', '--swap-only', '--symbol-kind', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--token-ttl', '--trusted-extraction', '--type', '--types', '--uninstall', '--unsafe-bypass-dream-guard', '--url', '--user', '--verbose', '--verify', '--version', '--walk-depth', '--watch', '--wedge-rescue', '--with-db', '--workers', '--working-tree', '--yes'],'lint': ['--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--exclude', '--explain', '--fast', '--fix', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--surface', '--timeout', '--token-ttl'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--retry-judge', '--save', '--source', '--strict-budget', '--yes'],'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--input', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--nice', '--no-mutate', '--older-than', '--once', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--progress-json', '--query', '--queue', '--quiet', '--rebuild', '--rebuild-rollup', '--regenerate', '--remediate', '--remediation-plan', '--reset', '--resume', '--run-id', '--safe', '--scope', '--since', '--since-created', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--url', '--verbose', '--window', '--workers', '--yes'],@@ -81,16 +81,16 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],'quarantine': ['--apply', '--brain', '--code', '--compile', '--fast', '--fix', '--force', '--force-rechunk', '--from-pages', '--help', '--http', '--include-flagged', '--json', '--lang', '--limit', '--markdown', '--no-embed', '--no-embedding', '--source', '--source-id', '--stale', '--surface', '--token-ttl'],'recall': ['--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recency', '--repo', '--restore-only', '--rollup', '--salience', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stats', '--stdin', '--supersessions', '--surface', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],- 'reconcile-links': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--explain', '--follow', '--full', '--help', '--include-frontmatter', '--json', '--name-status', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--strategy', '--timeout', '--type'],+ 'reconcile-links': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--explain', '--follow', '--full', '--help', '--include-frontmatter', '--include-hidden', '--json', '--name-status', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--strategy', '--timeout', '--type'],'reindex': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--from-pages', '--help', '--http', '--json', '--lang', '--limit', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--older-than', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--type', '--version', '--workers', '--yes'],'reindex-code': ['--abi', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--chunker-debug', '--code', '--compile', '--concurrency', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-rechunk', '--help', '--json', '--judge-model', '--lang', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--no', '--no-embed', '--older-than', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--serial', '--source', '--stale', '--timeout', '--to', '--version', '--workers', '--yes'],'reindex-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--workers', '--yes'],'reindex-search-vector': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--explain', '--follow', '--help', '--json', '--migrate-only', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--yes'],- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--chat-model', '--concurrency', '--confirm-destructive', '--diff-filter', '--dir', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--fast', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--interval', '--is-ancestor', '--issuer-url', '--json', '--key', '--lock', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--name-status', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--orphan', '--parallel', '--path', '--pglite', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--short', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],+ 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--diff-filter', '--dir', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--fast', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--full-history', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lock', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--name-status', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--orphan', '--others', '--parallel', '--path', '--pglite', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--short', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--mcp-only', '--no-embedding', '--scopes', '--source', '--surface', '--timeout', '--token-ttl'],'repair-jsonb': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--explain', '--fast', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--supabase', '--surface', '--timeout', '--token-ttl', '--url'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abbrev-ref', '--abort', '--all', '--all-sources', '--allow-unverified-remote', '--app-id', '--app-install', '--app-pem', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--days', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--file', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--http', '--id', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lang', '--limit', '--local', '--markdown', '--max-age', '--max-cost-usd', '--message', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--no-cron', '--no-embedding', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--porcelain', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repo', '--repos', '--restore-only', '--scope', '--scopes', '--secret', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--surface', '--symbol-kind', '--takes-holders', '--thin', '--token', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],+ 'repos': ['--abbrev-ref', '--abort', '--all', '--all-sources', '--allow-unverified-remote', '--app-id', '--app-install', '--app-pem', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--days', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--file', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--http', '--id', '--include-hidden', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lang', '--limit', '--local', '--markdown', '--max-age', '--max-cost-usd', '--message', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--no-cron', '--no-embedding', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--porcelain', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repo', '--repos', '--restore-only', '--scope', '--scopes', '--secret', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--surface', '--symbol-kind', '--takes-holders', '--thin', '--token', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],'resolvers': ['--auto', '--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--check', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-sunset-target', '--from-pages', '--help', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--max-age', '--model', '--multimodal', '--name', '--nice', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reranking', '--resume', '--retarget', '--slugs', '--source', '--stale', '--status', '--surface', '--timeout', '--to', '--token-ttl', '--version', '--yes'],'routing-eval': ['--brain', '--fix', '--help', '--json', '--llm', '--skills-dir', '--source', '--strict', '--verbose'],@@ -103,13 +103,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force', '--force-unlock', '--format', '--from', '--from-pages', '--frontmatter', '--full', '--harness', '--help', '--homepage', '--http', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-embedding', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--surface', '--target', '--tier', '--token-ttl', '--trust', '--url', '--verbose', '--verify', '--workspace', '--yes'],'skillpack-check': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--strict', '--timeout', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abbrev-ref', '--abort', '--all', '--all-sources', '--allow-unverified-remote', '--app-id', '--app-install', '--app-pem', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--days', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--file', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--http', '--id', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lang', '--limit', '--local', '--markdown', '--max-age', '--max-cost-usd', '--message', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--no-cron', '--no-embedding', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--porcelain', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repo', '--repos', '--restore-only', '--scope', '--scopes', '--secret', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--surface', '--symbol-kind', '--takes-holders', '--thin', '--token', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],- 'status': ['--ab-relational', '--abbrev-ref', '--abi', '--abort', '--against', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-regression', '--apply', '--asof', '--auto', '--background', '--baseline', '--batch', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--budget-usd', '--budget-usd-answer', '--budget-usd-per-day', '--budget-usd-retrieval', '--by-mention', '--cached', '--catch-up', '--check', '--clone-dir', '--code', '--column', '--committed-baseline', '--compare', '--compare-limit', '--compile', '--concurrency', '--concurrent', '--config-a', '--config-b', '--confirm-destructive', '--content', '--content-audit', '--corpus', '--cost-estimate', '--count', '--cycles', '--date', '--days', '--deadline-ms', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--distance-min', '--drain', '--dry-run', '--embedder', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expand', '--explain', '--fast', '--federated', '--ff-only', '--file', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-capture', '--from-meetings', '--from-pages', '--full', '--git-path', '--gold', '--grounding-min', '--hard-deadline', '--harness', '--help', '--http', '--image', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-holdout', '--include-null-signature', '--index-audit', '--infer-dates', '--input', '--install', '--interval', '--is-ancestor', '--json', '--judge', '--judge-model', '--justification', '--k', '--kind', '--lang', '--limit', '--link-source', '--link-type', '--llm', '--lock', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-pair-chars', '--max-rss', '--max-runtime', '--max-sources', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--migrate-only', '--min-context', '--min-recall', '--missing-path', '--mode', '--model', '--modes', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-cache', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-llm', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--offset', '--older-than', '--order', '--orphan', '--others', '--out', '--output', '--output-dir', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parity-baseline', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--receipt-dir', '--recency', '--reenrich-after', '--refresh', '--refresh-cache', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--rrf-k', '--run-id', '--runs', '--salience', '--sample', '--sampling', '--save', '--scope', '--scopes', '--section', '--seed', '--serial', '--session', '--session-id', '--severity', '--short', '--show-toplevel', '--since', '--since-created', '--skills-dir', '--skip-failed', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--strict', '--suite', '--suites', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--task', '--thin', '--thin-threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--token-env', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--trusted-extraction', '--type', '--types', '--until', '--update-baseline', '--url', '--usefulness-min', '--verbose', '--verify', '--version', '--walk-depth', '--watch', '--what', '--where', '--who', '--window', '--with-code-intel', '--with-db', '--workers', '--working-tree', '--yes'],+ 'sources': ['--abbrev-ref', '--abort', '--all', '--all-sources', '--allow-unverified-remote', '--app-id', '--app-install', '--app-pem', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--days', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--file', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--http', '--id', '--include-hidden', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lang', '--limit', '--local', '--markdown', '--max-age', '--max-cost-usd', '--message', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--no-cron', '--no-embedding', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--porcelain', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repo', '--repos', '--restore-only', '--scope', '--scopes', '--secret', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--surface', '--symbol-kind', '--takes-holders', '--thin', '--token', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],+ 'status': ['--ab-relational', '--abbrev-ref', '--abi', '--abort', '--accept', '--against', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-regression', '--apply', '--asof', '--auto', '--background', '--baseline', '--batch', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--bucket-size', '--budget-usd', '--budget-usd-answer', '--budget-usd-per-day', '--budget-usd-retrieval', '--by', '--by-mention', '--cached', '--catch-up', '--check', '--claim', '--clone-dir', '--code', '--column', '--committed-baseline', '--compare', '--compare-limit', '--compile', '--concurrency', '--concurrent', '--config-a', '--config-b', '--confirm-destructive', '--content', '--content-audit', '--corpus', '--cost-estimate', '--count', '--cycles', '--date', '--days', '--deadline-ms', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--distance-min', '--domain', '--drain', '--dry-run', '--embedder', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--evidence', '--exclude', '--exclude-standard', '--expand', '--expired', '--explain', '--fast', '--federated', '--ff-only', '--file', '--filters', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-capture', '--from-meetings', '--from-pages', '--full', '--full-history', '--git-path', '--gold', '--grounding-min', '--hard-deadline', '--harness', '--help', '--holder', '--http', '--image', '--include-covered', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-holdout', '--include-null-signature', '--index-audit', '--infer-dates', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--judge', '--judge-model', '--justification', '--k', '--kind', '--lang', '--limit', '--link-source', '--link-type', '--llm', '--lock', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-pages', '--max-pair-chars', '--max-rss', '--max-runtime', '--max-sources', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--migrate-only', '--min-context', '--min-recall', '--missing-path', '--mode', '--model', '--modes', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-cache', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-llm', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--offset', '--older-than', '--order', '--orphan', '--others', '--out', '--outcome', '--output', '--output-dir', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parity-baseline', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--qrels', '--quality', '--queries-file', '--query', '--questions', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--receipt-dir', '--recency', '--reenrich-after', '--refresh', '--refresh-cache', '--regenerate', '--reject', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--row', '--rrf-k', '--run-id', '--runs', '--salience', '--sample', '--sampling', '--save', '--scope', '--scopes', '--section', '--seed', '--semantic', '--serial', '--session', '--session-id', '--severity', '--short', '--show-toplevel', '--since', '--since-created', '--skills-dir', '--skip-failed', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--sort', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--strict', '--suite', '--suites', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--task', '--thin', '--thin-threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--token-env', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--trusted-extraction', '--type', '--types', '--unit', '--until', '--update-baseline', '--url', '--usefulness-min', '--value', '--verbose', '--verify', '--version', '--walk-depth', '--watch', '--weight', '--what', '--where', '--who', '--window', '--with-code-intel', '--with-db', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--federated', '--fix', '--help', '--json', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--to'],'sweep': ['--all', '--background', '--batch-limit', '--brain', '--brain-wide-max-cost-usd', '--budget-ms', '--check', '--delete-brain', '--explain', '--federated', '--follow', '--help', '--home', '--json', '--name', '--no-delegate', '--no-federated', '--once', '--parallel', '--path', '--prefix', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--source', '--source-guard', '--stale', '--stats', '--timeout'],- 'sync': ['--abbrev-ref', '--abi', '--abort', '--all', '--all-sources', '--allow-empty', '--asof', '--auto', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--git-path', '--hard-deadline', '--help', '--home', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--index-audit', '--infer-dates', '--interval', '--is-ancestor', '--json', '--kind', '--lang', '--link-source', '--link-type', '--lock', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--older-than', '--once', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--serial', '--short', '--show-toplevel', '--since', '--since-created', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--type', '--url', '--verbose', '--verify', '--watch', '--window', '--workers', '--working-tree', '--yes'],- 'takes': ['--accept', '--brain', '--bucket-size', '--by', '--claim', '--dir', '--domain', '--dry-run', '--evidence', '--expired', '--fast', '--federated', '--file', '--force', '--from-pages', '--help', '--holder', '--http', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embedding', '--no-federated', '--outcome', '--path', '--quality', '--reject', '--repo', '--restore-only', '--row', '--since', '--slugs', '--sort', '--source', '--source-guard', '--source-id', '--surface', '--token-ttl', '--unit', '--until', '--value', '--weight', '--who', '--yes'],- 'think': ['--anchor', '--brain', '--calibration-holder', '--explain', '--fast', '--federated', '--force', '--from-pages', '--help', '--http', '--json', '--max-usd', '--mcp-only', '--model', '--no-embedding', '--no-federated', '--path', '--repo', '--restore-only', '--rounds', '--save', '--since', '--source', '--source-guard', '--surface', '--take', '--timeout', '--token-ttl', '--until', '--with-calibration'],+ 'sync': ['--abbrev-ref', '--abi', '--abort', '--all', '--all-sources', '--allow-empty', '--asof', '--auto', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--full-history', '--git-path', '--hard-deadline', '--help', '--home', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--lock', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--older-than', '--once', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--serial', '--short', '--show-toplevel', '--since', '--since-created', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--type', '--url', '--verbose', '--verify', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'takes': ['--accept', '--all', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expired', '--fast', '--federated', '--file', '--force', '--from-pages', '--help', '--holder', '--http', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--no-federated', '--outcome', '--path', '--pglite', '--quality', '--reject', '--repo', '--restore-only', '--row', '--semantic', '--serial', '--since', '--slugs', '--sort', '--source', '--source-guard', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--token-ttl', '--unit', '--until', '--value', '--weight', '--who', '--yes'],+ 'think': ['--all', '--anchor', '--brain', '--calibration-holder', '--explain', '--fast', '--federated', '--force', '--from-pages', '--help', '--http', '--json', '--max-usd', '--mcp-only', '--model', '--no-embed', '--no-embedding', '--no-federated', '--path', '--repo', '--restore-only', '--rounds', '--save', '--serial', '--since', '--source', '--source-guard', '--surface', '--take', '--timeout', '--token-ttl', '--until', '--with-calibration'],'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--check', '--code', '--compile', '--days', '--dry-run', '--embed', '--explain', '--facts', '--fast', '--federated', '--follow', '--force', '--format', '--from-pages', '--full', '--help', '--http', '--include-self', '--json', '--limit', '--markdown', '--max-bytes', '--max-cost-usd', '--no-embedding', '--no-federated', '--path', '--print', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--since', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--surface', '--timeout', '--token-ttl'],'upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pglite', '--quiet', '--recency', '--repo', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'],'watch': ['--brain', '--fast', '--federated', '--force', '--from-pages', '--help', '--http', '--json', '--max-pages', '--min-confidence', '--no-embedding', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--stats', '--surface', '--token-ttl', '--window-turns'],diff --git a/src/core/config-db-merge.ts b/src/core/config-db-merge.tsindex 07269d9cd5..2776de596c 100644--- a/src/core/config-db-merge.ts+++ b/src/core/config-db-merge.ts@@ -53,6 +53,9 @@ export const DB_MERGED_PROVIDER_KEY_FIELDS = [export interface DbPlaneEngineReader {getConfig(key: string): Promise<string | null | undefined>;listConfigKeys?(prefix: string): Promise<string[]>;+ /** One-round-trip whole-table read (see config-snapshot.ts). Optional so+ * narrow readers and SDK callers keep working on the per-key path. */+ getAllConfig?(): Promise<Record<string, string>>;executeRaw?<T = Record<string, unknown>>(sql: string,params?: unknown[],diff --git a/src/core/config-snapshot.ts b/src/core/config-snapshot.tsnew file mode 100644index 0000000000..ca0a0c5277--- /dev/null+++ b/src/core/config-snapshot.ts@@ -0,0 +1,65 @@+/**+ * One-round-trip config reads.+ *+ * Two startup paths need dozens of config keys before the CLI does any work:+ * `loadConfigWithEngine()` merges the DB plane over file/env, and+ * `reconfigureGatewayWithEngine()` resolves six models through a precedence+ * chain that reads up to four keys each. Read one key at a time and that is+ * one network round trip per key.+ *+ * On PGLite each read costs microseconds, so the pattern stayed invisible for+ * a long time. On a hosted Postgres it is the wall clock: `gbrain stats`+ * against a Supabase brain spent over 3 seconds on config reads that+ * pg_stat_statements showed the server answering in under 3ms total.+ *+ * The config table is a handful of rows, so read it once and answer every key+ * from memory. The snapshot lives for one resolution pass, not for the life of+ * the process, so a `gbrain config set` from another process is picked up by+ * the next command exactly as before.+ */++/** The only thing config resolution needs from an engine. */+export interface ConfigReader {+ getConfig(key: string): Promise<string | null | undefined>;+}++/** An engine that can read its whole config table in one query. */+export interface BulkConfigReader extends ConfigReader {+ getAllConfig?(): Promise<Record<string, string>>;+}++/**+ * Read the whole config table as a key -> value map.+ *+ * Returns null when the bulk read is unavailable or fails — a brain+ * mid-migration has no config table, and an engine implemented outside this+ * repo may not have `getAllConfig`. Callers fall back to per-key reads, at the+ * old cost but with the old behavior.+ */+export async function loadConfigSnapshot(+ engine: BulkConfigReader | null | undefined,+): Promise<Record<string, string> | null> {+ if (!engine || typeof engine.getAllConfig !== 'function') return null;+ try {+ return await engine.getAllConfig();+ } catch {+ return null;+ }+}++/**+ * Return a reader that answers every key from a single snapshot, or the engine+ * itself when the snapshot is unavailable.+ */+export async function snapshotConfigReader(+ engine: BulkConfigReader | null | undefined,+): Promise<ConfigReader | null> {+ if (!engine) return null;+ const rows = await loadConfigSnapshot(engine);+ if (!rows) return engine;+ return {+ async getConfig(key: string): Promise<string | null> {+ return rows[key] ?? null;+ },+ };+}diff --git a/src/core/config.ts b/src/core/config.tsindex cb8e691471..a0a033018a 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -3,6 +3,7 @@ import { isAbsolute, join } from 'path';import { homedir } from 'os';import type { EngineConfig, EmbeddingColumnConfig } from './types.ts';import { applyDbPlaneReadSideMerge, type DbPlaneEngineReader } from './config-db-merge.ts';+import { loadConfigSnapshot } from './config-snapshot.ts';/*** Where is the active DB URL coming from? Pure introspection, no connection@@ -763,8 +764,10 @@ export { DB_MERGED_PROVIDER_KEY_FIELDS } from './config-db-merge.ts';* also documents why embedding_model/dims must NEVER join any list, #4287).*/export async function loadConfigWithEngine(- // DbPlaneEngineReader: { getConfig; listConfigKeys?; executeRaw? } — the- // optional executeRaw lets the #2119 merge batch its reads in one query.+ // DbPlaneEngineReader: { getConfig; listConfigKeys?; getAllConfig?;+ // executeRaw? } — the optional getAllConfig serves every read below from+ // one snapshot; the optional executeRaw lets the #2119 merge batch its+ // reads in one query when no snapshot is available.engine: DbPlaneEngineReader,base?: GBrainConfig | null,): Promise<GBrainConfig | null> {@@ -781,12 +784,22 @@ export async function loadConfigWithEngine((base !== undefined ? base : loadConfig()) ??({ engine: 'postgres' } as GBrainConfig);- // DB-plane reads. Quiet failures — if the config table doesn't exist yet- // (pre-v36 brain mid-migration), treat as null and let file/env defaults- // win. The migration runner reads file/env directly anyway.+ // This function reads two dozen config keys. One key per round trip is free+ // on PGLite and is most of the wall clock on a hosted Postgres, so read the+ // whole table once and answer every key from that. See config-snapshot.ts.+ //+ // Quiet failure below is deliberate and unchanged: when the snapshot is+ // unavailable (a pre-v36 brain mid-migration, or an engine from outside this+ // repo) every read falls back to a per-key getConfig(), same as before.+ const snapshot = await loadConfigSnapshot(engine);++ function dbRaw(key: string): Promise<string | null | undefined> {+ if (snapshot) return Promise.resolve(snapshot[key]);+ return Promise.resolve(engine.getConfig(key));+ }async function dbBool(key: string): Promise<boolean | undefined> {try {- const v = await engine.getConfig(key);+ const v = await dbRaw(key);if (v === undefined || v === null || v === '') return undefined;return v === 'true';} catch {@@ -795,7 +808,7 @@ export async function loadConfigWithEngine(}async function dbStr(key: string): Promise<string | undefined> {try {- const v = await engine.getConfig(key);+ const v = await dbRaw(key);if (v === undefined || v === null || v === '') return undefined;return v;} catch {@@ -803,11 +816,16 @@ export async function loadConfigWithEngine(}}async function dbPrefixMap(prefix: string): Promise<Record<string, string> | undefined> {- if (typeof engine.listConfigKeys !== 'function') return undefined;let keys: string[];- try {- keys = await engine.listConfigKeys(prefix);- } catch {+ if (snapshot) {+ keys = Object.keys(snapshot);+ } else if (typeof engine.listConfigKeys === 'function') {+ try {+ keys = await engine.listConfigKeys(prefix);+ } catch {+ return undefined;+ }+ } else {return undefined;}@@ -1018,7 +1036,7 @@ export async function loadConfigWithEngine(// behavior change for existing brains and belongs in its own PR.async function dbBoolStrict(key: string): Promise<boolean | undefined> {try {- const v = await engine.getConfig(key);+ const v = await dbRaw(key);if (v === 'true') return true;if (v === 'false') return false;return undefined;@@ -1047,8 +1065,20 @@ export async function loadConfigWithEngine(// #2119-class read-side merge (also #2137/#4297): provider credentials,// chat/expansion pins, chat_fallback_chain, flat cycle.* (env > file > DB).- // One batched, ~30s-memoized read per engine handle (D2 remediation).- await applyDbPlaneReadSideMerge(merged, engine);+ // Served from the SAME snapshot as the reads above when available (zero+ // extra round trips, and the merge can't disagree with the dbStr/dbBool+ // reads); otherwise one batched, ~30s-memoized read per engine handle+ // (D2 remediation).+ await applyDbPlaneReadSideMerge(+ merged,+ snapshot+ ? {+ getConfig: async (key) => snapshot[key] ?? null,+ listConfigKeys: async (prefix) =>+ Object.keys(snapshot).filter((k) => k.startsWith(prefix)),+ }+ : engine,+ );return merged;}diff --git a/src/core/context-engine.ts b/src/core/context-engine.tsindex 480dec62b4..be73005e95 100644--- a/src/core/context-engine.ts+++ b/src/core/context-engine.ts@@ -1091,7 +1091,7 @@ export function createGBrainContextEngine(ctx: {return { ingested: true };},- async assemble({ sessionId, sessionKey, messages, tokenBudget, availableTools, citationsMode }) {+ async assemble({ sessionId, sessionKey, messages, tokenBudget, availableTools, citationsMode, prompt }) {// Lazy SDK load on first method call (was top-level await pre-L0-B).await ensureSdkLoaded();@@ -1100,6 +1100,16 @@ export function createGBrainContextEngine(ctx: {// take down the whole context pipeline.const msgs = Array.isArray(messages) ? messages : [];+ // Some OpenClaw runtimes (e.g. the codex-app-server in 2026.7.x) deliver+ // the current user turn via `prompt` with an empty `messages` array.+ // Synthesize a single user turn so the Retrieval Reflex still sees the+ // text (the deterministic live-context/pass-through path is unaffected).+ const effectiveMessages = msgs.length > 0+ ? msgs+ : (typeof prompt === 'string' && prompt.trim()+ ? ([{ role: 'user', content: prompt }] as typeof msgs)+ : msgs);+// 1. Generate deterministic context (<5ms, zero LLM calls)const liveCtx = generateLiveContext(workspaceDir);const contextBlock = formatContextBlock(liveCtx);@@ -1131,11 +1141,11 @@ export function createGBrainContextEngine(ctx: {// nothing salient resolves. Detect + point, never auto-dump bodies.const reflexAddition = await buildReflexAddition({workspaceDir,- currentUserText: getLastUserText(msgs),- priorContextText: getPriorContextText(msgs),+ currentUserText: getLastUserText(effectiveMessages),+ priorContextText: getPriorContextText(effectiveMessages),// v0.43 (#2095): rolling window — assistant-introduced entities and// named-antecedent follow-ups from recent turns now resolve too.- windowTurns: getWindowTurns(msgs),+ windowTurns: getWindowTurns(effectiveMessages),resolveEntities: ctx.resolveEntities,});diff --git a/src/core/conversation-parser/transcript-signals.ts b/src/core/conversation-parser/transcript-signals.tsnew file mode 100644index 0000000000..f13f296cc7--- /dev/null+++ b/src/core/conversation-parser/transcript-signals.ts@@ -0,0 +1,65 @@+/**+ * Transcript-likeness signals (#4193).+ *+ * `conversation_format_coverage` used to treat every page whose type is in+ * the conversation allowlist as a transcript-parsing candidate, so summary+ * documents that legitimately use `meeting`/`slack` types counted as parser+ * failures even though they contain no conversation turns. This helper is+ * the single definition of "this page claims to contain a transcript" so a+ * `no_match` on a summary page can be reported as summary-only rather than+ * as coverage debt.+ *+ * Deliberately conservative: it never constructs messages and never treats+ * `Name: text` labels as a signal (builtins.ts's own test_negative shows+ * that shape is ambiguous in real summaries). A false positive only means+ * the page keeps today's behavior (counted as a miss).+ */+import type { Page } from '../types.ts';++/**+ * A `## Transcript` / `### Raw transcript` style section heading. Grounded+ * in the real meeting-page shape (`## Summary` + `## Transcript`,+ * see parse.ts's SCORING_HEAD_TRIGGER_THRESHOLD rationale).+ */+const TRANSCRIPT_HEADING_RX = /^#{1,6}\s*(?:raw\s+)?transcript\b/im;++/**+ * A time-of-day token near the start of a line — the anchor shape every+ * time-based builtin uses (`[10:12]`, `(Mon 11:18 AM)`, `18:37 <alice>`,+ * `**Name** (2024-03-15 9:00 AM):`). Checked against the first 24 chars of+ * each line so a stray "standup at 3:00" deep in a bullet doesn't count.+ */+const TIME_TOKEN_RX = /[[(]?\b\d{1,2}:\d{2}(?::\d{2})?\b\s*(?:[APap]\.?[Mm]\.?)?[\])]?/;++/** Min timestamped lines + min share of non-blank lines for the density+ * signal. Mirrors the parser's own density-floor philosophy+ * (SCORING_MIN_ACCEPTANCE): a couple of times in an agenda list is not a+ * transcript; a page where 10%+ of lines open with a clock time is. */+const TIME_DENSITY_MIN_LINES = 3;+const TIME_DENSITY_MIN_SHARE = 0.1;++/**+ * Does this page claim to contain conversation turns?+ *+ * True when ANY of:+ * 1. `frontmatter.raw_transcript` is a non-empty string — even if the file+ * did not resolve, the page claims a transcript, so an unparseable body+ * is genuine coverage debt;+ * 2. the body has a transcript section heading;+ * 3. enough lines open with a time-of-day token (>=3 lines and >=10% of+ * non-blank lines).+ */+export function isTranscriptClaiming(page: Page | undefined, body: string): boolean {+ const raw = page?.frontmatter?.raw_transcript;+ if (typeof raw === 'string' && raw.trim().length > 0) return true;++ if (TRANSCRIPT_HEADING_RX.test(body)) return true;++ const nonBlank = body.split(/\r?\n/).filter((l) => l.trim().length > 0);+ if (nonBlank.length === 0) return false;+ let timed = 0;+ for (const line of nonBlank) {+ if (TIME_TOKEN_RX.test(line.slice(0, 24))) timed++;+ }+ return timed >= TIME_DENSITY_MIN_LINES && timed / nonBlank.length >= TIME_DENSITY_MIN_SHARE;+}diff --git a/src/core/cross-modal-eval/aggregate.ts b/src/core/cross-modal-eval/aggregate.tsindex 0e71a9983a..b0180b3e46 100644--- a/src/core/cross-modal-eval/aggregate.ts+++ b/src/core/cross-modal-eval/aggregate.ts@@ -91,7 +91,8 @@ export function aggregate(input: AggregateInput): AggregateResult {for (const s of successes) {if (s.ok) {for (const dim of Object.keys(s.parsed.scores)) {- allDimNames.add(dim);+ const normalized = normalizeDimensionName(dim);+ if (normalized) allDimNames.add(normalized);}}}@@ -99,7 +100,8 @@ export function aggregate(input: AggregateInput): AggregateResult {const scores: number[] = [];for (const s of successes) {if (s.ok) {- const entry = s.parsed.scores[dim];+ const entry = Object.entries(s.parsed.scores)+ .find(([name]) => normalizeDimensionName(name) === dim)?.[1];if (entry && Number.isFinite(entry.score)) scores.push(entry.score);}}@@ -142,6 +144,10 @@ export function aggregate(input: AggregateInput): AggregateResult {};}+function normalizeDimensionName(name: string): string {+ return name.trim().toLowerCase();+}+function describeFailure(dimensions: Record<string, DimensionRoll>,successes: number,diff --git a/src/core/cross-modal-eval/runner.ts b/src/core/cross-modal-eval/runner.tsindex 11802d5e5f..64ab0968d2 100644--- a/src/core/cross-modal-eval/runner.ts+++ b/src/core/cross-modal-eval/runner.ts@@ -264,8 +264,26 @@ async function callSlot(}}-function buildPrompt(task: string, dimensions: string[], output: string): string {+/**+ * The JSON key a judge must use for a dimension: the label before the+ * ` — ` separator (whole trimmed string when a custom dimension has none).+ * Exported for the prompt-pinning test.+ */+export function dimensionScoreKey(dimension: string): string {+ return dimension.split('—')[0].trim();+}++/** Exported for the judge-key pinning test only. */+export function buildPrompt(task: string, dimensions: string[], output: string): string {const dimList = dimensions.map((d, i) => `${i + 1}. ${d}`).join('\n');+ // Root-cause fix for cross-model dimension splits (#3491, the #4338+ // approach): pin the exact "scores" keys instead of the old "dim_1_name"+ // placeholder that let each judge invent its own spelling/casing.+ // aggregate.ts's trim+lowercase normalization stays as the deterministic+ // backstop for judges that ignore the pinning.+ const scoreKeys = dimensions+ .map((d) => ` ${JSON.stringify(dimensionScoreKey(d))}: { "score": N, "feedback": "..." },`)+ .join('\n');return ['You are a strict quality evaluator. Given a TASK and an OUTPUT, evaluate whether the output achieves the task goals.','',@@ -284,11 +302,10 @@ function buildPrompt(task: string, dimensions: string[], output: string): string'','Then list exactly 10 specific, actionable improvements — concrete changes with examples, prioritized by impact.','',- 'Respond in JSON only (no markdown fences):',+ 'Respond in JSON only (no markdown fences), using EXACTLY these keys under "scores":','{',' "scores": {',- ' "dim_1_name": { "score": N, "feedback": "..." },',- ' ...',+ scoreKeys,' },',' "overall": N,',' "improvements": ["1. ...", "2. ...", ... "10. ..."]',diff --git a/src/core/cycle/auto-think.ts b/src/core/cycle/auto-think.tsindex afb10d49d2..5b65915eb0 100644--- a/src/core/cycle/auto-think.ts+++ b/src/core/cycle/auto-think.ts@@ -17,6 +17,7 @@import type { BrainEngine } from '../engine.ts';import { runThink, persistSynthesis, type ThinkLLMClient } from '../think/index.ts';import { resolveModel } from '../model-config.ts';+import { embedQuery } from '../embedding.ts';import { BudgetMeter } from './budget-meter.ts';/**@@ -160,9 +161,14 @@ export async function runPhaseAutoThink(try {const result = await runThink(engine, {question: q,+ // #3734: auto-think uses same vector takes retrieval as interactive think.+ embedQuestion: (text) => embedQuery(text),save: config.autoCommit,client: opts.client,model: modelId,+ // Fail-closed trust: the local dream cycle must say so explicitly, or+ // trajectory injection degrades to visibility='world' rows.+ remote: false,});// #1698: an empty synthesis (no LLM available / malformed output / empty-JSON answer)// must NOT count as complete or advance the cooldown — that is the same silent-successdiff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.tsindex 20484b8274..0538c69eac 100644--- a/src/core/cycle/conversation-facts-backfill.ts+++ b/src/core/cycle/conversation-facts-backfill.ts@@ -48,6 +48,7 @@ import { withBudgetTracker } from '../ai/gateway.ts';import { listSources } from '../sources-ops.ts';import {runExtractConversationFactsCore,+ isAbortError,type ExtractConversationFactsResult,} from '../../commands/extract-conversation-facts.ts';// The type allowlist comes straight from the canonical leaf module (same@@ -229,6 +230,9 @@ export async function runPhaseConversationFactsBackfill(segments_processed: 0,facts_extracted: 0,facts_inserted: 0,+ // #4052: alias_exact resolution counters (required on the result type).+ fallback_slugify_count: 0,+ resolution_errors: 0,});// #3627: the per-source caps (max_cost_usd / max_walltime_min) were parsed@@ -319,6 +323,12 @@ export async function runPhaseConversationFactsBackfill(budget_exhausted: true,error: err.message,};+ } else if (isAbortError(err)) {+ // #4052 wave abort-honesty fix: an abort that is neither our own+ // per-source deadline (walltimeFired) nor a flagged caller signal+ // is still cycle-runner control flow — propagate it rather than+ // downgrading it to a per-source failure record.+ throw err;} else {// Per-source failure: record + continue with next source.perSourceResults[src.id] = {@@ -334,8 +344,10 @@ export async function runPhaseConversationFactsBackfill(}}} catch (err) {- if ((err as Error).message === 'aborted' || opts.signal?.aborted) {- // Propagate abort.+ if (isAbortError(err) || opts.signal?.aborted) {+ // Abort is control flow owned by the cycle runner; never downgrade it+ // into a per-source warning or phase failure result. isAbortError also+ // matches the loop-top `throw new Error('aborted')`.throw err;}// Unexpected error.@@ -358,6 +370,8 @@ export async function runPhaseConversationFactsBackfill(pages_skipped_unrecognized_speaker: 0,pages_failed: 0,facts_inserted: 0,+ fallback_slugify_count: 0,+ resolution_errors: 0,sources_processed: 0,};for (const r of Object.values(perSourceResults)) {@@ -370,6 +384,8 @@ export async function runPhaseConversationFactsBackfill(totals.pages_skipped_unrecognized_speaker += r.pages_skipped_unrecognized_speaker;totals.pages_failed += r.pages_failed;totals.facts_inserted += r.facts_inserted;+ totals.fallback_slugify_count += r.fallback_slugify_count;+ totals.resolution_errors += r.resolution_errors;}const anyError = Object.values(perSourceResults).some(@@ -394,6 +410,8 @@ export async function runPhaseConversationFactsBackfill(pages_skipped_unrecognized_speaker: totals.pages_skipped_unrecognized_speaker,pages_failed: totals.pages_failed,facts_inserted: totals.facts_inserted,+ fallback_slugify_count: totals.fallback_slugify_count,+ resolution_errors: totals.resolution_errors,spent_usd: totalSpent,skipped_by_brain_wide_cap: skippedByBrainWideCap,skipped_by_brain_wide_walltime: skippedByBrainWideWalltime,diff --git a/src/core/cycle/grade-takes.ts b/src/core/cycle/grade-takes.tsindex 0cd0172596..192ac98f42 100644--- a/src/core/cycle/grade-takes.ts+++ b/src/core/cycle/grade-takes.ts@@ -225,7 +225,7 @@ export interface GradeTakesOpts extends BasePhaseOpts {/*** E2 ensemble judges. When useEnsemble=true and the single-model verdict* is borderline, all three judges are called in parallel via Promise.allSettled.- * Defaults to [openai:gpt-5.2, anthropic:claude-sonnet-4-6, google:gemini-2.0-flash]+ * Defaults to [openai:gpt-5.2, anthropic:claude-sonnet-4-6, google:gemini-2.5-flash]* via defaultJudge with model-string overrides. Tests inject deterministic* judges.*/diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.tsindex 8ecd9619ca..c3e5b33d1b 100644--- a/src/core/cycle/phases/consolidate.ts+++ b/src/core/cycle/phases/consolidate.ts@@ -99,12 +99,11 @@ export async function runPhaseConsolidate(try { await opts.yieldDuringPhase(); } catch { /* keepalive errors non-fatal */ }}- const facts = await engine.listFactsByEntity(b.source_id, b.entity_slug, {+ const unconsolidated = await engine.listFactsByEntity(b.source_id, b.entity_slug, {activeOnly: true,+ unconsolidatedOnly: true,limit: 100,});- // Re-filter to unconsolidated since listFactsByEntity returns all active.- const unconsolidated = facts.filter(f => f.consolidated_at == null);if (unconsolidated.length < minPerBucket) {bucketsSkipped += 1;continue;diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 23a6d00b2f..d69ac91587 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -45,6 +45,7 @@ import { writeFileSync, mkdirSync } from 'node:fs';import { randomUUID } from 'node:crypto';import { chat as gatewayChat, validateModelId, type ChatResult } from '../ai/gateway.ts';import { AIConfigError } from '../ai/errors.ts';+import { resolveChatContextTokens } from '../ai/model-resolver.ts';import { normalizeModelId, splitProviderModelId } from '../model-id.ts';import { hasAnthropicKey } from '../ai/anthropic-key.ts';import { basename, join, dirname, isAbsolute, resolve } from 'node:path';@@ -80,25 +81,6 @@ const SUMMARY_SLUG_RE = new RegExp(`^${PAGE_SLUG_SEG}(\\/${PAGE_SLUG_SEG})*$`, '// ── Model context budget (D1, D5, D7, D9) ─────────────────────────────-/**- * Anthropic model id → input context window (tokens).- * Unknown id (non-Anthropic alias, custom string) → safe 200K-token fallback- * via `computeChunkCharBudget`. Codex finding #4: `resolveModel()` does not- * canonicalize to Anthropic-only; this map keys on the exact strings the- * resolver returns for known Anthropic aliases.- */-const MODEL_CONTEXT_TOKENS: Record<string, number> = {- 'claude-fable-5': 1_000_000,- 'claude-opus-5': 1_000_000,- 'claude-sonnet-5': 1_000_000,- 'claude-opus-4-8': 1_000_000,- 'claude-opus-4-7': 1_000_000,- 'claude-opus-4-6': 1_000_000,- 'claude-sonnet-4-6': 200_000,- 'claude-sonnet-4-5': 200_000,- 'claude-haiku-4-5-20251001': 200_000,-};-/** Token-to-char ratio. 3.5 matches PR #748; conservative for English text. */export const CHARS_PER_TOKEN = 3.5;/** Reserve 10% of context window for system prompt + tool defs + output. */@@ -148,8 +130,8 @@ const DEFAULT_MAX_TURNS = 16;** Resolution:* - configMaxPromptTokens (already floored at MIN_PROMPT_TOKENS) wins when set.- * - Else the model's MODEL_CONTEXT_TOKENS entry × HEADROOM_RATIO.- * - Else (non-Anthropic alias / custom id) UNKNOWN_MODEL_BUDGET_TOKENS, with+ * - Else the official recipe/model resolver's context declaration × HEADROOM_RATIO.+ * - Else (unqualified custom id / unknown provider / undeclared recipe) UNKNOWN_MODEL_BUDGET_TOKENS, with* a once-per-process stderr warning.** D7 scope: this bounds the INITIAL prompt size only. Tool-loop turn-N@@ -163,14 +145,22 @@ export function computeChunkCharBudget(if (configMaxPromptTokens !== null) {return Math.floor(configMaxPromptTokens * CHARS_PER_TOKEN);}- // Lookup keyed on the bare model name (after prefix strip), mirroring- // ANTHROPIC_OUTPUT_CAPS in brainstorm/judges.ts: resolveModel returns- // provider-prefixed strings when TIER_DEFAULTS / config values carry a- // prefix (the current tier defaults all do), so a raw keyed lookup sent- // every tier-resolved brain to the unknown-model fallback — a 5x budget- // cut on 1M-context models.- const bare = splitProviderModelId(model).model || model;- const ctx = MODEL_CONTEXT_TOKENS[bare];+ // Bare Claude ids are the one legacy shape resolveModel may still return;+ // all other bare/custom ids remain unknown rather than guessing a provider.+ const split = splitProviderModelId(model);+ const qualified = split.provider+ ? model+ : model.startsWith('claude-')+ ? normalizeModelId(model)+ : null;+ let ctx: number | undefined;+ if (qualified) {+ try {+ ctx = resolveChatContextTokens(qualified);+ } catch (err) {+ if (!(err instanceof AIConfigError)) throw err;+ }+ }if (ctx === undefined) {warnUnknownModelOnce(model);return Math.floor(UNKNOWN_MODEL_BUDGET_TOKENS * CHARS_PER_TOKEN);@@ -183,7 +173,7 @@ function warnUnknownModelOnce(model: string): void {if (_unknownModelWarned.has(model)) return;_unknownModelWarned.add(model);process.stderr.write(- `[dream] model "${model}" is not in MODEL_CONTEXT_TOKENS; ` ++ `[dream] model "${model}" has no declared chat context window; ` +`using ${UNKNOWN_MODEL_BUDGET_TOKENS}-token fallback budget. ` +`Set dream.synthesize.max_prompt_tokens to override.\n`,);diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 5e01173bfd..329ad7f09b 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -220,6 +220,7 @@ export const META_CHECK_NAMES: ReadonlySet<string> = new Set([// coherence healed by `gbrain apply-migrations` (sibling of// timeline_dedup_index / schema_version).'pages_upsert_arbiter',+ 'schema_columns','schema_pack_active','schema_pack_consistency','schema_pack_source_drift',diff --git a/src/core/embed-takes.ts b/src/core/embed-takes.tsnew file mode 100644index 0000000000..afcc850ef0--- /dev/null+++ b/src/core/embed-takes.ts@@ -0,0 +1,80 @@+/**+ * Embedding pass for typed take claims.+ *+ * Takes already have vector search and a stale-row contract, but no writer.+ * Keep this pass separate from page/chunk embedding so callers can opt into+ * the extra provider work and see its counts independently.+ */++import type { BrainEngine, StaleTakeRow, TakeEmbeddingInput } from './engine.ts';+import { embedBatchWithBackoff } from '../commands/embed.ts';++const DEFAULT_BATCH_SIZE = 100;++export interface EmbedTakesOpts {+ batchSize?: number;+ dryRun?: boolean;+ signal?: AbortSignal;+ embedFn?: (texts: string[], opts: { abortSignal?: AbortSignal }) => Promise<Float32Array[]>;+ onProgress?: (done: number, total: number, embedded: number) => void;+}++export interface EmbedTakesResult {+ total_stale: number;+ embedded: number;+ would_embed: number;+ failures: number;+ failure_samples: string[];+ dryRun: boolean;+}++/** Embed active takes whose embedding column is NULL. */+export async function embedStaleTakes(+ engine: BrainEngine,+ opts: EmbedTakesOpts = {},+): Promise<EmbedTakesResult> {+ const stale = await engine.listStaleTakes();+ const result: EmbedTakesResult = {+ total_stale: stale.length,+ embedded: 0,+ would_embed: opts.dryRun ? stale.length : 0,+ failures: 0,+ failure_samples: [],+ dryRun: !!opts.dryRun,+ };+ if (opts.dryRun || stale.length === 0) {+ opts.onProgress?.(stale.length, stale.length, 0);+ return result;+ }++ const batchSize = Math.min(500, Math.max(1, Math.floor(opts.batchSize ?? DEFAULT_BATCH_SIZE)));+ const embedFn = opts.embedFn ?? ((texts: string[], embedOpts: { abortSignal?: AbortSignal }) =>+ embedBatchWithBackoff(texts, embedOpts));++ for (let start = 0; start < stale.length; start += batchSize) {+ if (opts.signal?.aborted) break;+ const batch = stale.slice(start, start + batchSize);+ try {+ const embeddings = await embedFn(+ batch.map((row) => row.claim),+ { abortSignal: opts.signal },+ );+ if (embeddings.length !== batch.length) {+ throw new Error(`embedding provider returned ${embeddings.length} vectors for ${batch.length} takes`);+ }+ const writes: TakeEmbeddingInput[] = batch.map((row: StaleTakeRow, index) => ({+ take_id: row.take_id,+ embedding: embeddings[index],+ }));+ result.embedded += await engine.updateTakeEmbeddings(writes, { signal: opts.signal });+ } catch (error: unknown) {+ result.failures += batch.length;+ if (result.failure_samples.length < 10) {+ result.failure_samples.push(error instanceof Error ? error.message : String(error));+ }+ }+ opts.onProgress?.(Math.min(start + batch.length, stale.length), stale.length, result.embedded);+ }++ return result;+}diff --git a/src/core/engine.ts b/src/core/engine.tsindex 2052dd7b1f..b099f31838 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -326,13 +326,8 @@ export interface TakeHit {score: number; // search rank score (ts_rank for keyword, 1-cos_dist for vector)}-/** v0.28 stale-takes row (mirrors StaleChunkRow shape). Embedding column intentionally omitted. */-export interface StaleTakeRow {- take_id: number;- page_slug: string;- row_num: number;- claim: string;-}+import type { StaleTakeRow, TakeEmbeddingInput } from './takes-row-types.ts';+export type { StaleTakeRow, TakeEmbeddingInput } from './takes-row-types.ts';/** Resolution metadata for resolveTake. */export interface TakeResolution {@@ -576,6 +571,8 @@ export interface NewFact {export interface FactListOpts {/** Hide expired_at IS NOT NULL rows. Default true. */activeOnly?: boolean;+ /** Return only facts where consolidated_at IS NULL. Default false. */+ unconsolidatedOnly?: boolean;limit?: number;offset?: number;/** Restrict to specific kinds. Default: all kinds. */@@ -649,7 +646,11 @@ export interface TrajectoryOpts {sourceId?: string;/** Federated array scope (mutually exclusive with sourceId; the array wins when set). */sourceIds?: string[];- /** When true, filters to visibility='world' only. Set by MCP layer from ctx.remote. */+ /**+ * Filters to visibility='world' unless strictly `false`. FAIL-CLOSED: an+ * omitted flag means world-only, so trusted local callers must pass+ * `remote: false` explicitly.+ */remote?: boolean;/** Metric filter. When set, only facts with this canonical metric label participate. */metric?: string;@@ -1723,6 +1724,9 @@ export interface BrainEngine {*/addTakesBatch(rows: TakeBatchInput[], opts?: BatchOpts): Promise<number>;+ /** Persist embeddings for active take rows; inactive rows are ignored. */+ updateTakeEmbeddings(rows: TakeEmbeddingInput[], opts?: BatchOpts): Promise<number>;+/** List takes filtered by holder/kind/active/etc. Resolves page_slug via JOIN. */listTakes(opts?: TakesListOpts): Promise<Take[]>;@@ -2322,6 +2326,20 @@ export interface BrainEngine {* Does NOT support glob/regex on purpose — the caller knows the prefix.*/listConfigKeys(prefix: string): Promise<string[]>;+ /**+ * Read the whole config table in one round trip, as a key -> value map.+ *+ * `loadConfigWithEngine()` needs ~44 config keys on every connect. Read one+ * key at a time that is 44 round trips, which costs nothing on PGLite and+ * dominates the wall clock on a hosted Postgres: `gbrain stats` against a+ * Supabase brain spent seconds on reads the server answered in under 3ms+ * total. The config table is a handful of rows, so fetching all of it is+ * cheaper than fetching any meaningful subset of it.+ *+ * Callers that need a single key still use getConfig(). This is for the+ * bulk-read path only.+ */+ getAllConfig(): Promise<Record<string, string>>;// Migration supportrunMigration(version: number, sql: string): Promise<void>;diff --git a/src/core/enrichment-service.ts b/src/core/enrichment-service.tsindex c165c2a989..2651bc5394 100644--- a/src/core/enrichment-service.ts+++ b/src/core/enrichment-service.ts@@ -108,7 +108,9 @@ export async function enrichEntity(request: EnrichmentRequest,opts?: EnrichmentTrustOptions,): Promise<EnrichmentResult> {- const slug = slugifyEntity(request.entityName, request.entityType);+ const candidateSlug = slugifyEntity(request.entityName, request.entityType);+ const sourceId = opts?.sourceId ?? 'default';+ const slug = await engine.resolveSlugWithAlias(candidateSlug, sourceId);// Fail-closed: only an explicit `trusted: true` writes authoritative pages.const trusted = opts?.trusted === true;const scope = opts?.sourceId ? { sourceId: opts.sourceId } : undefined;diff --git a/src/core/entities/resolve-on-save.ts b/src/core/entities/resolve-on-save.tsnew file mode 100644index 0000000000..d5d530e1ba--- /dev/null+++ b/src/core/entities/resolve-on-save.ts@@ -0,0 +1,102 @@+/**+ * Save-time caller around the shipped entity resolver.+ *+ * Bulk extract writes go through insertFacts and therefore skip+ * writeSingleFact's resolveEntitySlug hop. This module is the missing+ * write-path caller: it runs each extractor-provided entity through+ * resolveEntitySlugWithSource, which already owns the v0.46.15+ * alias_exact cascade via engine.resolveAliases.+ *+ * It does not re-implement the read-time cascade and does not introduce+ * alias_match / alias_redirect labels.+ */++import { BudgetExhausted } from '../budget/budget-tracker.ts';+import type { BrainEngine } from '../engine.ts';+import type { ExtractedFact } from '../facts/extract.ts';+import {+ resolveEntitySlugWithSource,+ type ResolutionSource,+} from './resolve.ts';++/** Shipped resolution tags, in stable log order. */+export const SAVE_TIME_RESOLUTION_SOURCES = [+ 'exact_page',+ 'alias_exact',+ 'fuzzy_match',+ 'fallback_slugify',+] as const satisfies readonly ResolutionSource[];++export interface SaveTimeResolutionCounts {+ counts: Partial<Record<ResolutionSource, number>>;+ fallback_slugify_count: number;+ resolution_errors: number;+}++export function emptySaveTimeResolutionCounts(): SaveTimeResolutionCounts {+ return { counts: {}, fallback_slugify_count: 0, resolution_errors: 0 };+}++export function mergeSaveTimeResolutionCounts(+ into: SaveTimeResolutionCounts,+ add: SaveTimeResolutionCounts,+): void {+ for (const [source, count] of Object.entries(add.counts)) {+ const typed = source as ResolutionSource;+ into.counts[typed] = (into.counts[typed] ?? 0) + (count ?? 0);+ }+ into.fallback_slugify_count += add.fallback_slugify_count;+ into.resolution_errors += add.resolution_errors;+}++export function formatSaveTimeResolutionCounts(+ counts: Partial<Record<ResolutionSource, number>>,+): string {+ const ordered: Partial<Record<ResolutionSource, number>> = {};+ for (const source of SAVE_TIME_RESOLUTION_SOURCES) {+ const count = counts[source];+ if (count) ordered[source] = count;+ }+ return JSON.stringify(ordered);+}++function isAbortError(err: unknown): boolean {+ if (!(err instanceof Error)) return false;+ return err.name === 'AbortError' || /aborted|cancell?ed/i.test(err.message);+}++/**+ * Canonicalize extractor-provided entity slugs through the shipped+ * resolver. Mutates `facts` in place. Sequential so a PGLite-pinned+ * transaction sees one alias probe at a time.+ *+ * Ordinary resolver failures keep the raw value and increment+ * resolution_errors. Abort and BudgetExhausted propagate.+ */+export async function resolveExtractedEntitiesForSave(+ engine: BrainEngine,+ sourceId: string,+ facts: ExtractedFact[],+ onError?: (raw: string, message: string) => void,+): Promise<SaveTimeResolutionCounts> {+ const stats = emptySaveTimeResolutionCounts();+ for (let i = 0; i < facts.length; i++) {+ const raw = facts[i].entity_slug;+ if (raw === null) continue;+ try {+ const resolved = await resolveEntitySlugWithSource(engine, sourceId, raw);+ facts[i] = { ...facts[i], entity_slug: resolved?.slug ?? null };+ if (!resolved) continue;+ stats.counts[resolved.source] = (stats.counts[resolved.source] ?? 0) + 1;+ if (resolved.source === 'fallback_slugify') {+ stats.fallback_slugify_count++;+ }+ } catch (err) {+ if (isAbortError(err) || err instanceof BudgetExhausted) throw err;+ stats.resolution_errors++;+ const message = err instanceof Error ? err.message : String(err);+ onError?.(raw, message);+ }+ }+ return stats;+}diff --git a/src/core/eval/metric-glossary.ts b/src/core/eval/metric-glossary.tsindex bb61a9b0de..eee5e31486 100644--- a/src/core/eval/metric-glossary.ts+++ b/src/core/eval/metric-glossary.ts@@ -34,22 +34,22 @@ export const METRIC_GLOSSARY: Readonly<Record<string, Readonly<MetricGlossEntry>// ────────────────────────────────────────────────────────────────────────'precision@k': Object.freeze({industry_term: 'Precision at k (P@k)',- eli10: 'Of the top k results the engine returned, what fraction were actually relevant? High precision means few junk results in the top of the list.',- range: '0..1, higher is better. P@10 = 0.7 means 7 of the top 10 results were on-topic.',+ eli10: 'Of the top k unique pages the engine returned, what fraction were actually relevant? Multiple chunks from one page count once. High precision means few junk pages in the top of the list.',+ range: '0..1, higher is better. The denominator stays k even when fewer than k unique pages are returned; P@10 = 0.7 means 7 relevant pages in the top 10 slots.',}),'recall@k': Object.freeze({industry_term: 'Recall at k (R@k)',- eli10: 'Of all the relevant results that exist in the brain, what fraction did the engine find in its top k? High recall means few missed answers.',- range: '0..1, higher is better. R@10 = 0.81 means out of every 100 questions, the right answer was in the top 10 for 81 of them.',+ eli10: 'Of all the relevant pages that exist in the brain, what fraction did the engine find in its first k unique pages? Multiple chunks from one page count once. High recall means few missed answers.',+ range: '0..1, higher is better. R@10 = 0.81 means 81% of all labeled relevant pages appeared in the first 10 unique results.',}),'mrr': Object.freeze({industry_term: 'Mean Reciprocal Rank (MRR)',- eli10: 'On average, how far down the list is the FIRST relevant result? An MRR of 1.0 means the first hit is always right; an MRR of 0.5 means it\'s typically at rank 2.',+ eli10: 'On average, how far down the unique-page list is the FIRST relevant result? Repeated chunks do not consume ranks. An MRR of 1.0 means the first page is always right; an MRR of 0.5 means it\'s typically at rank 2.',range: '0..1, higher is better. Computed as the average of 1/rank-of-first-relevant-result across all test queries.',}),'ndcg@k': Object.freeze({industry_term: 'Normalized Discounted Cumulative Gain at k (nDCG@k)',- eli10: 'Like precision@k, but the engine gets MORE credit for putting good results near the top than near rank k. A perfect ordering scores 1.0; a totally random ordering scores near 0.',+ eli10: 'Like precision@k, but the engine gets MORE credit for putting good pages near the top than near rank k. Each page earns gain once even if several chunks matched. A perfect ordering scores 1.0; a totally random ordering scores near 0.',range: '0..1, higher is better. nDCG@10 above 0.65 is the common "ship it" threshold for hybrid retrieval on technical corpora.',}),diff --git a/src/core/eval/ranked-docs.ts b/src/core/eval/ranked-docs.tsnew file mode 100644index 0000000000..f0d38fc280--- /dev/null+++ b/src/core/eval/ranked-docs.ts@@ -0,0 +1,16 @@+/**+ * Collapse chunk-level retrieval output to page-level ranked keys.+ *+ * Search may intentionally return several chunks from one page. Evaluation+ * treats that page as one document, preserving only its first (best) rank.+ */+export function dedupeRankedKeys(ranked: readonly string[]): string[] {+ const seen = new Set<string>();+ const unique: string[] = [];+ for (const key of ranked) {+ if (seen.has(key)) continue;+ seen.add(key);+ unique.push(key);+ }+ return unique;+}diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 44ebde5f0e..26e6fa2dd5 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -496,6 +496,29 @@ async function runPipelineWithBody(input: { turnText: string; isDreamGenerated: boolean; ref?: string },ctx: FactsBackstopCtx,abortSignal?: AbortSignal,+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason }> {+ // #4210: outside a withBudgetTracker scope (extract_facts op, sweep,+ // put_page backstop, checkpoint harvest, file/code import) the gateway's+ // chat/embed calls were budget no-ops — real spend, zero audit rows.+ // Install a record-only fallback tracker labeled by the entry point so+ // every pipeline invocation is visible to accounting. Uncapped, so it can+ // never throw BudgetExhausted (cost/runtime gates need a cap); the+ // pipeline's failure surface is unchanged. An ambient tracker (cycle+ // phases, transcripts ingest) wins — no double scope, labels preserved.+ const { getCurrentBudgetTracker, withBudgetTracker } = await import('../ai/gateway.ts');+ if (!getCurrentBudgetTracker()) {+ const { BudgetTracker } = await import('../budget/budget-tracker.ts');+ const fallback = new BudgetTracker({ label: `facts:${ctx.source}` });+ return withBudgetTracker(fallback, () => runPipelineBodyInner(input, ctx, abortSignal));+ }+ return runPipelineBodyInner(input, ctx, abortSignal);+}++/** The actual pipeline body — always runs inside a BudgetTracker scope (#4210). */+async function runPipelineBodyInner(+ input: { turnText: string; isDreamGenerated: boolean; ref?: string },+ ctx: FactsBackstopCtx,+ abortSignal?: AbortSignal,): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason }> {const { extractFactsFromTurnWithOutcome, FactsExtractionError } = await import('./extract.ts');const { resolveEntitySlug } = await import('../entities/resolve.ts');@@ -506,6 +529,10 @@ async function runPipelineWithBody(return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [] };}+ const filter = ctx.notabilityFilter ?? 'all';+ const notabilityAdmission = filter === 'high-only'+ ? { allowed: ['high'] as const, invalid: 'drop' as const }+ : undefined;const outcome = await extractFactsFromTurnWithOutcome({turnText: input.turnText,sessionId: ctx.sessionId,@@ -515,6 +542,7 @@ async function runPipelineWithBody(engine: ctx.engine,abortSignal,model: ctx.model,+ notabilityAdmission,});if (!outcome.ok) {@@ -541,7 +569,6 @@ async function runPipelineWithBody(const facts = outcome.facts;- const filter = ctx.notabilityFilter ?? 'all';// [ENG-8] Explicit ctx.visibility wins; unset resolves the operator-set// facts.default_visibility (fail-closed to 'private').const { resolveDefaultVisibility } = await import('./visibility.ts');diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.tsindex 2fac8986f6..5822cace28 100644--- a/src/core/facts/extract.ts+++ b/src/core/facts/extract.ts@@ -88,6 +88,8 @@ export const ALL_EXTRACT_KINDS: readonly FactKind[] = ['event', 'preference', 'commitment', 'belief', 'fact',] as const;+export type FactNotability = 'high' | 'medium' | 'low';+/*** #4209 — max entity hints forwarded to the extractor prompt. Anything past* this is silently dropped by the prompt builder, so the cap is NAMED here@@ -119,6 +121,11 @@ export interface ExtractInput {abortSignal?: AbortSignal;/** Cap on number of facts returned per turn. Defaults to 10. */maxFactsPerTurn?: number;+ /** Optional pre-embedding admission selector for extracted fact tiers. */+ notabilityAdmission?: {+ allowed: readonly FactNotability[];+ invalid: 'drop';+ };}/** A pre-INSERT fact ready for the engine.insertFact path. */@@ -429,8 +436,13 @@ export async function extractFactsFromTurnWithOutcome(? (candidate.kind as FactKind): 'fact';const confidence = clampConfidence(candidate.confidence);- const notability = ['high', 'medium', 'low'].includes(candidate.notability || '')- ? (candidate.notability as 'high' | 'medium' | 'low')+ const validTier = ['high', 'medium', 'low'].includes(candidate.notability ?? '');+ if (input.notabilityAdmission) {+ const tier = validTier ? candidate.notability as FactNotability : null;+ if (!tier || !input.notabilityAdmission.allowed.includes(tier)) continue;+ }+ const notability: FactNotability = validTier+ ? candidate.notability as FactNotability: 'medium';let embedding: Float32Array | null = null;diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 1fd541447b..41aaeab14d 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -274,7 +274,7 @@ export interface ImportResult {type_warning?: { kind: 'alias_of' | 'undeclared'; type: string; canonical?: string; directory?: string };}-const MAX_FILE_SIZE = 5_000_000; // 5MB+export const MAX_FILE_SIZE = 5_000_000; // 5MBfunction invalidYamlFrontmatterError(parsed: ReturnType<typeof parseMarkdown>): string | null {const yamlError = parsed.errors?.find((error) => error.code === 'YAML_PARSE');diff --git a/src/core/init-schema-retry.ts b/src/core/init-schema-retry.tsnew file mode 100644index 0000000000..5841521f0b--- /dev/null+++ b/src/core/init-schema-retry.ts@@ -0,0 +1,68 @@+import type { BrainEngine } from './engine.ts';+import {+ isRetryableConnError,+ isStatementTimeoutError,+} from './retry-matcher.ts';++export interface InitSchemaRetryOpts {+ maxAttempts?: number;+ backoffMs?: number;+ log?: (line: string) => void;+ _hooks?: {+ initSchema?: () => Promise<void>;+ sleep?: (ms: number) => Promise<void>;+ };+}++export interface InitSchemaRetryResult {+ attempts: number;+}++function isMigrationRetryExhausted(err: unknown): boolean {+ return err instanceof Error && err.name === 'MigrationRetryExhausted';+}++function isRetryableInitSchemaError(err: unknown): boolean {+ if (isMigrationRetryExhausted(err)) return false;+ return isStatementTimeoutError(err) || isRetryableConnError(err);+}++function retryReason(err: unknown): string {+ if (isStatementTimeoutError(err)) return 'statement_timeout';+ if (isRetryableConnError(err)) return 'transient connection error';+ return 'retryable schema error';+}++/**+ * Retry the full idempotent initSchema pass for pooler-level cold-start flakes.+ *+ * Individual migration statements already have their own retry envelope inside+ * runMigrations(); this wrapper only catches failures outside that envelope+ * (for example the embedded schema replay before pending migrations run).+ */+export async function runInitSchemaWithRetry(+ engine: Pick<BrainEngine, 'initSchema'>,+ opts: InitSchemaRetryOpts = {},+): Promise<InitSchemaRetryResult> {+ const maxAttempts = opts.maxAttempts ?? 5;+ const backoffMs = opts.backoffMs ?? 15_000;+ const initSchema = opts._hooks?.initSchema ?? (() => engine.initSchema());+ const sleep = opts._hooks?.sleep ?? ((ms: number) => new Promise(r => setTimeout(r, ms)));+ const log = opts.log ?? ((line: string) => process.stderr.write(`${line}\n`));++ for (let attempt = 1; attempt <= maxAttempts; attempt++) {+ try {+ await initSchema();+ return { attempts: attempt };+ } catch (err) {+ if (!isRetryableInitSchemaError(err) || attempt === maxAttempts) {+ throw err;+ }++ log(` [init retry ${attempt}/${maxAttempts}] schema setup hit ${retryReason(err)}; retrying in ${backoffMs}ms`);+ await sleep(backoffMs);+ }+ }++ throw new Error('initSchema retry loop exhausted unexpectedly');+}diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex da429f5db4..e20611c365 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -6200,6 +6200,65 @@ export const MIGRATIONS: Migration[] = [ADD COLUMN IF NOT EXISTS expected_limit_count INTEGER NOT NULL DEFAULT 0;`,},+ {+ version: 142,+ name: 'takes_embedding_dimension_matches_config',+ // #2089: takes was created with a hard-coded vector(1536), while the+ // configured embedding model can emit another width (for example the+ // default zembed-1 2560d). The vector writer cannot be useful until the+ // column shares the configured dimension with content_chunks/facts.+ // Renumbered v141 → v142: the wave-k branch shipped this AS v141 while+ // master consumed v141 for extract_rollup_expected_limit (#4482), so a+ // brain that ran the branch pre-merge recorded version 141 and would+ // skip master's v141 forever. The guarded DDL below re-applies it here+ // as a redundant first statement — idempotent, a no-op on fresh paths.+ idempotent: true,+ sql: '',+ handler: async (engine) => {+ // Skew guard (see renumber note above): branch-tester DBs at v141+ // missed extract_rollup_expected_limit; IF NOT EXISTS makes this free+ // everywhere else.+ await engine.executeRaw(+ `ALTER TABLE extract_rollup_7d+ ADD COLUMN IF NOT EXISTS expected_limit_count INTEGER NOT NULL DEFAULT 0`,+ );+ const dimRows = await engine.executeRaw<{ value: string }>(+ `SELECT value FROM config WHERE key = 'embedding_dimensions'`,+ );+ const configured = Number.parseInt(dimRows[0]?.value ?? '', 10);+ const embeddingDim = Number.isInteger(configured) && configured > 0 && configured <= 16000+ ? configured+ : 1536;++ const typeRows = await engine.executeRaw<{ formatted: string | null }>(+ `SELECT format_type(a.atttypid, a.atttypmod) AS formatted+ FROM pg_attribute a+ JOIN pg_class c ON c.oid = a.attrelid+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = 'public'+ AND c.relname = 'takes'+ AND a.attname = 'embedding'+ AND NOT a.attisdropped`,+ );+ const current = typeRows[0]?.formatted?.match(/vector\((\d+)\)/i)?.[1];+ if (current && Number.parseInt(current, 10) === embeddingDim) return;++ await engine.executeRaw(`DROP INDEX IF EXISTS idx_takes_embedding_hnsw`);+ // Existing vectors cannot be cast across dimensions. Null them before+ // replacing the column; the next `gbrain takes embed` repopulates them.+ await engine.executeRaw(`UPDATE takes SET embedding = NULL, embedded_at = NULL`);+ await engine.executeRaw(`ALTER TABLE takes DROP COLUMN IF EXISTS embedding`);+ await engine.executeRaw(`ALTER TABLE takes ADD COLUMN embedding VECTOR(${embeddingDim})`);+ if (embeddingDim <= hnswMaxDimsForType('vector')) {+ await engine.executeRaw(+ `CREATE INDEX IF NOT EXISTS idx_takes_embedding_hnsw ON takes+ USING hnsw (embedding vector_cosine_ops)+ WHERE active AND embedding IS NOT NULL`,+ );+ }+ process.stderr.write(` v142: takes.embedding resized to vector(${embeddingDim}); existing take vectors cleared\n`);+ },+ },];export const LATEST_VERSION = MIGRATIONS.length > 0diff --git a/src/core/model-config.ts b/src/core/model-config.tsindex 73457e09e7..0d913dc3ab 100644--- a/src/core/model-config.ts+++ b/src/core/model-config.ts@@ -20,7 +20,7 @@* AND lose to new-key config when both are set.*/-import type { BrainEngine } from './engine.ts';+import type { ConfigReader } from './config-snapshot.ts';import { splitProviderModelId } from './model-id.ts';import type { GBrainConfig } from './config.ts';import { loadConfig } from './config.ts';@@ -360,7 +360,7 @@ export type ResolveSource =* unservable Anthropic default.*/export async function resolveModelDetailed(- engine: BrainEngine | null,+ engine: ConfigReader | null,opts: ResolveModelOpts,): Promise<{ model: string; source: ResolveSource }> {const envVar = opts.envVar ?? 'GBRAIN_MODEL';@@ -439,7 +439,7 @@ export async function resolveModelDetailed(* `resolveModelDetailed` for the ~30 callers that don't care which step won.*/export async function resolveModel(- engine: BrainEngine | null,+ engine: ConfigReader | null,opts: ResolveModelOpts,): Promise<string> {return (await resolveModelDetailed(engine, opts)).model;@@ -554,7 +554,7 @@ void enforceSubagentAnthropic;* to `super-opus` which aliases to `opus`, we return `super-opus` and stop.*/export async function resolveAlias(- engine: BrainEngine | null,+ engine: ConfigReader | null,name: string,depth = 0,): Promise<string> {diff --git a/src/core/model-pricing.ts b/src/core/model-pricing.tsindex 6738d2ed82..3ae2c502fc 100644--- a/src/core/model-pricing.ts+++ b/src/core/model-pricing.ts@@ -130,11 +130,16 @@ export const CANONICAL_PRICING: Record<string, ModelPricing> = {// usage/audit rows still price. Not a valid default — it's deliberately// absent from the google recipe's chat list.'google:gemini-1.5-pro': { input: 1.25, output: 5.00 },- // Gemini 2.0 Flash: $0.10 in / $0.40 out (verified 2026-06-03). Reconciled- // from a stale $0.30/$1.20 entry that had drifted in takes-quality-eval.- // `gemini-2-flash` kept as an alias for the legacy id spelling.+ // The whole `gemini-2.0` family was retired the same way; kept for the same+ // reason, and equally absent from the recipe's chat list. `gemini-2-flash`+ // is the legacy id spelling of `gemini-2.0-flash` — keep the pair in+ // lockstep (the drift guard asserts they agree).'google:gemini-2.0-flash': { input: 0.10, output: 0.40 },'google:gemini-2-flash': { input: 0.10, output: 0.40 },+ // Gemini 2.5 Flash / Flash-Lite: the live successors, and what the recipe+ // lists today. Rates from Google's published pricing (2026-08-02).+ 'google:gemini-2.5-flash': { input: 0.30, output: 2.50 },+ 'google:gemini-2.5-flash-lite': { input: 0.10, output: 0.40 },// ── Together / DeepSeek (cross-modal-eval panel) ───────────────────────'together:meta-llama/Llama-3.3-70B-Instruct-Turbo': { input: 0.88, output: 0.88 },diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.tsindex bf5cbd19c0..14cce1f9d5 100644--- a/src/core/oauth-provider.ts+++ b/src/core/oauth-provider.ts@@ -26,7 +26,14 @@ import type { AuthInfo as SdkAuthInfo } from '@modelcontextprotocol/sdk/server/aimport { InvalidTokenError, InvalidClientMetadataError, InvalidGrantError } from '@modelcontextprotocol/sdk/server/auth/errors.js';import { hashToken, generateToken, isUndefinedColumnError } from './utils.ts';import { assertValidSourceId } from './source-id.ts';-import { hasScope, assertAllowedScopes, parseScopeString, InvalidScopeError } from './scope.ts';+import {+ hasScope,+ assertAllowedScopes,+ filterAllowedScopes,+ parseScopeString,+ InvalidScopeError,+ ALLOWED_SCOPES_LIST,+} from './scope.ts';import type { AuthInfo as CoreAuthInfo } from './operations.ts';import { parseLegacyTokenScope, parseTakesHoldersAllowList, coerceLegacyPermissions, normalizeTokenScopes } from './legacy-token-scope.ts';@@ -155,21 +162,42 @@ export function validateTokenEndpointAuthMethod(value: unknown): TokenEndpointAu}/**- * Validate a redirect_uri per RFC 6749 §3.1.2.1.+ * Re-throw non-OAuth registration errors as `InvalidClientMetadataError` so+ * the MCP SDK register handler returns HTTP 400 `invalid_client_metadata`+ * instead of a generic 500 `server_error`. Already-OAuth errors pass through.+ */+function asClientMetadataError(err: unknown): never {+ if (err instanceof InvalidClientMetadataError) throw err;+ // Duck-type OAuthError from the SDK (has .errorCode) without importing the+ // base class — keeps the dependency surface stable across SDK versions.+ if (err && typeof err === 'object' && 'errorCode' in err) throw err;+ const message = err instanceof Error ? err.message : String(err);+ console.warn(`[gbrain dcr] rejected registration: ${message}`);+ throw new InvalidClientMetadataError(message);+}++/**+ * Validate a redirect_uri for the DCR path.+ *+ * Allowed:+ * - `https://` (production web clients)+ * - loopback `http://` (127.0.0.1 / ::1 / localhost) — RFC 8252 §7.3+ * - custom URI schemes (`warp://`, `myapp://`, …) — RFC 8252 §7.1 native apps*- * Production redirect_uris MUST be HTTPS. The only allowed plaintext- * exceptions are loopback (127.0.0.1, ::1, localhost) which are unreachable- * from the network. Throws a descriptive error on rejection.+ * Rejected:+ * - non-loopback plaintext `http://` (auth-code exfiltration over the network)+ * - unparseable strings*- * Used by the DCR (Dynamic Client Registration) path; the CLI registration- * path trusts the operator and bypasses this gate.+ * Throws `InvalidClientMetadataError` (OAuthError → SDK maps to HTTP 400+ * `invalid_client_metadata`) so DCR validation failures never surface as+ * opaque 500s. CLI registration bypasses this gate (operator-trusted).*/-function validateRedirectUri(uri: string): void {+export function validateRedirectUri(uri: string): void {let parsed: URL;try {parsed = new URL(uri);} catch {- throw new Error(`Invalid redirect_uri: not a parseable URL: ${uri}`);+ throw new InvalidClientMetadataError(`Invalid redirect_uri: not a parseable URL: ${uri}`);}const isLoopback = parsed.hostname === 'localhost'|| parsed.hostname === '127.0.0.1'@@ -177,8 +205,22 @@ function validateRedirectUri(uri: string): void {|| parsed.hostname === '::1';if (parsed.protocol === 'https:') return;if (parsed.protocol === 'http:' && isLoopback) return;- throw new Error(- `redirect_uri must use https:// (or http://localhost for loopback): ${uri}`,+ // Native-app custom schemes (anything other than http/https). Require a+ // non-empty scheme name so bare strings like "://x" can't sneak through,+ // and reject browser-executable pseudo-schemes: a javascript:/data:/+ // vbscript:/blob: "redirect" is script injection, not a native-app callback.+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {+ const scheme = parsed.protocol.replace(/:$/, '');+ const pseudoSchemes = new Set(['javascript', 'data', 'vbscript', 'blob']);+ if (pseudoSchemes.has(scheme.toLowerCase())) {+ throw new InvalidClientMetadataError(+ `redirect_uri scheme '${scheme}:' is a browser pseudo-scheme, not a native-app scheme: ${uri}`,+ );+ }+ if (scheme.length > 0) return;+ }+ throw new InvalidClientMetadataError(+ `redirect_uri must use https://, a native-app custom scheme, or http:// loopback: ${uri}`,);}@@ -337,42 +379,69 @@ class GBrainClientsStore implements OAuthRegisteredClientsStore {async registerClient(client: Omit<OAuthClientInformationFull, 'client_id' | 'client_id_issued_at'>,): Promise<OAuthClientInformationFull> {- // Enforce HTTPS for all redirect_uris on the DCR path (RFC 6749 §3.1.2.1).- // Without this, an attacker could register a non-loopback http:// URI and- // exfiltrate auth codes over plaintext. CLI registrations bypass this gate- // (operators are trusted; they can register http:// for testing).- for (const uri of client.redirect_uris || []) {- validateRedirectUri(String(uri));- }+ // DCR is unauthenticated network input. Every validation failure here+ // MUST become InvalidClientMetadataError (HTTP 400) — plain Errors are+ // converted to opaque 500 server_error by the MCP SDK register handler,+ // which is what broke Warp/rmcp clients against gbrain.+ let authMethod: TokenEndpointAuthMethod;+ let registeredScope: string;+ let grantTypes: string[];+ try {+ // redirect_uri: https / loopback http / native custom schemes only.+ // Non-loopback plaintext http is still rejected (auth-code exfil).+ // CLI registrations bypass this gate (operator-trusted).+ for (const uri of client.redirect_uris || []) {+ validateRedirectUri(String(uri));+ }- // v0.28: ALLOWED_SCOPES allowlist. RFC 6749 §5.2 invalid_scope. The DCR- // path is reachable by any unauthenticated network caller when --enable-dcr- // is on, so this is the security-relevant gate (manual CLI registration- // is operator-trusted).- assertAllowedScopes(parseScopeString(client.scope));-- // v0.41.3 (T5): validate token_endpoint_auth_method on the DCR path so- // `--enable-dcr` is not the looser entry point. CLI and admin paths gate- // through the same `validateTokenEndpointAuthMethod` helper — all three- // registration entry points share one allow-list.- const authMethod = validateTokenEndpointAuthMethod(client.token_endpoint_auth_method);-- // v0.42 (#1353): the DCR path is the unauthenticated network entry point.- // `client_credentials` skips /authorize consent entirely, so a self-- // registered DCR client must NOT get it by default. Default the grant to- // `authorization_code` (the consent-bearing flow) when unspecified, and- // reject an explicit `client_credentials` request unless the operator opted- // in via `--enable-dcr-insecure`. Manual CLI/admin registration bypasses- // this store method, so operators can still mint machine clients directly.- const grantTypes = (client.grant_types && client.grant_types.length > 0)- ? client.grant_types- : ['authorization_code'];- if (!this.allowClientCredentialsDcr && grantTypes.includes('client_credentials')) {- throw new InvalidClientMetadataError(- 'client_credentials grant is not permitted via dynamic client registration; ' +- 'restart the server with --enable-dcr-insecure to allow it, or register the ' +- 'client via the gbrain CLI / admin API.',- );+ // Scope policy for DCR: filter unknowns (RFC 7591 value replacement)+ // instead of hard-rejecting. Spec-compliant clients and OIDC-flavored+ // stacks often append `offline_access` / `openid`; rejecting those as+ // 500 made every such client fail registration. authorize() already+ // clamps issued tokens to the registered grant, so dropping extras is+ // safe. Empty-after-filter with a non-empty request is a hard 400.+ // Operator CLI/admin paths still use assertAllowedScopes (typo-loud).+ const requestedScopes = parseScopeString(client.scope);+ const { allowed, dropped } = filterAllowedScopes(requestedScopes);+ if (dropped.length > 0) {+ console.warn(+ `[gbrain dcr] dropping unknown scopes from registration ` ++ `(client_name=${client.client_name || 'unnamed'}): ${dropped.join(' ')}`,+ );+ }+ if (requestedScopes.length > 0 && allowed.length === 0) {+ throw new InvalidClientMetadataError(+ `No recognized scopes in request (${requestedScopes.join(' ')}). ` ++ `Allowed: ${ALLOWED_SCOPES_LIST.join(', ')}.`,+ );+ }+ registeredScope = allowed.join(' ');++ // v0.41.3 (T5): validate token_endpoint_auth_method on the DCR path so+ // `--enable-dcr` is not the looser entry point. CLI and admin paths gate+ // through the same `validateTokenEndpointAuthMethod` helper — all three+ // registration entry points share one allow-list.+ authMethod = validateTokenEndpointAuthMethod(client.token_endpoint_auth_method);++ // v0.42 (#1353): the DCR path is the unauthenticated network entry point.+ // `client_credentials` skips /authorize consent entirely, so a self-+ // registered DCR client must NOT get it by default. Default the grant to+ // `authorization_code` (the consent-bearing flow) when unspecified, and+ // reject an explicit `client_credentials` request unless the operator opted+ // in via `--enable-dcr-insecure`. Manual CLI/admin registration bypasses+ // this store method, so operators can still mint machine clients directly.+ grantTypes = (client.grant_types && client.grant_types.length > 0)+ ? client.grant_types+ : ['authorization_code'];+ if (!this.allowClientCredentialsDcr && grantTypes.includes('client_credentials')) {+ throw new InvalidClientMetadataError(+ 'client_credentials grant is not permitted via dynamic client registration; ' ++ 'restart the server with --enable-dcr-insecure to allow it, or register the ' ++ 'client via the gbrain CLI / admin API.',+ );+ }+ } catch (err) {+ asClientMetadataError(err);}const clientId = generateToken('gbrain_cl_');@@ -406,7 +475,7 @@ class GBrainClientsStore implements OAuthRegisteredClientsStore {VALUES (${clientId}, ${secretHash}, ${client.client_name || 'unnamed'},${pgArray((client.redirect_uris || []).map(String))},${pgArray(grantTypes)},- ${client.scope || ''}, ${authMethod},+ ${registeredScope}, ${authMethod},${now}, ${'default'}, ${pgArray(['default'])})`;} catch (err) {@@ -419,7 +488,7 @@ class GBrainClientsStore implements OAuthRegisteredClientsStore {VALUES (${clientId}, ${secretHash}, ${client.client_name || 'unnamed'},${pgArray((client.redirect_uris || []).map(String))},${pgArray(grantTypes)},- ${client.scope || ''}, ${authMethod},+ ${registeredScope}, ${authMethod},${now}, ${'default'})`;} catch (err2) {@@ -431,7 +500,7 @@ class GBrainClientsStore implements OAuthRegisteredClientsStore {VALUES (${clientId}, ${secretHash}, ${client.client_name || 'unnamed'},${pgArray((client.redirect_uris || []).map(String))},${pgArray(grantTypes)},- ${client.scope || ''}, ${authMethod},+ ${registeredScope}, ${authMethod},${now})`;} else {@@ -446,7 +515,7 @@ class GBrainClientsStore implements OAuthRegisteredClientsStore {VALUES (${clientId}, ${secretHash}, ${client.client_name || 'unnamed'},${pgArray((client.redirect_uris || []).map(String))},${pgArray(grantTypes)},- ${client.scope || ''}, ${authMethod},+ ${registeredScope}, ${authMethod},${now})`;} else {@@ -480,8 +549,11 @@ class GBrainClientsStore implements OAuthRegisteredClientsStore {// public client, the authorization server MUST NOT issue a client// secret"). Confidential clients return the freshly-generated secret// exactly once — same shape as before.+ // Override scope with the filtered grant so the client sees what was+ // actually registered (RFC 7591 §3.2.1 returned metadata).const response: OAuthClientInformationFull = {...client,+ scope: registeredScope,client_id: clientId,client_id_issued_at: now,};diff --git a/src/core/onboard/checks.ts b/src/core/onboard/checks.tsindex 885f3e1b89..06b39a4a58 100644--- a/src/core/onboard/checks.ts+++ b/src/core/onboard/checks.ts@@ -18,6 +18,7 @@import type { BrainEngine } from '../engine.ts';import type { RemediationStep } from '../remediation-step.ts';import { makeRemediationStep } from '../remediation-step.ts';+import { QUARANTINE_FILTER_FRAGMENT } from '../quarantine.ts';/** Shared shape returned by all four checks. */export interface OnboardCheckResult {@@ -45,6 +46,77 @@ async function safeCount(engine: BrainEngine, sql: string, params: unknown[] = [}}+const VISIBLE_ENTITY_PREDICATE = `p.type IN ('person', 'company', 'organization', 'entity')+ AND p.deleted_at IS NULL+ AND ${QUARANTINE_FILTER_FRAGMENT}`;++type CoverageFeature =+ | { table: 'links'; pageIdColumn: 'to_page_id' }+ | { table: 'timeline_entries'; pageIdColumn: 'page_id' };++interface EntityCoverageSample {+ matched: number;+ sampleSize: number;+}++/** Parse a SQL count defensively: coverage is an operator-facing health metric,+ * so a malformed driver value must not escape as NaN or a negative count. */+function finiteCount(value: unknown): number {+ const n = Number(value);+ return Number.isFinite(n) ? Math.max(0, Math.floor(n)) : 0;+}++/**+ * Count the feature numerator and denominator from the SAME sampled CTE.+ * TABLESAMPLE BERNOULLI returns a random number of rows; deriving its+ * denominator from `total * requestedPercent` can make coverage exceed 100%.+ */+async function sampleVisibleEntityCoverage(+ engine: BrainEngine,+ sampleClause: string,+ feature: CoverageFeature,+): Promise<EntityCoverageSample> {+ try {+ const result = await engine.executeRaw(+ `WITH sampled_entities AS (+ SELECT p.id+ FROM pages p ${sampleClause}+ WHERE ${VISIBLE_ENTITY_PREDICATE}+ )+ SELECT+ COUNT(*)::int AS sample_size,+ COUNT(*) FILTER (+ WHERE EXISTS (+ SELECT 1+ FROM ${feature.table} f+ WHERE f.${feature.pageIdColumn} = s.id+ )+ )::int AS matched+ FROM sampled_entities s`,+ );+ const rows = (result as { rows?: Array<Record<string, unknown>> } | undefined)?.rows+ ?? (result as Array<Record<string, unknown>> | undefined)+ ?? [];+ const row = rows[0] ?? {};+ const sampleSize = finiteCount(row.sample_size);+ // The SQL shape guarantees matched <= sample_size. Keep a defensive clamp+ // at the rendering boundary so a driver/fixture anomaly still cannot emit+ // impossible percentages or feed a negative value into sqrt().+ const matched = Math.min(sampleSize, finiteCount(row.matched));+ return { matched, sampleSize };+ } catch {+ return { matched: 0, sampleSize: 0 };+ }+}++function coverageWithConfidence(sample: EntityCoverageSample): { coverage: number; ci: number } {+ const rawCoverage = sample.sampleSize > 0 ? sample.matched / sample.sampleSize : 0;+ const coverage = Math.min(1, Math.max(0, rawCoverage));+ const variance = Math.max(0, coverage * (1 - coverage));+ const ci = Math.sqrt(variance / Math.max(1, sample.sampleSize));+ return { coverage, ci };+}+/*** embed_staleness: count of chunks awaiting embedding.*@@ -152,12 +224,12 @@ async function resolveNerInferenceCapability(export async function checkEntityLinkCoverage(engine: BrainEngine,): Promise<OnboardCheckResult> {- // Total entity pages+ // Total visible entity pages. Quarantined pages are hidden from the brain,+ // so they are outside both the coverage numerator and denominator.const totalEntities = await safeCount(engine,- `SELECT COUNT(*) AS count FROM pages- WHERE type IN ('person', 'company', 'organization', 'entity')- AND deleted_at IS NULL`,+ `SELECT COUNT(*) AS count FROM pages p+ WHERE ${VISIBLE_ENTITY_PREDICATE}`,);if (totalEntities === 0) {@@ -174,23 +246,12 @@ export async function checkEntityLinkCoverage(: 100;const sampleClause = useSample ? `TABLESAMPLE BERNOULLI (${samplePct.toFixed(2)})` : '';- // Sample query: counts entities with inbound links- const linkedCount = await safeCount(+ const sample = await sampleVisibleEntityCoverage(engine,- `SELECT COUNT(*) AS count FROM (- SELECT p.id FROM pages p ${sampleClause}- WHERE p.type IN ('person', 'company', 'organization', 'entity')- AND p.deleted_at IS NULL- AND EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)- ) sub`,+ sampleClause,+ { table: 'links', pageIdColumn: 'to_page_id' },);- const sampleSize = useSample- ? Math.max(1, Math.round(totalEntities * (samplePct / 100)))- : totalEntities;-- const coverage = sampleSize > 0 ? linkedCount / sampleSize : 0;- // Wilson-ish confidence interval (1σ; ±sqrt(p(1-p)/n))- const ci = Math.sqrt((coverage * (1 - coverage)) / Math.max(1, sampleSize));+ const { coverage, ci } = coverageWithConfidence(sample);const pct = Math.round(coverage * 100);const ciPct = (ci * 100).toFixed(1);@@ -254,9 +315,8 @@ export async function checkTimelineCoverage(): Promise<OnboardCheckResult> {const totalEntities = await safeCount(engine,- `SELECT COUNT(*) AS count FROM pages- WHERE type IN ('person', 'company', 'organization', 'entity')- AND deleted_at IS NULL`,+ `SELECT COUNT(*) AS count FROM pages p+ WHERE ${VISIBLE_ENTITY_PREDICATE}`,);if (totalEntities === 0) {@@ -272,21 +332,12 @@ export async function checkTimelineCoverage(: 100;const sampleClause = useSample ? `TABLESAMPLE BERNOULLI (${samplePct.toFixed(2)})` : '';- const withTimelineCount = await safeCount(+ const sample = await sampleVisibleEntityCoverage(engine,- `SELECT COUNT(*) AS count FROM (- SELECT p.id FROM pages p ${sampleClause}- WHERE p.type IN ('person', 'company', 'organization', 'entity')- AND p.deleted_at IS NULL- AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id = p.id)- ) sub`,+ sampleClause,+ { table: 'timeline_entries', pageIdColumn: 'page_id' },);- const sampleSize = useSample- ? Math.max(1, Math.round(totalEntities * (samplePct / 100)))- : totalEntities;-- const coverage = sampleSize > 0 ? withTimelineCount / sampleSize : 0;- const ci = Math.sqrt((coverage * (1 - coverage)) / Math.max(1, sampleSize));+ const { coverage, ci } = coverageWithConfidence(sample);const pct = Math.round(coverage * 100);const ciPct = (ci * 100).toFixed(1);const sampleNote = useSample ? ` (sampled ${samplePct.toFixed(1)}%)` : '';@@ -557,9 +608,9 @@ export async function checkTypeProliferation(}/**- * dangling_aliases (F12): surfaces slug_aliases rows whose canonical page- * no longer exists in the pages table. Source-scoped JOIN prevents- * cross-source false-positive deletion.+ * dangling_aliases (F12): surfaces both slug_aliases redirects and+ * page_aliases free-text names whose target page no longer exists.+ * Source-scoped JOINs prevent cross-source false-positive deletion.** v0.42 ships surface-only (no auto-GC RemediationStep). v0.43+ may add* `cleanup-dangling-aliases` as an auto_apply handler once detection is@@ -572,7 +623,7 @@ export async function checkTypeProliferation(export async function checkDanglingAliases(engine: BrainEngine,): Promise<OnboardCheckResult> {- const n = await safeCount(+ const slugAliases = await safeCount(engine,`SELECT COUNT(*) AS count FROM slug_aliases saLEFT JOIN pages p@@ -581,16 +632,30 @@ export async function checkDanglingAliases(AND p.deleted_at IS NULLWHERE p.id IS NULL`,);+ const pageAliases = await safeCount(+ engine,+ `SELECT COUNT(*) AS count FROM page_aliases pa+ LEFT JOIN pages p+ ON p.slug = pa.slug+ AND p.source_id = pa.source_id+ AND p.deleted_at IS NULL+ WHERE p.id IS NULL`,+ );+ const n = slugAliases + pageAliases;if (n > 0) {return {check: {name: 'dangling_aliases',status: 'warn',message:- `${n} alias rows point at deleted canonicals. Safe GC (source-scoped): ` ++ `${n} alias rows point at missing/deleted pages ` ++ `(${slugAliases} slug redirects; ${pageAliases} free-text page aliases). ` ++ `Safe GC (source-scoped): ` +`\`DELETE FROM slug_aliases sa WHERE NOT EXISTS (SELECT 1 FROM pages p ` +`WHERE p.slug = sa.canonical_slug AND p.source_id = sa.source_id ` +- `AND p.deleted_at IS NULL);\``,+ `AND p.deleted_at IS NULL); DELETE FROM page_aliases pa WHERE NOT EXISTS ` ++ `(SELECT 1 FROM pages p WHERE p.slug = pa.slug ` ++ `AND p.source_id = pa.source_id AND p.deleted_at IS NULL);\``,},remediations: [], // v0.42: surface-only; auto-GC v0.43+};diff --git a/src/core/ops/chunks.ts b/src/core/ops/chunks.tsindex bcc7a731d2..a9f457deef 100644--- a/src/core/ops/chunks.ts+++ b/src/core/ops/chunks.ts@@ -7,7 +7,7 @@*/import type { Operation } from './contract.ts';-import { federatedSearchScope, sourceScopeOpts } from './context.ts';+import { federatedSearchScope, parseSourceIdParam, sourceScopeOpts } from './context.ts';import {findPrivateOnlySlugs,resolveExcludePrivatePages,@@ -21,13 +21,20 @@ const resolve_slugs: Operation = {description: 'Fuzzy-resolve a partial slug to matching page slugs',params: {partial: { type: 'string', required: true, description: "Partial slug or title text to match, e.g. 'alice-ex' or 'meeting notes'. This is the search text param — there is no `text` param." },+ source_id: {+ type: 'string',+ description:+ "Scope resolution to a single source. Defaults to OperationContext.sourceId; when unset, an unqualified resolve spans every federated source (matching search/get_page). Pass '__all__' to span every source for trusted local callers; for remote callers '__all__' spans only your granted sources.",+ },},handler: async (ctx, p) => {// #3242: was fully UNSCOPED — the one read that leaked every source's// slugs to any caller (the reporter's "resolve_slugs sees them but// get_page doesn't" matrix). Route through the same visibility set as- // get_page/search: grant > federated set > scalar source.- const scope = federatedSearchScope(ctx);+ // get_page/search: grant > federated set > scalar source. An explicit+ // per-call source_id narrows through resolveRequestedScope.+ const sourceIdParam = parseSourceIdParam(p.source_id, 'resolve_slugs', { allowAll: true });+ const scope = federatedSearchScope(ctx, sourceIdParam);const candidates = await ctx.engine.resolveSlugs(p.partial as string, scope);// #4352 remediation: fuzzy resolution must not enumerate private slugs to// an untrusted caller — same gate as get_page's candidate filter (trusteddiff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex 1f51983c25..4bf009a881 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -15,7 +15,7 @@ import { resolve, relative, sep } from 'path';import { OperationError } from './contract.ts';import type { AuthInfo, Operation, OperationContext } from './contract.ts';import { CJK_SLUG_CHARS, PAGE_SLUG_SEG } from '../cjk.ts';-import { ALL_SOURCES } from '../source-id.ts';+import { ALL_SOURCES, isValidSourceId } from '../source-id.ts';import { isSearchMode } from '../search/mode.ts';import { stampEvidence } from '../search/evidence.ts';import { captureEvalCandidate, isEvalCaptureEnabled, isEvalScrubEnabled } from '../eval-capture.ts';@@ -521,6 +521,40 @@ export function resolveRequestedScope(return sourceScopeOpts(ctx);}+/**+ * #4329: parse a per-call `source_id` param. Pre-fix, get_page / delete_page /+ * restore_page had NO source_id in their contracts, so an agent-passed+ * source_id was SILENTLY dropped and the op acted on ctx.sourceId —+ * soft-deleting the WRONG row on a multi-source brain while returning a+ * success that named the requested slug. A caller-supplied value is either+ * honored or rejected loudly — never ignored. `allowAll` admits the+ * `__all__` sentinel for read ops (resolveRequestedScope collapses it per+ * trust); destructive ops target exactly one source and reject it.+ */+export function parseSourceIdParam(+ raw: unknown,+ opName: string,+ opts?: { allowAll?: boolean },+): string | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw === 'string') {+ if (raw === ALL_SOURCES) {+ if (opts?.allowAll === true) return raw;+ throw new OperationError(+ 'invalid_params',+ `${opName}: source_id '${ALL_SOURCES}' is not a valid target — this op acts on exactly one source.`,+ 'Pass the single source_id of the row to target, or omit source_id to use the ambient source scope.',+ );+ }+ if (isValidSourceId(raw)) return raw;+ }+ throw new OperationError(+ 'invalid_params',+ `${opName}: invalid source_id ${JSON.stringify(raw)} — must be 1-32 lowercase alnum chars with optional interior hyphens.`,+ 'Pass a registered source id (see list_sources), or omit source_id to use the ambient source scope.',+ );+}+/*** #2561 / #3242 — source scope for the page-visibility read ops (`search`,* `query`, `get_page`, `list_pages`, `resolve_slugs`).@@ -533,11 +567,15 @@ export function resolveRequestedScope(* were invisible to get_page/search/list_pages while resolve_slugs leaked them).** The expansion NEVER applies when:- * - a per-call `source_id` was passed (explicit wins, including `__all__`);+ * - a concrete per-call `source_id` was passed (explicit wins);* - the resolver already produced a federated array (OAuth grant governs);* - the transport didn't populate `localFederatedSourceIds` (see that- * field's doc: it is only set for callers with NO explicit source scope,- * and never from caller-controlled params — so trust stays fail-closed).+ * field's doc: it is transport-computed and never derived from+ * caller-controlled params — so trust stays fail-closed).+ *+ * The read-only `__all__` sentinel is equivalent to an unqualified read when+ * it resolves to the caller's scalar floor. It may therefore use the same+ * transport-computed federated set, but never widens an OAuth grant.** Deliberately NOT inside `sourceScopeOpts`: code-intel ops collapse a* multi-element scope to an error (`resolveCodeIntelScope`), and the remaining@@ -549,7 +587,8 @@ export function federatedSearchScope(): { sourceId?: string; sourceIds?: string[] } {const scope = resolveRequestedScope(ctx, sourceIdParam);if (- sourceIdParam === undefined &&+ (sourceIdParam === undefined || sourceIdParam === ALL_SOURCES) &&+ ctx.auth?.allowedSources === undefined &&scope.sourceId !== undefined &&scope.sourceIds === undefined &&ctx.localFederatedSourceIds !== undefined &&diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.tsindex f54943b4d5..97040b6b53 100644--- a/src/core/ops/jobs.ts+++ b/src/core/ops/jobs.ts@@ -686,7 +686,9 @@ const pause_job: Operation = {id: { type: 'number', required: true, description: 'Job ID' },},scope: 'admin',+ mutating: true,handler: async (ctx, p) => {+ if (ctx.dryRun) return { dry_run: true, action: 'pause_job', id: p.id };const { MinionQueue } = await import('../minions/queue.ts');const queue = new MinionQueue(ctx.engine);const job = await queue.pauseJob(p.id as number);@@ -702,7 +704,9 @@ const resume_job: Operation = {id: { type: 'number', required: true, description: 'Job ID' },},scope: 'admin',+ mutating: true,handler: async (ctx, p) => {+ if (ctx.dryRun) return { dry_run: true, action: 'resume_job', id: p.id };const { MinionQueue } = await import('../minions/queue.ts');const queue = new MinionQueue(ctx.engine);const job = await queue.resumeJob(p.id as number);@@ -719,6 +723,7 @@ const replay_job: Operation = {data_overrides: { type: 'object', required: false, description: 'Data fields to override (merged with original)' },},scope: 'admin',+ mutating: true,handler: async (ctx, p) => {if (ctx.dryRun) return { dry_run: true, action: 'replay_job', id: p.id };const { MinionQueue } = await import('../minions/queue.ts');@@ -738,6 +743,7 @@ const send_job_message: Operation = {sender: { type: 'string', required: false, description: 'Sender identity (default: admin)' },},scope: 'admin',+ mutating: true,handler: async (ctx, p) => {if (ctx.dryRun) return { dry_run: true, action: 'send_job_message', id: p.id };const { MinionQueue } = await import('../minions/queue.ts');diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 6182cb1792..83a1b689bd 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -22,7 +22,6 @@ import type { WriterLintPayload } from '../output/post-write.ts';import { stripFactsFence } from '../facts-fence.ts';import { getContentFlag } from '../quarantine.ts';import { bumpLastRetrievedAt } from '../last-retrieved.ts';-import { isValidSourceId, ALL_SOURCES } from '../source-id.ts';import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs } from '../search/private-visibility.ts';import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descriptions.ts';import { OperationError } from './contract.ts';@@ -33,45 +32,12 @@ import {enforceClientSlugFence,federatedSearchScope,normalizeSlugPrefix,+ parseSourceIdParam,validatePageSlug,} from './context.ts';// --- Page CRUD ----/**- * #4329: parse a per-call `source_id` param. Pre-fix, get_page / delete_page /- * restore_page had NO source_id in their contracts, so an agent-passed- * source_id was SILENTLY dropped and the op acted on ctx.sourceId —- * soft-deleting the WRONG row on a multi-source brain while returning a- * success that named the requested slug. A caller-supplied value is either- * honored or rejected loudly — never ignored. `allowAll` admits the- * `__all__` sentinel for read ops (resolveRequestedScope collapses it per- * trust); destructive ops target exactly one source and reject it.- */-function parseSourceIdParam(- raw: unknown,- opName: string,- opts?: { allowAll?: boolean },-): string | undefined {- if (raw === undefined || raw === null) return undefined;- if (typeof raw === 'string') {- if (raw === ALL_SOURCES) {- if (opts?.allowAll === true) return raw;- throw new OperationError(- 'invalid_params',- `${opName}: source_id '${ALL_SOURCES}' is not a valid target — this op acts on exactly one source.`,- 'Pass the single source_id of the row to target, or omit source_id to use the ambient source scope.',- );- }- if (isValidSourceId(raw)) return raw;- }- throw new OperationError(- 'invalid_params',- `${opName}: invalid source_id ${JSON.stringify(raw)} — must be 1-32 lowercase alnum chars with optional interior hyphens.`,- 'Pass a registered source id (see list_sources), or omit source_id to use the ambient source scope.',- );-}-/*** #4329 (S1-tightened): write-authority gate for a per-call source_id on the* destructive page ops. Trusted local callers (ctx.remote === false) own the@@ -554,8 +520,8 @@ const put_page: Operation = {// v0.38 put_page write-through (ingestion cathedral):// After importFromContent succeeds, if `sync.repo_path` resolves to a// real directory, persist the markdown file to disk alongside the DB- // row. Failures non-fatal — DB write is durable; subsequent sync- // reconciles drift.+ // row. A failure here is fatal to the call (see the check right below)+ // except for the deliberate DB-only configurations.//// Trust gating:// - Subagent sandbox (viaSubagent without allowedSlugPrefixes) → DB-only.@@ -587,6 +553,42 @@ const put_page: Operation = {writeThrough = { written: false, skipped: 'dry_run' };}+ // The markdown file is the system of record (docs/architecture/+ // system-of-record.md); the DB row is a derived cache. The deliberate,+ // by-design DB-only outcomes are `no_repo_configured` (no `sync.repo_path`+ // set at all), `disabled_by_config` (operator opted out via+ // `sync.write_through=false`), `subagent_sandbox`, and `dry_run` (no real+ // write was supposed to happen). Every other non-written outcome — a+ // thrown write error, or a guard that REFUSED to write into an existing+ // repo (missing dir, sibling-source collision, escaped path, case-fold+ // clash, unreadable row) — means a file was supposed to exist and+ // doesn't, so put_page must not report success.+ if (writeThrough && !writeThrough.written+ && writeThrough.skipped !== 'no_repo_configured'+ && writeThrough.skipped !== 'disabled_by_config'+ && writeThrough.skipped !== 'subagent_sandbox'+ && writeThrough.skipped !== 'dry_run') {+ // Roll back rather than leave an index-only orphan, but only when this+ // call is what created the row: created_at === updated_at is set by+ // the SAME insert statement (the ON CONFLICT UPDATE branch never+ // touches created_at), so equality here means "brand new, this call."+ // An update (or a dedup hit resolved to a pre-existing page) is left+ // alone — the prior file on disk still matches the prior DB content.+ try {+ const row = await ctx.engine.getPage(result.slug, { sourceId: ctx.sourceId ?? 'default' });+ if (row && row.created_at.getTime() === row.updated_at.getTime()) {+ await ctx.engine.deletePage(result.slug, { sourceId: ctx.sourceId ?? 'default' });+ }+ } catch {+ // best-effort; the error thrown below still surfaces the failure+ }+ throw new OperationError(+ 'storage_error',+ `put_page: the page content could not be written to disk (${writeThrough.skipped ?? writeThrough.error}).`,+ 'Check that the configured repo path exists and is writable, then retry.',+ );+ }+// Auto-link post-hook: runs AFTER importFromContent (which is its own// transaction). Runs even on status='skipped' so reconciliation catches drift// between the page text and the links table. Failures are non-blocking.diff --git a/src/core/ops/salience.ts b/src/core/ops/salience.tsindex 69965e6aef..e8fc2206fb 100644--- a/src/core/ops/salience.ts+++ b/src/core/ops/salience.ts@@ -9,6 +9,7 @@*/import type { Operation } from './contract.ts';+import { sourceScopeOpts } from './context.ts';import {GET_RECENT_SALIENCE_DESCRIPTION,FIND_ANOMALIES_DESCRIPTION,@@ -49,16 +50,24 @@ const get_recent_salience: Operation = {},handler: async (ctx, p) => {const recencyBias = p.recency_bias === 'on' ? 'on' : 'flat';+ // Scope by the caller's source (canonical sourceScopeOpts ladder: federated+ // array > scalar > nothing), matching find_orphans/find_experts. Pre-fix+ // this op returned brain-wide salience regardless of a source-bound OAuth+ // client's grant — a read leak in the v0.34.1 (#861) source-isolation class+ // that the v0.29 salience/anomaly batch missed. Trusted local callers+ // (ctx.remote === false) still get the empty scope = full brain.const rows = await ctx.engine.getRecentSalience({days: typeof p.days === 'number' ? p.days : undefined,limit: typeof p.limit === 'number' ? p.limit : undefined,slugPrefix: typeof p.slugPrefix === 'string' ? p.slugPrefix : undefined,recency_bias: recencyBias,+ ...sourceScopeOpts(ctx),});// A `visibility: private` page's slug/title/metadata must not reach// remote readers through the salience list (same read-leak class as the- // delta page arm). The salience read is unscoped, so the private check- // spans the same span (empty scope).+ // delta page arm). The salience read is source-scoped above; the private+ // probe deliberately keeps the EMPTY scope — a broader privacy check can+ // only remove more rows (fail-closed), never leak, so don't narrow it.return dropPrivateOnlyRows(ctx.engine, ctx.remote, rows, r => r.slug, {});},// hidden: 'salience' is in CLI_ONLY (src/cli.ts) — runSalience owns the CLI@@ -85,10 +94,16 @@ const find_anomalies: Operation = {},},handler: async (ctx, p) => {+ // Scope by the caller's source (same v0.34.1 #861 source-isolation class as+ // get_recent_salience above — the v0.29 batch missed both). Applied to the+ // baseline AND today windows inside the engine so the anomaly math stays+ // self-consistent. Trusted local callers (ctx.remote === false) get the+ // empty scope = full brain.const anomalies = await ctx.engine.findAnomalies({since: typeof p.since === 'string' ? p.since : undefined,lookback_days: typeof p.lookback_days === 'number' ? p.lookback_days : undefined,sigma: typeof p.sigma === 'number' ? p.sigma : undefined,+ ...sourceScopeOpts(ctx),});// AnomalyResult.page_slugs can name `visibility: private` pages — a// private slug is still page metadata a remote reader must not see.@@ -110,7 +125,9 @@ const find_anomalies: Operation = {// is ALL private is dropped wholly even if uncapped world pages drove// it (fails closed toward confidentiality); baseline_mean/stddev remain// private-inclusive (world-only cohort aggregation is the deferred- // source-scope/row-grain TODO).+ // row-grain TODO — the source-scope half is now discharged: both the+ // baseline and today windows are source-scoped in the engine via+ // sourceScopeOpts above).// includeDeleted: the anomaly queries have no deleted_at predicate, so// a soft-deleted private page must still count as private-only.if (await resolveExcludePrivatePages(ctx.engine, ctx.remote)) {diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 8cba858f15..aeef79a10c 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -27,6 +27,7 @@ import { OperationError } from './contract.ts';import type { Operation, OperationContext } from './contract.ts';import {federatedSearchScope,+ parseSourceIdParam,resolvePerCallMode,stampDeepResearchIds,stampEvidenceSafe,@@ -140,17 +141,17 @@ const search: Operation = {limit: { type: 'number', description: 'Max results (default 20)' },offset: { type: 'number', description: 'Skip first N results (for pagination)' },mode: { type: 'string', description: 'Search mode (conservative|balanced|tokenmax). Local callers only.' },- // #3985: multi-type filter (plumbing shipped v0.33; exposed here).- types: { type: 'array', items: { type: 'string' }, description: TYPES_PARAM_DESCRIPTION },- // #3800: subagent token economy — per-call snippet cap.- snippet_chars: { type: 'number', description: SNIPPET_CHARS_PARAM_DESCRIPTION },// #4398: per-call source scope, mirroring `query` — MCP clients passed it// here, got 'unknown parameter ignored', and read UNSCOPED results.source_id: {type: 'string',description:- "Scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile). Pass '__all__' to span every source for trusted local callers; for remote callers '__all__' spans only your granted sources.",+ "Scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile); when unset, an unqualified read spans every federated source. Pass '__all__' to span every source for trusted local callers; for remote callers '__all__' spans only your granted sources.",},+ // #3985: multi-type filter (plumbing shipped v0.33; exposed here).+ types: { type: 'array', items: { type: 'string' }, description: TYPES_PARAM_DESCRIPTION },+ // #3800: subagent token economy — per-call snippet cap.+ snippet_chars: { type: 'number', description: SNIPPET_CHARS_PARAM_DESCRIPTION },// #4415: explicit ranking-axis overrides (the same knobs `query` has had// since v0.29.1). The auto-detect banks are English regex, so on a// non-English brain the recency/salience stages never fire — these flags@@ -180,11 +181,12 @@ const search: Operation = {const types = normalizeTypesParam(p.types);// #3800: snippet cap (param > subagent config default > full text).const snippetCap = await resolveSnippetCap(ctx, p);- // #4398: explicit per-call source_id wins over ctx.sourceId, resolved- // through the single trust+grant resolver (resolveRequestedScope inside- // federatedSearchScope) — out-of-grant ids throw permission_denied, and- // #2561's unqualified trusted-local federated span is unchanged.- const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;+ // #4398: explicit per-call source_id wins over ctx.sourceId, validated+ // (invalid ids throw invalid_params) then resolved through the single+ // trust+grant resolver (resolveRequestedScope inside federatedSearchScope)+ // — out-of-grant ids throw permission_denied, and #2561's unqualified+ // trusted-local federated span is unchanged.+ const sourceIdParam = parseSourceIdParam(p.source_id, 'search', { allowAll: true });const scope = federatedSearchScope(ctx, sourceIdParam);// #4352 — untrusted callers never see `visibility: private` pages// (config-gated; trusted local CLI unchanged).@@ -330,7 +332,7 @@ const query: Operation = {source_id: {type: 'string',description:- "v0.34: scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile). Pass '__all__' to span every source for trusted local callers; for remote callers '__all__' spans only your granted sources.",+ "v0.34: scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile). Pass '__all__' to span every source for trusted local callers. For remote callers, '__all__' uses the same scope as omission: an OAuth grant when present, otherwise the transport-computed federated sources for grantless local stdio.",},cross_modal: {type: 'string',diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex b42382d8a0..054b9645d5 100644--- a/src/core/ops/takes.ts+++ b/src/core/ops/takes.ts@@ -20,6 +20,7 @@ import {resolveTakesRepoDir,TakesWriteError,} from '../takes-write.ts';+import { embedQuery } from '../embedding.ts';// --- v0.28: Takes ---@@ -207,6 +208,8 @@ const think: Operation = {const { runThink, persistSynthesis } = await import('../think/index.ts');const result = await runThink(ctx.engine, {question: String(p.question),+ // #3734: MCP think must populate the question vector for takes retrieval.+ embedQuestion: (q) => embedQuery(q),anchor: p.anchor ? String(p.anchor) : undefined,rounds: typeof p.rounds === 'number' ? (p.rounds as number) : undefined,save: safeSave,diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex fc8f30ea09..14c5e64782 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -28,7 +28,7 @@ import type {ReservedConnection,DreamVerdict, DreamVerdictInput,FileSpec, FileRow,- TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow,+ TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow, TakeEmbeddingInput,TakeResolution, SynthesisEvidenceInput,TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,FactRow, FactInsertStatus,@@ -88,7 +88,7 @@ import type {} from './types.ts';import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, isUndefinedTableError, warnOncePerProcess } from './utils.ts';import { executeRawJsonb, type SqlValue } from './sql-query.ts';-import { sanitizeForJsonb, buildLinkRows, buildTimelineRows } from './batch-rows.ts';+import { sanitizeForJsonb, sanitizeText, buildLinkRows, buildTimelineRows } from './batch-rows.ts';import { PAGE_SORT_SQL, MIN_ENTITY_PAGES_FOR_COVERAGE } from './types.ts';import { finalizeLastSeen } from './chronicle/last-seen.ts';import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';@@ -1650,17 +1650,23 @@ export class PGLiteEngine implements BrainEngine {if (!includeDeleted) {where.push('deleted_at IS NULL');}+ // #3931: anchor the tiebreak on sourceIds[0] (the caller's own resolved+ // source — see localFederatedSourceIds) instead of a hardcoded 'default',+ // so a shadowed slug resolves to the caller's own copy.+ const anchorSourceId = sourceIds && sourceIds.length > 0 ? sourceIds[0] : 'default';+ params.push(anchorSourceId);+ const anchorParamIdx = params.length;const { rows } = await this.db.query(`SELECT id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, deleted_at,effective_date, effective_date_source,source_kind, source_uri, ingested_via, ingested_at,contextual_retrieval_modeFROM pages WHERE ${where.join(' AND ')}- ORDER BY (source_id = 'default') DESC, source_id ASC+ ORDER BY (source_id = $${anchorParamIdx}) DESC, source_id ASCLIMIT 1`,params);- // Deterministic multi-source tiebreak — default-source-first, then stable+ // Deterministic multi-source tiebreak: anchor-source-first, then stable// alpha. Engine parity: postgres-engine.ts carries the identical clause.if (rows.length === 0) return null;return rowToPage(rows[0] as Record<string, unknown>);@@ -1763,7 +1769,7 @@ export class PGLiteEngine implements BrainEngine {ingested_via = COALESCE(EXCLUDED.ingested_via, pages.ingested_via),ingested_at = COALESCE(EXCLUDED.ingested_at, pages.ingested_at)RETURNING id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at`,- [sourceId, slug, page.type, pageKind, page.title, page.compiled_truth, page.timeline || '', JSON.stringify(frontmatter), hash, effectiveDate, effectiveDateSource, importFilename, chunkerVersion, sourcePath, sourceKind, sourceUri, ingestedVia, ingestedAt]+ [sourceId, slug, page.type, pageKind, sanitizeText(page.title), sanitizeText(page.compiled_truth), sanitizeText(page.timeline || ''), JSON.stringify(frontmatter), hash, effectiveDate, effectiveDateSource, importFilename, chunkerVersion, sourcePath, sourceKind, sourceUri, ingestedVia, ingestedAt]);// PGLite can return zero rows from INSERT ... ON CONFLICT DO UPDATE ...// RETURNING in no-op/trigger edge cases, which made rowToPage(undefined)@@ -3107,14 +3113,19 @@ export class PGLiteEngine implements BrainEngine {`$${paramIdx++}, ${embeddingImagePh})`,);+ // NUL/lone-surrogate cleanup ONCE into a local shared by BOTH binds:+ // the md5() embedded_text_hash input and the stored chunk_text must see+ // the same bytes, or the hash diverges from the sanitized stored text+ // (and the raw NUL would still abort the INSERT via the md5 param).+ const sanitizedChunkText = sanitizeText(chunk.chunk_text);// Param push order MUST match placeholder allocation order. Both// embedding placeholders (when present) are allocated BEFORE the// bulk row placeholders, so their values must be pushed first.if (embeddingStr) params.push(embeddingStr);if (embeddingImageStr) params.push(embeddingImageStr);- if (embeddingStr) params.push(chunk.chunk_text); // embedded_text_hash md5() input+ if (embeddingStr) params.push(sanitizedChunkText); // embedded_text_hash md5() inputparams.push(- pageId, chunk.chunk_index, chunk.chunk_text, chunk.chunk_source,+ pageId, chunk.chunk_index, sanitizedChunkText, chunk.chunk_source,chunk.model || resolvedModel, chunk.token_count || null,chunk.language || null, chunk.symbol_name || null, chunk.symbol_type || null,chunk.start_line ?? null, chunk.end_line ?? null,@@ -5393,6 +5404,8 @@ export class PGLiteEngine implements BrainEngine {return takesImpl.listStaleTakes(this.takesDeps);}+ async updateTakeEmbeddings(rowsIn: TakeEmbeddingInput[], opts?: BatchOpts): Promise<number> { return takesImpl.updateTakeEmbeddings(this.takesDeps, rowsIn, opts); }+async updateTake(pageId: number,rowNum: number,@@ -5870,6 +5883,13 @@ export class PGLiteEngine implements BrainEngine {return (rows as { key: string }[]).map(r => r.key);}+ async getAllConfig(): Promise<Record<string, string>> {+ const { rows } = await this.db.query('SELECT key, value FROM config');+ const out: Record<string, string> = {};+ for (const row of rows as { key: string; value: string }[]) out[row.key] = row.value;+ return out;+ }+// Migration supportasync runMigration(_version: number, sql: string): Promise<void> {await this.db.exec(sql);diff --git a/src/core/pglite-engine/facts.ts b/src/core/pglite-engine/facts.tsindex 16843de0d6..a57954b910 100644--- a/src/core/pglite-engine/facts.ts+++ b/src/core/pglite-engine/facts.ts@@ -468,7 +468,10 @@ export async function findTrajectory(deps: PgliteFactsDeps, opts: import('../engconst useArray = Array.isArray(opts.sourceIds) && opts.sourceIds.length > 0;const sourceIds = useArray ? opts.sourceIds! : null;const sourceId = opts.sourceId ?? 'default';- const remoteFilter = opts.remote === true;+ // Fail-closed (CV6 / v0.26.9 F7b posture): anything not strictly local+ // is remote. An omitted flag (cast-bypassed context, caller that forgot+ // to thread it) degrades to world-only reads, never to a private-fact leak.+ const remoteFilter = opts.remote !== false;// Build SQL dynamically. PGLite uses $N positional params; we// assemble the WHERE clauses + params array in tandem to keep them@@ -626,6 +629,9 @@ async function _listFacts(if (opts.activeOnly !== false) {whereParts.push(`expired_at IS NULL`);}+ if (opts.unconsolidatedOnly === true) {+ whereParts.push(`consolidated_at IS NULL`);+ }if (opts.kinds && opts.kinds.length > 0) {whereParts.push(`kind = ANY($kinds)`);params.kinds = opts.kinds;diff --git a/src/core/pglite-engine/salience.ts b/src/core/pglite-engine/salience.tsindex bba093c909..db51f4699a 100644--- a/src/core/pglite-engine/salience.ts+++ b/src/core/pglite-engine/salience.ts@@ -98,6 +98,16 @@ export async function getRecentSalience(deps: PgliteSalienceDeps, opts: Salienceconst excludeBriefings = !(slugPrefix && slugPrefix.startsWith('briefings'))? `AND p.slug NOT LIKE 'briefings/%'`: '';+ // Source scope: array wins over scalar (canonical precedence). Parity with+ // postgres-engine.getRecentSalience() and listEnrichCandidates().+ let sourceCondition = '';+ if (opts.sourceIds && opts.sourceIds.length > 0) {+ params.push(opts.sourceIds);+ sourceCondition = `AND p.source_id = ANY($${params.length}::text[])`;+ } else if (opts.sourceId) {+ params.push(opts.sourceId);+ sourceCondition = `AND p.source_id = $${params.length}`;+ }params.push(limit);const limitParam = `$${params.length}`;@@ -133,6 +143,7 @@ export async function getRecentSalience(deps: PgliteSalienceDeps, opts: SalienceWHERE GREATEST(p.updated_at, COALESCE(p.salience_touched_at, p.updated_at)) >= $1::timestamptz${prefixCondition}${excludeBriefings}+ ${sourceCondition}GROUP BY p.idORDER BY score DESCLIMIT ${limitParam}`,@@ -234,6 +245,23 @@ export async function findAnomalies(deps: PgliteSalienceDeps, opts: AnomaliesOptconst sinceEnd = new Date(sinceDate.getTime() + 86400000);const baselineStart = new Date(sinceDate.getTime() - lookbackDays * 86400000);+ // Source scope (array wins over scalar). Bound as $3 in EVERY cohort query+ // below so today's counts and the baseline share one scope — otherwise the+ // anomaly math would compare a scoped today against an unscoped baseline.+ // Every query's params are [$1 date, $2 date, ...sourceParam].+ const sourceClause =+ opts.sourceIds && opts.sourceIds.length > 0+ ? `AND p.source_id = ANY($3::text[])`+ : opts.sourceId+ ? `AND p.source_id = $3`+ : '';+ const sourceParam: unknown[] =+ opts.sourceIds && opts.sourceIds.length > 0+ ? [opts.sourceIds]+ : opts.sourceId+ ? [opts.sourceId]+ : [];+const tagBaselineRes = await deps.db.query(`WITH days AS (SELECT day::date FROM generate_series(@@ -242,20 +270,20 @@ export async function findAnomalies(deps: PgliteSalienceDeps, opts: AnomaliesOpt),cohort_keys AS (SELECT DISTINCT t.tag FROM tags t JOIN pages p ON p.id = t.page_id- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause}),touched AS (SELECT t.tag,date_trunc('day', p.updated_at)::date AS day,COUNT(DISTINCT p.id) AS cntFROM tags t JOIN pages p ON p.id = t.page_id- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause}GROUP BY 1, 2)SELECT cd.tag AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS countFROM cohort_keys cd CROSS JOIN days dLEFT JOIN touched t ON t.tag = cd.tag AND t.day = d.day`,- [baselineStart.toISOString(), sinceDate.toISOString()]+ [baselineStart.toISOString(), sinceDate.toISOString(), ...sourceParam]);const typeBaselineRes = await deps.db.query(@@ -266,20 +294,20 @@ export async function findAnomalies(deps: PgliteSalienceDeps, opts: AnomaliesOpt),cohort_keys AS (SELECT DISTINCT p.type FROM pages p- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause}),touched AS (SELECT p.type,date_trunc('day', p.updated_at)::date AS day,COUNT(DISTINCT p.id) AS cntFROM pages p- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause}GROUP BY 1, 2)SELECT cd.type AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS countFROM cohort_keys cd CROSS JOIN days dLEFT JOIN touched t ON t.type = cd.type AND t.day = d.day`,- [baselineStart.toISOString(), sinceDate.toISOString()]+ [baselineStart.toISOString(), sinceDate.toISOString(), ...sourceParam]);const tagTodayRes = await deps.db.query(@@ -287,9 +315,9 @@ export async function findAnomalies(deps: PgliteSalienceDeps, opts: AnomaliesOptCOUNT(DISTINCT p.id)::int AS count,array_agg(DISTINCT p.slug) AS slugsFROM tags t JOIN pages p ON p.id = t.page_id- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause}GROUP BY 1`,- [sinceIso, sinceEnd.toISOString()]+ [sinceIso, sinceEnd.toISOString(), ...sourceParam]);const typeTodayRes = await deps.db.query(@@ -297,9 +325,9 @@ export async function findAnomalies(deps: PgliteSalienceDeps, opts: AnomaliesOptCOUNT(DISTINCT p.id)::int AS count,array_agg(DISTINCT p.slug) AS slugsFROM pages p- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause}GROUP BY 1`,- [sinceIso, sinceEnd.toISOString()]+ [sinceIso, sinceEnd.toISOString(), ...sourceParam]);const baseline = [diff --git a/src/core/pglite-engine/takes.ts b/src/core/pglite-engine/takes.tsindex 53fdb427ce..5c4e9a1ee4 100644--- a/src/core/pglite-engine/takes.ts+++ b/src/core/pglite-engine/takes.ts@@ -7,6 +7,7 @@ import type { PGlite } from '@electric-sql/pglite';import type {BatchOpts,TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow,+ TakeEmbeddingInput,TakeResolution, SynthesisEvidenceInput,TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,} from '../engine.ts';@@ -409,6 +410,52 @@ export async function listStaleTakes(deps: PgliteTakesDeps): Promise<StaleTakeRoreturn rows as unknown as StaleTakeRow[];}+export async function updateTakeEmbeddings(+ deps: PgliteTakesDeps,+ rowsIn: TakeEmbeddingInput[],+ opts?: BatchOpts,+): Promise<number> {+ if (rowsIn.length === 0) return 0;+ return deps.batchRetry(+ opts?.auditSite ?? 'updateTakeEmbeddings',+ opts?.signal,+ () => _updateTakeEmbeddingsOnce(deps, rowsIn),+ rowsIn.length,+ );+}++async function _updateTakeEmbeddingsOnce(+ deps: PgliteTakesDeps,+ rowsIn: TakeEmbeddingInput[],+): Promise<number> {+ const seen = new Set<number>();+ const rows = rowsIn.map(({ take_id, embedding }) => {+ if (!Number.isInteger(take_id) || take_id <= 0) throw new Error(`invalid take_id: ${take_id}`);+ if (seen.has(take_id)) throw new Error(`duplicate take_id in embedding batch: ${take_id}`);+ seen.add(take_id);+ const values = Array.from(embedding);+ if (values.length === 0 || values.some(v => !Number.isFinite(v))) {+ throw new Error(`invalid embedding for take_id=${take_id}`);+ }+ return { take_id, embedding: `[${values.join(',')}]` };+ });+ const result = await deps.executeRawJsonb(+ `WITH updated AS (+ UPDATE takes AS t+ SET embedding = v.embedding::vector,+ embedded_at = now(),+ updated_at = now()+ FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(take_id bigint, embedding text)+ WHERE t.id = v.take_id AND t.active+ RETURNING t.id+ )+ SELECT id FROM updated`,+ [],+ [{ rows }],+ );+ return result.length;+}+export async function updateTake(deps: PgliteTakesDeps,pageId: number,diff --git a/src/core/pglite-lock.ts b/src/core/pglite-lock.tsindex 5a0d7fef11..3af7689f42 100644--- a/src/core/pglite-lock.ts+++ b/src/core/pglite-lock.ts@@ -14,8 +14,9 @@* try { ... } finally { await releaseLock(lock); }*/-import { mkdirSync, existsSync, readFileSync, writeFileSync, rmSync, statSync, renameSync } from 'fs';+import { mkdirSync, existsSync, readFileSync, writeFileSync, rmSync, statSync, renameSync, readlinkSync, type Stats } from 'fs';import { join } from 'path';+import { execFileSync } from 'node:child_process';import { parseGlobalFlags } from './cli-options.ts';const LOCK_DIR_NAME = '.gbrain-lock';@@ -41,16 +42,24 @@ function isServeCommand(lockData: { subcommand?: unknown; command?: unknown }):}// #2348: there is NO steal-on-stale-heartbeat anymore. A holder whose PID is-// alive is NEVER reaped, regardless of how long its heartbeat has been stale.+// alive AND still the same program is NEVER reaped, regardless of how long its+// heartbeat has been stale.// PGLite/WASM is strictly single-writer; the heartbeat runs on the JS event// loop, which is BLOCKED during long synchronous imports/CHECKPOINTs, so a// genuinely working `gbrain dream`/embed holder can look stale while alive.// Reaping it (the old #2058 grace window) let a second OS process open the same// data dir and corrupt the catalog + pgvector extension state (58P01 /// internal_load_library / `type "vector" does not exist`), recoverable only by-// wipe+restore. Only a DEAD PID is reaped now. A live serve-tagged holder gets-// the immediate process-conflict explanation below; other wedged-but-alive or-// PID-reused holders time out. Neither path steals the lock.+// wipe+restore. Only affirmative proof of death reaps now: ESRCH from kill-0,+// or a command line (via `ps`/proc) proving the PID was recycled by a+// non-gbrain program — and the latter only with affirmative same-namespace+// proof (the lock's recorded pid_ns/boot_id must be readable and match ours),+// so a cross-namespace or legacy holder is never reaped on cmdline evidence.+// Every reap serializes on an atomic claim dir and re-validates the victim's+// ownership token while the lock is still in place, so concurrent reapers+// can't delete each other's fresh locks.+// A live serve-tagged holder gets the immediate process-conflict explanation+// below; wedged-but-alive holders still time out — never stolen.export interface LockHandle {lockDir: string;@@ -175,6 +184,243 @@ export function isProcessAlive(pid: number): boolean {}}+/**+ * Read a process's full command line, or null when it can't be determined.+ * `ps -o args=` works on Linux + macOS (same pattern as autopilot-lock's+ * readProcessCommand); the /proc fallback covers minimal Linux containers+ * where `ps` is absent (cf. #4300). Null means "unknowable" — callers must+ * treat it as ALIVE, never as evidence of death.+ */+function readProcessArgs(pid: number): string | null {+ try {+ const out = execFileSync('ps', ['-p', String(pid), '-o', 'args='], {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ timeout: 1000,+ }).trim();+ if (out.length > 0) return out;+ } catch { /* fall through to /proc */ }+ try {+ const raw = readFileSync(`/proc/${pid}/cmdline`, 'utf-8');+ const args = raw.replace(/\0/g, ' ').trim();+ if (args.length > 0) return args;+ } catch { /* unreadable — unknowable */ }+ return null;+}++/**+ * This process's PID-namespace id (Linux `pid:[inode]`), or null elsewhere.+ * A PID is only meaningful inside the namespace that produced it: a lock+ * written by a holder in ANOTHER container (shared data dir) records a PID+ * that here belongs to an unrelated process — kill-0 says "alive" and the+ * cmdline is that unrelated process's, so BOTH liveness and cmdline evidence+ * are meaningless across namespaces (the #2840 false-steal class). Unlike+ * boot_id (host-scoped — same-host containers share it), the pid-namespace+ * inode distinguishes containers. Null when unavailable (non-Linux).+ */+function readPidNs(): string | null {+ try {+ return readlinkSync('/proc/self/ns/pid');+ } catch {+ return null;+ }+}++/**+ * Boot id of this host (Linux). Complements pid_ns for the cross-HOST case+ * (same data dir shared between VMs/machines, where pid_ns inode numbers can+ * collide). Null when unavailable.+ */+function readBootId(): string | null {+ try {+ const id = readFileSync('/proc/sys/kernel/random/boot_id', 'utf-8').trim();+ return id.length > 0 ? id : null;+ } catch {+ return null; // non-Linux — no comparable marker+ }+}++/**+ * PID-reuse detection. `isProcessAlive` (kill-0) only proves SOME process owns+ * the PID — a dead holder's PID can be recycled by an unrelated program+ * (docker-proxy, a shell, a supervisor's next child), which previously wedged+ * the lock until acquire timeout with no automatic recovery. A command line+ * that matches neither "gbrain" nor the recorded command's first token is+ * affirmative proof the original holder is gone — equivalent to an ESRCH+ * verdict — so the lock can be reaped.+ *+ * Fail-safe like isProcessAlive: ANY doubt reads as "not reused" (alive) —+ * unreadable/missing command line, a same-process PID (#1963 semantics: a+ * second acquire from the holder process still waits out the timeout), or+ * missing/mismatched namespace markers. On Linux the cmdline verdict REQUIRES+ * affirmative same-namespace proof (lock's recorded pid_ns === ours; boot_id+ * must also match when both are recorded): legacy locks without markers are+ * never cmdline-reaped (ESRCH reaps still apply). Platforms without namespace+ * markers (macOS) have no reachable cross-namespace data-dir sharing — a+ * Docker VM's PIDs aren't visible to host `ps` at all — so the cmdline+ * verdict stands alone there.+ */+function isPidReusedByOtherProgram(+ pid: number,+ recordedCommand: unknown,+ recordedPidNs: unknown,+ recordedBootId: unknown,+): boolean {+ if (!Number.isInteger(pid) || pid <= 0) return false;+ // Same-process re-acquire: WE are the recorded holder, so the PID is by+ // definition not recycled. (Also keeps non-gbrain test harnesses that hold a+ // lock with their own PID from reaping themselves.)+ if (pid === process.pid) return false;+ if (process.platform === 'linux') {+ // Linux: cmdline evidence is only meaningful within one PID namespace on+ // one host, so EVERY marker must be readable AND matching — pid_ns rules+ // out other containers, boot_id rules out other hosts (pid_ns inode+ // numbers can collide across machines sharing a data dir). An unreadable+ // local marker, a legacy lock without markers, or any mismatch all veto+ // the reap (fail-closed; ESRCH reaps are unaffected).+ const ourNs = readPidNs();+ const ourBoot = readBootId();+ if (ourNs === null || ourBoot === null) return false;+ if (recordedPidNs !== ourNs) return false;+ if (recordedBootId !== ourBoot) return false;+ }+ const cmdline = readProcessArgs(pid);+ if (cmdline === null) return false; // unknowable — cannot prove reuse+ if (cmdline.includes('gbrain')) return false;+ if (typeof recordedCommand === 'string' && recordedCommand.length > 0) {+ const firstToken = recordedCommand.trim().split(/\s+/)[0];+ if (firstToken && cmdline.includes(firstToken)) return false;+ // False-steal hardening: the recorded first token is often an ABSOLUTE+ // script path (Bun normalizes argv[1]) while `ps`/procfs report the+ // spawn-time RELATIVE form (`bun run src/cli.ts serve …`), so the literal+ // includes() above never matches and a LIVE holder gets classified as+ // recycled — observed as a harness mint stealing a running serve's lock+ // and writing its token to a second PGLite instance the serve never+ // sees. Compare the token's basename too: an unrelated program that+ // genuinely recycled the PID is no more likely to carry `cli.ts` in its+ // argv than the full path, so precision holds.+ const baseToken = firstToken ? firstToken.split('/').pop() : undefined;+ if (baseToken && baseToken.length > 0 && cmdline.includes(baseToken)) return false;+ }+ return true;+}++const REAP_CLAIM_TTL_MS = 30_000;++/**+ * Remove a claim dir whose claimant is provably gone (dead PID) or stalled+ * (older than the TTL — a reap is three syscalls, so 30s means crashed).+ * Returns true when the claim was cleared. Best-effort: losing a concurrent+ * clear race is fine, the caller just retries the claim.+ */+function breakStaleClaim(claimDir: string): boolean {+ let stale: boolean;+ try {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- claimDir derives from getLockDir(dataDir) (internal brain dir) + LOCK_FILE constant — no user input+ const raw = JSON.parse(readFileSync(join(claimDir, LOCK_FILE), 'utf-8'));+ const alive = typeof raw.pid === 'number' && isProcessAlive(raw.pid);+ const fresh = typeof raw.at === 'number' && Date.now() - raw.at < REAP_CLAIM_TTL_MS;+ // Legitimately held only while the claimant is alive AND within TTL;+ // a dead claimant breaks immediately, a live one after the TTL.+ stale = !(alive && fresh);+ } catch {+ // Metadata missing/unparseable: acquisition in flight (mkdir done,+ // metadata not yet published) vs crashed claimant — only the claim DIR's+ // age distinguishes them, so never break a young claim on this evidence.+ try {+ stale = Date.now() - statSync(claimDir).mtimeMs >= REAP_CLAIM_TTL_MS;+ } catch {+ return true; // claim dir already gone — nothing to break+ }+ }+ if (!stale) return false;+ try { rmSync(claimDir, { recursive: true, force: true }); return true; } catch { return false; }+}++/**+ * Remove a lock dir we classified as reaped, WITHOUT racing concurrent+ * reapers. Two acquirers can classify the same dead/recycled victim; a plain+ * rmSync (or rename-aside, which momentarily makes the lock dir vanish) lets+ * the slower reaper delete — or displace — the FASTER one's freshly installed+ * lock: two writers on one data dir.+ *+ * Instead, reapers serialize on an atomic claim dir (mkdir). While holding+ * the claim — the only entitlement to remove the lock — the winner+ * re-validates that the lock on disk is still the victim it classified, and+ * only then deletes. A loser (or a validator that finds a NEW holder's lock)+ * touches nothing. The claim self-heals: a crashed claimant's dir is broken+ * after REAP_CLAIM_TTL_MS or when its PID is dead.+ *+ * `victimToken` null = corrupt/unparseable lock (no token to compare; we+ * re-confirm it is still unparseable instead).+ */+function tryReapLockDir(lockDir: string, victimToken: string | null): boolean {+ // Capture the victim directory's identity before we claim the reap. If the+ // directory is replaced (same path, different inode) while we hold the+ // claim, an ENOENT read would no longer describe the lock we classified.+ let victimDirStat: Stats;+ try {+ victimDirStat = statSync(lockDir);+ } catch {+ return false; // vanished before we could claim it+ }++ const claimDir = `${lockDir}.reap-claim`;+ const claim = (): boolean => {+ try {+ mkdirSync(claimDir);+ // Publish ownership atomically (tmp+rename) — a concurrent stale-claim+ // breaker must never see a claimed dir with missing/torn metadata.+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- same: internal lock dir + constant + own pid+ const tmp = join(claimDir, `${LOCK_FILE}.tmp-${process.pid}`);+ writeFileSync(tmp, JSON.stringify({ pid: process.pid, at: Date.now() }), { mode: 0o644 });+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- same: internal lock dir + constant+ renameSync(tmp, join(claimDir, LOCK_FILE));+ return true;+ } catch {+ return false;+ }+ };+ if (!claim() && !(breakStaleClaim(claimDir) && claim())) {+ return false; // another reaper holds the claim — outer loop re-reads+ }+ try {+ if (victimToken !== null) {+ let current: string;+ try {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- lockDir = getLockDir(dataDir), internal + constant+ current = tokenOf(JSON.parse(readFileSync(join(lockDir, LOCK_FILE), 'utf-8')));+ } catch {+ return false; // vanished (another outcome already resolved it)+ }+ if (current !== victimToken) return false; // a NEW holder's lock — leave it+ } else {+ try {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- same: internal lock dir + constant+ JSON.parse(readFileSync(join(lockDir, LOCK_FILE), 'utf-8'));+ return false; // became parseable — not the corrupt lock we classified+ } catch (err) {+ // ENOENT can mean "still corrupt" OR "the lockDir was replaced by a+ // new holder that hasn't written its file yet". Reap only if the+ // directory inode is unchanged, i.e. it is the same directory we+ // classified as corrupt.+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {+ try {+ if (statSync(lockDir).ino !== victimDirStat.ino) return false;+ } catch {+ return false; // gone+ }+ }+ /* any other read/parse error = still corrupt — proceed */+ }+ }+ try { rmSync(lockDir, { recursive: true, force: true }); } catch { /* best-effort */ }+ return true;+ } finally {+ try { rmSync(claimDir, { recursive: true, force: true }); } catch { /* stale-claim breaker handles leftovers */ }+ }+}+function formatLockTimestamp(value: unknown): string {return typeof value === 'number' && Number.isFinite(value)? new Date(value).toISOString()@@ -233,19 +479,23 @@ export async function acquireLock(dataDir: string | undefined, opts?: { timeoutMconst lockData = JSON.parse(readFileSync(lockPath, 'utf-8'));const lockPid = lockData.pid as number;- // #2348: classify ONLY by PID liveness. A live holder is NEVER reaped- // (stealing a live single-writer is what corrupted the catalog/extension- // state). A long synchronous import blocks the heartbeat, so "stale- // heartbeat" is NOT evidence of death — only a dead PID is.- const alive = isProcessAlive(lockPid);+ // #2348: classify ONLY by affirmative proof of death. A live holder is+ // NEVER reaped (stealing a live single-writer is what corrupted the+ // catalog/extension state). A long synchronous import blocks the+ // heartbeat, so "stale heartbeat" is NOT evidence of death — only a+ // dead PID (ESRCH) or a PID provably recycled by a non-gbrain program+ // (cmdline mismatch under affirmative same-namespace proof) is.+ const alive = isProcessAlive(lockPid)+ && !isPidReusedByOtherProgram(lockPid, lockData.command, lockData.pid_ns, lockData.boot_id);if (!alive) {// Holder process is gone — reap and try to acquire. This verdict is// affirmative (kill-0 threw ESRCH; EPERM reads as alive), so no// cross-process quarantine marker: the same-acquisition `reaped`// flag alone gates repair, keeping the dead-holder recovery cost at- // one failed command + one re-run.- reaped = true;- try { rmSync(lockDir, { recursive: true, force: true }); } catch { /* race condition, try again */ }+ // one failed command + one re-run. tryReapLockDir serializes+ // concurrent reapers on an atomic claim dir; losing it just means+ // the winner's fresh lock shows up on the next loop iteration.+ if (tryReapLockDir(lockDir, tokenOf(lockData))) reaped = true;} else {if (isServeCommand(lockData)) {throw new LiveServeLockError(@@ -283,9 +533,12 @@ export async function acquireLock(dataDir: string | undefined, opts?: { timeoutM}// Corrupt lock file — remove it. The holder's liveness is UNKNOWABLE// here (unreadable PID), so this counts as a reap for the repair gate.- reaped = true;- recordReap(dataDir as string);- try { rmSync(lockDir, { recursive: true, force: true }); } catch { /* race condition */ }+ // Same serialized claim + revalidation as the dead-PID path (the+ // corrupt case re-confirms the file is still unparseable).+ if (tryReapLockDir(lockDir, null)) {+ reaped = true;+ recordReap(dataDir as string);+ }}}@@ -306,6 +559,8 @@ export async function acquireLock(dataDir: string | undefined, opts?: { timeoutMrefreshed_at: now,command: process.argv.slice(1).join(' '),subcommand: parseGlobalFlags(process.argv.slice(2)).rest[0] ?? null,+ pid_ns: readPidNs(),+ boot_id: readBootId(),}), { mode: 0o644 });renameSync(initTmp, lockPath);diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex affdd70385..2b24650a42 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -6,7 +6,7 @@ import type {ReservedConnection,DreamVerdict, DreamVerdictInput,FileSpec, FileRow,- TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow,+ TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow, TakeEmbeddingInput,TakeResolution, SynthesisEvidenceInput,TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,FactRow, FactInsertStatus,@@ -39,7 +39,7 @@ import type {} from './types.ts';import { MAX_SEARCH_LIMIT, clampSearchLimit } from './engine.ts';import { executeRawJsonb, type SqlValue } from './sql-query.ts';-import { sanitizeForJsonb, buildLinkRows, buildTimelineRows } from './batch-rows.ts';+import { sanitizeForJsonb, sanitizeText, buildLinkRows, buildTimelineRows } from './batch-rows.ts';import { runMigrations } from './migrate.ts';import { SCHEMA_SQL } from './schema-embedded.generated.ts';import { verifySchema } from './schema-verify.ts';@@ -682,6 +682,9 @@ export class PostgresEngine implements BrainEngine {? tx`AND source_id = ${sourceId}`: tx``;const deletedCondition = includeDeleted ? tx`` : tx`AND deleted_at IS NULL`;+ // #3931: anchor on sourceIds[0] (caller's own resolved source, see+ // localFederatedSourceIds) instead of a hardcoded 'default'.+ const anchorSourceId = sourceIds && sourceIds.length > 0 ? sourceIds[0] : 'default';const rows = await tx`SELECT id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, deleted_at,effective_date, effective_date_source,@@ -689,14 +692,11 @@ export class PostgresEngine implements BrainEngine {contextual_retrieval_modeFROM pagesWHERE slug = ${slug} ${sourceCondition} ${deletedCondition}- ORDER BY (source_id = 'default') DESC, source_id ASC+ ORDER BY (source_id = ${anchorSourceId}) DESC, source_id ASCLIMIT 1`;- // Deterministic multi-source tiebreak: without an ORDER BY, LIMIT 1 on a- // slug that exists in several sources returned an ARBITRARY row.- // Default-source-first (then stable alpha) — plain alpha would prefer- // e.g. 'archive' over 'default'. Engine parity: pglite-engine.ts carries- // the identical clause.+ // Deterministic multi-source tiebreak: anchor-source-first, then stable+ // alpha. Engine parity: pglite-engine.ts carries the identical clause.if (rows.length === 0) return null;return rowToPage(rows[0]);});@@ -785,7 +785,7 @@ export class PostgresEngine implements BrainEngine {const ingestedAt = (sourceKind || sourceUri || ingestedVia) ? new Date() : null;const rows = await sql`INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at)- VALUES (${sourceId}, ${slug}, ${page.type}, ${pageKind}, ${page.title}, ${page.compiled_truth}, ${page.timeline || ''}, ${sql.json(frontmatter as Parameters<typeof sql.json>[0])}, ${hash}, now(), ${effectiveDate}, ${effectiveDateSource}, ${importFilename}, COALESCE(${chunkerVersion}::smallint, ${MARKDOWN_CHUNKER_VERSION}), ${sourcePath}, ${sourceKind}, ${sourceUri}, ${ingestedVia}, ${ingestedAt})+ VALUES (${sourceId}, ${slug}, ${page.type}, ${pageKind}, ${sanitizeText(page.title)}, ${sanitizeText(page.compiled_truth)}, ${sanitizeText(page.timeline || '')}, ${sql.json(frontmatter as Parameters<typeof sql.json>[0])}, ${hash}, now(), ${effectiveDate}, ${effectiveDateSource}, ${importFilename}, COALESCE(${chunkerVersion}::smallint, ${MARKDOWN_CHUNKER_VERSION}), ${sourcePath}, ${sourceKind}, ${sourceUri}, ${ingestedVia}, ${ingestedAt})ON CONFLICT (source_id, slug) DO UPDATE SETtype = EXCLUDED.type,page_kind = EXCLUDED.page_kind,@@ -2344,12 +2344,17 @@ export class PostgresEngine implements BrainEngine {`$${paramIdx++}, ${embeddingImagePh})`,);+ // NUL/lone-surrogate cleanup ONCE into a local shared by BOTH binds:+ // the md5() embedded_text_hash input and the stored chunk_text must see+ // the same bytes, or the hash diverges from the sanitized stored text+ // (and the raw NUL would still abort the INSERT via the md5 param).+ const sanitizedChunkText = sanitizeText(chunk.chunk_text);// Param push order MUST match placeholder allocation order.if (embeddingStr) params.push(embeddingStr);if (embeddingImageStr) params.push(embeddingImageStr);- if (embeddingStr) params.push(chunk.chunk_text); // embedded_text_hash md5() input+ if (embeddingStr) params.push(sanitizedChunkText); // embedded_text_hash md5() inputparams.push(- pageId, chunk.chunk_index, chunk.chunk_text, chunk.chunk_source,+ pageId, chunk.chunk_index, sanitizedChunkText, chunk.chunk_source,chunk.model || resolvedModel, chunk.token_count || null,chunk.language || null, chunk.symbol_name || null, chunk.symbol_type || null,chunk.start_line ?? null, chunk.end_line ?? null,@@ -4705,6 +4710,8 @@ export class PostgresEngine implements BrainEngine {return takesImpl.listStaleTakes(this.takesDeps);}+ async updateTakeEmbeddings(rowsIn: TakeEmbeddingInput[], opts?: BatchOpts): Promise<number> { return takesImpl.updateTakeEmbeddings(this.takesDeps, rowsIn, opts); }+async updateTake(pageId: number,rowNum: number,@@ -5231,6 +5238,17 @@ export class PostgresEngine implements BrainEngine {});}+ async getAllConfig(): Promise<Record<string, string>> {+ return this.connRetry(async () => {+ const rows = await this.sql<{ key: string; value: string }[]>`+ SELECT key, value FROM config+ `;+ const out: Record<string, string> = {};+ for (const row of rows) out[row.key] = row.value;+ return out;+ });+ }+// Migration supportasync runMigration(_version: number, sqlStr: string): Promise<void> {const conn = this.sql;diff --git a/src/core/postgres-engine/facts.ts b/src/core/postgres-engine/facts.tsindex 27a53ccddb..8e4122081c 100644--- a/src/core/postgres-engine/facts.ts+++ b/src/core/postgres-engine/facts.ts@@ -310,6 +310,7 @@ export async function listFactsByEntity(const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);const offset = Math.max(0, opts?.offset ?? 0);const activeOnly = opts?.activeOnly !== false;+ const unconsolidatedOnly = opts?.unconsolidatedOnly === true;const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null;const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;const excludeAuditRows = opts?.excludeAuditRows === true;@@ -318,6 +319,7 @@ export async function listFactsByEntity(WHERE source_id = ${source_id}AND entity_slug = ${entitySlug}${activeOnly ? sql`AND expired_at IS NULL` : sql``}+ ${unconsolidatedOnly ? sql`AND consolidated_at IS NULL` : sql``}${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``}${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``}${excludeAuditRows ? sql`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sql``}@@ -337,6 +339,7 @@ export async function listFactsSince(const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);const offset = Math.max(0, opts?.offset ?? 0);const activeOnly = opts?.activeOnly !== false;+ const unconsolidatedOnly = opts?.unconsolidatedOnly === true;const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null;const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;const entitySlug = opts?.entitySlug ?? null;@@ -348,6 +351,7 @@ export async function listFactsSince(AND ${eventTime ? sql`COALESCE(valid_from, created_at)` : sql`created_at`} >= ${since}${entitySlug ? sql`AND entity_slug = ${entitySlug}` : sql``}${activeOnly ? sql`AND expired_at IS NULL` : sql``}+ ${unconsolidatedOnly ? sql`AND consolidated_at IS NULL` : sql``}${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``}${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``}${excludeAuditRows ? sql`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sql``}@@ -367,6 +371,7 @@ export async function listFactsBySession(const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);const offset = Math.max(0, opts?.offset ?? 0);const activeOnly = opts?.activeOnly !== false;+ const unconsolidatedOnly = opts?.unconsolidatedOnly === true;const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null;const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;const excludeAuditRows = opts?.excludeAuditRows === true;@@ -375,6 +380,7 @@ export async function listFactsBySession(WHERE source_id = ${source_id}AND source_session = ${sessionId}${activeOnly ? sql`AND expired_at IS NULL` : sql``}+ ${unconsolidatedOnly ? sql`AND consolidated_at IS NULL` : sql``}${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``}${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``}${excludeAuditRows ? sql`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sql``}@@ -470,7 +476,10 @@ export async function findTrajectory(deps: PgFactsDeps, opts: import('../engine.const useArray = Array.isArray(opts.sourceIds) && opts.sourceIds.length > 0;const sourceIds = useArray ? opts.sourceIds! : null;const sourceId = opts.sourceId ?? 'default';- const remoteFilter = opts.remote === true;+ // Fail-closed (CV6 / v0.26.9 F7b posture): anything not strictly local+ // is remote. An omitted flag (cast-bypassed context, caller that forgot+ // to thread it) degrades to world-only reads, never to a private-fact leak.+ const remoteFilter = opts.remote !== false;// Source-scope predicate: array path (federated) wins over scalar.// Engine.ts contract: returns chronological points; regressions +diff --git a/src/core/postgres-engine/salience.ts b/src/core/postgres-engine/salience.tsindex a3f0a68fa9..b73b13084b 100644--- a/src/core/postgres-engine/salience.ts+++ b/src/core/postgres-engine/salience.ts@@ -126,6 +126,13 @@ export async function getRecentSalience(deps: PgSalienceDeps, opts: SalienceOptsconst excludeBriefings = !(slugPrefix && slugPrefix.startsWith('briefings'))? sql`AND p.slug NOT LIKE 'briefings/%'`: sql``;+ // Source scope: array wins over scalar (canonical precedence). Parity with+ // pglite-engine.getRecentSalience() and listEnrichCandidates().+ const sourceCondition = opts.sourceIds && opts.sourceIds.length > 0+ ? sql`AND p.source_id = ANY(${opts.sourceIds}::text[])`+ : opts.sourceId+ ? sql`AND p.source_id = ${opts.sourceId}`+ : sql``;// v0.29.1: third score term via buildRecencyComponentSql. Default// 'flat' = v0.29.0 behavior (1 / (1 + days_old)). 'on' opts into the// per-prefix decay map (concepts/ evergreen, daily/ aggressive, etc.).@@ -159,6 +166,7 @@ export async function getRecentSalience(deps: PgSalienceDeps, opts: SalienceOptsWHERE GREATEST(p.updated_at, COALESCE(p.salience_touched_at, p.updated_at)) >= ${boundaryIso}::timestamptz${prefixCondition}${excludeBriefings}+ ${sourceCondition}GROUP BY p.idORDER BY score DESCLIMIT ${limit}@@ -254,6 +262,15 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):const sinceEnd = new Date(sinceDate.getTime() + 86400000);const baselineStart = new Date(sinceDate.getTime() - lookbackDays * 86400000);+ // Source scope (array wins over scalar). Applied to the baseline AND today+ // windows so the anomaly math stays self-consistent. Parity with+ // pglite-engine.findAnomalies().+ const sourceCondition = opts.sourceIds && opts.sourceIds.length > 0+ ? sql`AND p.source_id = ANY(${opts.sourceIds}::text[])`+ : opts.sourceId+ ? sql`AND p.source_id = ${opts.sourceId}`+ : sql``;+// Tag cohort baseline with day densification + zero-fill (codex C4#6).const tagBaseline = await sql`WITH days AS (@@ -267,6 +284,7 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):SELECT DISTINCT t.tag FROM tags t JOIN pages p ON p.id = t.page_idWHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptzAND p.updated_at < ${sinceDate.toISOString()}::timestamptz+ ${sourceCondition}),touched AS (SELECT t.tag,@@ -275,6 +293,7 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):FROM tags t JOIN pages p ON p.id = t.page_idWHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptzAND p.updated_at < ${sinceDate.toISOString()}::timestamptz+ ${sourceCondition}GROUP BY 1, 2)SELECT cd.tag AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count@@ -294,6 +313,7 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):SELECT DISTINCT p.type FROM pages pWHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptzAND p.updated_at < ${sinceDate.toISOString()}::timestamptz+ ${sourceCondition}),touched AS (SELECT p.type,@@ -302,6 +322,7 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):FROM pages pWHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptzAND p.updated_at < ${sinceDate.toISOString()}::timestamptz+ ${sourceCondition}GROUP BY 1, 2)SELECT cd.type AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count@@ -317,6 +338,7 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):FROM tags t JOIN pages p ON p.id = t.page_idWHERE p.updated_at >= ${sinceIso}::timestamptzAND p.updated_at < ${sinceEnd.toISOString()}::timestamptz+ ${sourceCondition}GROUP BY 1`;const typeToday = await sql`@@ -326,6 +348,7 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):FROM pages pWHERE p.updated_at >= ${sinceIso}::timestamptzAND p.updated_at < ${sinceEnd.toISOString()}::timestamptz+ ${sourceCondition}GROUP BY 1`;diff --git a/src/core/postgres-engine/takes.ts b/src/core/postgres-engine/takes.tsindex edd6f28149..c057d6c93a 100644--- a/src/core/postgres-engine/takes.ts+++ b/src/core/postgres-engine/takes.ts@@ -10,6 +10,7 @@ type PgSql = ReturnType<typeof postgres>;import type {BatchOpts,TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow,+ TakeEmbeddingInput,TakeResolution, SynthesisEvidenceInput,TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,} from '../engine.ts';@@ -422,6 +423,52 @@ export async function listStaleTakes(deps: PgTakesDeps): Promise<StaleTakeRow[]>return rows as unknown as StaleTakeRow[];}+export async function updateTakeEmbeddings(+ deps: PgTakesDeps,+ rowsIn: TakeEmbeddingInput[],+ opts?: BatchOpts,+): Promise<number> {+ if (rowsIn.length === 0) return 0;+ return deps.batchRetry(+ opts?.auditSite ?? 'updateTakeEmbeddings',+ opts?.signal,+ () => _updateTakeEmbeddingsOnce(deps, rowsIn),+ rowsIn.length,+ );+}++async function _updateTakeEmbeddingsOnce(+ deps: PgTakesDeps,+ rowsIn: TakeEmbeddingInput[],+): Promise<number> {+ const seen = new Set<number>();+ const rows = rowsIn.map(({ take_id, embedding }) => {+ if (!Number.isInteger(take_id) || take_id <= 0) throw new Error(`invalid take_id: ${take_id}`);+ if (seen.has(take_id)) throw new Error(`duplicate take_id in embedding batch: ${take_id}`);+ seen.add(take_id);+ const values = Array.from(embedding);+ if (values.length === 0 || values.some(v => !Number.isFinite(v))) {+ throw new Error(`invalid embedding for take_id=${take_id}`);+ }+ return { take_id, embedding: `[${values.join(',')}]` };+ });+ const result = await deps.executeRawJsonb(+ `WITH updated AS (+ UPDATE takes AS t+ SET embedding = v.embedding::vector,+ embedded_at = now(),+ updated_at = now()+ FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(take_id bigint, embedding text)+ WHERE t.id = v.take_id AND t.active+ RETURNING t.id+ )+ SELECT id FROM updated`,+ [],+ [{ rows }],+ );+ return result.length;+}+export async function updateTake(deps: PgTakesDeps,pageId: number,diff --git a/src/core/retry.ts b/src/core/retry.tsindex 2840a1c18f..81f4768876 100644--- a/src/core/retry.ts+++ b/src/core/retry.ts@@ -77,6 +77,7 @@ export const BATCH_AUDIT_SITES = ['addLinksBatch','addTimelineEntriesBatch','addTakesBatch',+ 'updateTakeEmbeddings','upsertChunks',// extract.ts per-site labels.'extract.links_inc',diff --git a/src/core/schema-version-health.ts b/src/core/schema-version-health.tsnew file mode 100644index 0000000000..4e1d68a020--- /dev/null+++ b/src/core/schema-version-health.ts@@ -0,0 +1,48 @@+export interface SchemaVersionHealth {+ status: 'ok' | 'warn' | 'fail';+ message: string;+}++/** Compare the database schema with the schema understood by this client. */+export function schemaVersionHealth(+ version: number,+ latestVersion: number,+ opts: { remote?: boolean } = {},+): SchemaVersionHealth {+ const migrationFix = opts.remote+ ? 'Run `gbrain apply-migrations --yes` on the host.'+ : 'Fix: gbrain apply-migrations --yes';++ if (version === latestVersion) {+ return { status: 'ok', message: `Version ${version} (latest: ${latestVersion})` };+ }++ if (version === 0) {+ return {+ status: 'fail',+ message: opts.remote+ ? `No schema version recorded. Migrations never ran. ${migrationFix}`+ : `No schema version recorded. Migrations never ran. ${migrationFix}. ` ++ `If you installed via 'bun install -g github:...', see https://github.com/garrytan/gbrain/issues/218.`,+ };+ }++ if (version > latestVersion) {+ // Forward skew: another node migrated the shared DB past what this client+ // knows (multi-node brain, hub + spokes on one Postgres). Warn, not fail+ // (#2036 semantics as shipped on master): the client can still read, and+ // "upgrade this client" is the real fix — apply-migrations here would be+ // actively wrong.+ return {+ status: 'warn',+ message:+ `Version ${version} is AHEAD of this client's latest known version (${latestVersion}). ` ++ 'Another node migrated this DB past what this client knows — upgrade this client before writing.',+ };+ }++ return {+ status: 'warn',+ message: `Version ${version}, latest is ${latestVersion}. ${migrationFix}`,+ };+}diff --git a/src/core/scope.ts b/src/core/scope.tsindex c3a53b5d75..0bb7b6f9a6 100644--- a/src/core/scope.ts+++ b/src/core/scope.ts@@ -108,6 +108,33 @@ export function assertAllowedScopes(scopes: readonly string[]): void {}}+/**+ * Split a requested scope list into allowed vs unknown entries.+ *+ * Used by the unauthenticated DCR path so clients that send OIDC-style+ * extras (e.g. `offline_access`, `openid`) still register successfully+ * with the intersection of known scopes. RFC 7591 §2 lets the AS replace+ * client metadata values; dropping unknowns is that replacement.+ *+ * Operator-trusted paths (CLI / admin) keep using `assertAllowedScopes`+ * so typos surface loudly instead of silently shrinking the grant.+ */+export function filterAllowedScopes(scopes: readonly string[]): {+ allowed: Scope[];+ dropped: string[];+} {+ const allowed: Scope[] = [];+ const dropped: string[] = [];+ const seen = new Set<string>();+ for (const s of scopes) {+ if (seen.has(s)) continue;+ seen.add(s);+ if (isScope(s)) allowed.push(s);+ else dropped.push(s);+ }+ return { allowed, dropped };+}+/*** Parse a space-separated scope string (OAuth wire format) into an array,* dropping empty fragments. Does NOT validate against ALLOWED_SCOPES — calldiff --git a/src/core/search/eval.ts b/src/core/search/eval.tsindex 0cb0d5f7f3..5174585033 100644--- a/src/core/search/eval.ts+++ b/src/core/search/eval.ts@@ -13,6 +13,7 @@ import type { BrainEngine } from '../engine.ts';import { embed } from '../embedding.ts';import { hybridSearch } from './hybrid.ts';import type { HybridSearchOpts } from './hybrid.ts';+import { dedupeRankedKeys } from '../eval/ranked-docs.ts';// ─────────────────────────────────────────────────────────────────// Ground truth types@@ -88,21 +89,23 @@ export interface EvalReport {// ─────────────────────────────────────────────────────────────────/**- * Precision@k: fraction of top-k hits that are relevant.+ * Page-level Precision@k: relevant unique pages in the top k divided by k.+ * The denominator remains k when fewer than k unique pages were returned.*/export function precisionAtK(hits: string[], relevant: Set<string>, k: number): number {if (k <= 0 || hits.length === 0 || relevant.size === 0) return 0;- const topK = hits.slice(0, k);+ const topK = dedupeRankedKeys(hits).slice(0, k);const relevantHits = topK.filter(h => relevant.has(h)).length;return relevantHits / k;}/**- * Recall@k: fraction of all relevant docs found in top-k hits.+ * Page-level Recall@k: fraction of all relevant pages found in the first k+ * unique pages. Duplicate chunks neither inflate hits nor consume the cutoff.*/export function recallAtK(hits: string[], relevant: Set<string>, k: number): number {if (k <= 0 || hits.length === 0 || relevant.size === 0) return 0;- const topK = hits.slice(0, k);+ const topK = dedupeRankedKeys(hits).slice(0, k);const relevantHits = topK.filter(h => relevant.has(h)).length;return relevantHits / relevant.size;}@@ -112,8 +115,9 @@ export function recallAtK(hits: string[], relevant: Set<string>, k: number): num*/export function mrr(hits: string[], relevant: Set<string>): number {if (hits.length === 0 || relevant.size === 0) return 0;- for (let i = 0; i < hits.length; i++) {- if (relevant.has(hits[i])) return 1 / (i + 1);+ const uniqueHits = dedupeRankedKeys(hits);+ for (let i = 0; i < uniqueHits.length; i++) {+ if (relevant.has(uniqueHits[i])) return 1 / (i + 1);}return 0;}@@ -131,7 +135,7 @@ export function mrr(hits: string[], relevant: Set<string>): number {export function ndcgAtK(hits: string[], grades: Map<string, number>, k: number): number {if (k <= 0 || hits.length === 0 || grades.size === 0) return 0;- const topK = hits.slice(0, k);+ const topK = dedupeRankedKeys(hits).slice(0, k);let dcg = 0;for (let i = 0; i < topK.length; i++) {const grade = grades.get(topK[i]) ?? 0;@@ -150,7 +154,7 @@ export function ndcgAtK(hits: string[], grades: Map<string, number>, k: number):}if (idcg === 0) return 0;- return dcg / idcg;+ return Math.min(1, Math.max(0, dcg / idcg));}// ─────────────────────────────────────────────────────────────────@@ -183,7 +187,7 @@ export async function runEval(let done = 0;for (const qrel of qrels) {- const hits = await runQuery(engine, qrel.query, strategy, config, limit);+ const hits = dedupeRankedKeys(await runQuery(engine, qrel.query, strategy, config, limit));const relevantSet = new Set(qrel.relevant);const gradesMap = buildGradesMap(qrel);diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex bfd672e0d8..dcbdd26189 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -2441,7 +2441,7 @@ export async function hybridSearchCached(// read/write the cache anyway.const pagedRequest = (opts?.offset ?? 0) !== 0;// #4352 follow-up — excludePrivate no longer skips the cache: the posture- // is folded into knobsHash (xp=, v=23), so a private-included (trusted)+ // is folded into knobsHash (xp=), so a private-included (trusted)// write can never serve a private-excluding lookup and vice versa. The// original wholesale skip disabled the semantic cache for every remote MCP// caller (excludePrivate=true is their default) — exactly thediff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex b7f04b5f1c..b81be82e92 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -927,9 +927,9 @@ export function attributeKnob<K extends keyof ModeBundle>(// D8 convention). Same one-time global cold-miss pattern as the bumps// above; refills within cache.ttl_seconds (3600s).//-// bump 24→25: `kof=` (keyword AND→OR fallback knob) joins the key. The PR-// authored this as 23→24, but 24 was claimed by the negative-offset bump-// above while it was open, so it takes the next free number per the D8+// bump 24→25 (#3617): `kof=` (keyword AND→OR fallback knob) joins the key.+// The PR authored this as 23→24, but 24 was claimed by the negative-offset+// bump above while it was open, so it takes the next free number per the D8// convention. Same one-time global cold-miss pattern as the bumps above.//// bump 25→26 folds salience/recency + intent_patterns (#4415) — wave-g. Three@@ -1158,7 +1158,7 @@ export function knobsHash(// Strict `=== true` mirrors the enforcement predicate so undefined and// false (both private-included) hash identically.`xp=${ctx?.excludePrivate === true ? 1 : 0}`,- // v=25 addition (append-only): keyword AND→OR fallback knob. A+ // v=25 addition (#3617, append-only): keyword AND→OR fallback knob. A// fallback-on write (OR-relaxed rows blended in) must not be served// to a fallback-off lookup — the zero-strict-recall result sets are// disjoint (relaxed rows vs empty keyword arm). `?? true` mirrors thediff --git a/src/core/storage-config.ts b/src/core/storage-config.tsindex c6003b7310..29fa82a940 100644--- a/src/core/storage-config.ts+++ b/src/core/storage-config.ts@@ -368,6 +368,11 @@ export function isDbOnly(slug: string, config: StorageConfig): boolean {export const DERIVE_PHASE_DB_ONLY_DEFAULTS: readonly string[] = ['life/events/','atoms/',+ // synthesize_concepts writes through importFromContent without creating a+ // backing markdown file. Keep this implicit (rather than merging it into+ // storage.db_only) so installations that do file-back concepts are never+ // auto-gitignored by manageGitignore.+ 'concepts/','extracts/','dream-cycle-summaries/',];diff --git a/src/core/sync-failure-ledger.ts b/src/core/sync-failure-ledger.tsindex f30c1de362..31a11e92ef 100644--- a/src/core/sync-failure-ledger.ts+++ b/src/core/sync-failure-ledger.ts@@ -58,6 +58,8 @@ import { createHash as _createHash } from 'crypto';export const DEFAULT_SOURCE_ID = 'default';/** Reserved sentinel paths (e.g. `<head>`) start with this; never file paths. */export const SENTINEL_PREFIX = '<';+/** `<rename:…>` sentinel prefix (#3056 — a rename-reconcile delete failed). */+export const RENAME_SENTINEL_PREFIX = '<rename:';export const DEFAULT_AUTOSKIP_AFTER = 3;const LOCK_STALE_MS = 30_000;const LOCK_SPIN_MS = 50;@@ -99,6 +101,90 @@ export function isSkippablePath(path: string): boolean {return !path.startsWith(SENTINEL_PREFIX);}+/** The `<rename:…>` sentinel key for a rename whose destination is `to`. */+export function renameSentinelPath(to: string): string {+ return `${RENAME_SENTINEL_PREFIX}${to}>`;+}++/**+ * The one place the `<rename:…>` sentinel's error text is composed. The+ * format is load-bearing: `parseRenameReconcileFrom` below reads the OLD+ * path back out of it so a later run can decide whether the sentinel is+ * orphaned (#3479 blocker 2 — a force-push can invalidate the pinned+ * target, the destination never re-enters the diff, and the ordinary+ * success path can then never clear the row).+ *+ * The slug and path slots are JSON-encoded, NOT raw prose: a raw+ * interpolation would make the format ambiguous for a path that itself+ * contains the ` not removed): ` delimiter, and a misparse there flows+ * straight into the orphan probe — which could then clear a sentinel while+ * the real duplicate still exists. JSON escaping makes the quoted span+ * self-delimiting for ANY path bytes. The stale slug slot is always+ * present (`?` when the resolve itself failed before it was known) so the+ * prefix parses unambiguously, and so the blocked-run message can tell the+ * operator exactly which row `gbrain delete` should remove.+ */+export function renameReconcileErrorMessage(+ from: string,+ staleSlug: string | undefined,+ cause: string,+): string {+ const slugSlot = staleSlug === undefined ? '?' : JSON.stringify(staleSlug);+ return (+ `rename reconcile failed (stale row ${slugSlot} for ${JSON.stringify(from)} not removed): ${cause}`+ );+}++/** The literal that closes the path slot in BOTH sentinel formats. */+const RENAME_SENTINEL_DELIM = ' not removed): ';++/**+ * Recover the rename's OLD path from a `<rename:…>` sentinel's error text+ * (written by `renameReconcileErrorMessage` — this pair owns the format).+ * Returns undefined on anything that doesn't parse; callers treat that as+ * "leave the row alone" (fail-closed), so a hand-edited row can never be+ * auto-cleared on a misread.+ *+ * Two formats are read. The current one JSON-encodes the path, which makes+ * the quoted span self-delimiting for any path bytes. The PRE-#3479 one+ * interpolated the path raw and carried no slug slot:+ *+ * rename reconcile failed (stale row for <path> not removed): <cause>+ *+ * Reading only the current format would leave anyone ALREADY wedged by+ * #3056 before upgrading wedged forever: their ledger row cannot be parsed,+ * so the self-heal can never prove it orphaned, so `doctor` keeps failing —+ * the exact condition this self-heal exists to end, denied to the users who+ * need it most (review: "incomplete fix"). The legacy branch is admitted+ * ONLY when it is unambiguous: the raw interpolation is undecidable if the+ * delimiter appears more than once (a path or a cause containing it), so+ * that case still returns undefined and the row stays open. The two formats+ * cannot be confused — the current one always has a slug slot between+ * `stale row ` and ` for `, which the legacy pattern does not match.+ */+export function parseRenameReconcileFrom(error: string): string | undefined {+ const m = /^rename reconcile failed \(stale row (?:"(?:[^"\\]|\\.)*"|\?) for ("(?:[^"\\]|\\.)*") not removed\): /.exec(error);+ if (m) {+ try {+ const parsed: unknown = JSON.parse(m[1]);+ return typeof parsed === 'string' ? parsed : undefined;+ } catch {+ return undefined;+ }+ }+ const legacy = /^rename reconcile failed \(stale row for (.+) not removed\): /.exec(error);+ if (!legacy) return undefined;+ // Undecidable if the delimiter occurs more than once: the greedy capture+ // above would swallow a cause that contains it, and a lazy one would cut+ // a path that contains it. Neither guess is safe when the consequence is+ // clearing a sentinel that still guards a real duplicate.+ let occurrences = 0;+ for (let i = error.indexOf(RENAME_SENTINEL_DELIM); i !== -1;+ i = error.indexOf(RENAME_SENTINEL_DELIM, i + 1)) occurrences++;+ if (occurrences !== 1) return undefined;+ return legacy[1] === '' ? undefined : legacy[1];+}+/*** Resolve the auto-skip threshold from `GBRAIN_SYNC_AUTOSKIP_AFTER`* (default 3). `0` disables the valve entirely (pure fail-closed).@@ -117,6 +203,14 @@ export function resolveAutoSkipThreshold(): number {* ones so Postgres `duplicate key` isn't mislabeled as a YAML duplicate-key.*/export function classifyErrorCode(errorMsg: string): string {+ // `<rename:…>` sentinel envelope (#3056) — checked FIRST so the code is+ // stable regardless of the underlying cause: the envelope wraps a raw DB+ // error whose text would otherwise match a cause-level pattern below+ // (STATEMENT_TIMEOUT, DB_DUPLICATE_KEY, …) and make the same sentinel+ // class surface under different codes run to run (#3479 review). Without+ // it the blocked-run breakdown also printed a bare `UNKNOWN: 1`.+ if (/rename reconcile failed|RENAME_RECONCILE/i.test(errorMsg)) return 'RENAME_RECONCILE';+// SLUG_MISMATCH: thrown by importFromFile() at src/core/import-file.ts.if (/slug.*does not match|SLUG_MISMATCH/i.test(errorMsg)) return 'SLUG_MISMATCH';@@ -268,7 +362,7 @@ export function syncFailuresPath(): string {function _ledgerKey(f: { source_id: string; path: string }): string {// NUL separator can't appear in a source id or path.- return `${f.source_id} ${f.path}`;+ return `${f.source_id}\u0000${f.path}`;}// ─── State mirror ───────────────────────────────────────────────────@@ -550,6 +644,26 @@ export function clearFailures(sourceId: string, paths: string[]): void {});}+/**+ * Re-insert previously-cleared rows VERBATIM (attempts, first_seen, ts,+ * commit, state all preserved) — the undo half of a clear that a+ * post-clear verification found premature (#3583: the orphan-sentinel+ * sweep's clear-then-verify restore). Skips any (source_id, path) that+ * already has a row so it can never double-record or fight a concurrent+ * re-record. Returns how many rows were actually restored.+ */+export function restoreFailures(sourceId: string, rows: SyncFailure[]): number {+ const mine = rows.filter(r => r.source_id === sourceId);+ if (mine.length === 0) return 0;+ return withLedgerLock(() => {+ const entries = loadSyncFailures();+ const present = new Set(entries.map(e => _ledgerKey(e)));+ const missing = mine.filter(r => !present.has(_ledgerKey(r)));+ if (missing.length > 0) _writeAll([...entries, ...missing]);+ return missing.length;+ });+}+/*** Acknowledge OPEN or AUTO_SKIPPED file failures (human `--skip-failed`).* Scoped to one source when `sourceId` is given (never acks another sourcediff --git a/src/core/sync-git.ts b/src/core/sync-git.tsindex 1210c945a5..08a04f7a8b 100644--- a/src/core/sync-git.ts+++ b/src/core/sync-git.ts@@ -7,7 +7,7 @@ import { existsSync, readFileSync, realpathSync } from 'fs';import { execFileSync } from 'child_process';import { isAbsolute, join, relative, sep } from 'path';import type { BrainEngine } from './engine.ts';-import { resolveSlugForPath } from './sync.ts';+import { resolveSlugForPath, DEFAULT_SOURCE_ID } from './sync.ts';import { DELETE_BATCH_SIZE } from './engine-constants.ts';import { loadStorageConfig } from './storage-config.ts';@@ -33,18 +33,27 @@ export async function resolveSlugByPathOrSourcePath(// resolveSlugsByPaths so single-call and batched paths share one SQL// owner + one fallback semantic. One Map allocation per single-call;// negligible cost. When sourceId is undefined (legacy unscoped callers),- // fall back to the original executeRaw shape — the batch method- // requires sourceId to prevent the multi-source-bug-class on its new- // surface (D5). The unscoped fallback preserves back-compat.+ // a direct executeRaw runs instead — the batch method requires sourceId+ // to prevent the multi-source-bug-class on its new surface (D5). That+ // branch is NOT the historical unscoped query any more; see below.try {if (sourceId) {const m = await engine.resolveSlugsByPaths([path], { sourceId });const slug = m.get(path);if (slug) return slug;} else {+ // #3583 gate14: scoped to 'default', matching every WRITE the bare+ // no-sourceId path performs (updateSlug, deletePage, the rename+ // bookkeeping repair — all default-scoped). The historical unscoped+ // form could hand back a row from ANOTHER source that happened to+ // share the source_path; the rename loop takes this return value+ // directly as its cheap-move target, so that foreign slug went to+ // updateSlug, the default-scoped move silently no-opped, and the+ // fallback import landed under a cross-source dedup. Resolve and+ // mutate must agree on the scope.const rows = await engine.executeRaw<{ slug: string }>(- `SELECT slug FROM pages WHERE source_path = $1 LIMIT 1`,- [path],+ `SELECT slug FROM pages WHERE source_path = $1 AND source_id = $2 LIMIT 1`,+ [path, DEFAULT_SOURCE_ID],);if (rows.length > 0 && rows[0].slug) return rows[0].slug;}@@ -306,6 +315,21 @@ export function git(}).trim();}+/**+ * git() minus the trim — REQUIRED for NUL-delimited listings (`ls-files -z`,+ * `ls-tree -z`): a filename that begins with a space is the FIRST entry of+ * the listing, and trim() silently rewrites it into a different path (#3583+ * review — the misread let a decoy blob stand in for the real file and a+ * live page was deleted on the corrupted evidence).+ */+export function gitRawOutput(repoPath: string, args: string[]): string {+ return execFileSync('git', buildGitInvocation(repoPath, args, []), {+ encoding: 'utf-8',+ timeout: 30000,+ maxBuffer: 100 * 1024 * 1024,+ });+}+/*** #753/#774: walk up from inputPath to the nearest git repo root via* `git -C <path> rev-parse --show-toplevel`. Handles worktrees and submodulesdiff --git a/src/core/sync.ts b/src/core/sync.tsindex 01714de585..07b84b0116 100644--- a/src/core/sync.ts+++ b/src/core/sync.ts@@ -38,6 +38,14 @@ interface SyncableOptions {strategy?: SyncStrategy;include?: string[];exclude?: string[];+ /**+ * Repeatable `--include-hidden <glob>` patterns (same glob dialect as+ * `include`/`exclude`, matched against the same path form `classifySync`+ * receives). Waives the leading-dot prune heuristic in `isPathPruned` for+ * paths that match — see that function's doc comment for exactly what is+ * and isn't waivable.+ */+ includeHidden?: string[];}// v0.19.0 shipped a 9-extension allowlist (ts/tsx/js/jsx/mjs/cjs/py/rb/go). The@@ -394,6 +402,49 @@ export function pruneDir(name: string, parentDir?: string): boolean {return true;}+/**+ * Path-string form of the exclusion `pruneDir` enforces during a live+ * directory descent, evaluated per-segment against a full path — the+ * canonical gate for the two PURE classifiers that never walk a real+ * directory tree: `classifySync` (drives `sync`'s incremental + full-sync+ * dry-run/reconcile paths) and `isCollectibleForWalker` in `commands/+ * import.ts` (drives `import`'s git-ls-files fast path, which is what+ * every git-tracked source — the common case — actually uses). Both used+ * to reimplement this segment loop independently; funnelling them through+ * one function is what keeps a future change from fixing one and leaving+ * the other silently pruning differently, the way #923/#202 drifted before+ * `PRUNE_DIR_NAMES` existed.+ *+ * `includeHidden`: repeatable `--include-hidden <glob>` patterns (same+ * glob dialect as `include`/`exclude`, matched against the full `path`+ * argument as given — callers are responsible for passing the same path+ * form their other include/exclude matching already uses). When a path is+ * pruned ONLY because a segment is dot-prefixed (`.dira/entries/x.md`) and+ * the full path matches one of these globs, the dot-prune is waived. The+ * `PRUNE_DIR_NAMES` / `*.raw` exclusions are NEVER waivable — this flag+ * reaches past the leading-dot heuristic specifically (`.git`, `.dira`,+ * `.obsidian`, …), not past generated/vendored-tree exclusions.+ *+ * SCOPE: this only reaches the two pure-string classifiers above. It does+ * NOT reach `pruneDir`'s other, live-filesystem-walk callers — `import`'s+ * fallback walker for non-git directories, and `storage.ts`'s+ * `walkBrainRepo` — which decide per-directory during real recursive+ * descent and would need prefix-of-a-glob reasoning to honor the same+ * waiver safely (a directory named `.dira` must stay open for descent to+ * reach `.dira/entries/*.md` even though `.dira` alone doesn't match that+ * glob). Every `gbrain sources add`'d git repository — which is virtually+ * all of them, including every hq-shaped brain — goes through the+ * git-listing fast path this function guards, so the gap is scoped to+ * importing a bare (non-git) directory.+ */+export function isPathPruned(path: string, includeHidden?: string[]): boolean {+ const segments = path.split('/');+ if (segments.some((seg) => PRUNE_DIR_NAMES.has(seg) || seg.endsWith('.raw'))) return true;+ const dotPruned = segments.some((seg) => seg.startsWith('.'));+ if (!dotPruned) return false;+ return !(includeHidden && includeHidden.length > 0 && matchesAnyGlob(path, includeHidden));+}+/*** Discriminator for WHY a path is not syncable. Returned by `unsyncableReason`* so the sync cleanup loop in `commands/sync.ts` can distinguish "metafile we@@ -510,10 +561,12 @@ function classifySync(path: string, opts: SyncableOptions = {}): SyncableReason// Skip every path segment that pruneDir would block walkers from descending// into. Catches hidden dirs (`.git`, `.obsidian`), `.raw/` sidecars, and// vendor/generated trees (`node_modules/`, `vendor/`, …) at any depth.- const segments = path.split('/');- if (segments.some(p => !pruneDir(p))) return 'pruned-dir';+ // `opts.includeHidden` can waive the leading-dot part of this — see+ // `isPathPruned`'s doc comment for exactly what is and isn't waivable.+ if (isPathPruned(path, opts.includeHidden)) return 'pruned-dir';// Skip meta files that aren't pages+ const segments = path.split('/');const basename = segments[segments.length - 1] || '';if ((SYNC_SKIP_FILES as readonly string[]).includes(basename)) return 'metafile';@@ -677,6 +730,7 @@ export {acknowledgeSyncFailures,recordFailures,clearFailures,+ restoreFailures,acknowledgeFailures,autoSkipFailures,withLedgerLock,@@ -689,6 +743,10 @@ export {applySyncFailureGate,DEFAULT_SOURCE_ID,SENTINEL_PREFIX,+ RENAME_SENTINEL_PREFIX,+ renameSentinelPath,+ renameReconcileErrorMessage,+ parseRenameReconcileFrom,DEFAULT_AUTOSKIP_AFTER,} from './sync-failure-ledger.ts';export type {diff --git a/src/core/takes-quality-eval/pricing.ts b/src/core/takes-quality-eval/pricing.tsindex ba5c5f6a52..956e6ba40a 100644--- a/src/core/takes-quality-eval/pricing.ts+++ b/src/core/takes-quality-eval/pricing.ts@@ -42,8 +42,11 @@ const SUPPORTED_MODELS = ['anthropic:claude-sonnet-5','anthropic:claude-sonnet-4-6','anthropic:claude-haiku-4-5',- // gemini-1.5-pro was retired by Google (#3510); gemini-2.0-flash replaces- // it in DEFAULT_MODEL_PANEL. `gemini-2-flash` stays as the legacy alias.+ // gemini-2.5-flash holds the DEFAULT_MODEL_PANEL slot; gemini-1.5-pro+ // (#3510) and the gemini-2.0 family before it were retired by Google. The+ // retired ids stay listed so a `--models` run over historical results still+ // budget-gates, but they are no longer reachable defaults.+ 'google:gemini-2.5-flash','google:gemini-2.0-flash','google:gemini-2-flash',] as const;diff --git a/src/core/takes-quality-eval/runner.ts b/src/core/takes-quality-eval/runner.tsindex f9b9a45c74..c1ce3960ee 100644--- a/src/core/takes-quality-eval/runner.ts+++ b/src/core/takes-quality-eval/runner.ts@@ -38,12 +38,13 @@ import { DEFAULT_CYCLES_NONTTY } from '../eval/cycle-default.ts';* be listed in its recipe's chat touchpoint AND in the SUPPORTED_MODELS* pricing allowlist — pinned by test/default-model-panels.test.ts.* google:gemini-1.5-pro (retired by Google) and openai:gpt-4o (dropped from- * the OpenAI recipe's chat list) sat here dead until #3510.+ * the OpenAI recipe's chat list) sat here dead until #3510; gemini-2.0-flash+ * replaced the former and was itself retired before it was ever swept.*/export const DEFAULT_MODEL_PANEL = ['openai:gpt-5.2','anthropic:claude-opus-4-7',- 'google:gemini-2.0-flash',+ 'google:gemini-2.5-flash',] as const;export interface RunOpts {diff --git a/src/core/takes-row-types.ts b/src/core/takes-row-types.tsnew file mode 100644index 0000000000..9aefb7c0f2--- /dev/null+++ b/src/core/takes-row-types.ts@@ -0,0 +1,19 @@+/**+ * Shared row-shape types for the takes pipeline (stale rows + embedding+ * writes), peeled out of engine.ts so the engine classes and their takes+ * delegates stay within the module-size ratchet.+ */++/** v0.28 stale-takes row (mirrors StaleChunkRow shape). Embedding column intentionally omitted. */+export interface StaleTakeRow {+ take_id: number;+ page_slug: string;+ row_num: number;+ claim: string;+}++/** Vector write for an existing take row. */+export interface TakeEmbeddingInput {+ take_id: number;+ embedding: Float32Array;+}diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex b5a1970af2..9f0f53d74f 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -127,9 +127,11 @@ export interface RunThinkOpts {*/allowedSources?: string[];/**- * v0.40.2.0 — scalar projection of `OperationContext.remote`. When- * true, trajectory queries apply `visibility='world'` filter (mirrors- * the recall posture for untrusted callers). CLI defaults to false.+ * v0.40.2.0 — scalar projection of `OperationContext.remote`. Trajectory+ * queries apply the `visibility='world'` filter unless this is strictly+ * `false` (FAIL-CLOSED). Every trusted caller (CLI, dream cycle) passes+ * `remote: false` explicitly; omitting it degrades trajectory injection+ * to world-only rows.*/remote?: boolean;}diff --git a/src/core/types.ts b/src/core/types.tsindex d750bf8047..44644f9333 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -462,6 +462,10 @@ export interface SalienceOpts {* Default preserves v0.29.0 ranking; 'on' is opt-in.*/recency_bias?: 'flat' | 'on';+ /** Source scope (canonical precedence: array wins over scalar). Undefined =+ * unscoped (trusted local callers). */+ sourceId?: string;+ sourceIds?: string[];}export interface SalienceResult {@@ -553,6 +557,11 @@ export interface AnomaliesOpts {lookback_days?: number;/** Sigma threshold. Default 3.0. */sigma?: number;+ /** Source scope (canonical precedence: array wins over scalar). Applied to+ * BOTH the baseline and today windows so the anomaly math stays consistent.+ * Undefined = unscoped (trusted local callers). */+ sourceId?: string;+ sourceIds?: string[];}export interface AnomalyResult {diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex 018573427e..65ab7d1cd3 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -261,7 +261,8 @@ const synthesize: Operation = {takesHoldersAllowList: ctx.takesHoldersAllowList,...(scope.sourceId !== undefined ? { sourceId: scope.sourceId } : {}),...(scope.sourceIds !== undefined ? { allowedSources: scope.sourceIds } : {}),- remote: ctx.remote === true,+ // Fail-closed: only a context that explicitly says local gets local.+ remote: ctx.remote !== false,});// [c10] runThink degrades gracefully to a no-LLM stub RESULT; the protocoldiff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.tsindex 3e4f9db5ce..94656fd71d 100644--- a/src/core/verbs/entity-card.ts+++ b/src/core/verbs/entity-card.ts@@ -7,13 +7,14 @@* depth-1 indexed reads. Deliberately NOT the recursive-CTE traversal* (traversePaths) — the card is a latency contract, not a graph walk.*- * Resolution precedence (frozen): alias > exact title > slug-suffix; ties- * break on GREATEST(updated_at, last_retrieved_at) — "last_touched" is the- * card's OUTPUT name, not a column. Multi-hit → best match wins, runners-up- * land in `suggestions`. Miss → `found: false` + keyword near-misses with- * create_safety hints. NEVER throws for data reasons; each arm is guarded so- * a pre-page_aliases brain still resolves via arm 2 (same posture as the- * shipped reflex).+ * Resolution precedence (frozen): alias > exact slug > exact title >+ * slug-suffix. Exact-title collisions prefer entity-shaped pages over+ * transcript/note containers; otherwise ties break on GREATEST(updated_at,+ * last_retrieved_at) — "last_touched" is the card's OUTPUT name, not a+ * column. Multi-hit → best match wins, runners-up land in `suggestions`.+ * Miss → `found: false` + keyword near-misses with create_safety hints. NEVER+ * throws for data reasons; each arm is guarded so a pre-page_aliases brain+ * still resolves via arm 2 (same posture as the shipped reflex).** Privacy: `summary` runs through safeSynopsis (the get_page fence boundary);* facts respect visibility for remote callers (world-only).@@ -31,6 +32,7 @@ const OPEN_THREADS_CAP = 3;const OPEN_THREAD_TIMELINE_WINDOW_DAYS = 90;const SUGGESTION_CAP = 3;const FACT_FETCH_CAP = 100;+const ENTITY_PAGE_TYPES = new Set(['person', 'company', 'organization', 'entity']);export interface EntityCardEdge {type: string;@@ -181,11 +183,19 @@ export async function buildEntityCard(}}- // Rank candidates: arm rank asc, then GREATEST(updated_at, last_retrieved_at) desc.+ // Rank candidates: arm rank asc. Inside the precision arm an explicit slug+ // stays stronger than title inference; otherwise exact-title collisions+ // prefer an entity page over transcript/note containers. Recency remains+ // the final tie-break within the same match shape.const candidates = [...rankBySlug.entries()].map(([s, rank]) => ({ slug: s, rank, row: rowBySlug.get(s) })).filter((c): c is { slug: string; rank: number; row: CardPageRow } => c.row !== undefined)- .sort((a, b) => a.rank - b.rank || lastTouchedMs(b.row) - lastTouchedMs(a.row));+ .sort((a, b) =>+ a.rank - b.rank+ || (a.rank === ARM_EXACT+ ? exactMatchPreference(a.row, exactSlugs) - exactMatchPreference(b.row, exactSlugs)+ : 0)+ || lastTouchedMs(b.row) - lastTouchedMs(a.row));if (candidates.length === 0) {return { found: false, suggestions: await nearMissSuggestions(engine, sourceId, trimmed, excludePrivate) };@@ -207,6 +217,11 @@ export async function buildEntityCard(};}+function exactMatchPreference(row: CardPageRow, exactSlugs: string[]): number {+ if (exactSlugs.includes(row.slug)) return 0;+ return ENTITY_PAGE_TYPES.has(row.type ?? '') ? 1 : 2;+}+async function assembleCard(engine: BrainEngine,sourceId: string,diff --git a/src/eval/retrieval-quality/harness.ts b/src/eval/retrieval-quality/harness.tsindex f02ba1be8c..b45d3557d0 100644--- a/src/eval/retrieval-quality/harness.ts+++ b/src/eval/retrieval-quality/harness.ts@@ -16,6 +16,8 @@* pglite + a deterministic stub.*/+import { dedupeRankedKeys } from '../../core/eval/ranked-docs.ts';+export type Family =| 'title-substring'| 'generic-to-named'@@ -85,20 +87,21 @@ export interface RetrievalQualityReport {const K = 3;export function scoreQuestion(q: NamedThingQuestion, ranked: string[]): QuestionResult {+ const uniqueRanked = dedupeRankedKeys(ranked);if (q.family === 'hard-negative') {const forbidden = new Set(q.forbidden ?? []);- const topK = ranked.slice(0, K);+ const topK = uniqueRanked.slice(0, K);const clean = !topK.some(s => forbidden.has(s));return { family: q.family, query: q.query, hit_at_1: clean, hit_at_3: clean, reciprocal_rank: clean ? 1 : 0, negative_clean: clean, recall_at_k: 0, recall_at_10: 0 };}const relevant = new Set(q.relevant ?? []);- const firstRelevantIdx = ranked.findIndex(s => relevant.has(s));+ const firstRelevantIdx = uniqueRanked.findIndex(s => relevant.has(s));const hit1 = firstRelevantIdx === 0;const hit3 = firstRelevantIdx >= 0 && firstRelevantIdx < K;const rr = firstRelevantIdx >= 0 ? 1 / (firstRelevantIdx + 1) : 0;const recallAt = (k: number): number => {if (relevant.size === 0) return 0;- const top = ranked.slice(0, k);+ const top = uniqueRanked.slice(0, k);const found = top.filter(s => relevant.has(s)).length;return found / relevant.size;};diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex c1d4c0d1be..ec4d32232d 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.46.31.0 -->+<!-- gbrain-template-stamp: 0.46.32.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/ai/capabilities.test.ts b/test/ai/capabilities.test.tsindex e5b261ecf5..eee6c4d49c 100644--- a/test/ai/capabilities.test.ts+++ b/test/ai/capabilities.test.ts@@ -10,6 +10,10 @@ describe('getProviderCapabilities (v0.38 Slice 1 — D6/D7 recipe-driven capabilexpect(caps.maxContext).toBe(200000);});+ it('uses model-specific recipe context metadata when declared', () => {+ expect(getProviderCapabilities('anthropic:claude-opus-4-7').maxContext).toBe(1_000_000);+ });+it('returns capabilities for OpenAI (automatic prefix caching counts)', () => {const caps = getProviderCapabilities('openai:gpt-5.2');expect(caps.supportsToolCalling).toBe(true);diff --git a/test/ai/gateway-chat.test.ts b/test/ai/gateway-chat.test.tsindex ccd1e056a8..d229f66d49 100644--- a/test/ai/gateway-chat.test.ts+++ b/test/ai/gateway-chat.test.ts@@ -191,7 +191,7 @@ describe('chat touchpoint — model resolver + aliases (Codex F-OV-5)', () => {test('assertTouchpoint accepts chat for chat-capable native + openai-compat providers', () => {expect(() => assertTouchpoint(getRecipe('anthropic')!, 'chat', 'claude-opus-4-7')).not.toThrow();expect(() => assertTouchpoint(getRecipe('openai')!, 'chat', 'gpt-5.2')).not.toThrow();- expect(() => assertTouchpoint(getRecipe('google')!, 'chat', 'gemini-2.0-flash')).not.toThrow();+ expect(() => assertTouchpoint(getRecipe('google')!, 'chat', 'gemini-2.5-flash')).not.toThrow();expect(() => assertTouchpoint(getRecipe('deepseek')!, 'chat', 'deepseek-v4-flash')).not.toThrow();// Legacy id retired by DeepSeek 2026-07-24 (#1255): still passes local// validation (openai-compat tier), rejection surfaces at the provider.diff --git a/test/ai/gateway-tools-schema.test.ts b/test/ai/gateway-tools-schema.test.tsindex f5c57790cc..87c87b1bd2 100644--- a/test/ai/gateway-tools-schema.test.ts+++ b/test/ai/gateway-tools-schema.test.ts@@ -93,4 +93,29 @@ describe('gateway tool schema + message shape (real AI SDK v6)', () => {generateText({ model: model as any, tools: tools as any, messages: preFixMessages as any }),).rejects.toThrow();});++ it('FIX: a tool-call with undefined toolCallId (GLM omission) is coerced to a non-empty string', () => {+ // The exact poisoned shape z.ai/GLM produced: a tool-call part with NO+ // toolCallId. Replayed as assistant history on turn N+1, pre-fix this threw+ // "The messages do not match the ModelMessage[] schema" (toolCallId: z.string())+ // and wedged the job across all 528 autopilot retries. ensureToolCallId()+ // synthesizes a stable id so the v6 ModelMessage schema no longer rejects it.+ // (chat() applies the SAME coercion at the source, so the id it emits flows+ // to BOTH the assistant tool-call block AND its matching tool-result block —+ // a complete matched conversation is covered by the first test above.)+ const poisoned: ChatMessage[] = [+ { role: 'user', content: 'find foo' },+ { role: 'assistant', content: [{ type: 'tool-call', toolCallId: undefined as unknown as string, toolName: 'search', input: { q: 'foo' } }] },+ ];+ const converted = toModelMessages(poisoned) as any[];+ const asst = converted.find((m) => m.role === 'assistant');+ const toolCallPart = asst.content.find((p: any) => p.type === 'tool-call');+ expect(typeof toolCallPart.toolCallId).toBe('string');+ expect(toolCallPart.toolCallId.length).toBeGreaterThan(0);+ // An empty-string id must also be coerced (not just undefined).+ const emptyId = toModelMessages([+ { role: 'assistant', content: [{ type: 'tool-call', toolCallId: '', toolName: 'search', input: {} }] },+ ]) as any[];+ expect(emptyId[0].content[0].toolCallId.length).toBeGreaterThan(0);+ });});diff --git a/test/all-sources-sentinel.test.ts b/test/all-sources-sentinel.test.tsindex 5bd6fa91a8..bde089101b 100644--- a/test/all-sources-sentinel.test.ts+++ b/test/all-sources-sentinel.test.ts@@ -142,6 +142,51 @@ describe('__all__ is never narrower than an unqualified read', () => {// …and __all__ must be a superset of that: the whole brain ({}).const all = ctxOf({ remote: false, sourceId: '__all__' });expect(federatedSearchScope(all)).toEqual({});++ // An explicit sentinel keeps trusted-local whole-brain semantics too.+ expect(federatedSearchScope(unqualified, '__all__')).toEqual({});+ });++ test('grantless stdio treats explicit __all__ like an omitted source', () => {+ const ctx = ctxOf({+ remote: true,+ sourceId: 'default',+ localFederatedSourceIds: ['default', 'src-a', 'src-b'],+ });++ expect(federatedSearchScope(ctx)).toEqual({+ sourceIds: ['default', 'src-a', 'src-b'],+ });+ expect(federatedSearchScope(ctx, '__all__')).toEqual({+ sourceIds: ['default', 'src-a', 'src-b'],+ });+ expect(federatedSearchScope(ctx, 'src-a')).toEqual({ sourceId: 'src-a' });+ });++ test('remote scalar scope stays pinned when no transport federation exists', () => {+ const ctx = ctxOf({ remote: true, sourceId: 'src-b' });+ expect(federatedSearchScope(ctx, '__all__')).toEqual({ sourceId: 'src-b' });+ });++ test('OAuth grants, including empty grants, stay authoritative over local federation', () => {+ const localFederatedSourceIds = ['default', 'src-a', 'src-b'];+ const granted = ctxOf({+ remote: true,+ sourceId: 'default',+ localFederatedSourceIds,+ auth: { token: 't', clientId: 'c', scopes: [], allowedSources: ['tenant-a', 'tenant-b'] } as any,+ });+ expect(federatedSearchScope(granted, '__all__')).toEqual({+ sourceIds: ['tenant-a', 'tenant-b'],+ });++ const emptyGrant = ctxOf({+ remote: true,+ sourceId: 'default',+ localFederatedSourceIds,+ auth: { token: 't', clientId: 'c', scopes: [], allowedSources: [] } as any,+ });+ expect(federatedSearchScope(emptyGrant, '__all__')).toEqual({ sourceId: 'default' });});});diff --git a/test/auto-link-targeted-probe-2544.test.ts b/test/auto-link-targeted-probe-2544.test.tsindex 4ffa2fd2e9..94d7c8fa73 100644--- a/test/auto-link-targeted-probe-2544.test.ts+++ b/test/auto-link-targeted-probe-2544.test.ts@@ -15,7 +15,8 @@*/import { afterAll, beforeAll, beforeEach, describe, expect, setDefaultTimeout, test } from 'bun:test';-import { readFileSync } from 'node:fs';+import { mkdtempSync, readFileSync } from 'node:fs';+import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';@@ -100,9 +101,13 @@ describe('#2544 — auto-link behavior through put_page (targeted probe)', () =>test('resolution stays scoped to the write source', async () => {// Target exists ONLY in 'default'. A write into source-b must not link to it.+ // Real writable dir: #3935 (absorbed this wave) makes put_page throw+ // storage_error on a failed write-through, so a fake path would fail the+ // put before scoped resolution is ever exercised.+ const sourceBDir = mkdtempSync(join(tmpdir(), 'gbrain-2544-source-b-'));await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config, created_at)- VALUES ('source-b', 'source-b', '/fake/source-b', '{}'::jsonb, NOW())+ VALUES ('source-b', 'source-b', '${sourceBDir.replace(/'/g, "''")}', '{}'::jsonb, NOW())ON CONFLICT (id) DO NOTHING`,);await put('people/alice-example', 'A person page in default.');diff --git a/test/bench/correctness-gate.test.ts b/test/bench/correctness-gate.test.tsindex ebf1125491..912635d7b3 100644--- a/test/bench/correctness-gate.test.ts+++ b/test/bench/correctness-gate.test.ts@@ -34,6 +34,25 @@ describe('correctness-gate: per-query iteration + aggregate math', () => {expect(result.summary.queries_errored).toBe(0);});+ test('duplicate chunks count once in page-level recall and retrieved_count', async () => {+ const qrels = makeQrels([+ {+ query_id: 'q-duplicate',+ query: 'x',+ relevant: [{ source_id: 'default', slug: 'a' }],+ },+ ]);+ const result = await runCorrectnessGate(fakeEngine, qrels, {+ k: 2,+ searchFn: async () => [+ { source_id: 'default', slug: 'a' },+ { source_id: 'default', slug: 'a' },+ ],+ });+ expect(result.per_query[0].recall_at_k).toBe(1);+ expect(result.per_query[0].retrieved_count).toBe(1);+ });+test('per-query throw → errored=true; query NOT counted in aggregates; gate flagged', async () => {// Finding 2D: a query throw flips verdict to fail. The orchestrator records// the throw as a per-query failure; the caller (eval-gate.ts) treatsdiff --git a/test/bench/qrels-file.test.ts b/test/bench/qrels-file.test.tsindex a8fbff1669..c8fa6ed694 100644--- a/test/bench/qrels-file.test.ts+++ b/test/bench/qrels-file.test.ts@@ -101,6 +101,12 @@ describe('qrels-file: math', () => {expect(computeRecallAtK(['a', 'b', 'c'], ['a', 'b'], 1)).toBe(0.5);});+ test('deduplicates retrieved and relevant page keys before the cutoff', () => {+ expect(computeRecallAtK(['a', 'a'], ['a'], 2)).toBe(1);+ expect(computeRecallAtK(['x', 'x', 'a'], ['a'], 2)).toBe(1);+ expect(computeRecallAtK(['a'], ['a', 'a'], 2)).toBe(1);+ });+test('computeRecallAtK empty relevant set returns 0 (defensive)', () => {expect(computeRecallAtK(['a'], [], 10)).toBe(0);});diff --git a/test/brain-allowlist.serial.test.ts b/test/brain-allowlist.serial.test.tsindex 7cfd5c2a7b..1c6f28b939 100644--- a/test/brain-allowlist.serial.test.ts+++ b/test/brain-allowlist.serial.test.ts@@ -9,6 +9,7 @@*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import * as fs from 'node:fs';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { operations, OperationError } from '../src/core/operations.ts';import {@@ -151,6 +152,9 @@ describe('buildBrainTools', () => {// put_page → importFromContent, so subagent writes land in the cycle's// resolved source instead of the hardcoded 'default'.test('execute() on put_page writes to the configured sourceId (#1586)', async () => {+ // Write-through needs a real directory for this source's local_path —+ // put_page now rejects a write whose file can't be written to disk.+ fs.mkdirSync('/tmp/mybrain', { recursive: true });await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config, archived, created_at)VALUES ('mybrain', 'My Brain', '/tmp/mybrain', '{}'::jsonb, false, now())diff --git a/test/cli-help-discoverability.test.ts b/test/cli-help-discoverability.test.tsindex b49f9749b5..75cdcd9cbb 100644--- a/test/cli-help-discoverability.test.ts+++ b/test/cli-help-discoverability.test.ts@@ -162,6 +162,67 @@ describe('#1175 — main `gbrain --help` SOURCES block matches the real subcomma});});+describe('#4003 — `gbrain auth --help` reaches the detailed usage block', () => {+ test('output contains the real auth subcommand usage, not the generic stub', () => {+ const { stdout, status } = runCli(['auth', '--help']);+ expect(status).toBe(0);+ // Pre-fix: `auth` was missing from CLI_ONLY_SELF_HELP, so this printed+ // only "gbrain auth - run gbrain --help for the full command list."+ expect(stdout).toContain('GBrain Token Management');+ expect(stdout).toContain('gbrain auth create <name>');+ expect(stdout).toContain('gbrain auth register-client');+ expect(stdout).not.toContain('run gbrain --help for the full command list');+ });++ test('-h short flag also works', () => {+ const { stdout, status } = runCli(['auth', '-h']);+ expect(status).toBe(0);+ expect(stdout).toContain('GBrain Token Management');+ });++ test('main `gbrain --help` lists auth', () => {+ const { stdout, status } = runCli(['--help']);+ expect(status).toBe(0);+ expect(stdout).toMatch(/^\s*auth </m);+ expect(stdout).toMatch(/^\s*auth --help\s/m);+ });+});++describe('#4083 follow-up — auth subcommand + --help shows usage, never executes', () => {+ // Caught by automated PR review on #4083: once `auth` joined+ // CLI_ONLY_SELF_HELP, the generic --help short-circuit in cli.ts stopped+ // intercepting `gbrain auth <subcommand> --help` before it reached+ // runAuth. Without an early --help check inside runAuth itself, a+ // trailing --help on a real subcommand fell through to that+ // subcommand's real handler instead of showing help — e.g. `gbrain auth+ // create foo --help` would mint a real token named "foo".+ test('`gbrain auth create <name> --help` shows usage, does not create a token', () => {+ const { stdout, status } = runCli(['auth', 'create', 'definitely-not-a-real-token-name', '--help']);+ expect(status).toBe(0);+ expect(stdout).toContain('GBrain Token Management');+ expect(stdout).not.toContain('Token created for');+ });++ test('`gbrain auth revoke <name> --help` shows usage, does not attempt a revoke', () => {+ const { stdout, status } = runCli(['auth', 'revoke', 'definitely-not-a-real-token-name', '--help']);+ expect(status).toBe(0);+ expect(stdout).toContain('GBrain Token Management');+ });++ test('`gbrain auth register-client <name> --help` shows usage, does not register a client', () => {+ const { stdout, status } = runCli(['auth', 'register-client', 'definitely-not-a-real-client', '--help']);+ expect(status).toBe(0);+ expect(stdout).toContain('GBrain Token Management');+ });++ test('-h works the same way as --help on a subcommand', () => {+ const { stdout, status } = runCli(['auth', 'create', 'definitely-not-a-real-token-name', '-h']);+ expect(status).toBe(0);+ expect(stdout).toContain('GBrain Token Management');+ expect(stdout).not.toContain('Token created for');+ });+});+describe('#3834 — extract flags are discoverable from both help surfaces', () => {const implementedFlags = ['--by-mention',@@ -298,3 +359,37 @@ describe('`sources webhook --help` reaches its own detailed help, not the generaexpect(stderr).not.toContain('TypeError');});});++describe('`gbrain takes --help` reaches the detailed subcommand block', () => {+ test('every mutate + read subcommand is listed', () => {+ const { stdout, status } = runCli(['takes', '--help']);+ expect(status).toBe(0);+ // Pre-fix these were undiscoverable from the CLI: `takes` was in CLI_ONLY+ // but not CLI_ONLY_SELF_HELP, so the generic stub fired before runTakes.+ expect(stdout).toContain('takes add');+ expect(stdout).toContain('takes update');+ expect(stdout).toContain('takes supersede');+ expect(stdout).toContain('takes resolve');+ expect(stdout).toContain('takes scorecard');+ expect(stdout).toContain('takes calibration');+ expect(stdout).toContain('takes search');+ });++ test('output is NOT the generic short-circuit fallback', () => {+ const { stdout } = runCli(['takes', '--help']);+ // Pre-fix output was exactly: "Usage: gbrain takes\n\ngbrain takes - run+ // gbrain --help for the full command list."+ expect(stdout).not.toContain('run gbrain --help for the full command list');+ expect(stdout).not.toMatch(/^Usage: gbrain takes\s*$/m);+ expect(stdout.split('\n').length).toBeGreaterThan(10);+ });++ test('help works with no brain configured (pre-engine-bind branch)', () => {+ // runCli points GBRAIN_HOME at a nonexistent dir. Without the pre-engine+ // branch this printed "No brain configured. Run: gbrain init".+ const { stdout, status } = runCli(['takes', '--help']);+ expect(status).toBe(0);+ expect(stdout).not.toContain('No brain configured');+ expect(stdout).toContain('--dir <path>');+ });+});diff --git a/test/config-db-plane-round-trips.test.ts b/test/config-db-plane-round-trips.test.tsnew file mode 100644index 0000000000..8cf7ab6716--- /dev/null+++ b/test/config-db-plane-round-trips.test.ts@@ -0,0 +1,172 @@+// Regression: loadConfigWithEngine() read every DB-plane key one at a time.+//+// SYMPTOM. On a Supabase-hosted brain, `gbrain stats` took 7.7s wall clock.+// pg_stat_statements showed 54 queries totalling 2.3ms of server time — 44 of+// them `SELECT value FROM config WHERE key = $1`. The database did no work;+// the CLI paid one ~70ms round trip per config key. The same command against a+// local PGLite brain took 0.26s, which is why the pattern survived so long: on+// an embedded database each read costs microseconds and is invisible.+//+// The config table is a handful of rows, so it is now read once via+// getAllConfig() and every key is answered from that snapshot. These tests pin+// the round-trip count, not the wall clock: a timing assertion would be flaky+// in CI, while a call counter is deterministic.+//+// Against the pre-fix code the first two cases report 18+ per-key reads.++import { describe, expect, test } from 'bun:test';+import { loadConfigWithEngine, type GBrainConfig } from '../src/core/config.ts';++/** Engine double that counts how many times each config read is issued. */+function makeCountingEngine(values: Record<string, string> = {}) {+ const stats = { getConfig: 0, getAllConfig: 0, listConfigKeys: 0 };++ return {+ stats,+ async getConfig(key: string): Promise<string | null> {+ stats.getConfig++;+ return key in values ? values[key] : null;+ },+ async getAllConfig(): Promise<Record<string, string>> {+ stats.getAllConfig++;+ return { ...values };+ },+ async listConfigKeys(prefix: string): Promise<string[]> {+ stats.listConfigKeys++;+ return Object.keys(values).filter((k) => k.startsWith(prefix));+ },+ };+}++/** Engine without the bulk read — an older or third-party implementation. */+function makeLegacyEngine(values: Record<string, string> = {}) {+ const stats = { getConfig: 0 };+ return {+ stats,+ async getConfig(key: string): Promise<string | null> {+ stats.getConfig++;+ return key in values ? values[key] : null;+ },+ async listConfigKeys(prefix: string): Promise<string[]> {+ return Object.keys(values).filter((k) => k.startsWith(prefix));+ },+ };+}++const BASE: GBrainConfig = { engine: 'postgres' } as GBrainConfig;++describe('loadConfigWithEngine DB-plane round trips', () => {+ test('reads the config table once, not once per key', async () => {+ const engine = makeCountingEngine();++ await loadConfigWithEngine(engine, BASE);++ expect(engine.stats.getAllConfig).toBe(1);+ expect(engine.stats.getConfig).toBe(0);+ expect(engine.stats.listConfigKeys).toBe(0);+ });++ test('resolves a key prefix map from the same snapshot', async () => {+ // dbPrefixMap used to list keys, then read one value per matched key, so+ // its cost scaled with how many keys the prefix matched.+ const engine = makeCountingEngine({+ 'provider_base_urls.openai': 'https://a.example',+ 'provider_base_urls.anthropic': 'https://b.example',+ 'provider_base_urls.voyage': 'https://c.example',+ });++ const merged = await loadConfigWithEngine(engine, BASE);++ expect(merged?.provider_base_urls).toEqual({+ openai: 'https://a.example',+ anthropic: 'https://b.example',+ voyage: 'https://c.example',+ });+ expect(engine.stats.getAllConfig).toBe(1);+ expect(engine.stats.getConfig).toBe(0);+ });++ test('the snapshot does not change which values win', async () => {+ const engine = makeCountingEngine({+ embedding_multimodal: 'true',+ embedding_multimodal_model: 'voyage:voyage-multimodal-3',+ 'content_sanity.bytes_warn': '1024',+ 'dream.synthesize.verdict_model': 'anthropic:claude-haiku-4-5',+ });++ const merged = await loadConfigWithEngine(engine, BASE);++ expect(merged?.embedding_multimodal).toBe(true);+ expect(merged?.embedding_multimodal_model).toBe('voyage:voyage-multimodal-3');+ expect(merged?.content_sanity?.bytes_warn).toBe(1024);+ expect(merged?.dream?.synthesize?.verdict_model).toBe('anthropic:claude-haiku-4-5');+ });++ test('file/env config still beats the DB plane', async () => {+ // Precedence is the reason each key is resolved separately in the first+ // place; the snapshot must not disturb it.+ const engine = makeCountingEngine({ embedding_multimodal_model: 'db:model' });+ const base = { ...BASE, embedding_multimodal_model: 'file:model' } as GBrainConfig;++ const merged = await loadConfigWithEngine(engine, base);++ expect(merged?.embedding_multimodal_model).toBe('file:model');+ });++ test('an engine without getAllConfig still resolves every key', async () => {+ // Fallback path: a pre-v43 or third-party engine keeps the per-key reads.+ const engine = makeLegacyEngine({+ embedding_multimodal: 'true',+ 'provider_base_urls.openai': 'https://a.example',+ });++ const merged = await loadConfigWithEngine(engine, BASE);++ expect(merged?.embedding_multimodal).toBe(true);+ expect(merged?.provider_base_urls).toEqual({ openai: 'https://a.example' });+ expect(engine.stats.getConfig).toBeGreaterThan(10);+ });++ test('a failing bulk read degrades to per-key reads', async () => {+ // A brain mid-migration has no config table. getAllConfig throwing must+ // not abort the load, and must not skip the DB plane on a brain where the+ // per-key path would have worked.+ const stats = { getConfig: 0 };+ const engine = {+ async getAllConfig(): Promise<Record<string, string>> {+ throw new Error('relation "config" does not exist');+ },+ async getConfig(key: string): Promise<string | null> {+ stats.getConfig++;+ return key === 'embedding_multimodal' ? 'true' : null;+ },+ async listConfigKeys(): Promise<string[]> {+ return [];+ },+ };++ const merged = await loadConfigWithEngine(engine, BASE);++ expect(merged?.embedding_multimodal).toBe(true);+ expect(stats.getConfig).toBeGreaterThan(10);+ });++ test('a brain with no config table at all still loads', async () => {+ const engine = {+ async getAllConfig(): Promise<Record<string, string>> {+ throw new Error('relation "config" does not exist');+ },+ async getConfig(): Promise<string | null> {+ throw new Error('relation "config" does not exist');+ },+ async listConfigKeys(): Promise<string[]> {+ throw new Error('relation "config" does not exist');+ },+ };++ const merged = await loadConfigWithEngine(engine, BASE);++ expect(merged).toBeTruthy();+ expect(merged?.embedding_multimodal).toBeUndefined();+ });+});diff --git a/test/consolidate-valid-until.test.ts b/test/consolidate-valid-until.test.tsindex 807e57a10c..f7f96931f6 100644--- a/test/consolidate-valid-until.test.ts+++ b/test/consolidate-valid-until.test.ts@@ -81,6 +81,56 @@ async function insertFact(args: {return r[0].id;}+describe('#4057 — consolidation work-window eligibility', () => {+ test('#4057: consolidated rows cannot hide older unconsolidated facts beyond the 100-row window', async () => {+ const slug = 'cdx4-over-100-active';+ const pageId = await seedPage(slug);+ const oldDate = new Date('2025-01-01T00:00:00Z');+ const recentDate = new Date('2026-01-01T00:00:00Z');++ for (let i = 0; i < 100; i++) {+ await insertFact({+ entity_slug: slug,+ text: 'already consolidated claim',+ valid_from: new Date(recentDate.getTime() + i * 60_000),+ });+ }+ const take = await engine.executeRaw<{ id: number }>(+ `INSERT INTO takes (page_id, row_num, claim, kind, holder)+ VALUES ($1, 1, 'already consolidated claim', 'fact', 'self')+ RETURNING id`,+ [pageId],+ );+ await engine.executeRaw(+ `UPDATE facts+ SET consolidated_at = now(), consolidated_into = $1+ WHERE entity_slug = $2`,+ [take[0].id, slug],+ );++ for (let i = 0; i < 3; i++) {+ await insertFact({+ entity_slug: slug,+ text: 'still pending claim',+ valid_from: new Date(oldDate.getTime() + i * 60_000),+ });+ }++ const result = await runPhaseConsolidate(engine, {});++ expect(result.details.facts_consolidated).toBe(3);+ const pending = await engine.executeRaw<{ count: number }>(+ `SELECT COUNT(*)::int AS count+ FROM facts+ WHERE entity_slug = $1+ AND expired_at IS NULL+ AND consolidated_at IS NULL`,+ [slug],+ );+ expect(Number(pending[0].count)).toBe(0);+ });+});+describe('R4a — chronological valid_until writeback', () => {test('cluster of 3 chronologically-ordered facts: 2 older get valid_until set, newest stays NULL', async () => {await seedPage('cdx4-acme-mrr');diff --git a/test/conversation-facts-type-allowlist-drift.test.ts b/test/conversation-facts-type-allowlist-drift.test.tsindex d21e09dd69..e3d3b83226 100644--- a/test/conversation-facts-type-allowlist-drift.test.ts+++ b/test/conversation-facts-type-allowlist-drift.test.ts@@ -183,6 +183,7 @@ describe('ALLOWED_TYPES — canonical source of truth (leaf module)', () => {describe('DRIFT GUARD — consumer sites derive from the leaf module (re-hardcode + wrong-import trip-wire)', () => {for (const [label, relPath] of [['doctor.ts', 'commands/doctor.ts'],+ ['conversation-coverage.ts', 'commands/doctor/checks/conversation-coverage.ts'],['jobs.ts', 'commands/jobs.ts'],['sources.ts', 'commands/sources.ts'],['conversation-facts-backfill.ts', 'core/cycle/conversation-facts-backfill.ts'],@@ -209,12 +210,18 @@ describe('DRIFT GUARD — consumer sites derive from the leaf module (re-hardcodexpect(countAllowedTypesImportsFrom(src, '\\.\\./facts/conversation-types\\.ts')).toBe(1);});- test('doctor.ts: imports ALLOWED_TYPES from the leaf exactly once', () => {- // Post-peel (v0.46.9.1 containment sprint) doctor.ts keeps ONE call site- // (the buildChecks parser sample); the backlog check moved to- // doctor/checks/search-eval.ts and is guarded separately below.+ test('doctor.ts: no longer imports ALLOWED_TYPES (all call sites peeled)', () => {+ // The backlog check moved to doctor/checks/search-eval.ts and the+ // parser-sample scan (conversation_format_coverage, #4193) moved to+ // doctor/checks/conversation-coverage.ts; each is guarded separately.const src = readSrc('commands/doctor.ts');- expect(countAllowedTypesImportsFrom(src, '\\.\\./core/facts/conversation-types\\.ts')).toBe(1);+ expect(countAllowedTypesImportsFrom(src, '\\.\\./core/facts/conversation-types\\.ts')).toBe(0);+ expect((src.match(/\bALLOWED_TYPES\b/g) ?? []).length).toBe(0);+ });++ test('doctor/checks/conversation-coverage.ts: the peeled coverage check derives from the leaf', () => {+ const src = readSrc('commands/doctor/checks/conversation-coverage.ts');+ expect(countAllowedTypesImportsFrom(src, '\\.\\./\\.\\./\\.\\./core/facts/conversation-types\\.ts')).toBe(1);expect((src.match(/\bALLOWED_TYPES\b/g) ?? []).length).toBeGreaterThanOrEqual(2); // import + 1 usage});diff --git a/test/conversation-parser-transcript-signals.test.ts b/test/conversation-parser-transcript-signals.test.tsnew file mode 100644index 0000000000..b2e7bb911b--- /dev/null+++ b/test/conversation-parser-transcript-signals.test.ts@@ -0,0 +1,64 @@+import { describe, expect, test } from 'bun:test';+import { isTranscriptClaiming } from '../src/core/conversation-parser/transcript-signals.ts';+import type { Page } from '../src/core/types.ts';++function pageWith(frontmatter: Record<string, unknown>): Page {+ return { frontmatter } as unknown as Page;+}++const SUMMARY = [+ '## Highlights',+ '- Shipped the new onboarding flow',+ '- Reviewed the quarterly metrics doc',+ '## Decisions',+ '- Move the launch to next week',+ '- Alice owns the follow-up doc',+].join('\n');++describe('isTranscriptClaiming (#4193)', () => {+ test('summary-only headings + bullets: false', () => {+ expect(isTranscriptClaiming(undefined, SUMMARY)).toBe(false);+ });++ test('empty body: false', () => {+ expect(isTranscriptClaiming(undefined, '')).toBe(false);+ });++ test('raw_transcript frontmatter claims a transcript even when unresolvable', () => {+ expect(isTranscriptClaiming(pageWith({ raw_transcript: 'transcripts/x.txt' }), SUMMARY)).toBe(true);+ });++ test('blank raw_transcript is not a claim', () => {+ expect(isTranscriptClaiming(pageWith({ raw_transcript: ' ' }), SUMMARY)).toBe(false);+ });++ test('## Transcript section heading: true', () => {+ expect(isTranscriptClaiming(undefined, '## Summary\n- notes\n\n## Transcript\nweird turn shape')).toBe(true);+ expect(isTranscriptClaiming(undefined, '### Raw Transcript\nstuff')).toBe(true);+ });++ test('timestamp-dense lines: true (telegram/irc style anchors)', () => {+ const body = ['[10:12] alice: hi', '[10:13] bob: hello', '[10:15] alice: bye'].join('\n');+ expect(isTranscriptClaiming(undefined, body)).toBe(true);+ });++ test('a single time mention in an agenda does not trip the density signal', () => {+ const body = [+ '## Agenda',+ '- standup at 3:00',+ '- retro planning',+ '- metrics review',+ '- launch checklist',+ '- follow-ups',+ '- docs pass',+ '- close out',+ ].join('\n');+ expect(isTranscriptClaiming(undefined, body)).toBe(false);+ });++ test('prose label lines (builtins test_negative shape) are not a signal', () => {+ expect(+ isTranscriptClaiming(undefined, 'Owner: this is a prose label, not a transcript line\nNext: more prose'),+ ).toBe(false);+ });+});diff --git a/test/core/retry.test.ts b/test/core/retry.test.tsindex c1639e7696..dfa789fb23 100644--- a/test/core/retry.test.ts+++ b/test/core/retry.test.ts@@ -339,7 +339,7 @@ describe('BATCH_AUDIT_SITES typed enum + isBatchAuditSite guard (D10c codex)', (// Pin the set so a future "cleanup" PR can't silently drop a site and// break audit-attribution for the corresponding caller.const expected = new Set([- 'addLinksBatch', 'addTimelineEntriesBatch', 'addTakesBatch', 'upsertChunks',+ 'addLinksBatch', 'addTimelineEntriesBatch', 'addTakesBatch', 'updateTakeEmbeddings', 'upsertChunks','extract.links_inc', 'extract.timeline_inc','extract.links_fs', 'extract.timeline_fs','extract.links_db', 'extract.timeline_db',diff --git a/test/cross-modal-default-slots.test.ts b/test/cross-modal-default-slots.test.tsindex 08129e6f1e..5d19c50a9e 100644--- a/test/cross-modal-default-slots.test.ts+++ b/test/cross-modal-default-slots.test.ts@@ -9,7 +9,12 @@*/import { describe, expect, test } from 'bun:test';-import { DEFAULT_SLOTS } from '../src/core/cross-modal-eval/runner.ts';+import {+ DEFAULT_SLOTS,+ DEFAULT_DIMENSIONS,+ buildPrompt,+ dimensionScoreKey,+} from '../src/core/cross-modal-eval/runner.ts';import { getRecipe } from '../src/core/ai/recipes/index.ts';import { splitProviderModelId } from '../src/core/model-id.ts';import { canonicalLookup } from '../src/core/model-pricing.ts';@@ -45,3 +50,25 @@ describe('cross-modal DEFAULT_SLOTS ↔ recipe consistency', () => {expect(providers.size).toBe(3);});});++// #3491 (the #4338 approach): the judge prompt pins the exact "scores" keys.+// The pre-fix "dim_1_name" placeholder let each judge invent its own+// spelling/casing, splitting one dimension into per-model singletons at+// aggregation; aggregate.ts's trim+lowercase normalization is the backstop.+describe('cross-modal judge-key pinning', () => {+ test('dimensionScoreKey takes the label before the em-dash', () => {+ expect(dimensionScoreKey('GOAL_ACHIEVEMENT — Does it work?')).toBe('GOAL_ACHIEVEMENT');+ expect(dimensionScoreKey(' custom dimension without separator ')).toBe(+ 'custom dimension without separator',+ );+ });++ test('buildPrompt enumerates every dimension key verbatim (no placeholder)', () => {+ const prompt = buildPrompt('task', DEFAULT_DIMENSIONS, 'output');+ for (const dim of DEFAULT_DIMENSIONS) {+ expect(prompt).toContain(`"${dimensionScoreKey(dim)}": { "score": N, "feedback": "..." },`);+ }+ expect(prompt).not.toContain('dim_1_name');+ expect(prompt).toContain('using EXACTLY these keys under "scores"');+ });+});diff --git a/test/cross-modal-eval-aggregate.test.ts b/test/cross-modal-eval-aggregate.test.tsindex f42c4c8614..5facf563b5 100644--- a/test/cross-modal-eval-aggregate.test.ts+++ b/test/cross-modal-eval-aggregate.test.ts@@ -79,6 +79,21 @@ describe('cross-modal-eval/aggregate', () => {expect(out.errors).toEqual([{ modelId: 'google:gemini-1.5-pro', error: 'rate limited' }]);});+ test('dimension names are aggregated case-insensitively across models', () => {+ const out = aggregate({+ slots: [+ ok('openai:gpt-4o', { CORRECTNESS: 9 }),+ ok('anthropic:claude-opus-4-7', { correctness: 5 }),+ err('google:gemini-1.5-pro', 'rate limited'),+ ],+ });++ expect(Object.keys(out.dimensions)).toEqual(['correctness']);+ expect(out.dimensions.correctness!.scores).toEqual([9, 5]);+ expect(out.dimensions.correctness!.mean).toBe(7);+ expect(out.verdict).toBe('pass');+ });+test('1 of 3 succeeded -> INCONCLUSIVE (Q3=A)', () => {const out = aggregate({slots: [diff --git a/test/cross-modal-phase1.test.ts b/test/cross-modal-phase1.test.tsindex 4ff1608a5b..75760374f2 100644--- a/test/cross-modal-phase1.test.ts+++ b/test/cross-modal-phase1.test.ts@@ -179,7 +179,7 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {return resolveSearchMode({ mode: 'balanced' });}- test('KNOBS_HASH_VERSION is 26 (cross-modal still appended; 20→21 recency fallback re-key #895; 21→22 result-stamp/injection epoch; 22→23 excludePrivate posture fold #4352; 23→24 negative-offset cache-skip gap #4358 residual; 24→25 keywordOrFallback knob kof=; 25→26 salience/recency + intent_patterns fold #4415)', () => {+ test('KNOBS_HASH_VERSION is 26 (cross-modal still appended; 20→21 recency fallback re-key #895; 21→22 result-stamp/injection epoch; 22→23 excludePrivate posture fold #4352; 23→24 negative-offset cache-skip gap #4358 residual; 24→25 keywordOrFallback knob kof= #3617; 25→26 salience/recency + intent_patterns fold #4415)', () => {// v0.35 ladder: 1→2 reranker, 2→3 floor_ratio. v0.36 piggybacks on v=3// with 7 cross-modal knobs + column/provider context. v0.40.4 (salem) +// v0.39 T21 (master) bump to v=4 for graph_signals + schema-pack fields.@@ -206,7 +206,7 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {// replaces the wholesale cache skip for excludePrivate=true callers.// 23→24 (#4358 residual): negative-offset requests could read/write the// same cache row an offset=0 request shares.- // 24→25: kof= (keyword AND→OR fallback knob) joins the key.+ // 24→25 (#3617): kof= (keyword AND→OR fallback knob) joins the key.// 25→26: sal=/rec=/ipat= — salience/recency + intent_patterns fold (#4415).expect(KNOBS_HASH_VERSION).toBe(26);});diff --git a/test/cycle/synthesize-concepts-source-scope.test.ts b/test/cycle/synthesize-concepts-source-scope.test.tsindex ddf1ac7bce..ace8792c90 100644--- a/test/cycle/synthesize-concepts-source-scope.test.ts+++ b/test/cycle/synthesize-concepts-source-scope.test.ts@@ -10,6 +10,14 @@// docs/architecture/brains-and-sources.md) every synthesized concept page// silently lands under the seeded 'default' source instead of the cycle's// source — wrong provenance, invisible to source-scoped reads.+//+// On v0.45.x the same missing sourceId was fatal rather than silent: the+// existence probe there was source-agnostic, so an update to an existing+// concept page found the row in the real source, then createVersion looked+// it up under 'default' and threw+// createVersion failed: page "concepts/..." (source=default) not found+// which killed the cycle and every phase ordered after synthesize_concepts.+// Observed in production on a single-source brain.import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';diff --git a/test/default-model-panels.test.ts b/test/default-model-panels.test.tsindex 11e1181346..7a32bc6ac3 100644--- a/test/default-model-panels.test.ts+++ b/test/default-model-panels.test.ts@@ -46,3 +46,39 @@ describe('takes-quality DEFAULT_MODEL_PANEL ↔ recipe consistency', () => {expect(providers.size).toBe(3);});});++/**+ * The guard above only bites while recipes list LIVE models, so the recipe+ * lists need a guard of their own. Every id here answered 404 on a real+ * `generateContent` call; re-adding one to quiet a failing default would put+ * the panel guard back to sleep, which is how gemini-2.0-flash came to+ * replace the retired 1.5-pro and then sit dead in its place.+ */+describe('google recipe lists no retired model', () => {+ const RETIRED = [+ 'gemini-1.5-pro',+ 'gemini-2.0-flash',+ 'gemini-2.0-flash-lite',+ 'gemini-2.0-flash-exp',+ ];++ test('neither the chat nor the expansion touchpoint offers a dead model', () => {+ const google = getRecipe('google');+ expect(google).toBeDefined();+ const offered = [+ ...(google!.touchpoints.chat?.models ?? []),+ ...(google!.touchpoints.expansion?.models ?? []),+ ];+ expect(offered.length).toBeGreaterThan(0);+ for (const dead of RETIRED) {+ expect(offered, `"${dead}" is retired and answers 404`).not.toContain(dead);+ }+ });++ test('every model the google recipe offers is priced', () => {+ const google = getRecipe('google')!;+ for (const model of google.touchpoints.chat?.models ?? []) {+ expect(canonicalLookup(`google:${model}`), `google:${model} unpriced`).toBeDefined();+ }+ });+});diff --git a/test/doctor-conversation-format-coverage.test.ts b/test/doctor-conversation-format-coverage.test.tsnew file mode 100644index 0000000000..cf0828372b--- /dev/null+++ b/test/doctor-conversation-format-coverage.test.ts@@ -0,0 +1,114 @@+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { computeConversationFormatCoverageCheck } from '../src/commands/doctor.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++/** A summary-only page: headings + short bullets, no transcript shape.+ * Mirrors the seven pages observed in #4193 (5-30 nonblank lines). */+const SLACK_SUMMARY_BODY = [+ '## Highlights',+ '',+ '- Shipped the new onboarding flow',+ '- Reviewed the quarterly metrics doc',+ '',+ '## Decisions',+ '',+ '- Move the launch to next week',+ '- Alice owns the follow-up doc',+].join('\n');++/** Transcript-claiming page (explicit `## Transcript` section) whose turn+ * shape no builtin matches — must STILL count as a parser miss. */+const UNSUPPORTED_TRANSCRIPT_BODY = [+ '## Transcript',+ '',+ '9.03.12 -- Alice -- kicking off',+ '9.04.55 -- Bob -- sounds good',+ '9.06.20 -- Alice -- shipping it',+].join('\n');++/** Body matching the builtin `imessage-slack` pattern (its own test_positive shape). */+const SUPPORTED_TRANSCRIPT_BODY = [+ '**Alice Example** (2024-03-15 9:00 AM): hello',+ '**Bob Example** (2024-03-15 9:02 AM): hi there',+ '**Alice Example** (2024-03-15 9:05 AM): shipping it',+].join('\n');++async function seedPage(slug: string, type: string, body: string): Promise<void> {+ await engine.putPage(slug, {+ type,+ title: slug,+ compiled_truth: body,+ timeline: '',+ frontmatter: {},+ });+}++describe('conversation_format_coverage summary-only handling (#4193)', () => {+ test('a slack/meeting summary page (headings + bullets) is not _no_match coverage debt', async () => {+ await seedPage('slack-weekly-summary', 'slack', SLACK_SUMMARY_BODY);+ await seedPage('meeting-standup-notes', 'meeting', SLACK_SUMMARY_BODY);++ const check = await computeConversationFormatCoverageCheck(engine);+ expect(check.name).toBe('conversation_format_coverage');+ expect(check.status).toBe('ok');+ expect(check.message).toContain('_summary_only=2');+ expect(check.message).not.toContain('_no_match');+ });++ test('a transcript-claiming page with an unsupported turn shape still counts as a miss', async () => {+ await seedPage('meeting-odd-transcript', 'meeting', UNSUPPORTED_TRANSCRIPT_BODY);++ const check = await computeConversationFormatCoverageCheck(engine);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('_no_match=1');+ });++ test('supported transcript patterns keep their current results in the denominator', async () => {+ await seedPage('slack-real-transcript', 'slack', SUPPORTED_TRANSCRIPT_BODY);+ await seedPage('slack-weekly-summary', 'slack', SLACK_SUMMARY_BODY);++ const check = await computeConversationFormatCoverageCheck(engine);+ expect(check.status).toBe('ok');+ expect(check.message).toContain('imessage-slack=1');+ expect(check.message).toContain('_summary_only=1');+ });++ test('mixed brain: summaries excluded from the denominator, real misses still warn', async () => {+ // 1 supported + 1 unsupported transcript + 2 summaries.+ // Old math: 3/4 unmatched = 75% -> warn either way, but with summaries+ // wrongly in the numerator. New math: 1/2 transcript-claiming unmatched+ // = 50% -> warn, with the summaries reported separately.+ await seedPage('slack-real-transcript', 'slack', SUPPORTED_TRANSCRIPT_BODY);+ await seedPage('meeting-odd-transcript', 'meeting', UNSUPPORTED_TRANSCRIPT_BODY);+ await seedPage('slack-weekly-summary', 'slack', SLACK_SUMMARY_BODY);+ await seedPage('meeting-standup-notes', 'meeting', SLACK_SUMMARY_BODY);++ const check = await computeConversationFormatCoverageCheck(engine);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('1/2');+ expect(check.message).toContain('_summary_only=2');+ });++ test('no conversation pages -> not-applicable ok', async () => {+ const check = await computeConversationFormatCoverageCheck(engine);+ expect(check.status).toBe('ok');+ expect(check.message).toContain('No conversation-type pages');+ });+});diff --git a/test/doctor-silent-death-checks.test.ts b/test/doctor-silent-death-checks.test.tsindex 850493d86c..90f59d82d6 100644--- a/test/doctor-silent-death-checks.test.ts+++ b/test/doctor-silent-death-checks.test.ts@@ -234,6 +234,14 @@ describe('undeclared_db_only_pages (#2784)', () => {expect(c.message).toContain('life/events/');});+ test('native synthesize_concepts output is implicitly declared', async () => {+ const repo = makeRepo();+ await addSource('src-a', repo);+ await addPage('concepts/generated-theme', { sourceId: 'src-a' });+ const c = await checkUndeclaredDbOnlyPages(engine);+ expect(c.status).toBe('ok');+ });+test('declared db_only prefix in gbrain.yml keeps the check quiet', async () => {const repo = makeRepo();writeFileSync(join(repo, 'gbrain.yml'), 'storage:\n db_only:\n - notes/\n');diff --git a/test/doctor.test.ts b/test/doctor.test.tsindex 49a005d48b..e755bcb3c6 100644--- a/test/doctor.test.ts+++ b/test/doctor.test.ts@@ -1350,12 +1350,17 @@ describe('stub_guard_24h check (v0.34.5)', () => {});describe('v0.40.4 — graph_signals_coverage check', () => {- const { PGLiteEngine } = require('../src/core/pglite-engine.ts');- const { checkGraphSignalsCoverage } = require('../src/commands/doctor.ts');+ // await import, not require: a sync require() of the ESM doctor graph makes+ // Bun's warm transpiler cache parse `with { type: 'file' }` template assets+ // as code (Syntax Error → "module not instantiated" cascade on re-runs).+ let PGLiteEngine: any;+ let checkGraphSignalsCoverage: any;let engine: any;beforeAll(async () => {+ ({ PGLiteEngine } = await import('../src/core/pglite-engine.ts'));+ ({ checkGraphSignalsCoverage } = await import('../src/commands/doctor.ts'));engine = new PGLiteEngine();await engine.connect({ engine: 'pglite' });await engine.initSchema();@@ -1457,12 +1462,15 @@ describe('v0.40.4 — graph_signals_coverage check', () => {// ─── issue #972 — link_resolution_opportunity check ───────────────────────describe('issue #972 — link_resolution_opportunity check', () => {- const { PGLiteEngine } = require('../src/core/pglite-engine.ts');- const { checkLinkResolutionOpportunity } = require('../src/commands/doctor.ts');+ // await import, not require — see graph_signals_coverage describe above.+ let PGLiteEngine: any;+ let checkLinkResolutionOpportunity: any;let engine: any;beforeAll(async () => {+ ({ PGLiteEngine } = await import('../src/core/pglite-engine.ts'));+ ({ checkLinkResolutionOpportunity } = await import('../src/commands/doctor.ts'));engine = new PGLiteEngine();await engine.connect({ engine: 'pglite' });await engine.initSchema();diff --git a/test/e2e/bootstrap-harness-lifecycle.serial.test.ts b/test/e2e/bootstrap-harness-lifecycle.serial.test.tsindex 699705164e..6988557de4 100644--- a/test/e2e/bootstrap-harness-lifecycle.serial.test.ts+++ b/test/e2e/bootstrap-harness-lifecycle.serial.test.ts@@ -52,6 +52,22 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {return { runner, calls };}+ // Harness detection MUST be pinned, not inherited from the host. The+ // production default is Bun.which(), which reads the real password-database+ // HOME and ignores this test's remapped HOME/PATH — so without this seam the+ // suite silently asserts different things depending on which agent CLIs the+ // machine happens to have installed. Concretely: `claude` is on a developer+ // laptop's PATH but absent on a GitHub runner, so the claude lane never ran+ // in CI, no `claude mcp add` was exec'd, and no user-scope settings file was+ // written — failing at lines 175 and 220 every night since 2026-08-17 while+ // passing locally. Both harnesses are declared present here because that is+ // the scenario these assertions describe.+ const HARNESS_DETECT = {+ claude: () => true,+ codex: () => true,+ opencode: () => false,+ } as const;+async function capture<T>(fn: () => Promise<T>): Promise<{ result: T; out: string; err: string }> {const origLog = console.log;const origErr = console.error;@@ -150,7 +166,7 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {const { runner } = makeClaudeRunner();const { result, err } = await withEnv(envFor(), () =>capture(() =>- runBootstrap(['harness', '--yes', '--port', String(PORT), '--harness', 'codex'], { runner }),+ runBootstrap(['harness', '--yes', '--port', String(PORT), '--harness', 'codex'], { runner, harnessDetect: HARNESS_DETECT }),),);expect(result).toBe(1);@@ -170,7 +186,7 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {'--token', token,'--gbrain-bin', '/opt/fake/gbrain',],- { runner },+ { runner, harnessDetect: HARNESS_DETECT },),),);@@ -214,7 +230,7 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {test('--status: live probes, token recovered from the codex block, exit 0', async () => {const { runner } = makeClaudeRunner();const { result, out } = await withEnv(envFor(), () =>- capture(() => runBootstrap(['harness', '--status'], { runner })),+ capture(() => runBootstrap(['harness', '--status'], { runner, harnessDetect: HARNESS_DETECT })),);expect(result).toBe(0);expect(out).toMatch(/serve: OK/);@@ -224,7 +240,7 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {test('--remove: host wiring cleared, codex config byte-identical to pre-apply, receipt consumed', async () => {const { runner } = makeClaudeRunner();const { result } = await withEnv(envFor(), () =>- capture(() => runBootstrap(['harness', '--remove', '--yes'], { runner })),+ capture(() => runBootstrap(['harness', '--remove', '--yes'], { runner, harnessDetect: HARNESS_DETECT })),);expect(result).toBe(0);expect(readFileSync(codexConfig(), 'utf8')).toBe('# preexisting codex config\nmodel = "o5"\n');diff --git a/test/e2e/contextual-retrieval-pglite.test.ts b/test/e2e/contextual-retrieval-pglite.test.tsindex c226b8b50f..ac3f2028dc 100644--- a/test/e2e/contextual-retrieval-pglite.test.ts+++ b/test/e2e/contextual-retrieval-pglite.test.ts@@ -33,6 +33,10 @@ import {resetGateway,} from '../../src/core/ai/gateway.ts';import { MARKDOWN_CHUNKER_VERSION } from '../../src/core/chunkers/recursive.ts';+import { operationsByName } from '../../src/core/operations.ts';+import type { OperationContext } from '../../src/core/operations.ts';+import { runReindex } from '../../src/commands/reindex.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';const STUB_DIMS = 1536;@@ -187,3 +191,106 @@ describe('T9 reindex sweep predicate', () => {expect(rows[0].count).toBeGreaterThanOrEqual(1);});});++describe('per-source CR mode on the import path (#3885)', () => {+ beforeEach(async () => {+ await resetPgliteState(engine);+ });++ async function seedSource(id: string, mode: string): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO sources (id, name, config, contextual_retrieval_mode)+ VALUES ($1, $1, '{}'::jsonb, $2)+ ON CONFLICT (id) DO UPDATE SET contextual_retrieval_mode = EXCLUDED.contextual_retrieval_mode`,+ [id, mode],+ );+ }++ async function pageMode(slug: string, sourceId: string): Promise<string | null> {+ const rows = await engine.executeRaw<{ mode: string | null }>(+ `SELECT contextual_retrieval_mode AS mode FROM pages WHERE slug = $1 AND source_id = $2`,+ [slug, sourceId],+ );+ return rows[0]?.mode ?? null;+ }++ function putPageCtx(sourceId: string): OperationContext {+ return {+ engine,+ config: { engine: 'pglite' as const },+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: false,+ sourceId,+ };+ }++ test('importFromContent honors sources.set-cr-mode=none over global title', async () => {+ const sourceId = 'src-none-import';+ await seedSource(sourceId, 'none');+ const slug = 'wiki/concepts/source-none-import';+ await importFromContent(+ engine,+ slug,+ '---\ntitle: "Source None"\n---\n\nBody that must not wrap.',+ { sourceId },+ );++ expect(await pageMode(slug, sourceId)).toBe('none');+ const wrapped = embedderInputs.flat();+ expect(wrapped.length).toBeGreaterThan(0);+ expect(wrapped[0]).not.toContain('<context>');+ });++ test('put_page (capture write path) honors per-source none', async () => {+ const sourceId = 'src-none-capture';+ await seedSource(sourceId, 'none');+ const slug = 'inbox/source-none-capture';+ const result = await operationsByName['put_page']!.handler(putPageCtx(sourceId), {+ slug,+ content: '---\ntitle: "Capture None"\n---\n\nCaptured body for CR source override.',+ });+ expect(['imported', 'created_or_updated']).toContain((result as { status: string }).status);+ expect(await pageMode(slug, sourceId)).toBe('none');+ expect(embedderInputs.flat()[0]).not.toContain('<context>');+ });++ test('reindex --markdown honors per-source none', async () => {+ const sourceId = 'src-none-reindex';+ await seedSource(sourceId, 'none');+ const slug = 'wiki/concepts/source-none-reindex';+ await engine.executeRaw(+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth, chunker_version, contextual_retrieval_mode)+ VALUES ($1, $2, 'concept', 'Reindex None', 'Body that must not wrap after markdown reindex.', 1, NULL)`,+ [sourceId, slug],+ );++ const result = await runReindex(engine, ['--markdown', '--json', '--limit', '10']);+ expect(result.reindexed).toBeGreaterThanOrEqual(1);+ expect(await pageMode(slug, sourceId)).toBe('none');+ const wrapped = embedderInputs.flat();+ expect(wrapped.length).toBeGreaterThan(0);+ expect(wrapped.every((text) => !text.includes('<context>'))).toBe(true);+ });++ test('source per_chunk_synopsis beats global conservative (inline demotes to title wrap)', async () => {+ const sourceId = 'src-synopsis-import';+ await seedSource(sourceId, 'per_chunk_synopsis');+ await engine.setConfig('search.mode', 'conservative');+ try {+ const slug = 'wiki/concepts/source-synopsis-import';+ await importFromContent(+ engine,+ slug,+ '---\ntitle: "Source Synopsis"\n---\n\nBody that should wrap at the title tier.',+ { sourceId },+ );+ // Inline import refuses paid synopsis generation; it must still SEE the+ // source override and land at title instead of global none.+ expect(await pageMode(slug, sourceId)).toBe('title');+ expect(embedderInputs.flat()[0]).toContain('<context>Source Synopsis');+ } finally {+ await engine.setConfig('search.mode', 'balanced');+ }+ });+});diff --git a/test/e2e/facts-separation-postgres.test.ts b/test/e2e/facts-separation-postgres.test.tsindex fe719386d0..ecb59a34ed 100644--- a/test/e2e/facts-separation-postgres.test.ts+++ b/test/e2e/facts-separation-postgres.test.ts@@ -184,4 +184,28 @@ d("Cross-session recall test (Postgres)", () => {expect(bySession.some(r => r.fact === 'EXTRACTION_COMPLETE' && r.source === 'test')).toBe(true);expect(bySession.some(r => r.fact === 'real fact under the same entity/session (pg)')).toBe(true);});++ test('unconsolidatedOnly filters before the result limit on real Postgres', async () => {+ const engine = getEngine();+ const entitySlug = 'consolidation-filter-postgres';+ const pending = await engine.insertFact(+ { fact: 'still pending', kind: 'fact', entity_slug: entitySlug, source: 'test' },+ { source_id: 'default' },+ );+ const consolidated = await engine.insertFact(+ { fact: 'already consolidated', kind: 'fact', entity_slug: entitySlug, source: 'test' },+ { source_id: 'default' },+ );+ await engine.executeRaw(+ `UPDATE facts SET consolidated_at = now() WHERE id = $1`,+ [consolidated.id],+ );++ const rows = await engine.listFactsByEntity('default', entitySlug, {+ unconsolidatedOnly: true,+ limit: 1,+ });++ expect(rows.map(f => f.id)).toEqual([pending.id]);+ });});diff --git a/test/e2e/salience-anomalies-source-isolation-pglite.test.ts b/test/e2e/salience-anomalies-source-isolation-pglite.test.tsnew file mode 100644index 0000000000..490e3cb618--- /dev/null+++ b/test/e2e/salience-anomalies-source-isolation-pglite.test.ts@@ -0,0 +1,127 @@+/**+ * Source-isolation regression for the v0.29 read ops the #861 (v0.34.1) sweep+ * missed: get_recent_salience and find_anomalies. Both are scope:'read' and+ * reachable over MCP, yet pre-fix ignored the caller's source scope entirely —+ * a source-bound OAuth client could read salient pages and anomaly cohorts from+ * every source in the brain. (get_recent_transcripts is NOT covered: it is+ * localOnly + remote-gated, so it's fail-closed to remote callers by design.)+ *+ * Runs against PGLite in-memory (exercises both engines' parity surface).+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';++let engine: PGLiteEngine;++// A minimal remote ctx for driving op handlers directly (matches the+// source-isolation-pglite regression's dispatcher simulation).+function ctxFor(scope: { sourceId?: string; allowedSources?: string[] }) {+ return {+ engine,+ config: { engine: 'pglite' as const },+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: true,+ sourceId: scope.sourceId,+ ...(scope.allowedSources+ ? { auth: { token: 't', clientId: 't', scopes: ['read'], allowedSources: scope.allowedSources } }+ : {}),+ } as never;+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ // 'default' is seeded by initSchema; add src-b.+ await engine.executeRaw(+ `INSERT INTO sources (id, name, config) VALUES ('src-b', 'src-b', '{}'::jsonb) ON CONFLICT DO NOTHING`,+ );++ // Same slug in both sources — proves filtering is on source_id, not slug.+ await engine.putPage('people/alice', { type: 'person', title: 'Alice A', compiled_truth: 'A' }, { sourceId: 'default' });+ await engine.putPage('people/alice', { type: 'person', title: 'Alice B', compiled_truth: 'B' }, { sourceId: 'src-b' });++ // 3 default pages tagged `spikea`, 3 src-b pages tagged `spikeb`, all touched+ // today. Empty baseline (no history in the lookback window) + count > 1 makes+ // each tag cohort fire the zero-baseline anomaly branch, scoped to its source.+ for (let i = 0; i < 3; i++) {+ await engine.putPage(`notes/a-${i}`, { type: 'note', title: `A note ${i}`, compiled_truth: 'x' }, { sourceId: 'default' });+ await engine.addTag(`notes/a-${i}`, 'spikea', { sourceId: 'default' });+ await engine.putPage(`notes/b-${i}`, { type: 'note', title: `B note ${i}`, compiled_truth: 'y' }, { sourceId: 'src-b' });+ await engine.addTag(`notes/b-${i}`, 'spikeb', { sourceId: 'src-b' });+ }+}, 30_000); // PGLite initSchema + seeding exceeds the default 5s hook timeout++afterAll(async () => {+ if (engine) await engine.disconnect();+});++describe('get_recent_salience source isolation', () => {+ test('sourceId=default excludes src-b rows (incl. the shared slug)', async () => {+ const rows = await engine.getRecentSalience({ days: 30, limit: 100, sourceId: 'default' });+ expect(rows.length).toBeGreaterThan(0);+ for (const r of rows) expect(r.source_id).toBe('default');+ // The shared slug resolves to the default page, never src-b's.+ expect(rows.find((r) => r.title === 'Alice B')).toBeUndefined();+ });++ test('sourceId=src-b excludes default rows', async () => {+ const rows = await engine.getRecentSalience({ days: 30, limit: 100, sourceId: 'src-b' });+ expect(rows.length).toBeGreaterThan(0);+ for (const r of rows) expect(r.source_id).toBe('src-b');+ });++ test('sourceIds=[default,src-b] returns the union', async () => {+ const rows = await engine.getRecentSalience({ days: 30, limit: 100, sourceIds: ['default', 'src-b'] });+ const sources = new Set(rows.map((r) => r.source_id));+ expect(sources.has('default')).toBe(true);+ expect(sources.has('src-b')).toBe(true);+ });++ test('no source scope returns all sources (trusted local unchanged)', async () => {+ const rows = await engine.getRecentSalience({ days: 30, limit: 100 });+ expect(new Set(rows.map((r) => r.source_id)).size).toBeGreaterThanOrEqual(2);+ });++ test('op handler threads ctx.sourceId through sourceScopeOpts', async () => {+ const { operations } = await import('../../src/core/operations.ts');+ const op = operations.find((o) => o.name === 'get_recent_salience')!;+ const rows = (await op.handler(ctxFor({ sourceId: 'src-b' }), { days: 30, limit: 100 })) as Array<{ source_id: string }>;+ expect(rows.length).toBeGreaterThan(0);+ for (const r of rows) expect(r.source_id).toBe('src-b');+ });+});++describe('find_anomalies source isolation', () => {+ const slugsOf = (rows: Array<{ page_slugs: string[] }>) => rows.flatMap((r) => r.page_slugs);++ test('sourceId=default surfaces only default cohorts/slugs', async () => {+ const rows = await engine.findAnomalies({ sourceId: 'default' });+ expect(rows.find((r) => r.cohort_value === 'spikea')).toBeDefined();+ expect(rows.find((r) => r.cohort_value === 'spikeb')).toBeUndefined();+ for (const s of slugsOf(rows)) expect(s.startsWith('notes/b-')).toBe(false);+ });++ test('sourceId=src-b surfaces only src-b cohorts/slugs', async () => {+ const rows = await engine.findAnomalies({ sourceId: 'src-b' });+ expect(rows.find((r) => r.cohort_value === 'spikeb')).toBeDefined();+ expect(rows.find((r) => r.cohort_value === 'spikea')).toBeUndefined();+ for (const s of slugsOf(rows)) expect(s.startsWith('notes/a-')).toBe(false);+ });++ test('sourceIds=[default,src-b] surfaces both cohorts', async () => {+ const rows = await engine.findAnomalies({ sourceIds: ['default', 'src-b'] });+ expect(rows.find((r) => r.cohort_value === 'spikea')).toBeDefined();+ expect(rows.find((r) => r.cohort_value === 'spikeb')).toBeDefined();+ });++ test('op handler threads ctx.sourceId through sourceScopeOpts', async () => {+ const { operations } = await import('../../src/core/operations.ts');+ const op = operations.find((o) => o.name === 'find_anomalies')!;+ const rows = (await op.handler(ctxFor({ sourceId: 'src-b' }), {})) as Array<{ cohort_value: string; page_slugs: string[] }>;+ expect(rows.find((r) => r.cohort_value === 'spikea')).toBeUndefined();+ for (const s of rows.flatMap((r) => r.page_slugs)) expect(s.startsWith('notes/a-')).toBe(false);+ });+});diff --git a/test/e2e/serve-stdio-roundtrip.test.ts b/test/e2e/serve-stdio-roundtrip.test.tsindex 8c9459cece..a8b3297736 100644--- a/test/e2e/serve-stdio-roundtrip.test.ts+++ b/test/e2e/serve-stdio-roundtrip.test.ts@@ -36,6 +36,7 @@ import { VERB_NAMES } from '../../src/core/verbs.ts';// Distinctive token so keyword search can't accidentally match anything else.const MARKER = 'qantani-marker-9f3z';+const FEDERATED_MARKER = 'umbriel-federated-marker-71c4';function textOf(result: unknown): string {const content = (result as { content?: Array<{ type?: string; text?: string }> })?.content;@@ -43,6 +44,11 @@ function textOf(result: unknown): string {return content.map((c) => (typeof c?.text === 'string' ? c.text : '')).join('\n');}+function resultSourceIds(text: string): string[] {+ const result = JSON.parse(text) as Array<{ source_id?: unknown }>;+ return result.flatMap((row) => (typeof row.source_id === 'string' ? [row.source_id] : []));+}+describe('serve stdio round-trip E2E (local PGLite → real MCP tool calls)', () => {let home: string;let client: Client | null = null;@@ -62,6 +68,7 @@ describe('serve stdio round-trip E2E (local PGLite → real MCP tool calls)', ()env.GBRAIN_HOME = home;delete env.DATABASE_URL;delete env.GBRAIN_DATABASE_URL;+ delete env.GBRAIN_SOURCE;// 1. Init a local PGLite brain (the "from nothing" step).execFileSync('bun', ['run', 'src/cli.ts', 'init', '--pglite', '--no-embedding', '--non-interactive'], {@@ -81,6 +88,26 @@ describe('serve stdio round-trip E2E (local PGLite → real MCP tool calls)', ()cwd: process.cwd(), env, stdio: 'ignore',});+ // Seed a second source that participates in unqualified federated reads.+ // Import through the CLI so this uses the ordinary source registration+ // and page-routing path.+ const federatedNotes = join(home, 'federated-notes');+ mkdirSync(federatedNotes, { recursive: true });+ writeFileSync(+ join(federatedNotes, 'marker.md'),+ `---\ntitle: ${FEDERATED_MARKER} note\n---\n\n# ${FEDERATED_MARKER}\n\nThis page exists only in the federated source.\n`,+ );+ execFileSync(+ 'bun',+ ['run', 'src/cli.ts', 'sources', 'add', 'federated-source', '--path', federatedNotes, '--federated', '--force'],+ { cwd: process.cwd(), env, stdio: 'ignore' },+ );+ execFileSync(+ 'bun',+ ['run', 'src/cli.ts', 'import', federatedNotes, '--no-embed', '--source-id', 'federated-source'],+ { cwd: process.cwd(), env, stdio: 'ignore' },+ );+// 3. Let the MCP SDK spawn `gbrain serve` (stdio) and run the initialize// handshake — exactly what `claude mcp add gbrain -- gbrain serve` does.transport = new StdioClientTransport({@@ -131,6 +158,28 @@ describe('serve stdio round-trip E2E (local PGLite → real MCP tool calls)', ()// The result payload (slug / title / snippet) must mention the marker.expect(text).toContain(MARKER);}, 30_000);++ test('query treats an explicit __all__ like an omitted source in federated stdio', async () => {+ expect(connected).toBe(true);+ const args = { query: FEDERATED_MARKER, expand: false, limit: 5 };++ const omitted = textOf(await client!.callTool({ name: 'query', arguments: args }));+ const explicitAll = textOf(await client!.callTool({+ name: 'query',+ arguments: { ...args, source_id: '__all__' },+ }));+ const explicitDefault = textOf(await client!.callTool({+ name: 'query',+ arguments: { ...args, source_id: 'default' },+ }));++ expect(omitted).toContain(FEDERATED_MARKER);+ expect(explicitAll).toContain(FEDERATED_MARKER);+ expect(explicitDefault).not.toContain(FEDERATED_MARKER);+ expect(resultSourceIds(omitted)).toContain('federated-source');+ expect(resultSourceIds(explicitAll)).toContain('federated-source');+ expect(resultSourceIds(explicitDefault)).not.toContain('federated-source');+ }, 30_000);});// Distinct marker for the verbs-surface session (own temp brain, own token).diff --git a/test/e2e/sync-reconcile-postgres.test.ts b/test/e2e/sync-reconcile-postgres.test.tsnew file mode 100644index 0000000000..45df5381a4--- /dev/null+++ b/test/e2e/sync-reconcile-postgres.test.ts@@ -0,0 +1,169 @@+/**+ * #3583 — the rename reconcile against REAL PostgreSQL.+ *+ * The reconcile resolves its candidates through `engine.executeRaw` with a+ * slug-array binding (`= ANY($1::text[])`), which on this engine goes+ * through postgres.js `unsafe()`. Every other test for this feature runs on+ * PGLite, where that binding cannot fail the way it can on the real driver+ * — the review named exactly this as inferred rather than executed. These+ * tests exercise the reconcile end to end on Postgres: the stale row goes,+ * the live row sharing its `source_path` stays, and an orphaned+ * `<rename:…>` sentinel self-heals on a quiet run.+ *+ * Requires DATABASE_URL (skipped otherwise, like every e2e file here).+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { setupDB, teardownDB, hasDatabase } from './helpers.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { execSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const skip = !hasDatabase();+const describeIfDB = skip ? describe.skip : describe;++let engine: PostgresEngine;+const repos: string[] = [];+let tmpHome: string | undefined;+const originalGbrainHome = process.env.GBRAIN_HOME;++beforeAll(async () => {+ if (skip) return;+ engine = (await setupDB()) as PostgresEngine;+});++afterAll(async () => {+ if (skip) return;+ if (originalGbrainHome !== undefined) process.env.GBRAIN_HOME = originalGbrainHome;+ else delete process.env.GBRAIN_HOME;+ while (repos.length) {+ const d = repos.pop();+ if (d) rmSync(d, { recursive: true, force: true });+ }+ await teardownDB();+});++beforeEach(async () => {+ if (skip) return;+ // The failure ledger lives under the gbrain home — isolate it per test so+ // a sentinel planted here never touches the operator's real ledger.+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-3583-pg-home-'));+ process.env.GBRAIN_HOME = tmpHome;+ await engine.executeRaw(`DELETE FROM pages WHERE source_id = 'default'`);+ // local_path must reset too: each test mkRepo()s a fresh directory, and the+ // v0.46.25.0 registered-directory guard refuses to advance last_commit for+ // a repo that is neither the registered dir nor within its tree — leaving+ // the second test's quiet run at 'first_sync' instead of 'up_to_date'.+ // (Latent since authoring: this file skips without DATABASE_URL, so the+ // guard interaction never fired until a real-Postgres run.)+ await engine.executeRaw(+ `UPDATE sources SET last_sync_at = NULL, last_commit = NULL, local_path = NULL WHERE id = 'default'`,+ );+});++function personMd(title: string, body: string): string {+ return ['---', 'type: person', `title: ${title}`, '---', '', body].join('\n');+}++function mkRepo(files: Record<string, string>): string {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-3583-pg-'));+ repos.push(dir);+ execSync('git init', { cwd: dir, stdio: 'pipe' });+ execSync('git config user.email "[email protected]"', { cwd: dir, stdio: 'pipe' });+ execSync('git config user.name "Test"', { cwd: dir, stdio: 'pipe' });+ for (const [rel, content] of Object.entries(files)) {+ mkdirSync(join(dir, rel, '..'), { recursive: true });+ writeFileSync(join(dir, rel), content);+ }+ execSync('git add -A && git commit -m "initial"', { cwd: dir, stdio: 'pipe' });+ return dir;+}++const SYNC_OPTS = { noPull: true, noEmbed: true, noExtract: true, sourceId: 'default' } as const;++describeIfDB('#3583: rename reconcile on PostgreSQL', () => {+ test('occupied-destination rename: the stale row goes, the live row sharing its path stays', async () => {+ const { performSync } = await import('../../src/commands/sync.ts');+ // The blocker-1 shape on the real driver: a live row carries an OLD+ // source_path, a new file reoccupies that path, and a later rename of it+ // into an occupied destination falls back to add + reconcile. The+ // reconcile's active-row resolve binds the path array through+ // executeRaw — the exact statement the review could not execute.+ const repo = mkRepo({ 'people/alpha.md': personMd('Alpha', 'Alpha the original.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "cheap rename"', { cwd: repo, stdio: 'pipe' });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('people/beta')).not.toBeNull();++ // Put the row into the stale-bookkeeping state deliberately. The cheap+ // rename above repairs source_path, so this shape is not what a rename+ // leaves behind TODAY — it is what a row renamed before that repair+ // existed still carries, and it is the shape the reconcile must not+ // delete. Set it explicitly rather than relying on the rename to+ // produce it: without this the row is not even a candidate, and the+ // live-row assertion below passes with liveness protection disabled+ // (adversarial review).+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/beta'`,+ );+ const betaRows = await engine.executeRaw<{ source_path: string | null }>(+ `SELECT source_path FROM pages WHERE source_id = 'default' AND slug = 'people/beta'`,+ );+ expect(betaRows).toHaveLength(1);+ expect(betaRows[0].source_path).toBe('people/alpha.md');++ // A NEW unrelated file at the old path…+ writeFileSync(join(repo, 'people/alpha.md'), personMd('Alpha Two', 'A different Alpha.'));+ execSync('git add -A && git commit -m "new alpha"', { cwd: repo, stdio: 'pipe' });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ // …renamed into an OCCUPIED destination (gamma pre-exists), forcing the+ // fallback-to-add + reconcile path.+ await engine.putPage('people/gamma', {+ type: 'person', title: 'Gamma (occupant)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/gamma.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename into occupied destination"', { cwd: repo, stdio: 'pipe' });+ const run = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(run.status).toBe('synced');++ // The destination carries the renamed file's content, the stale duplicate+ // is gone, and — the review's blocker-1 assertion — the LIVE beta row+ // survives even though its bookkeeping still names the old path: a+ // tracked file (people/beta.md) derives to its slug, so it is live.+ const gamma = await engine.getPage('people/gamma');+ expect(gamma).not.toBeNull();+ expect(gamma!.compiled_truth).toContain('A different Alpha.');+ expect(await engine.getPage('people/alpha')).toBeNull();+ expect(await engine.getPage('people/beta')).not.toBeNull();+ }, 300_000);++ test('an orphaned rename sentinel self-heals on a quiet run', async () => {+ const { performSync } = await import('../../src/commands/sync.ts');+ const { recordFailures, renameSentinelPath, renameReconcileErrorMessage, loadSyncFailures } =+ await import('../../src/core/sync-failure-ledger.ts');+ // Blocker 2's sibling path on the real driver: the orphan probe resolves+ // "any active row still carrying this path?" through the same array+ // binding, and a clear must only happen when the answer is provably no.+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ recordFailures('default', [{+ path: renameSentinelPath('people/dana.md'),+ error: renameReconcileErrorMessage('people/dana-old.md', 'people/dana-old', 'injected wedge'),+ }], 'deadbeef');+ const open = () => loadSyncFailures().filter(+ f => f.path === '<rename:people/dana.md>' && f.state === 'open',+ );+ expect(open()).toHaveLength(1);++ const quiet = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(quiet.status).toBe('up_to_date');+ expect(open()).toHaveLength(0);+ }, 300_000);+});diff --git a/test/e2e/system-of-record-invariant.test.ts b/test/e2e/system-of-record-invariant.test.tsindex 89399687e4..98ee30ad39 100644--- a/test/e2e/system-of-record-invariant.test.ts+++ b/test/e2e/system-of-record-invariant.test.ts@@ -43,6 +43,8 @@ import { runExtractCore } from '../../src/commands/extract.ts';import { extractTakes } from '../../src/core/cycle/extract-takes.ts';import { runExtractFacts } from '../../src/core/cycle/extract-facts.ts';import { parseFactsFence, stripFactsFence } from '../../src/core/facts-fence.ts';+import { operationsByName } from '../../src/core/operations.ts';+import type { OperationContext } from '../../src/core/operations.ts';let engine: PGLiteEngine;let brainDir: string;@@ -345,6 +347,117 @@ ${remoteBody}`, { noEmbed: true, sourceId: 'default', remote: true });expect(after?.compiled_truth).toContain('PRIVATE_ONLY_FACT');expect(parseFactsFence(after?.compiled_truth ?? '').facts).toHaveLength(1);});++ // #3625 escalation: splitBody() routes a `## Facts` fence placed below the+ // timeline sentinel into page.timeline instead of compiled_truth. The+ // get_page strip trigger above only covered compiled_truth, so an+ // untrusted remote caller could read a private fence row verbatim via the+ // `timeline` field. Exercises the real get_page operation handler (not+ // just the stripFactsFence helper) with ctx.remote=true.+ test('a below-sentinel facts fence in page.timeline is stripped for untrusted remote readers too', async () => {+ const slug = 'people/timeline-fence-leak';+ await engine.putPage(slug, {+ title: 'Timeline Fence Leak',+ type: 'person',+ compiled_truth: '# Timeline Fence Leak\n\nSome text.\n\n<!-- timeline -->\n',+ frontmatter: {},+ timeline: `## Facts++<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | WORLD_TIMELINE_ROW | fact | 1.0 | world | high | 2026-01-01 | | s | |+| 2 | PRIVATE_TIMELINE_ROW | fact | 1.0 | private | high | 2026-01-01 | | s | |+<!--- gbrain:facts:end -->+`,+ });++ const ctx = { engine, remote: true, sourceId: 'default' } as unknown as OperationContext;+ const remote = await operationsByName.get_page.handler(ctx, { slug }) as { timeline?: string };+ expect(remote.timeline).toContain('WORLD_TIMELINE_ROW');+ expect(remote.timeline).not.toContain('PRIVATE_TIMELINE_ROW');++ // Local CLI callers still see the full fence, unaffected by the strip.+ const local = await operationsByName.get_page.handler(+ { engine, remote: false, sourceId: 'default' } as unknown as OperationContext,+ { slug },+ ) as { timeline?: string };+ expect(local.timeline).toContain('PRIVATE_TIMELINE_ROW');+ });++ // #3625, real splitBody() path (not a hand-built post-split fixture): a+ // page authored with the `## Facts` fence below `<!-- timeline -->` — the+ // LLM-composed shape the issue describes — imported through the actual+ // production write path (importFromContent → parseMarkdown → splitBody).+ test('a fence written below the sentinel really does land in page.timeline via splitBody, and extract_facts preserves the existing index instead of wiping it', async () => {+ const slug = 'people/real-split-fence';+ const fenceRows = `| 1 | REAL_SPLIT_FACT | fact | 1.0 | world | high | 2026-01-01 | | s | |`;++ // v1: fence correctly placed above the sentinel — reconciles normally.+ await importFromContent(engine, slug, `---+type: person+title: Real Split Fence+slug: ${slug}+---++# Real Split Fence++## Facts++<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+${fenceRows}+<!--- gbrain:facts:end -->++<!-- timeline -->+`, { noEmbed: true, sourceId: 'default' });++ const seeded = await engine.getPage(slug, { sourceId: 'default' });+ expect(seeded?.compiled_truth).toContain('gbrain:facts:begin');+ await runExtractFacts(engine, { slugs: [slug] });+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const seededRows = await (engine as any).db.query(+ `SELECT fact FROM facts WHERE source_markdown_slug = $1`, [slug],+ );+ expect(seededRows.rows.map((r: { fact: string }) => r.fact)).toEqual(['REAL_SPLIT_FACT']);++ // v2: same fence, moved below the sentinel — the LLM-composed shape.+ await importFromContent(engine, slug, `---+type: person+title: Real Split Fence+slug: ${slug}+---++# Real Split Fence++<!-- timeline -->++## Facts++<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+${fenceRows}+<!--- gbrain:facts:end -->+`, { noEmbed: true, sourceId: 'default' });++ // Prove splitBody really did route it to timeline, not compiled_truth —+ // the premise this whole fix rests on.+ const moved = await engine.getPage(slug, { sourceId: 'default' });+ expect(moved?.compiled_truth ?? '').not.toContain('gbrain:facts:begin');+ expect(moved?.timeline ?? '').toContain('gbrain:facts:begin');++ const r = await runExtractFacts(engine, { slugs: [slug] });+ expect(r.warnings.some(w => w.includes('FACTS_FENCE_BELOW_SENTINEL'))).toBe(true);+ expect(r.factsDeleted).toBe(0);++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const afterRows = await (engine as any).db.query(+ `SELECT fact FROM facts WHERE source_markdown_slug = $1`, [slug],+ );+ expect(afterRows.rows.map((r: { fact: string }) => r.fact)).toEqual(['REAL_SPLIT_FACT']);+ });});afterAll(() => {diff --git a/test/e2e/think-trajectory-pglite.test.ts b/test/e2e/think-trajectory-pglite.test.tsindex 6804a6b0d3..37fa4911db 100644--- a/test/e2e/think-trajectory-pglite.test.ts+++ b/test/e2e/think-trajectory-pglite.test.ts@@ -140,6 +140,7 @@ describe('e2e/think-trajectory: temporal intent end-to-end', () => {const { client, captured } = captureClient();const result = await runThink(engine, {+ remote: false,question: 'When did Marco last switch jobs?',client,});@@ -164,6 +165,7 @@ describe('e2e/think-trajectory: temporal intent end-to-end', () => {const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'What is the current role for marco?',client,});@@ -182,6 +184,7 @@ describe('e2e/think-trajectory: other intent short-circuits', () => {const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'Summarize the company',client,});@@ -201,6 +204,7 @@ describe('e2e/think-trajectory: kill switch via think.trajectory_enabled', () =>const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'When did Marco last switch jobs?',client,});@@ -218,6 +222,7 @@ describe('e2e/think-trajectory: empty brain (no facts) graceful no-op', () => {const { client, captured } = captureClient();const result = await runThink(engine, {+ remote: false,question: 'When did Marco last switch jobs?',client,});@@ -235,6 +240,7 @@ describe('e2e/think-trajectory: multi-entity ordering deterministic', () => {// Question references both Marco and Acme — both have facts.await runThink(engine, {+ remote: false,question: 'when did marco at acme last change roles',client,});@@ -273,6 +279,7 @@ describe('e2e/think-trajectory: prompt sanitization end-to-end', () => {const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'When did I meet eve?',client,});diff --git a/test/engine-find-trajectory.test.ts b/test/engine-find-trajectory.test.tsindex 4415c4a4ba..58fc8a79d9 100644--- a/test/engine-find-trajectory.test.ts+++ b/test/engine-find-trajectory.test.ts@@ -108,7 +108,7 @@ describe('findTrajectory — chronological ordering (R3)', () => {const idJan = await insertTyped({ entity_slug: 'traj-order', metric: 'mrr', value: 50000, valid_from: new Date('2026-01-15') });const idApr = await insertTyped({ entity_slug: 'traj-order', metric: 'mrr', value: 200000, valid_from: new Date('2026-04-12') });- const points = await engine.findTrajectory({ entitySlug: 'traj-order' });+ const points = await engine.findTrajectory({ entitySlug: 'traj-order', remote: false });expect(points.map(p => p.fact_id)).toEqual([idJan, idApr, idJul]);expect(points[0].valid_from.toISOString().slice(0, 10)).toBe('2026-01-15');expect(points[2].valid_from.toISOString().slice(0, 10)).toBe('2026-07-08');@@ -120,11 +120,11 @@ describe('findTrajectory — source scoping (D-CDX-6)', () => {await insertTyped({ source_id: 'traj-src-A', entity_slug: 'traj-srcscope', metric: 'mrr', value: 50000, valid_from: new Date('2026-01-15') });await insertTyped({ source_id: 'traj-src-B', entity_slug: 'traj-srcscope', metric: 'mrr', value: 99999, valid_from: new Date('2026-01-15') });- const pointsA = await engine.findTrajectory({ entitySlug: 'traj-srcscope', sourceId: 'traj-src-A' });+ const pointsA = await engine.findTrajectory({ entitySlug: 'traj-srcscope', sourceId: 'traj-src-A', remote: false });expect(pointsA.length).toBe(1);expect(pointsA[0].value).toBe(50000);- const pointsB = await engine.findTrajectory({ entitySlug: 'traj-srcscope', sourceId: 'traj-src-B' });+ const pointsB = await engine.findTrajectory({ entitySlug: 'traj-srcscope', sourceId: 'traj-src-B', remote: false });expect(pointsB.length).toBe(1);expect(pointsB[0].value).toBe(99999);});@@ -137,6 +137,7 @@ describe('findTrajectory — source scoping (D-CDX-6)', () => {const points = await engine.findTrajectory({entitySlug: 'traj-fed',sourceIds: ['traj-src-A', 'traj-src-B'],+ remote: false,});// Two of three sources visible, in chronological order.expect(points.length).toBe(2);@@ -157,13 +158,16 @@ describe('findTrajectory — visibility filter (D-CDX-1 / R6)', () => {expect(remote[0].value).toBe(99999);});- test('remote default (undefined) is treated as trusted — sees both', async () => {+ test('FAIL-CLOSED: remote default (undefined) is world-only — private rows hidden', async () => {await insertTyped({ entity_slug: 'traj-vis-default', metric: 'mrr', value: 50000, visibility: 'private', valid_from: new Date('2026-01-15') });await insertTyped({ entity_slug: 'traj-vis-default', metric: 'mrr', value: 99999, visibility: 'world', valid_from: new Date('2026-04-12') });- // No `remote` field — engine default must be trusted.- const all = await engine.findTrajectory({ entitySlug: 'traj-vis-default' });- expect(all.length).toBe(2);+ // No `remote` field — fail-closed: an omitted flag (cast-bypassed+ // context, forgotten threading) must degrade to world-only, never leak+ // private rows.+ const worldOnly = await engine.findTrajectory({ entitySlug: 'traj-vis-default' });+ expect(worldOnly.length).toBe(1);+ expect(worldOnly[0].value).toBe(99999);});});@@ -172,7 +176,7 @@ describe('findTrajectory — metric + since + until filters', () => {await insertTyped({ entity_slug: 'traj-m', metric: 'mrr', value: 50000, valid_from: new Date('2026-01-15') });await insertTyped({ entity_slug: 'traj-m', metric: 'arr', value: 600000, valid_from: new Date('2026-01-15') });- const mrrOnly = await engine.findTrajectory({ entitySlug: 'traj-m', metric: 'mrr' });+ const mrrOnly = await engine.findTrajectory({ entitySlug: 'traj-m', metric: 'mrr', remote: false });expect(mrrOnly.length).toBe(1);expect(mrrOnly[0].metric).toBe('mrr');});@@ -186,6 +190,7 @@ describe('findTrajectory — metric + since + until filters', () => {entitySlug: 'traj-w',since: '2026-02-01',until: '2026-05-01',+ remote: false,});expect(inWindow.length).toBe(1);expect(inWindow[0].value).toBe(99999);diff --git a/test/engine-parity-event-type.test.ts b/test/engine-parity-event-type.test.tsindex 174b6d051e..e535816edc 100644--- a/test/engine-parity-event-type.test.ts+++ b/test/engine-parity-event-type.test.ts@@ -51,7 +51,7 @@ describe('PGLite — facts.event_type round-trip', () => {`);// kind: 'all' (default) returns all three- const all = await engine.findTrajectory({ entitySlug: 'people/alice' });+ const all = await engine.findTrajectory({ entitySlug: 'people/alice', remote: false });expect(all.length).toBe(3);// Find the event row and assert event_type round-trips@@ -78,6 +78,7 @@ describe('PGLite — facts.event_type round-trip', () => {const points = await engine.findTrajectory({entitySlug: 'people/alice',kind: 'metric',+ remote: false,});expect(points.length).toBe(1);expect(points[0].metric).toBe('mrr');@@ -88,6 +89,7 @@ describe('PGLite — facts.event_type round-trip', () => {const points = await engine.findTrajectory({entitySlug: 'people/alice',kind: 'event',+ remote: false,});expect(points.length).toBe(1);expect(points[0].metric).toBeNull();@@ -98,14 +100,15 @@ describe('PGLite — facts.event_type round-trip', () => {const explicit = await engine.findTrajectory({entitySlug: 'people/alice',kind: 'all',+ remote: false,});- const implicit = await engine.findTrajectory({ entitySlug: 'people/alice' });+ const implicit = await engine.findTrajectory({ entitySlug: 'people/alice', remote: false });expect(explicit.length).toBe(implicit.length);expect(explicit.length).toBe(3);});test('chronological ordering preserved when mixed metric + event rows', async () => {- const points = await engine.findTrajectory({ entitySlug: 'people/alice' });+ const points = await engine.findTrajectory({ entitySlug: 'people/alice', remote: false });expect(points.length).toBe(3);// 2026-01-01 → 2026-02-15 → 2026-03-01expect(points[0].valid_from.toISOString().slice(0, 10)).toBe('2026-01-01');@@ -119,6 +122,7 @@ describe('PGLite — facts.event_type round-trip', () => {const points = await engine.findTrajectory({entitySlug: 'people/alice',metric: 'mrr',+ remote: false,});expect(points.length).toBe(1);expect(points[0].metric).toBe('mrr');diff --git a/test/eval-takes-quality-pricing.test.ts b/test/eval-takes-quality-pricing.test.tsindex 73b25bddcd..c6df343442 100644--- a/test/eval-takes-quality-pricing.test.ts+++ b/test/eval-takes-quality-pricing.test.ts@@ -13,7 +13,7 @@ describe('getPricing — fail-closed contract', () => {test('returns pricing for the default 3-model panel', () => {expect(getPricing('openai:gpt-5.2')).toBeDefined();expect(getPricing('anthropic:claude-opus-4-7')).toBeDefined();- expect(getPricing('google:gemini-2.0-flash')).toBeDefined();+ expect(getPricing('google:gemini-2.5-flash')).toBeDefined();});test('retired google:gemini-1.5-pro is no longer in the allowlist (#3510)', () => {diff --git a/test/eval-takes-quality-runner.serial.test.ts b/test/eval-takes-quality-runner.serial.test.tsindex 1d565d9b1d..2846e38eb5 100644--- a/test/eval-takes-quality-runner.serial.test.ts+++ b/test/eval-takes-quality-runner.serial.test.ts@@ -176,9 +176,9 @@ describe('runner — budget cap (codex review #4)', () => {const r = await runEval(engine, {limit: 5,cycles: 3,- // gemini-2.0-flash (not the retired 1.5-pro) — the budget path- // pre-flights getPricing, which is allowlist-gated (#3510).- models: ['openai:gpt-4o', 'anthropic:claude-opus-4-7', 'google:gemini-2.0-flash'],+ // gemini-2.5-flash (not the retired 1.5-pro or 2.0 family) — the+ // budget path pre-flights getPricing, which is allowlist-gated (#3510).+ models: ['openai:gpt-4o', 'anthropic:claude-opus-4-7', 'google:gemini-2.5-flash'],budgetUsd: 0.05, // tighter than projected per-cycle cost (~$0.109)});// No cycle ever ran successfully because pre-flight aborted cycle 1.diff --git a/test/eval.test.ts b/test/eval.test.tsindex 7aa49d3d24..32b163802c 100644--- a/test/eval.test.ts+++ b/test/eval.test.ts@@ -49,6 +49,10 @@ describe('precisionAtK', () => {expect(precisionAtK(['a', 'b'], relevant, 10)).toBeCloseTo(2 / 10);});+ test('duplicate chunks count as one page while the denominator remains k', () => {+ expect(precisionAtK(['a', 'a'], new Set(['a']), 2)).toBe(0.5);+ });+test('empty hits → 0', () => {expect(precisionAtK([], new Set(['a']), 5)).toBe(0);});@@ -88,6 +92,11 @@ describe('recallAtK', () => {expect(recallAtK(['a', 'x', 'y', 'z', 'b'], relevant, 3)).toBeCloseTo(1 / 2);});+ test('deduplicates before the cutoff and cannot count one relevant page twice', () => {+ expect(recallAtK(['a', 'a'], new Set(['a']), 2)).toBe(1);+ expect(recallAtK(['x', 'x', 'a'], new Set(['a']), 2)).toBe(1);+ });+test('empty hits → 0', () => {expect(recallAtK([], new Set(['a']), 5)).toBe(0);});@@ -130,6 +139,10 @@ describe('mrr', () => {// 'b' is rank 2, 'c' is rank 3 — MRR should use 'b' at rank 2expect(mrr(['x', 'b', 'c'], new Set(['b', 'c']))).toBeCloseTo(0.5);});++ test('duplicate non-relevant chunks do not consume page-level ranks', () => {+ expect(mrr(['x', 'x', 'a'], new Set(['a']))).toBeCloseTo(0.5);+ });});// ─────────────────────────────────────────────────────────────────@@ -148,6 +161,10 @@ describe('ndcgAtK', () => {expect(ndcgAtK(['a', 'x', 'y'], grades, 5)).toBeCloseTo(1.0);});+ test('a repeated relevant page receives gain once and remains bounded at 1', () => {+ expect(ndcgAtK(['a', 'a'], new Map([['a', 1]]), 2)).toBe(1);+ });+test('single relevant doc at rank 2 → less than 1', () => {const grades = new Map([['a', 1]]);const score = ndcgAtK(['x', 'a', 'y'], grades, 5);diff --git a/test/extract-conversation-facts-entity-resolution.test.ts b/test/extract-conversation-facts-entity-resolution.test.tsnew file mode 100644index 0000000000..0da1654915--- /dev/null+++ b/test/extract-conversation-facts-entity-resolution.test.ts@@ -0,0 +1,397 @@+/**+ * Conversation backfill save-time resolution against the shipped+ * alias_exact cascade (v0.46.15 / #3730).+ */+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ spyOn,+ test,+} from 'bun:test';+import {+ extractConversationFactsFingerprint,+ PER_SEGMENT_SOURCE_PREFIX,+ runExtractConversationFactsCore,+ TERMINAL_AUDIT_SOURCE,+} from '../src/commands/extract-conversation-facts.ts';+import {+ BudgetExhausted,+ BudgetTracker,+} from '../src/core/budget/budget-tracker.ts';+import { runPhaseConversationFactsBackfill } from '../src/core/cycle/conversation-facts-backfill.ts';+import * as resolve from '../src/core/entities/resolve.ts';+import type { ExtractedFact } from '../src/core/facts/extract.ts';+import { loadOpCheckpoint } from '../src/core/op-checkpoint.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++function message(name: string, date: string, time: string, body: string): string {+ return `**${name}** (${date} ${time}): ${body}`;+}++const ONE_SEGMENT_BODY = [+ message('Alpha Example', '2026-08-12', '10:00 AM', 'The role was accepted.'),+ message('Beta Example', '2026-08-12', '10:01 AM', 'Congratulations.'),+].join('\n');++const TWO_SEGMENT_BODY = [+ message('Alpha Example', '2026-08-12', '10:00 AM', 'First segment.'),+ message('Beta Example', '2026-08-12', '10:01 AM', 'Still first.'),+ message('Alpha Example', '2026-08-12', '11:00 AM', 'Second segment.'),+ message('Beta Example', '2026-08-12', '11:01 AM', 'Still second.'),+].join('\n');++const extractedFacts: ExtractedFact[] = [+ {+ fact: 'Brian accepted the role',+ kind: 'event',+ entity_slug: 'Brian',+ source: 'test',+ source_session: null,+ confidence: 1,+ notability: 'medium',+ },+ {+ fact: 'An unlisted person attended',+ kind: 'event',+ entity_slug: 'Unlisted Person',+ source: 'test',+ source_session: null,+ confidence: 1,+ notability: 'medium',+ },+ {+ fact: 'The weather was clear',+ kind: 'fact',+ entity_slug: null,+ source: 'test',+ source_session: null,+ confidence: 1,+ notability: 'low',+ },+];++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('facts.extraction_enabled', 'true');+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');+ await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'true');+ await seedConversation(ONE_SEGMENT_BODY);+});++async function seedConversation(body: string): Promise<void> {+ await engine.putPage('sessions/example', {+ type: 'conversation',+ title: 'Example conversation',+ compiled_truth: body,+ timeline: '',+ frontmatter: {},+ });+ await engine.putPage('people/brian-example', {+ type: 'person',+ title: 'Brian Example',+ compiled_truth: '# Brian Example',+ timeline: '',+ frontmatter: {},+ });+ await engine.setPageAliases('people/brian-example', 'default', ['brian']);+}++function extractorFor(...batches: ExtractedFact[][]) {+ let index = 0;+ return async (): Promise<ExtractedFact[]> =>+ (batches[index++] ?? []).map((row) => ({ ...row }));+}++async function checkpointEntries(): Promise<string[]> {+ return loadOpCheckpoint(engine, {+ op: 'extract-conversation-facts',+ fingerprint: extractConversationFactsFingerprint({ sourceId: 'default' }),+ });+}++async function dataEntities(): Promise<Array<string | null>> {+ const rows = await engine.executeRaw<{ entity_slug: string | null }>(+ `SELECT entity_slug+ FROM facts+ WHERE source = $1+ AND source_markdown_slug = 'sessions/example'+ ORDER BY row_num`,+ [PER_SEGMENT_SOURCE_PREFIX],+ );+ return rows.map((row) => row.entity_slug);+}++async function terminalCount(): Promise<number> {+ const rows = await engine.executeRaw<{ count: string | number }>(+ `SELECT COUNT(*) AS count+ FROM facts+ WHERE source = $1+ AND source_markdown_slug = 'sessions/example'`,+ [TERMINAL_AUDIT_SOURCE],+ );+ return Number(rows[0]?.count ?? 0);+}++describe('conversation backfill entity resolution', () => {+ test('canonicalizes aliases via alias_exact, preserves null, and counts fallback slugification', async () => {+ const writeSpy = spyOn(process.stderr, 'write').mockImplementation(() => true);+ try {+ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default',+ slug: 'sessions/example',+ types: ['conversation'],+ sleepMs: 0,+ extractor: extractorFor(extractedFacts),+ });++ expect(await dataEntities()).toEqual([+ 'people/brian-example',+ 'unlisted-person',+ null,+ ]);+ expect(result.fallback_slugify_count).toBe(1);+ expect(result.resolution_errors).toBe(0);+ expect(result.facts_inserted).toBe(3);+ expect(await terminalCount()).toBe(1);++ const stderr = writeSpy.mock.calls.map((call) => String(call[0])).join('');+ expect(stderr).toContain(+ 'entity_resolution_counts={"alias_exact":1,"fallback_slugify":1}',+ );+ expect(stderr).not.toContain('alias_match');+ expect(stderr).not.toContain('alias_redirect');+ } finally {+ writeSpy.mockRestore();+ }+ });++ test('a lowercase hyphenated display form still hits page_aliases', async () => {+ await engine.putPage('people/kendall-example', {+ type: 'person',+ title: 'Kendall Example',+ compiled_truth: '# Kendall Example',+ timeline: '',+ frontmatter: {},+ });+ await engine.setPageAliases('people/kendall-example', 'default', [+ 'kendall',+ 'kendall-example',+ ]);++ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default',+ slug: 'sessions/example',+ types: ['conversation'],+ sleepMs: 0,+ extractor: extractorFor([+ {+ fact: 'Kendall joined the call',+ kind: 'event',+ entity_slug: 'kendall',+ source: 'test',+ source_session: null,+ confidence: 1,+ notability: 'medium',+ },+ {+ fact: 'Kendall Example spoke again',+ kind: 'event',+ entity_slug: 'kendall-example',+ source: 'test',+ source_session: null,+ confidence: 1,+ notability: 'medium',+ },+ ]),+ });++ expect(await dataEntities()).toEqual([+ 'people/kendall-example',+ 'people/kendall-example',+ ]);+ expect(result.fallback_slugify_count).toBe(0);+ expect(result.resolution_errors).toBe(0);+ });++ test('a deleted page alias falls through instead of stamping a dead target', async () => {+ await engine.putPage('people/ghost-example', {+ type: 'person',+ title: 'Ghost Example',+ compiled_truth: '# Ghost Example',+ timeline: '',+ frontmatter: {},+ });+ await engine.setPageAliases('people/ghost-example', 'default', ['spectre']);+ await engine.softDeletePage('people/ghost-example');++ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default',+ slug: 'sessions/example',+ types: ['conversation'],+ sleepMs: 0,+ extractor: extractorFor([{+ fact: 'A ghost was mentioned',+ kind: 'event',+ entity_slug: 'Spectre',+ source: 'test',+ source_session: null,+ confidence: 1,+ notability: 'medium',+ }]),+ });++ expect(await dataEntities()).toEqual(['spectre']);+ expect(result.fallback_slugify_count).toBe(1);+ });++ test('best-effort resolver failure keeps the raw value and later segments checkpoint', async () => {+ await seedConversation(TWO_SEGMENT_BODY);+ const original = resolve.resolveEntitySlugWithSource;+ const spy = spyOn(resolve, 'resolveEntitySlugWithSource').mockImplementation(+ async (eng, sourceId, raw) => {+ if (raw === 'Unlisted Person') {+ throw new Error('resolver unavailable for unlisted person');+ }+ return original(eng, sourceId, raw);+ },+ );+ const writeSpy = spyOn(process.stderr, 'write').mockImplementation(() => true);+ try {+ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default',+ slug: 'sessions/example',+ types: ['conversation'],+ sleepMs: 0,+ extractor: extractorFor(+ [extractedFacts[0]],+ [extractedFacts[1], extractedFacts[0], extractedFacts[2]],+ ),+ });++ expect(await dataEntities()).toEqual([+ 'people/brian-example',+ 'Unlisted Person',+ 'people/brian-example',+ null,+ ]);+ expect(result.resolution_errors).toBe(1);+ expect(result.fallback_slugify_count).toBe(0);+ expect(result.segments_processed).toBe(2);+ expect(result.facts_inserted).toBe(4);+ expect(result.pages_processed).toBe(1);+ expect(await checkpointEntries()).toContain(+ 'default|sessions/example|2026-08-12T11:01:00Z',+ );+ expect(await terminalCount()).toBe(1);++ const stderr = writeSpy.mock.calls.map((call) => String(call[0])).join('');+ expect(stderr).toContain('entity resolution failed for "Unlisted Person"');+ expect(stderr).toContain('keeping raw value');+ } finally {+ spy.mockRestore();+ writeSpy.mockRestore();+ }+ });++ test('BudgetExhausted from resolution halts without becoming a resolution error', async () => {+ const spy = spyOn(resolve, 'resolveEntitySlugWithSource').mockImplementation(+ async () => {+ throw new BudgetExhausted('resolver budget exhausted', {+ reason: 'cost',+ spent: 2,+ cap: 1,+ });+ },+ );+ try {+ const tracker = new BudgetTracker({ maxCostUsd: 1, label: 'track1-resolution' });+ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default',+ slug: 'sessions/example',+ types: ['conversation'],+ sleepMs: 0,+ budgetTracker: tracker,+ extractor: extractorFor(extractedFacts),+ });++ expect(result.budget_exhausted).toBeTrue();+ expect(result.resolution_errors).toBe(0);+ expect(result.facts_inserted).toBe(0);+ expect(await dataEntities()).toEqual([]);+ expect(await terminalCount()).toBe(0);+ expect(await checkpointEntries()).toEqual([]);+ } finally {+ spy.mockRestore();+ }+ });++ test('failed data insert writes no terminal or telemetry and retries cleanly', async () => {+ const originalInsertFacts = engine.insertFacts.bind(engine);+ const writeSpy = spyOn(process.stderr, 'write').mockImplementation(() => true);+ try {+ engine.insertFacts = async (facts, opts) => {+ if (facts.some((row) => row.source === PER_SEGMENT_SOURCE_PREFIX)) {+ throw new Error('constraint sentinel');+ }+ return originalInsertFacts(facts, opts);+ };+ await expect(runExtractConversationFactsCore(engine, {+ sourceId: 'default',+ slug: 'sessions/example',+ types: ['conversation'],+ sleepMs: 0,+ extractor: extractorFor(extractedFacts),+ })).rejects.toThrow('constraint sentinel');++ expect(await dataEntities()).toEqual([]);+ expect(await terminalCount()).toBe(0);+ expect(await checkpointEntries()).toEqual([]);+ const failedStderr = writeSpy.mock.calls.map((call) => String(call[0])).join('');+ expect(failedStderr).not.toContain('entity_resolution_counts=');+ engine.insertFacts = originalInsertFacts;++ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default',+ slug: 'sessions/example',+ types: ['conversation'],+ sleepMs: 0,+ extractor: extractorFor(extractedFacts),+ });+ expect(result.facts_inserted).toBe(3);+ expect(result.fallback_slugify_count).toBe(1);+ expect(result.resolution_errors).toBe(0);+ expect(await terminalCount()).toBe(1);+ expect(await checkpointEntries()).toContain(+ 'default|sessions/example|2026-08-12T10:01:00Z',+ );+ } finally {+ engine.insertFacts = originalInsertFacts;+ writeSpy.mockRestore();+ }+ });++ test('cycle propagates an abort instead of aggregating it as a source warning', async () => {+ const controller = new AbortController();+ controller.abort();+ await expect(runPhaseConversationFactsBackfill(engine, {+ signal: controller.signal,+ dryRun: true,+ })).rejects.toThrow('aborted');+ });+});diff --git a/test/extract-conversation-facts.test.ts b/test/extract-conversation-facts.test.tsindex 2c3dc39068..1af92fedf8 100644--- a/test/extract-conversation-facts.test.ts+++ b/test/extract-conversation-facts.test.ts@@ -20,6 +20,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import {__setChatTransportForTests,__setEmbedTransportForTests,+ configureGateway,resetGateway,type ChatResult,} from '../src/core/ai/gateway.ts';@@ -326,6 +327,7 @@ describe('runExtractConversationFactsCore', () => {let mainChatCalls = 0;let chatStopReason: ChatResult['stopReason'] = 'end';let chatTextOverride: string | null = null;+ let embeddedTexts: string[] = [];let fallbackCalls = 0;let fallbackContents: string[] = [];let fallbackControlError: Error | null = null;@@ -410,9 +412,10 @@ describe('runExtractConversationFactsCore', () => {// Deterministic embedding stub.__setEmbedTransportForTests(- (async () => ({- embeddings: [Array.from({ length: 1536 }, () => 0.1)],- })) as never,+ (async ({ values }: { values: string[] }) => {+ embeddedTexts.push(...values);+ return { embeddings: values.map(() => Array.from({ length: 1536 }, () => 0.1)) };+ }) as never,);});@@ -430,6 +433,7 @@ describe('runExtractConversationFactsCore', () => {mainChatCalls = 0;chatStopReason = 'end';chatTextOverride = null;+ embeddedTexts = [];fallbackCalls = 0;fallbackContents = [];fallbackControlError = null;@@ -530,6 +534,60 @@ describe('runExtractConversationFactsCore', () => {expect(result.segments_processed).toBeGreaterThanOrEqual(1);});+ test('historical backfill embeds and retains high, medium, low, and absent-tier facts', async () => {+ // Regression target: passing high-only admission into the historical+ // extractor call would suppress low (and absent-tier) facts before embed.+ chatTextOverride = JSON.stringify({+ facts: [+ { fact: 'historical-high', kind: 'event', notability: 'high' },+ { fact: 'historical-medium', kind: 'fact', notability: 'medium' },+ { fact: 'historical-low', kind: 'fact', notability: 'low' },+ { fact: 'historical-absent', kind: 'fact' },+ ],+ });+ configureGateway({+ embedding_model: 'openai:text-embedding-3-small',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'test' },+ });+ await engine.putPage('conversations/historical-tier-coverage', {+ type: 'conversation',+ title: 'Historical tier coverage',+ compiled_truth: [+ fmt('Alice Example', '2024-03-15', '9:00 AM', 'first message'),+ fmt('Bob Demo', '2024-03-15', '9:05 AM', 'second message'),+ ].join('\n'),+ timeline: '',+ frontmatter: {},+ });++ const result = await runExtractConversationFactsCore(engine, {+ sourceId: 'default',+ slug: 'conversations/historical-tier-coverage',+ sleepMs: 0,+ });+ const rows = await engine.executeRaw<{ fact: string; notability: string; has_embedding: boolean }>(+ `SELECT fact, notability, embedding IS NOT NULL AS has_embedding+ FROM facts WHERE source = $1 ORDER BY row_num`,+ [PER_SEGMENT_SOURCE_PREFIX],+ );++ expect(result.facts_extracted).toBe(4);+ expect(result.facts_inserted).toBe(4);+ expect(embeddedTexts).toEqual([+ 'historical-high',+ 'historical-medium',+ 'historical-low',+ 'historical-absent',+ ]);+ expect(rows).toEqual([+ { fact: 'historical-high', notability: 'high', has_embedding: true },+ { fact: 'historical-medium', notability: 'medium', has_embedding: true },+ { fact: 'historical-low', notability: 'low', has_embedding: true },+ { fact: 'historical-absent', notability: 'medium', has_embedding: true },+ ]);+ });+test('dry-run does not write the extract_rollup_7d cache row', async () => {// Regression: --dry-run promises "no DB writes" but writeRunReceiptAndRollup// upsert-ed extract_rollup_7d unconditionally. A preview must not mutate the DB.diff --git a/test/extract-facts-phase.test.ts b/test/extract-facts-phase.test.tsindex 5815f64a9f..47af6a2f91 100644--- a/test/extract-facts-phase.test.ts+++ b/test/extract-facts-phase.test.ts@@ -293,6 +293,39 @@ describe('runExtractFacts — happy path', () => {expect(cleanRows.rows.map((row: { fact: string }) => row.fact)).toEqual(['Clean']);});+ test('#3625: a Facts fence below the timeline sentinel is loud-skipped, never treated as absence', async () => {+ await putPage('people/carol', FACT_FENCE(+ `| 1 | Seeded | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,+ ));+ await runExtractFacts(engine, { slugs: ['people/carol'] });++ // splitBody() would route a fence placed below the timeline sentinel+ // into page.timeline instead of compiled_truth (the LLM-composed shape+ // the issue describes). Simulate that post-split state directly: the+ // fence is present on the page, just in the wrong column.+ await engine.putPage('people/carol', {+ title: 'people/carol',+ type: 'person',+ compiled_truth: '# Page\n\nBody.\n\n<!-- timeline -->\n',+ frontmatter: {},+ timeline: FACT_FENCE(+ `| 1 | Seeded | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,+ ),+ });++ const r = await runExtractFacts(engine, { slugs: ['people/carol'] });++ expect(r.warnings.some(w => w.includes('FACTS_FENCE_BELOW_SENTINEL'))).toBe(true);+ expect(r.factsDeleted).toBe(0);+ expect(r.factsInserted).toBe(0);++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const rows = await (engine as any).db.query(+ `SELECT fact FROM facts WHERE source_markdown_slug = 'people/carol'`,+ );+ expect(rows.rows.map((row: { fact: string }) => row.fact)).toEqual(['Seeded']);+ });+test('page with no facts fence → DB facts for that page wiped (empty fence reconciles to empty index)', async () => {await putPage('people/alice', FACT_FENCE(`| 1 | seeded | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,diff --git a/test/extraction-review.test.ts b/test/extraction-review.test.tsindex 5598ea6ecb..75ffe202e9 100644--- a/test/extraction-review.test.ts+++ b/test/extraction-review.test.ts@@ -72,6 +72,7 @@ beforeEach(async () => {await engine.executeRaw('DELETE FROM links');await engine.executeRaw('DELETE FROM timeline_entries');await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw('DELETE FROM slug_aliases');});function ctx(over: Partial<OperationContext> = {}): OperationContext {@@ -175,6 +176,32 @@ describe('rrfFusion compiled-truth boost skip', () => {// ---------------------------------------------------------------------------describe('enrichEntity trust lane', () => {+ test('resolves slug aliases before checking or writing entity pages', async () => {+ await engine.putPage('people/aditya-vikram-singh', {+ title: 'Aditya Vikram Singh',+ type: 'person',+ compiled_truth: '# Aditya Vikram Singh',+ timeline: '',+ frontmatter: {},+ });+ await engine.executeRaw(+ `INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug)+ VALUES ('default', 'people/avsingh', 'people/aditya-vikram-singh')`,+ );++ const result = await enrichEntity(engine, {+ entityName: 'Avsingh',+ entityType: 'person',+ context: 'canonical identity mention',+ sourceSlug: 'notes/daily',+ }, { trusted: true });++ expect(result.slug).toBe('people/aditya-vikram-singh');+ expect(result.action).toBe('updated');+ expect(await engine.getPage('people/avsingh')).toBeNull();+ expect(await engine.getPage('people/aditya-vikram-singh')).not.toBeNull();+ });+test('default (opts omitted) → fail-closed quarantine markers', async () => {const r = await enrichEntity(engine, {entityName: 'Mallory Fake',diff --git a/test/facts-backstop.test.ts b/test/facts-backstop.test.tsindex 9e3d25f061..faac6c766e 100644--- a/test/facts-backstop.test.ts+++ b/test/facts-backstop.test.ts@@ -15,6 +15,8 @@ import { runFactsBackstop } from '../src/core/facts/backstop.ts';import type { FactsBackstopCtx } from '../src/core/facts/backstop.ts';import {__setChatTransportForTests,+ __setEmbedTransportForTests,+ configureGateway,resetGateway,type ChatResult,} from '../src/core/ai/gateway.ts';@@ -40,7 +42,7 @@ afterEach(() => {const LONG_BODY = 'this is a real meeting note longer than 80 chars '.repeat(3);-function chatStub(facts: Array<{ fact: string; kind: string; notability: 'high' | 'medium' | 'low'; entity?: string | null }>) {+function chatStub(facts: Array<{ fact: string; kind: string; notability?: string; entity?: string | null }>) {__setChatTransportForTests(async (): Promise<ChatResult> => ({text: JSON.stringify({facts: facts.map(f => ({@@ -76,6 +78,16 @@ const meetingPage = (slug = 'meetings/test-' + Math.random().toString(36).slice(frontmatter: {} as Record<string, unknown>,});+async function factsForIds(ids: number[]): Promise<Array<{ fact: string }>> {+ return Promise.all(ids.map(async (id) => {+ // PGLite's test engine deliberately exposes its raw query client for+ // storage assertions where the public API only offers scoped listings.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const rows = await (engine as any).db.query('SELECT fact FROM facts WHERE id = $1', [id]);+ return rows.rows[0];+ }));+}+describe('runFactsBackstop — eligibility + kill-switch gates', () => {test('skips with extraction_disabled when kill-switch off', async () => {await engine.setConfig('facts.extraction_enabled', 'false');@@ -120,12 +132,24 @@ describe('runFactsBackstop — mode: inline', () => {}});- test('notabilityFilter=high-only drops MEDIUM + LOW from the insert path', async () => {+ test('notabilityFilter=high-only embeds and persists only HIGH facts', async () => {+ const embeddedTexts: string[] = [];+ configureGateway({+ embedding_model: 'openai:text-embedding-3-small',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'test' },+ });chatStub([{ fact: 'high-only-1', kind: 'event', notability: 'high', entity: 'people/bob-test' },- { fact: 'high-only-2-skip', kind: 'event', notability: 'medium', entity: 'people/bob-test' },- { fact: 'high-only-3-skip', kind: 'event', notability: 'low', entity: 'people/bob-test' },+ { fact: 'high-only-medium-skip', kind: 'event', notability: 'medium', entity: 'people/bob-test' },+ { fact: 'high-only-low-skip', kind: 'event', notability: 'low', entity: 'people/bob-test' },+ { fact: 'high-only-absent-skip', kind: 'event', entity: 'people/bob-test' },+ { fact: 'high-only-unknown-skip', kind: 'event', notability: 'unknown', entity: 'people/bob-test' },]);+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ embeddedTexts.push(...values);+ return { embeddings: values.map(() => Array.from({ length: 1536 }, () => 0.1)) };+ }) as never);const r = await runFactsBackstop(meetingPage(),makeCtx({ mode: 'inline', notabilityFilter: 'high-only' }),@@ -134,6 +158,35 @@ describe('runFactsBackstop — mode: inline', () => {if (r.mode === 'inline') {expect(r.inserted).toBe(1);expect(r.fact_ids.length).toBe(1);+ const rows = await factsForIds(r.fact_ids);+ expect(embeddedTexts).toEqual(['high-only-1']);+ expect(rows.map(f => f.fact)).toEqual(['high-only-1']);+ }+ });++ test('notabilityFilter=all embeds and persists every tier', async () => {+ const embeddedTexts: string[] = [];+ configureGateway({+ embedding_model: 'openai:text-embedding-3-small',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'test' },+ });+ chatStub([+ { fact: 'all-high', kind: 'event', notability: 'high', entity: 'people/all-test' },+ { fact: 'all-medium', kind: 'event', notability: 'medium', entity: 'people/all-test' },+ { fact: 'all-low', kind: 'event', notability: 'low', entity: 'people/all-test' },+ { fact: 'all-absent', kind: 'event', entity: 'people/all-test' },+ ]);+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ embeddedTexts.push(...values);+ return { embeddings: values.map(() => Array.from({ length: 1536 }, () => 0.1)) };+ }) as never);+ const r = await runFactsBackstop(meetingPage(), makeCtx({ mode: 'inline', notabilityFilter: 'all' }));+ expect(r.mode).toBe('inline');+ if (r.mode === 'inline') {+ const rows = await factsForIds(r.fact_ids);+ expect(embeddedTexts).toEqual(['all-high', 'all-medium', 'all-low', 'all-absent']);+ expect(rows.map(f => f.fact)).toEqual(['all-high', 'all-medium', 'all-low', 'all-absent']);}});diff --git a/test/facts-engine.test.ts b/test/facts-engine.test.tsindex f4a0741b5a..460b68efeb 100644--- a/test/facts-engine.test.ts+++ b/test/facts-engine.test.ts@@ -69,6 +69,30 @@ describe('insertFact + listFactsByEntity', () => {expect(ours!.confidence).toBe(1.0);});+ test('unconsolidatedOnly excludes active facts with consolidated_at set', async () => {+ const entitySlug = 'people/consolidation-filter-example';+ const consolidated = await engine.insertFact(+ { fact: 'already consolidated', kind: 'fact', entity_slug: entitySlug, source: 'test' },+ { source_id: 'default' },+ );+ const pending = await engine.insertFact(+ { fact: 'still pending', kind: 'fact', entity_slug: entitySlug, source: 'test' },+ { source_id: 'default' },+ );+ await engine.executeRaw(+ `UPDATE facts SET consolidated_at = now() WHERE id = $1`,+ [consolidated.id],+ );++ const active = await engine.listFactsByEntity('default', entitySlug);+ const unconsolidated = await engine.listFactsByEntity('default', entitySlug, {+ unconsolidatedOnly: true,+ });++ expect(new Set(active.map(f => f.id))).toEqual(new Set([consolidated.id, pending.id]));+ expect(unconsolidated.map(f => f.id)).toEqual([pending.id]);+ });+test('respects kind CHECK', async () => {const r = await engine.insertFact({ fact: 'durable', kind: 'preference', entity_slug: 'alice-test', source: 'test' },diff --git a/test/facts-extract-smoke.test.ts b/test/facts-extract-smoke.test.tsindex bb4a27801e..0c56235c1d 100644--- a/test/facts-extract-smoke.test.ts+++ b/test/facts-extract-smoke.test.ts@@ -18,13 +18,19 @@import { describe, test, expect, afterEach } from 'bun:test';import {__setChatTransportForTests,+ __setEmbedTransportForTests,+ configureGateway,resetGateway,type ChatResult,} from '../src/core/ai/gateway.ts';-import { extractFactsFromTurn } from '../src/core/facts/extract.ts';+import {+ extractFactsFromTurn,+ extractFactsFromTurnWithOutcome,+} from '../src/core/facts/extract.ts';afterEach(() => {__setChatTransportForTests(null);+ __setEmbedTransportForTests(null);resetGateway();});@@ -142,4 +148,78 @@ describe('extractFactsFromTurn — B1 end-to-end smoke', () => {expect(facts).toHaveLength(3);expect(facts.map(f => f.notability)).toEqual(['high', 'medium', 'low']);});++ test('high-only admission embeds only high-tier candidates', async () => {+ const embeddedTexts: string[] = [];+ configureGateway({+ embedding_model: 'zeroentropyai:zembed-1',+ embedding_dimensions: 1280,+ env: { ZEROENTROPY_API_KEY: 'test' },+ });+ __setChatTransportForTests(async (): Promise<ChatResult> => ({+ text: JSON.stringify({+ facts: [+ { fact: 'H', kind: 'event', notability: 'high' },+ { fact: 'M', kind: 'fact', notability: 'medium' },+ { fact: 'L', kind: 'fact', notability: 'low' },+ { fact: 'missing', kind: 'fact' },+ { fact: 'unknown', kind: 'fact', notability: 'critical' },+ ],+ }),+ blocks: [],+ stopReason: 'end',+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'test:stub',+ providerId: 'test',+ }));+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ embeddedTexts.push(...values);+ return { embeddings: values.map(() => Array.from({ length: 1280 }, () => 0.1)) };+ }) as never);++ const outcome = await extractFactsFromTurnWithOutcome({+ turnText: 'content',+ source: 'test',+ notabilityAdmission: { allowed: ['high'], invalid: 'drop' },+ });++ expect(outcome).toEqual(expect.objectContaining({ ok: true }));+ expect(embeddedTexts).toEqual(['H']);+ });++ test('without admission, high, medium, low, and absent tiers embed', async () => {+ const embeddedTexts: string[] = [];+ configureGateway({+ embedding_model: 'zeroentropyai:zembed-1',+ embedding_dimensions: 1280,+ env: { ZEROENTROPY_API_KEY: 'test' },+ });+ __setChatTransportForTests(async (): Promise<ChatResult> => ({+ text: JSON.stringify({+ facts: [+ { fact: 'H', kind: 'event', notability: 'high' },+ { fact: 'M', kind: 'fact', notability: 'medium' },+ { fact: 'L', kind: 'fact', notability: 'low' },+ { fact: 'missing', kind: 'fact' },+ ],+ }),+ blocks: [],+ stopReason: 'end',+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'test:stub',+ providerId: 'test',+ }));+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ embeddedTexts.push(...values);+ return { embeddings: values.map(() => Array.from({ length: 1280 }, () => 0.1)) };+ }) as never);++ const outcome = await extractFactsFromTurnWithOutcome({+ turnText: 'content',+ source: 'test',+ });++ expect(outcome).toEqual(expect.objectContaining({ ok: true }));+ expect(embeddedTexts).toEqual(['H', 'M', 'L', 'missing']);+ });});diff --git a/test/facts-pipeline-budget-accounting.test.ts b/test/facts-pipeline-budget-accounting.test.tsnew file mode 100644index 0000000000..29e3a0e2bd--- /dev/null+++ b/test/facts-pipeline-budget-accounting.test.ts@@ -0,0 +1,176 @@+/**+ * #4210 — extract_facts op (and every other runFactsPipeline entry point+ * outside a cycle) ran with no ambient BudgetTracker, so the Haiku+ * extraction spend was a budget no-op: real money spent, zero rows in the+ * budget audit.+ *+ * Pins the fix's contract at the pipeline choke point (backstop.ts):+ * - With NO ambient tracker, the pipeline installs a record-only+ * fallback tracker labeled `facts:<ctx.source>` — the chat spend lands+ * in the budget audit JSONL.+ * - With an ambient tracker (the cycle case), the fallback does NOT+ * engage: rows keep the ambient label and are recorded exactly once.+ * - The fallback is uncapped, so it can never throw BudgetExhausted —+ * the pipeline's failure surface is unchanged.+ *+ * Hermetic: PGLite engine + __setChatTransportForTests (which keeps+ * chat()'s real reserve/record wiring active) + GBRAIN_AUDIT_DIR pointed+ * at a temp dir. Env-mutating → serial-safe file (no test.concurrent).+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { withEnv } from './helpers/with-env.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runFactsPipeline } from '../src/core/facts/backstop.ts';+import { operations } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import {+ __setChatTransportForTests,+ resetGateway,+ withBudgetTracker,+ type ChatResult,+} from '../src/core/ai/gateway.ts';+import { BudgetTracker } from '../src/core/budget/budget-tracker.ts';++let engine: PGLiteEngine;+let auditDir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+}, 60_000);++beforeEach(() => {+ auditDir = mkdtempSync(join(tmpdir(), 'gbrain-facts-budget-'));+});++afterEach(() => {+ __setChatTransportForTests(null);+ resetGateway();+ rmSync(auditDir, { recursive: true, force: true });+});++/** Stub the extractor's chat call. Priced model id → real cost math runs. */+function chatStub(): void {+ __setChatTransportForTests(async (): Promise<ChatResult> => ({+ text: JSON.stringify({+ facts: [+ { fact: 'budget-accounting-probe fact', kind: 'fact', entity: null, confidence: 1.0, notability: 'medium' },+ ],+ }),+ blocks: [],+ stopReason: 'end',+ usage: { input_tokens: 321, output_tokens: 45, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5-20251001',+ providerId: 'anthropic',+ }));+}++/** Every parsed row from every budget-*.jsonl in the temp audit dir. */+function readAuditRows(): any[] {+ const rows: any[] = [];+ for (const f of readdirSync(auditDir)) {+ if (!f.startsWith('budget')) continue;+ for (const line of readFileSync(join(auditDir, f), 'utf-8').split('\n')) {+ if (line.trim()) rows.push(JSON.parse(line));+ }+ }+ return rows;+}++describe('facts pipeline budget accounting (#4210)', () => {+ test('runFactsPipeline with no ambient tracker records chat spend in the budget audit', async () => {+ chatStub();+ await withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ const r = await runFactsPipeline('a turn worth extracting', {+ engine,+ sourceId: 'default',+ sessionId: null,+ source: 'mcp:extract_facts',+ });+ expect(r.inserted).toBe(1);+ });++ const records = readAuditRows().filter(r => r.event === 'record');+ // The core of #4210: pre-fix this is [] — the Haiku call happened,+ // the money was spent, and no audit row exists anywhere.+ expect(records.length).toBe(1);+ expect(records[0].label).toBe('facts:mcp:extract_facts');+ expect(records[0].sub_label).toBe('gateway.chat');+ expect(records[0].model).toBe('anthropic:claude-haiku-4-5-20251001');+ expect(records[0].input_tokens).toBe(321);+ expect(records[0].output_tokens).toBe(45);+ expect(records[0].actual_cost_usd).toBeGreaterThan(0);+ });++ test('extract_facts op handler end-to-end: spend is audited, response envelope unchanged', async () => {+ chatStub();+ const op = operations.find(o => o.name === 'extract_facts')!;+ const ctx = {+ engine,+ config: {},+ logger: console,+ dryRun: false,+ remote: true,+ } as unknown as OperationContext;++ let result: any;+ await withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ result = await op.handler(ctx, { turn_text: 'another turn worth extracting' });+ });++ // Response contract untouched by the fix.+ expect(typeof result.inserted).toBe('number');+ expect(Array.isArray(result.fact_ids)).toBe(true);++ const records = readAuditRows().filter(r => r.event === 'record');+ expect(records.length).toBe(1);+ expect(records[0].label).toBe('facts:mcp:extract_facts');+ });++ test('the fallback label carries the entry point: hook:compact audits as facts:hook:compact', async () => {+ chatStub();+ await withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ await runFactsPipeline('a compaction-boundary turn', {+ engine,+ sourceId: 'default',+ sessionId: null,+ source: 'hook:compact',+ });+ });+ const records = readAuditRows().filter(r => r.event === 'record');+ expect(records.length).toBe(1);+ expect(records[0].label).toBe('facts:hook:compact');+ });++ test('an ambient tracker (cycle case) wins: rows keep the ambient label, recorded exactly once', async () => {+ chatStub();+ const ambient = new BudgetTracker({ label: 'cycle-phase-test', auditPath: join(auditDir, 'budget-ambient.jsonl') });+ await withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ await withBudgetTracker(ambient, () =>+ runFactsPipeline('a cycle-scoped turn', {+ engine,+ sourceId: 'default',+ sessionId: null,+ source: 'sync:import',+ }),+ );+ });++ const records = readAuditRows().filter(r => r.event === 'record');+ // Exactly one record, under the ambient label — the fallback must not+ // double-wrap an already-scoped call.+ expect(records.length).toBe(1);+ expect(records[0].label).toBe('cycle-phase-test');+ expect(ambient.snapshot().callsRecorded).toBe(1);+ expect(ambient.totalSpent).toBeGreaterThan(0);+ });+});diff --git a/test/get-page-federated-scope.test.ts b/test/get-page-federated-scope.test.tsindex 0404f6d352..9e4da33887 100644--- a/test/get-page-federated-scope.test.ts+++ b/test/get-page-federated-scope.test.ts@@ -147,6 +147,52 @@ describe('engine.getPage honors sourceIds[] (federated grant)', () => {});});+// ---------------------------------------------------------------------------+// #3931 — get_page returns a nondeterministic row when a slug is shadowed+// across federated sources. `shared/dup` (seeded above) exists in BOTH+// 'alpha' and 'beta' — the ambiguous case. Without an anchor-aware ORDER BY,+// LIMIT 1 either returns planner-order-dependent rows (pre-fix) or always+// prefers a hardcoded 'default' / lexical-first source regardless of which+// source the caller actually resolved to (the gap left after #4219, which+// fixed pure nondeterminism but hardcoded the anchor to 'default').+// ---------------------------------------------------------------------------+describe('#3931 engine.getPage same-slug shadowing across federated sources is deterministic', () => {+ test('anchor source (sourceIds[0]) wins even when it is not lexically first', async () => {+ // 'alpha' < 'beta' lexically, so a lexical-only tiebreak would always+ // prefer alpha regardless of caller intent. Anchor-first must override+ // that when the caller's own resolved source (position 0) is beta.+ const page = await engine.getPage('shared/dup', { sourceIds: ['beta', 'alpha'] });+ expect(page?.title).toBe('Dup beta');+ });++ test('re-anchoring the same slug flips the winner', async () => {+ const asAlphaAnchor = await engine.getPage('shared/dup', { sourceIds: ['alpha', 'beta'] });+ const asBetaAnchor = await engine.getPage('shared/dup', { sourceIds: ['beta', 'alpha'] });+ expect(asAlphaAnchor?.title).toBe('Dup alpha');+ expect(asBetaAnchor?.title).toBe('Dup beta');+ });++ test('anchor absent from the candidate rows falls back to lexical source_id order', async () => {+ // 'gamma' is a real granted source but owns no 'shared/dup' page — the+ // anchor itself has no matching row, so the tiebreak falls through to+ // plain `source_id ASC` among the sources that DO have the page.+ await engine.executeRaw(+ `INSERT INTO sources (id, name, local_path) VALUES ('gamma', 'gamma', '/tmp/gamma') ON CONFLICT (id) DO NOTHING`,+ );+ const page = await engine.getPage('shared/dup', { sourceIds: ['gamma', 'beta', 'alpha'] });+ expect(page?.title).toBe('Dup alpha'); // 'alpha' < 'beta' lexically+ });++ test('repeated calls with the same scope are stable, not planner-order luck', async () => {+ const results = await Promise.all(+ Array.from({ length: 10 }, () => engine.getPage('shared/dup', { sourceIds: ['beta', 'alpha'] })),+ );+ for (const page of results) {+ expect(page?.title).toBe('Dup beta');+ }+ });+});+describe('get_page handler closes the cross-source exact-read leak', () => {test('remote client granted only [alpha] CANNOT read a beta-only slug', async () => {const ctx = ctxOf({ remote: true, auth: { token: 't', clientId: 'c', scopes: [], allowedSources: ['alpha'] } as any });diff --git a/test/hybrid-cache-hit-limit-honors-mode.serial.test.ts b/test/hybrid-cache-hit-limit-honors-mode.serial.test.tsindex 7152889728..1742382724 100644--- a/test/hybrid-cache-hit-limit-honors-mode.serial.test.ts+++ b/test/hybrid-cache-hit-limit-honors-mode.serial.test.ts@@ -31,10 +31,10 @@** Drives a real store→hit roundtrip (mocked `embed`/`embedQuery` for a* deterministic vector, real PGLite SemanticQueryCache — same pattern as- * test/hybrid-cached-hit-budget-meta.serial.test.ts) with 30 keyword-+ * test/hybrid-cached-hit-budget-meta.serial.test.ts) with 60 keyword-* findable pages spread across 6 page types (dedup's type-diversity layer* caps any one type at 60% of the result set, so a single type would- * silently shrink the pool below 25 regardless of this fix). `autocut` and+ * silently shrink the pool below 50 regardless of this fix). `autocut` and* `relationalRetrieval` are forced off per-call so the result count is* driven only by the limit slice under test, not by an unrelated cliff cut* or graph arm.@@ -78,7 +78,7 @@ let tmpHome: string;const savedGbrainHome = process.env.GBRAIN_HOME;const PAGE_TYPES = ['note', 'company', 'person', 'decision', 'concept', 'idea'];-const PAGE_COUNT = 30; // > balanced searchLimit (25), so the bug (slice to 20) is observable.+const PAGE_COUNT = 60; // > tokenmax searchLimit (50), so every mode's cap — not the pool — drives the count.const KEYWORD = 'gbrain4356widget';beforeAll(async () => {@@ -170,6 +170,33 @@ describe('cache HIT — limit honors the resolved mode (#4356)', () => {expect(hitResults.length).toBe(missResults.length);});+ test('tokenmax mode, limit omitted: miss and hit both return searchLimit=50 (above the old flat 20)', async () => {+ let missMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const missResults = await hybridSearchCached(engine, KEYWORD, {+ mode: 'tokenmax',+ autocut: false,+ relationalRetrieval: false,+ onMeta: (m) => { missMeta = m; },+ });+ expect(missMeta?.cache?.status).toBe('miss');+ // Sanity: the 60-page pool keeps the mode's searchLimit (50), not the+ // pool size, as the cap — same reasoning as the balanced test above.+ expect(missResults.length).toBe(50);++ await awaitPendingSearchCacheWrites();++ let hitMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const hitResults = await hybridSearchCached(engine, KEYWORD, {+ mode: 'tokenmax',+ autocut: false,+ relationalRetrieval: false,+ onMeta: (m) => { hitMeta = m; },+ });+ expect(hitMeta?.cache?.status).toBe('hit');+ expect(hitResults.length).toBe(missResults.length);+ expect(hitResults.length).toBe(50);+ });+test('explicit numeric limit round-trips through a hit (limit is folded into knobsHash, so a hit only ever serves a lookup with the SAME resolved limit as the write — this pins that path still behaves, not just the mode-default path above)', async () => {await hybridSearchCached(engine, KEYWORD, { limit: 3, autocut: false, relationalRetrieval: false });await awaitPendingSearchCacheWrites();diff --git a/test/import-source-id-bookkeeping.test.ts b/test/import-source-id-bookkeeping.test.tsnew file mode 100644index 0000000000..b9e26135ea--- /dev/null+++ b/test/import-source-id-bookkeeping.test.ts@@ -0,0 +1,88 @@+/**+ * #3838 — the sync-failures ledger and ingest_log both hard-coded+ * `source_id: 'default'` for a bare `gbrain import <dir>` run, even when+ * the resolver's `sole_non_default` tier (5.5) routed the run to a+ * different source. `recordFailures` was called with+ * `opts.sourceId ?? 'default'` — the unresolved CLI parameter, which stays+ * undefined for a bare invocation — instead of the `sourceId` local+ * variable every `importFile` call in the same run actually used.+ * `engine.logIngest(...)` never passed `source_id` at all.+ *+ * Hermetic PGLite in-memory. Sandboxes the failure ledger under a temp+ * GBRAIN_HOME via `withEnv` so this test never touches the real+ * ~/.gbrain/sync-failures.jsonl on the machine running it (see #2121).+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync } from 'fs';+import { execSync } from 'child_process';+import { join } from 'path';+import { tmpdir } from 'os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runImport } from '../src/commands/import.ts';+import { withEnv } from './helpers/with-env.ts';+import { loadSyncFailures } from '../src/core/sync-failure-ledger.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ // Registering the ONLY non-default source with a local_path is what+ // fires resolveSourceWithTier's sole_non_default tier (5.5) — the tier+ // import.ts actually adopts into its local `sourceId` variable for a+ // bare CLI call. (Setting `sources.default`/tier 5 does NOT reach this+ // code path: import.ts's own resolution block only ever adopts+ // `resolved.source_id` when `resolved.tier === 'sole_non_default'`, by+ // design — every other tier falls through and `sourceId` stays+ // undefined, defaulting the actual writes to 'default' regardless of+ // what the resolver reports. The path doesn't need to exist on disk;+ // pickSoleNonDefaultSource only checks the column is non-null.)+ await engine.executeRaw(+ `INSERT INTO sources (id, name, local_path) VALUES ('dept-x', 'dept-x', '/nonexistent/dept-x') ON CONFLICT DO NOTHING`,+ );+});++afterAll(async () => {+ await engine.disconnect();+});++describe('import bookkeeping records the resolved source (#3838)', () => {+ test('failure ledger and ingest_log both say dept-x, not default', async () => {+ const repo = mkdtempSync(join(tmpdir(), 'gbrain-source-bookkeeping-'));+ execSync('git init', { cwd: repo, stdio: 'pipe' });+ execSync('git config user.email "[email protected]"', { cwd: repo, stdio: 'pipe' });+ execSync('git config user.name "T"', { cwd: repo, stdio: 'pipe' });+ writeFileSync(join(repo, 'seed.md'), '---\ntype: note\n---\n# Seed\n\nbody\n');+ execSync('git add seed.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m seed', { cwd: repo, stdio: 'pipe' });++ // Deterministic soft-failure: import-file.ts rejects any file over+ // MAX_FILE_SIZE (5_000_000 bytes) with a real `result.error`, which+ // runImport pushes into `failures[]` without needing a thrown+ // exception — the exact code path recordFailures reads from.+ writeFileSync(join(repo, 'oversized.md'), '---\ntype: note\n---\n' + 'x'.repeat(5_000_001));++ const gbrainHome = mkdtempSync(join(tmpdir(), 'gbrain-home-'));+ await withEnv({ GBRAIN_HOME: gbrainHome }, async () => {+ // No --source-id: the resolver must reach tier 5 on its own.+ await runImport(engine, [repo, '--no-embed', '--json']);++ const failures = loadSyncFailures().filter((f) => f.path === 'oversized.md');+ expect(failures.length).toBe(1);+ expect(failures[0].source_id).toBe('dept-x');+ });++ // Not filtering by source_ref: runImport resolves `dir` to its real,+ // symlink-free path (macOS: /tmp -> /private/tmp) before logging it,+ // so it won't byte-match the pre-realpath `repo` string here. This is+ // the only import in the test, so the latest row is unambiguous.+ const ingestRows = await engine.executeRaw<{ source_id: string; source_ref: string }>(+ `SELECT source_id, source_ref FROM ingest_log ORDER BY id DESC LIMIT 1`,+ );+ expect(ingestRows.length).toBe(1);+ expect(ingestRows[0].source_ref).toContain('gbrain-source-bookkeeping-');+ expect(ingestRows[0].source_id).toBe('dept-x');+ });+});diff --git a/test/ingestion/put-page-write-through.test.ts b/test/ingestion/put-page-write-through.test.tsindex 64b446289a..98174613a0 100644--- a/test/ingestion/put-page-write-through.test.ts+++ b/test/ingestion/put-page-write-through.test.ts@@ -13,7 +13,7 @@ import * as path from 'node:path';import * as os from 'node:os';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { resetPgliteState } from '../helpers/reset-pglite.ts';-import { operations } from '../../src/core/operations.ts';+import { operations, OperationError } from '../../src/core/operations.ts';import type { OperationContext } from '../../src/core/operations.ts';import { resetGateway } from '../../src/core/ai/gateway.ts';@@ -184,14 +184,16 @@ describe('put_page write-through — config edge cases', () => {expect(result.write_through?.skipped).toBe('no_repo_configured');});- test('repo path points at a missing directory → skipped repo_not_found', async () => {+ test('repo path points at a missing directory → put_page rejects, no orphan row', async () => {await engine.setConfig('sync.repo_path', path.join(tmpRoot, 'does-not-exist'));const ctx = makeCtx();- const result = (await putPage.handler(ctx, {- slug: 'inbox/missing-repo',- content: '---\ntitle: M\n---\n\nbody',- })) as { write_through?: { skipped?: string } };- expect(result.write_through?.skipped).toBe('repo_not_found');+ await expect(+ putPage.handler(ctx, {+ slug: 'inbox/missing-repo',+ content: '---\ntitle: M\n---\n\nbody',+ }),+ ).rejects.toBeInstanceOf(OperationError);+ expect(await ctx.engine.getPage('inbox/missing-repo', { sourceId: 'default' })).toBeNull();});});@@ -214,7 +216,7 @@ describe('put_page write-through — multi-source filing', () => {});describe('put_page write-through — failure isolation', () => {- test('disk-write failure does not roll back DB', async () => {+ test('disk-write failure rejects the call and rolls back the new page (no index-only orphan)', async () => {// Point the config at a path that exists but isn't writable so the// write fails. Best portable trick: a regular file (writeFileSync to// a path inside a regular file fails with ENOTDIR).@@ -223,18 +225,17 @@ describe('put_page write-through — failure isolation', () => {await engine.setConfig('sync.repo_path', blockFile);const ctx = makeCtx();- const result = (await putPage.handler(ctx, {- slug: 'inbox/fail-isolated',- content: '---\ntitle: F\n---\n\nbody',- })) as { write_through?: { skipped?: string; error?: string } };- // Either skipped (existsSync sees a file, not a dir) or error during write.- expect(- result.write_through?.skipped === 'repo_not_found' ||- typeof result.write_through?.error === 'string',- ).toBe(true);-- // DB write succeeded.+ await expect(+ putPage.handler(ctx, {+ slug: 'inbox/fail-isolated',+ content: '---\ntitle: F\n---\n\nbody',+ }),+ ).rejects.toBeInstanceOf(OperationError);++ // The markdown file is the system of record; a page that only exists+ // as a DB row is an orphan the caller can't see or fix. Since this was+ // a brand-new slug, the failed write is rolled back entirely.const page = await engine.getPage('inbox/fail-isolated');- expect(page).not.toBeNull();+ expect(page).toBeNull();});});diff --git a/test/local-federated-search-scope.test.ts b/test/local-federated-search-scope.test.tsindex d1f5945adc..ed34ec8110 100644--- a/test/local-federated-search-scope.test.ts+++ b/test/local-federated-search-scope.test.ts@@ -231,3 +231,99 @@ describe('#3242 — get_page / list_pages / resolve_slugs share the federated viexpect(scalar).not.toContain('old/topic');});});++// A per-call source_id lets an agent narrow search/get_page to one source even+// when the transport widened the unqualified scope to the federated set. Only+// `query` accepted this before; search + get_page dropped it silently.+describe('per-call source_id narrows search / get_page over a federated ctx', () => {+ const getPage = operations.find((o) => o.name === 'get_page')!;++ function federatedCtx(overrides: Partial<OperationContext> = {}): OperationContext {+ return ctxOf({ localFederatedSourceIds: ['default', 'wiki'], ...overrides });+ }++ test('search source_id declared as a param', () => {+ expect(search.params.source_id?.type).toBe('string');+ expect(getPage.params.source_id?.type).toBe('string');+ });++ test('search: source_id narrows the federated scope to one source', async () => {+ const results = (await search.handler(federatedCtx(), {+ query: 'zebra telescope',+ source_id: 'wiki',+ })) as Array<{ slug: string }>;+ const slugs = results.map((r) => r.slug);+ expect(slugs).toEqual(['wiki/topic']);+ expect(slugs).not.toContain('notes/home');+ });++ test('get_page: source_id pins the lookup — foreign source is not found', async () => {+ // Federated ctx would otherwise resolve wiki/topic; pinning to 'default'+ // excludes it.+ await expect(+ getPage.handler(federatedCtx(), { slug: 'wiki/topic', source_id: 'default' }),+ ).rejects.toThrow(/not found/i);+ // Pinning to the correct source still resolves it.+ const page = (await getPage.handler(federatedCtx(), {+ slug: 'wiki/topic',+ source_id: 'wiki',+ })) as { slug: string };+ expect(page.slug).toBe('wiki/topic');+ });++ test('remote caller cannot escape its grant via source_id', async () => {+ // A federated grant that does NOT include 'wiki' must reject the narrow.+ const ctx = ctxOf({+ remote: true,+ auth: { allowedSources: ['default'] } as OperationContext['auth'],+ });+ await expect(+ search.handler(ctx, { query: 'zebra telescope', source_id: 'wiki' }),+ ).rejects.toThrow(/outside your granted sources/i);+ });+});++// Parity: list_pages and resolve_slugs share the same federated-widening default+// and must also accept a per-call source_id to narrow it.+describe('per-call source_id narrows list_pages / resolve_slugs over a federated ctx', () => {+ const listPages = operations.find((o) => o.name === 'list_pages')!;+ const resolveSlugsOp = operations.find((o) => o.name === 'resolve_slugs')!;++ function federatedCtx(overrides: Partial<OperationContext> = {}): OperationContext {+ return ctxOf({ localFederatedSourceIds: ['default', 'wiki'], ...overrides });+ }++ test('source_id declared as a param on both ops', () => {+ expect(listPages.params.source_id?.type).toBe('string');+ expect(resolveSlugsOp.params.source_id?.type).toBe('string');+ });++ test('list_pages: source_id narrows the federated scope to one source', async () => {+ const rows = (await listPages.handler(federatedCtx(), { source_id: 'wiki' })) as Array<{ slug: string }>;+ const slugs = rows.map((r) => r.slug);+ expect(slugs).toContain('wiki/topic');+ expect(slugs).not.toContain('notes/home');+ });++ test('resolve_slugs: source_id narrows the federated scope to one source', async () => {+ const wikiOnly = (await resolveSlugsOp.handler(federatedCtx(), { partial: 'topic', source_id: 'wiki' })) as string[];+ expect(wikiOnly).toContain('wiki/topic');+ expect(wikiOnly).not.toContain('notes/home');++ const defaultOnly = (await resolveSlugsOp.handler(federatedCtx(), { partial: 'topic', source_id: 'default' })) as string[];+ expect(defaultOnly).not.toContain('wiki/topic');+ });++ test('remote caller cannot escape its grant via source_id (both ops)', async () => {+ const ctx = ctxOf({+ remote: true,+ auth: { allowedSources: ['default'] } as OperationContext['auth'],+ });+ await expect(+ listPages.handler(ctx, { source_id: 'wiki' }),+ ).rejects.toThrow(/outside your granted sources/i);+ await expect(+ resolveSlugsOp.handler(ctx, { partial: 'topic', source_id: 'wiki' }),+ ).rejects.toThrow(/outside your granted sources/i);+ });+});diff --git a/test/memory-verbs-conformance.test.ts b/test/memory-verbs-conformance.test.tsindex 4ecba91cbc..09c78638aa 100644--- a/test/memory-verbs-conformance.test.ts+++ b/test/memory-verbs-conformance.test.ts@@ -45,7 +45,7 @@ import {__setEmbedTransportForTests,} from '../src/core/ai/gateway.ts';import { __setUsageLogPathForTests } from '../src/core/verbs/usage-log.ts';-import { withEnv } from './helpers/with-env.ts';+import { emptyHome, withEnv } from './helpers/with-env.ts';let engine: PGLiteEngine;let home: string;@@ -101,14 +101,23 @@ async function callRemote(name: string, params: Record<string, unknown>) {return { isError: res.isError === true, body: JSON.parse(res.content[0].text) };}-async function seedEntityPage(slug: string, title: string, body = 'A synthetic test entity.') {+async function seedPage(+ slug: string,+ title: string,+ type: string,+ body = 'Synthetic test content.',+) {const put = operationsByName['put_page'];await put.handler(localCtx(), {slug,- content: `---\ntitle: ${title}\ntype: person\n---\n\n# ${title}\n\n${body}\n`,+ content: `---\ntitle: ${title}\ntype: ${type}\n---\n\n# ${title}\n\n${body}\n`,});}+async function seedEntityPage(slug: string, title: string, body = 'A synthetic test entity.') {+ await seedPage(slug, title, 'person', body);+}+describe('recall — G1B superset + budget packing', () => {it('legacy-param recall keeps every legacy field shape and adds only the v1 fields', async () => {const r1 = await callRemote('remember', {@@ -219,6 +228,66 @@ describe('remember — contract behavior', () => {});describe('entity — card, arms, zero LLM', () => {+ it('prefers an entity page when a newer conversation has the same exact title', async () => {+ await seedEntityPage('people/jordan-example', 'Jordan Example');+ await seedPage(+ 'conversations/jordan-example-session',+ 'Jordan Example',+ 'conversation',+ 'A newer conversation transcript with the same title.',+ );+ await engine.executeRaw(+ `UPDATE pages+ SET updated_at = CASE slug+ WHEN 'people/jordan-example' THEN '2026-01-01T00:00:00Z'::timestamptz+ ELSE '2026-02-01T00:00:00Z'::timestamptz+ END+ WHERE source_id = 'default'+ AND slug IN ('people/jordan-example', 'conversations/jordan-example-session')`,+ );++ const { isError, body } = await callRemote('entity', { name: 'Jordan Example' });+ expect(isError).toBe(false);+ expect(body.card.entity.slug).toBe('people/jordan-example');+ expect(body.suggestions).toContainEqual(expect.objectContaining({+ slug: 'conversations/jordan-example-session',+ }));+ });++ it('keeps an explicit namespaced slug above an entity-shaped exact-title collision', async () => {+ await seedPage('notes/exact-target', 'Operational Runbook', 'note');+ await seedEntityPage('people/slug-shaped-title', 'notes/exact-target');+ await engine.executeRaw(+ `UPDATE pages+ SET updated_at = CASE slug+ WHEN 'notes/exact-target' THEN '2026-01-01T00:00:00Z'::timestamptz+ ELSE '2026-02-01T00:00:00Z'::timestamptz+ END+ WHERE source_id = 'default'+ AND slug IN ('notes/exact-target', 'people/slug-shaped-title')`,+ );++ const { body } = await callRemote('entity', { name: 'notes/exact-target' });+ expect(body.card.entity.slug).toBe('notes/exact-target');+ });++ it('keeps an explicit alias above entity-type preference', async () => {+ await seedEntityPage('people/alias-title-collision', 'Jordan Alias');+ await seedPage('notes/alias-target', 'Archived Context', 'note');+ await engine.setPageAliases('notes/alias-target', 'default', ['jordan alias']);++ const { body } = await callRemote('entity', { name: 'Jordan Alias' });+ expect(body.card.entity.slug).toBe('notes/alias-target');+ });++ it('retains a non-entity exact-title page as the fallback when no entity page exists', async () => {+ await seedPage('notes/release-checklist', 'Release Checklist', 'note');++ const { body } = await callRemote('entity', { name: 'Release Checklist' });+ expect(body.found).toBe(true);+ expect(body.card.entity.slug).toBe('notes/release-checklist');+ });+it('resolves an exact namespaced slug to a schema-valid card with the chat gateway rigged to throw', async () => {__setChatTransportForTests(() => {throw new Error('entity must NEVER call the chat LLM');@@ -472,10 +541,12 @@ describe('writeSingleFact — supersession rule [X1] + degraded dedup', () => {});it('reports degraded_dedup when no embedding provider is configured', async () => {- const r = await writeSingleFact(engine, 'default', {- fact: 'a fact written with no embedding provider',- provenance: 'test', entity: 'people/degraded-test',- });+ const r = await withNoEmbeddingProvider(() =>+ writeSingleFact(engine, 'default', {+ fact: 'a fact written with no embedding provider',+ provenance: 'test', entity: 'people/degraded-test',+ }),+ );expect(r.status).toBe('inserted');expect(r.degraded_dedup).toBe(true);});@@ -502,34 +573,42 @@ describe('conformance runner — negative self-test [F3]', () => {it('a certifier that cannot fail certifies nothing: missing fields, bad enums, wrong id types all flag', async () => {// Mutation 1: remember drops the required `status` field.- const r1 = await runConformance(- lyingClient((verb, body) => (verb === 'remember' ? (({ status: _s, ...rest }) => rest)(body as { status?: unknown } & Record<string, unknown>) : body)),- { marker: 'neg1' },+ const r1 = await withNoEmbeddingProvider(() =>+ runConformance(+ lyingClient((verb, body) => (verb === 'remember' ? (({ status: _s, ...rest }) => rest)(body as { status?: unknown } & Record<string, unknown>) : body)),+ { marker: 'neg1' },+ ),);expect(r1.ok).toBe(false);// Mutation 2: remember returns an out-of-enum status.- const r2 = await runConformance(- lyingClient((verb, body) => (verb === 'remember' ? { ...body, status: 'absorbed' } : body)),- { marker: 'neg2' },+ const r2 = await withNoEmbeddingProvider(() =>+ runConformance(+ lyingClient((verb, body) => (verb === 'remember' ? { ...body, status: 'absorbed' } : body)),+ { marker: 'neg2' },+ ),);expect(r2.ok).toBe(false);// Mutation 3: recall re-types fact_id to a number (the opaque-string mandate [T4]).- const r3 = await runConformance(- lyingClient((verb, body) => {- if (verb !== 'recall' || !Array.isArray((body as { facts?: unknown[] }).facts)) return body;- return {- ...body,- facts: (body.facts as Array<Record<string, unknown>>).map(f => ({ ...f, fact_id: Number(f.fact_id) })),- };- }),- { marker: 'neg3' },+ const r3 = await withNoEmbeddingProvider(() =>+ runConformance(+ lyingClient((verb, body) => {+ if (verb !== 'recall' || !Array.isArray((body as { facts?: unknown[] }).facts)) return body;+ return {+ ...body,+ facts: (body.facts as Array<Record<string, unknown>>).map(f => ({ ...f, fact_id: Number(f.fact_id) })),+ };+ }),+ { marker: 'neg3' },+ ),);expect(r3.ok).toBe(false);// Honest server passes (sanity: the failures above are the mutations' doing).- const honest = await runConformance(lyingClient((_v, b) => b), { marker: 'pos1' });+ const honest = await withNoEmbeddingProvider(() =>+ runConformance(lyingClient((_v, b) => b), { marker: 'pos1' }),+ );const failures = honest.results.filter(r => r.status === 'fail');expect(failures).toEqual([]);}, 20_000); // v0.45.7: two full runConformance passes now exercise 7 verbs;@@ -568,7 +647,9 @@ describe('fixture mirror + surface invariants', () => {return { isError: res.isError, text: res.content[0].text };},};- const r = await runConformance(fiveVerbClient, { marker: `five-${Date.now()}` });+ const r = await withNoEmbeddingProvider(() =>+ runConformance(fiveVerbClient, { marker: `five-${Date.now()}` }),+ );// The additive verbs must appear ONLY as skips — never executed, never failed.const additive = r.results.filter((x) => x.verb === 'context_pack' || x.verb === 'delta');expect(additive.length).toBeGreaterThan(0);@@ -580,3 +661,24 @@ describe('fixture mirror + surface invariants', () => {expect(advertFails).toEqual([]);});});++function withNoEmbeddingProvider<T>(fn: () => T | Promise<T>): Promise<T> {+ return withEnv(+ {+ GBRAIN_HOME: emptyHome(),+ OPENAI_API_KEY: undefined,+ VOYAGE_API_KEY: undefined,+ GOOGLE_GENERATIVE_AI_API_KEY: undefined,+ },+ async () => {+ resetGateway();+ __setEmbedTransportForTests(null);+ try {+ return await fn();+ } finally {+ resetGateway();+ __setEmbedTransportForTests(null);+ }+ },+ );+}diff --git a/test/migrate-retry.test.ts b/test/migrate-retry.test.tsindex ef3208232f..ed70a0af1d 100644--- a/test/migrate-retry.test.ts+++ b/test/migrate-retry.test.ts@@ -13,13 +13,17 @@* 7. 250ms poll interval honored (custom interval respected)* 8. isDeadlockError matches SQLSTATE 40P01 in code field* 9. isDeadlockError matches "deadlock detected" in message text+ * 10. initSchema retry catches raw 57014 setup flakes+ * 11. initSchema retry does not wrap an exhausted per-migration retry*/import { describe, test, expect } from 'bun:test';import {tryRunPendingMigrations,isDeadlockError,+ MigrationRetryExhausted,type TryRunPendingMigrationsResult,} from '../src/core/migrate.ts';+import { runInitSchemaWithRetry } from '../src/core/init-schema-retry.ts';import type { BrainEngine } from '../src/core/engine.ts';// Fake engine for typing — never used because _hooks override everything.@@ -30,6 +34,14 @@ class FakeDeadlock extends Error {constructor() { super('deadlock detected'); this.name = 'FakeDeadlock'; }}+class FakeStatementTimeout extends Error {+ code = '57014';+ constructor() {+ super('canceling statement due to statement timeout');+ this.name = 'FakeStatementTimeout';+ }+}+describe('isDeadlockError', () => {test('matches SQLSTATE 40P01 in `.code`', () => {expect(isDeadlockError({ code: '40P01', message: 'whatever' })).toBe(true);@@ -58,6 +70,59 @@ describe('isDeadlockError', () => {});});+describe('runInitSchemaWithRetry', () => {+ test('retries raw statement_timeout failures from schema setup', async () => {+ let initCalls = 0;+ const sleeps: number[] = [];+ const logs: string[] = [];++ const result = await runInitSchemaWithRetry(fakeEngine, {+ maxAttempts: 5,+ backoffMs: 0,+ log: (line) => logs.push(line),+ _hooks: {+ sleep: async (ms) => { sleeps.push(ms); },+ initSchema: async () => {+ initCalls++;+ if (initCalls < 3) throw new FakeStatementTimeout();+ },+ },+ });++ expect(result.attempts).toBe(3);+ expect(initCalls).toBe(3);+ expect(sleeps).toEqual([0, 0]);+ expect(logs).toHaveLength(2);+ expect(logs[0]).toContain('statement_timeout');+ });++ test('does not double-wrap an exhausted migration retry envelope', async () => {+ const exhausted = new MigrationRetryExhausted(+ 16,+ 'sample_migration',+ 3,+ [],+ new FakeStatementTimeout(),+ );+ let initCalls = 0;+ const sleeps: number[] = [];++ await expect(runInitSchemaWithRetry(fakeEngine, {+ backoffMs: 0,+ _hooks: {+ sleep: async (ms) => { sleeps.push(ms); },+ initSchema: async () => {+ initCalls++;+ throw exhausted;+ },+ },+ })).rejects.toBe(exhausted);++ expect(initCalls).toBe(1);+ expect(sleeps).toEqual([]);+ });+});+describe('tryRunPendingMigrations', () => {test('returns not_needed when hasPending returns false up front', async () => {const result = await tryRunPendingMigrations(fakeEngine, {diff --git a/test/model-pricing.test.ts b/test/model-pricing.test.tsindex aa77b96fbc..239e52f56d 100644--- a/test/model-pricing.test.ts+++ b/test/model-pricing.test.ts@@ -64,6 +64,13 @@ describe('CANONICAL_PRICING — table integrity', () => {);});+ // Retired ids stay priced so historical usage/audit rows still resolve;+ // the live successors have to be priced for anything new to be estimated.+ test('the live Gemini ids are priced alongside the retired ones', () => {+ expect(CANONICAL_PRICING['google:gemini-2.5-flash']).toEqual({ input: 0.3, output: 2.5 });+ expect(CANONICAL_PRICING['google:gemini-2.5-flash-lite']).toEqual({ input: 0.1, output: 0.4 });+ });+// #4218 drift guard extension: cache_read/cache_write are DERIVED from the// input rate via the exported multipliers — a hand-edited cache number that// drifts from input*mult fails here.diff --git a/test/oauth.test.ts b/test/oauth.test.tsindex cdbb5f027e..8ea597ffc4 100644--- a/test/oauth.test.ts+++ b/test/oauth.test.ts@@ -1018,7 +1018,7 @@ describe('redirect_uri validation (DCR)', () => {scope: 'read',token_endpoint_auth_method: 'client_secret_post',}),- ).rejects.toThrow(/https/);+ ).rejects.toThrow(/https|loopback|custom scheme/i);});test('non-URL string is rejected', async () => {@@ -1033,6 +1033,59 @@ describe('redirect_uri validation (DCR)', () => {).rejects.toThrow();});+ test('native-app custom scheme redirect_uri is allowed (RFC 8252 §7.1)', async () => {+ const result = await provider.clientsStore.registerClient!({+ client_name: 'warp-custom-scheme',+ redirect_uris: ['warp://oauth/callback'],+ grant_types: ['authorization_code'],+ scope: 'read',+ token_endpoint_auth_method: 'none',+ });+ expect(result.client_id).toStartWith('gbrain_cl_');+ const stored = await provider.clientsStore.getClient(result.client_id);+ expect(stored!.redirect_uris).toEqual(['warp://oauth/callback']);+ });++ test('browser pseudo-schemes are rejected in the custom-scheme branch', async () => {+ // javascript:/data:/vbscript:/blob: are not native-app schemes — a+ // "redirect" to one is script injection. The custom-scheme allow branch+ // must not let them through.+ for (const uri of [+ 'javascript://alert(1)',+ 'data://text/html;base64,PGh0bWw+',+ 'vbscript://msgbox',+ 'blob://example.com/uuid',+ ]) {+ await expect(+ provider.clientsStore.registerClient!({+ client_name: 'pseudo-scheme-client',+ redirect_uris: [uri],+ grant_types: ['authorization_code'],+ scope: 'read',+ token_endpoint_auth_method: 'none',+ }),+ ).rejects.toThrow(/pseudo-scheme/);+ }+ });++ test('DCR validation failures throw InvalidClientMetadataError (not plain Error)', async () => {+ const { InvalidClientMetadataError } = await import(+ '@modelcontextprotocol/sdk/server/auth/errors.js'+ );+ try {+ await provider.clientsStore.registerClient!({+ client_name: 'http-rejected-type',+ redirect_uris: ['http://example.com/callback'],+ grant_types: ['authorization_code'],+ scope: 'read',+ token_endpoint_auth_method: 'client_secret_post',+ });+ throw new Error('expected throw');+ } catch (e) {+ expect(e).toBeInstanceOf(InvalidClientMetadataError);+ }+ });+// pgArray escape regression: an element containing a comma must be stored// as ONE element, not parsed by Postgres as TWO. Without the fix, the// comma would smuggle a second redirect_uri into the registered list.@@ -1318,16 +1371,38 @@ describe('v0.28 ALLOWED_SCOPES allowlist', () => {}});- test('registerClient (DCR) rejects unknown scope strings', async () => {- await expect(- provider.clientsStore.registerClient!({- client_name: 'dcr-bad-scope',+ test('registerClient (DCR) filters unknown scopes and keeps allowed ones', async () => {+ // DCR is unauthenticated and clients (rmcp / OIDC-flavored stacks) often+ // append offline_access etc. Filter unknowns instead of 500ing.+ const result = await provider.clientsStore.registerClient!({+ client_name: 'dcr-filter-scope',+ redirect_uris: ['https://example.com/cb'],+ grant_types: ['authorization_code'],+ scope: 'read write offline_access openid',+ token_endpoint_auth_method: 'none',+ } as any);+ expect(result.scope).toBe('read write');+ const stored = await provider.clientsStore.getClient(result.client_id);+ expect(stored!.scope).toBe('read write');+ });++ test('registerClient (DCR) rejects when every requested scope is unknown', async () => {+ const { InvalidClientMetadataError } = await import(+ '@modelcontextprotocol/sdk/server/auth/errors.js'+ );+ try {+ await provider.clientsStore.registerClient!({+ client_name: 'dcr-all-unknown-scope',redirect_uris: ['https://example.com/cb'],grant_types: ['authorization_code'],- scope: 'read bogus_scope',- token_endpoint_auth_method: 'client_secret_post',- } as any),- ).rejects.toThrow(/Unknown scope/);+ scope: 'openid offline_access',+ token_endpoint_auth_method: 'none',+ } as any);+ throw new Error('expected throw');+ } catch (e) {+ expect(e).toBeInstanceOf(InvalidClientMetadataError);+ expect((e as Error).message).toMatch(/No recognized scopes/);+ }});});@@ -1769,7 +1844,9 @@ describe('v0.41.3 DCR validator (T5)', () => {test('DCR rejects unknown token_endpoint_auth_method — closes --enable-dcr loose path', async () => {// Pre-v0.41.3 the DCR registration handler defaulted to 'client_secret_post'// for any unknown value, silently swallowing typos. T5 throws so the bad- // input fails loud — same gate as CLI + admin paths.+ // input fails loud. DCR wraps the inner InvalidTokenEndpointAuthMethodError+ // as InvalidClientMetadataError so the MCP SDK returns HTTP 400 instead of+ // opaque 500 (Warp/rmcp regression).await expect(provider.clientsStore.registerClient!({client_name: 'dcr-bad-test',@@ -1778,7 +1855,7 @@ describe('v0.41.3 DCR validator (T5)', () => {redirect_uris: ['https://example.test/cb'],token_endpoint_auth_method: 'frobnicate',} as any),- ).rejects.toThrow(InvalidTokenEndpointAuthMethodError);+ ).rejects.toThrow(InvalidClientMetadataError);});test('DCR accepts "none" → public PKCE client', async () => {diff --git a/test/onboard-coverage-invariants.test.ts b/test/onboard-coverage-invariants.test.tsnew file mode 100644index 0000000000..bf02717d38--- /dev/null+++ b/test/onboard-coverage-invariants.test.ts@@ -0,0 +1,130 @@+/**+ * Coverage checks must derive numerator and denominator from the same visible+ * entity sample. An estimated Bernoulli denominator can be smaller than the+ * actual sample, producing impossible values above 100% and a NaN confidence+ * interval. Quarantined pages are hidden from the brain and must be excluded+ * from both sides of every coverage ratio.+ */++import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ checkEntityLinkCoverage,+ checkTimelineCoverage,+} from '../src/core/onboard/checks.ts';+import { buildQuarantineMarker } from '../src/core/quarantine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++async function seedVisibleAndQuarantinedEntities(): Promise<void> {+ await engine.putPage('people/visible-example', {+ type: 'person',+ title: 'Visible Example',+ compiled_truth: 'A visible synthetic entity.',+ timeline: '',+ });+ await engine.putPage('people/quarantined-example', {+ type: 'person',+ title: 'Quarantined Example',+ compiled_truth: 'A quarantined synthetic entity.',+ timeline: '',+ frontmatter: {+ quarantine: buildQuarantineMarker('junk_pattern', 'synthetic fixture'),+ },+ });+ await engine.putPage('notes/source-example', {+ type: 'note',+ title: 'Source Example',+ compiled_truth: 'A synthetic source page.',+ timeline: '',+ });+}++describe('onboard entity coverage invariants', () => {+ test('uses the actual Bernoulli sample size and never emits >100% or NaN', async () => {+ const queries: string[] = [];+ let call = 0;+ const postgres = {+ kind: 'postgres',+ async executeRaw(sql: string) {+ queries.push(sql);+ call++;+ if (call === 1) return [{ count: 100_000 }];+ // The old implementation reads count=7,050 but divides by the+ // estimated 5,000 rows, yielding "Coverage 141% ± NaN%". The actual+ // sampled denominator is 10,000, so the truthful result is 71%.+ return [{ count: 7_050, matched: 7_050, sample_size: 10_000 }];+ },+ } as unknown as BrainEngine;++ const result = await checkEntityLinkCoverage(postgres);++ expect(result.check.message).toMatch(/^Coverage 71% ± \d+\.\d%/);+ expect(result.check.message).not.toMatch(/NaN|Infinity/);+ expect(result.check.message).not.toMatch(/Coverage 1\d\d%/);+ expect(queries).toHaveLength(2);+ });++ test('defensively clamps malformed sampled counts to the 0-100% invariant', async () => {+ let call = 0;+ const postgres = {+ kind: 'postgres',+ async executeRaw() {+ call++;+ if (call === 1) return [{ count: 100_000 }];+ return [{ matched: 12_000, sample_size: 10_000 }];+ },+ } as unknown as BrainEngine;++ const result = await checkEntityLinkCoverage(postgres);++ expect(result.check.message).toMatch(/^Coverage 100% ± 0\.0%/);+ expect(result.check.message).not.toMatch(/NaN|Infinity/);+ });++ test('entity-link coverage excludes quarantined entities from numerator and denominator', async () => {+ await seedVisibleAndQuarantinedEntities();+ await engine.addLink(+ 'notes/source-example',+ 'people/quarantined-example',+ '',+ 'mentions',+ 'manual',+ );++ const result = await checkEntityLinkCoverage(engine);++ expect(result.check.message).toMatch(/^Coverage 0% ± 0\.0%/);+ expect(result.check.message).not.toContain('50%');+ });++ test('timeline coverage applies the same visible-sample invariant', async () => {+ await seedVisibleAndQuarantinedEntities();+ await engine.addTimelineEntry('people/quarantined-example', {+ date: '2026-01-01',+ source: 'synthetic fixture',+ summary: 'Synthetic event',+ });++ const result = await checkTimelineCoverage(engine);++ expect(result.check.message).toMatch(/^Coverage 0% ± 0\.0%/);+ expect(result.check.message).not.toContain('50%');+ });+});diff --git a/test/onboard-pack-upgrade-checks.test.ts b/test/onboard-pack-upgrade-checks.test.tsindex 826f67fde4..fb4e3f3d2c 100644--- a/test/onboard-pack-upgrade-checks.test.ts+++ b/test/onboard-pack-upgrade-checks.test.ts@@ -156,6 +156,60 @@ describe('checkDanglingAliases (F12 source-scoped JOIN)', () => {const result = await checkDanglingAliases(engine);expect(result.check.status).toBe('warn');expect(result.check.message).toContain('1 alias rows');+ expect(result.check.message).toContain('1 slug redirects');+ expect(result.check.message).toContain('0 free-text page aliases');+ });++ it('warns when a free-text alias points at a missing page', async () => {+ await engine.executeRaw(+ `INSERT INTO page_aliases (source_id, alias_norm, slug)+ VALUES ('default', 'alice example', 'people/alice-example')`,+ );+ const result = await checkDanglingAliases(engine);+ expect(result.check.status).toBe('warn');+ expect(result.check.message).toContain('1 alias rows');+ expect(result.check.message).toContain('0 slug redirects');+ expect(result.check.message).toContain('1 free-text page aliases');+ });++ it('returns ok when a free-text alias points at an active page', async () => {+ await seedPages(['note']);+ await engine.executeRaw(+ `INSERT INTO page_aliases (source_id, alias_norm, slug)+ VALUES ('default', 'page zero', 'p0')`,+ );+ const result = await checkDanglingAliases(engine);+ expect(result.check.status).toBe('ok');+ });++ it('warns when a free-text alias points at a soft-deleted page', async () => {+ await seedPages(['note']);+ await engine.executeRaw(+ `INSERT INTO page_aliases (source_id, alias_norm, slug)+ VALUES ('default', 'old page', 'p0')`,+ );+ await engine.softDeletePage('p0', { sourceId: 'default' });+ const result = await checkDanglingAliases(engine);+ expect(result.check.status).toBe('warn');+ expect(result.check.message).toContain('1 free-text page aliases');+ });++ it('does not let another source satisfy a free-text alias target', async () => {+ await engine.executeRaw(+ `INSERT INTO sources (id, name) VALUES ('alt', 'alt') ON CONFLICT DO NOTHING`,+ );+ await engine.putPage('shared-page', {+ title: 'shared', type: 'note' as never,+ compiled_truth: 'body that is long enough to pass any min-length guards in the codebase',+ timeline: '', frontmatter: {}, source_path: 'shared-page.md',+ }, { sourceId: 'alt' });+ await engine.executeRaw(+ `INSERT INTO page_aliases (source_id, alias_norm, slug)+ VALUES ('default', 'shared', 'shared-page')`,+ );+ const result = await checkDanglingAliases(engine);+ expect(result.check.status).toBe('warn');+ expect(result.check.message).toContain('1 free-text page aliases');});it('does NOT false-positive across sources (F12 regression)', async () => {diff --git a/test/operations-find-trajectory.test.ts b/test/operations-find-trajectory.test.tsindex e4adbf5045..863cd1db86 100644--- a/test/operations-find-trajectory.test.ts+++ b/test/operations-find-trajectory.test.ts@@ -147,6 +147,23 @@ describe('find_trajectory MCP op — visibility filter (R6 / D-CDX-1)', () => {expect(remote.points.length).toBe(1);expect(remote.points[0].value).toBe(99999);});++ test('FAIL-CLOSED cast bypass: a context missing `remote` is world-only (F7b)', async () => {+ await insertTyped({ entity_slug: 'optraj-vis-bypass', metric: 'mrr', value: 50000, visibility: 'private', valid_from: new Date('2026-01-15') });+ await insertTyped({ entity_slug: 'optraj-vis-bypass', metric: 'mrr', value: 99999, visibility: 'world', valid_from: new Date('2026-04-12') });++ const op = operationsByName['find_trajectory'];+ // Simulate the type bypass this fix closes: a widened context (Partial<>+ // cast) whose `remote` was never threaded. If the ops-layer coercion ever+ // regresses to `ctx.remote === true`, this context becomes an explicit+ // remote: false and reads the private row — the exact leak class F7b+ // closed for whoami. It must degrade to world-only instead.+ const ctx = mkCtx();+ delete (ctx as any).remote;+ const result = await op.handler(ctx, { entity_slug: 'optraj-vis-bypass' }) as any;+ expect(result.points.length).toBe(1);+ expect(result.points[0].value).toBe(99999);+ });});describe('find_trajectory MCP op — source scoping (D-CDX-6)', () => {diff --git a/test/operations-trust-boundary.test.ts b/test/operations-trust-boundary.test.tsindex 7cde4502ca..b3143839ca 100644--- a/test/operations-trust-boundary.test.ts+++ b/test/operations-trust-boundary.test.ts@@ -43,6 +43,7 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:tesimport { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { operations, type OperationContext } from '../src/core/operations.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';import { hasScope } from '../src/core/scope.ts';let engine: PGLiteEngine;@@ -131,6 +132,47 @@ describe('operations contract — every op has scope + correct mutability shape').toBe(true);}});++ test('state-changing job controls declare mutating metadata', () => {+ for (const name of ['pause_job', 'resume_job', 'replay_job', 'send_job_message']) {+ const op = operations.find(candidate => candidate.name === name);+ expect(op, `expected canonical op "${name}" to exist`).toBeDefined();+ expect(op!.mutating, `state-changing op "${name}" must declare mutating`).toBe(true);+ }+ });+});++describe('job-control operations — dry run never changes queue state', () => {+ test('pause_job previews without pausing, then a real call pauses', async () => {+ await engine.setConfig('version', '130');+ const queue = new MinionQueue(engine);+ const job = await queue.add('sync', {});+ const op = operations.find(candidate => candidate.name === 'pause_job')!;++ const preview = await op.handler(makeContext({ remote: false, dryRun: true }), { id: job.id });+ expect(preview).toEqual({ dry_run: true, action: 'pause_job', id: job.id });+ expect((await queue.getJob(job.id))!.status).toBe('waiting');++ const result = await op.handler(makeContext({ remote: false }), { id: job.id });+ expect(result).toEqual({ id: job.id, status: 'paused' });+ expect((await queue.getJob(job.id))!.status).toBe('paused');+ });++ test('resume_job previews without resuming, then a real call resumes', async () => {+ await engine.setConfig('version', '130');+ const queue = new MinionQueue(engine);+ const job = await queue.add('sync', {});+ await queue.pauseJob(job.id);+ const op = operations.find(candidate => candidate.name === 'resume_job')!;++ const preview = await op.handler(makeContext({ remote: false, dryRun: true }), { id: job.id });+ expect(preview).toEqual({ dry_run: true, action: 'resume_job', id: job.id });+ expect((await queue.getJob(job.id))!.status).toBe('paused');++ const result = await op.handler(makeContext({ remote: false }), { id: job.id });+ expect(result).toEqual({ id: job.id, status: 'waiting' });+ expect((await queue.getJob(job.id))!.status).toBe('waiting');+ });});describe('mcpOperations filter — localOnly ops are excluded from the HTTP-exposed surface', () => {diff --git a/test/pages-body-nul-sanitize.test.ts b/test/pages-body-nul-sanitize.test.tsnew file mode 100644index 0000000000..fc24e02e01--- /dev/null+++ b/test/pages-body-nul-sanitize.test.ts@@ -0,0 +1,105 @@+// gbrain#3998 regression (also covers the #4392 ingest-abort shape) — pages+// body columns (title, compiled_truth, timeline) and content_chunks.chunk_text+// must survive a raw NUL and a lone UTF-16 surrogate. Pre-fix, putPage and+// upsertChunks bound the raw strings, so one 0x00 byte aborted the INSERT with+// `invalid byte sequence for encoding "UTF8": 0x00` and dropped the whole+// document. #2011's sanitizeForJsonb only covered links/timeline/takes+// free-text; `sanitizeText` extends the same policy to the body columns.+//+// PGLite half (always-on): PGLite may not reproduce the exact Postgres+// encoding abort, but it locks the JS-side sanitization the same way+// links-timeline-jsonb-poison.test.ts does for the batch builders.++import { afterAll, beforeAll, describe, expect, it } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';++// Built via fromCharCode so no literal NUL / lone surrogate lands in this file.+const NUL = String.fromCharCode(0);+const LONE_HI = String.fromCharCode(0xd83c);++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++describe('putPage — NUL/lone-surrogate body sanitization (#3998)', () => {+ it('persists and round-trips a page whose body columns carry NUL + lone surrogate', async () => {+ const page = await engine.putPage('poisoned-page', {+ type: 'concept' as never,+ title: `ti${NUL}tle${LONE_HI}`,+ compiled_truth: `body with a raw${NUL} NUL and a lone ${LONE_HI} surrogate, long enough to pass backstops`,+ timeline: `- 2026-01-01: something${NUL} happened${LONE_HI}`,+ frontmatter: {},+ source_path: 'poisoned-page.md',+ });+ // The page persisted (pre-fix: the INSERT aborts) and the stored values+ // are NUL-free and well-formed (lone surrogate → U+FFFD).+ expect(page.title).toBe('title�');+ expect(page.compiled_truth).not.toContain(NUL);+ expect(page.compiled_truth).toContain('�');+ expect(page.timeline).not.toContain(NUL);++ const fetched = await engine.getPage('poisoned-page');+ expect(fetched).not.toBeNull();+ expect(fetched!.title).toBe('title�');+ expect(fetched!.compiled_truth).not.toContain(NUL);+ expect(fetched!.timeline).not.toContain(NUL);+ });+});++describe('upsertChunks — NUL/lone-surrogate chunk_text sanitization (#3998)', () => {+ it('persists poisoned chunk_text and keeps embedded_text_hash consistent with the stored text', async () => {+ await engine.putPage('poisoned-chunks', {+ type: 'concept' as never,+ title: 'poisoned chunks',+ compiled_truth: 'clean body long enough to pass any minimum length backstop',+ timeline: '',+ frontmatter: {},+ source_path: 'poisoned-chunks.md',+ });+ await engine.upsertChunks('poisoned-chunks', [+ {+ chunk_index: 0,+ chunk_text: `chunk with${NUL} NUL and lone ${LONE_HI} surrogate`,+ chunk_source: 'compiled_truth',+ // Embedding present so the embedded_text_hash md5() bind path runs —+ // pre-fix that second raw chunk_text bind aborted the INSERT even if+ // the stored-text bind were sanitized, and the hash diverged.+ embedding: new Float32Array(1536),+ },+ {+ chunk_index: 1,+ chunk_text: `unembedded chunk with${NUL} NUL`,+ chunk_source: 'compiled_truth',+ },+ ]);++ const rows = await engine.executeRaw<{+ chunk_index: number;+ chunk_text: string;+ embedded_text_hash: string | null;+ recomputed: string;+ }>(+ `SELECT c.chunk_index, c.chunk_text, c.embedded_text_hash, md5(c.chunk_text) AS recomputed+ FROM content_chunks c+ JOIN pages p ON p.id = c.page_id+ WHERE p.slug = 'poisoned-chunks' AND p.source_id = 'default'+ ORDER BY c.chunk_index`,+ );+ expect(rows.length).toBe(2);+ for (const row of rows) {+ expect(row.chunk_text).not.toContain(NUL);+ }+ expect(rows[0].chunk_text).toContain('�');+ // The hash was computed over the SAME sanitized bytes as the stored text.+ expect(rows[0].embedded_text_hash).toBe(rows[0].recomputed);+ expect(rows[1].embedded_text_hash).toBeNull();+ });+});diff --git a/test/pglite-lock.test.ts b/test/pglite-lock.test.tsindex 4dff5c9b0e..0a44dac527 100644--- a/test/pglite-lock.test.ts+++ b/test/pglite-lock.test.ts@@ -1,5 +1,6 @@import { describe, test, expect, beforeEach, afterEach } from 'bun:test';-import { mkdirSync, mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync } from 'fs';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync, readlinkSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';import { acquireLock, releaseLock, type LockHandle } from '../src/core/pglite-lock';@@ -366,3 +367,203 @@ describe('pglite-lock reap classification (WAL-repair wave)', () => {}}, 30_000);});++describe('pglite-lock PID-reuse detection', () => {+ // The wedge this covers: a gbrain holder dies, the OS recycles its PID into+ // an unrelated process (docker-proxy, a shell, ...), and kill(pid, 0) keeps+ // saying "alive" — so the stale lock was never reaped and every acquirer+ // timed out until manual cleanup.+ const canProbe = process.platform !== 'win32'; // ps + sleep/bash available+ const isLinux = process.platform === 'linux';++ function currentBootId(): string | null {+ try { return readFileSync('/proc/sys/kernel/random/boot_id', 'utf-8').trim() || null; }+ catch { return null; }+ }++ function currentPidNs(): string | null {+ try { return readlinkSync('/proc/self/ns/pid'); } catch { return null; }+ }++ function writeHolderAt(dataDir: string, pid: number, command: string, opts?: { subcommand?: string; bootId?: string | null; pidNs?: string | null }) {+ const lockDir = join(dataDir, '.gbrain-lock');+ mkdirSync(lockDir, { recursive: true });+ const now = Date.now();+ writeFileSync(join(lockDir, 'lock'), JSON.stringify({+ pid,+ acquired_at: now - 60_000,+ refreshed_at: now - 60_000,+ command,+ boot_id: opts?.bootId === undefined ? currentBootId() : opts.bootId,+ pid_ns: opts?.pidNs === undefined ? currentPidNs() : opts.pidNs,+ ...(opts?.subcommand === undefined ? {} : { subcommand: opts.subcommand }),+ }));+ }++ /**+ * Wait until the spawned child has exec'd into its target program. Between+ * spawn and exec, the child's command line still shows the PARENT's argv —+ * which under the repo test runner contains "gbrain" (the checkout path) and+ * would spoof the reuse check. Poll via `ps` until the real args are in place.+ */+ async function waitForExec(pid: number, pattern: RegExp): Promise<void> {+ const deadline = Date.now() + 5000;+ while (Date.now() < deadline) {+ try {+ const args = execFileSync('ps', ['-p', String(pid), '-o', 'args='], {+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 1000,+ }).trim();+ if (args.length > 0 && pattern.test(args)) return;+ } catch { /* not exec'd yet — retry */ }+ await new Promise(r => setTimeout(r, 25));+ }+ throw new Error(`child ${pid} never exec'd into ${pattern}`);+ }++ test.skipIf(!canProbe)('reaps a lock whose PID was recycled by an unrelated program', async () => {+ // `sleep` is a live process that is provably NOT the gbrain holder.+ const squatter = Bun.spawn(['sleep', '60'], { stdout: 'ignore', stderr: 'ignore' });+ try {+ await waitForExec(squatter.pid, /sleep/);+ writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', { subcommand: 'serve' });++ const lock = await acquireLock(TEST_DIR, { timeoutMs: 5000 });+ try {+ expect(lock.acquired).toBe(true);+ expect(lock.reaped).toBe(true);+ } finally {+ await releaseLock(lock);+ }+ } finally {+ squatter.kill();+ }+ }, 15_000);++ test.skipIf(!canProbe)('does NOT reap a live process whose cmdline identifies it as gbrain', async () => {+ // The gbrain marker rides in a REAL argv slot (bash's $0), simulating a+ // live holder without running gbrain itself. Not `exec -a` argv[0]+ // spoofing: on hosts where coreutils is a multicall binary behind shebang+ // wrappers (e.g. sandbox images), the kernel's shebang rewrite destroys+ // the spoofed argv[0]. The compound command keeps bash from exec-replacing+ // itself, so its argv (and the marker) stays visible for the test's life.+ const holder = Bun.spawn(['bash', '-c', 'sleep 60; exit 0', 'gbrain-fake-holder'], { stdout: 'ignore', stderr: 'ignore' });+ try {+ await waitForExec(holder.pid, /gbrain-fake-holder/);+ writeHolderAt(TEST_DIR, holder.pid, 'gbrain-fake-holder embed', { subcommand: 'embed' });++ await expect(acquireLock(TEST_DIR, { timeoutMs: 1200 })).rejects.toThrow(/Timed out/);+ // Live holder's lock was never stolen.+ expect(existsSync(join(TEST_DIR, '.gbrain-lock'))).toBe(true);+ } finally {+ holder.kill();+ }+ }, 15_000);++ test.skipIf(!canProbe)('does NOT reap a live holder whose recorded command is an absolute path but whose cmdline shows the relative bun-run form', async () => {+ // False-steal regression (caught by the harness-lifecycle E2E): a serve+ // spawned as `bun run src/cli.ts serve …` reports a RELATIVE cmdline via+ // ps, while its lock records Bun's ABSOLUTE argv[1]. The literal+ // includes(firstToken) veto never matches and, when the checkout path+ // carries no 'gbrain' substring, the live holder was classified as a+ // recycled PID and its lock stolen — the thief then wrote to a second+ // PGLite instance the live serve never sees. The basename veto+ // ('cli.ts' appears in the cmdline) must keep the holder alive.+ const holder = Bun.spawn(['bash', '-c', 'sleep 60; exit 0', 'bun run src/cli.ts serve --http'], { stdout: 'ignore', stderr: 'ignore' });+ try {+ await waitForExec(holder.pid, /cli\.ts/);+ writeHolderAt(TEST_DIR, holder.pid, '/home/user/checkouts/brain-project/src/cli.ts serve --http', { subcommand: 'serve' });++ await expect(acquireLock(TEST_DIR, { timeoutMs: 1200 })).rejects.toThrow(/already open through `gbrain serve`/);+ expect(existsSync(join(TEST_DIR, '.gbrain-lock'))).toBe(true);+ } finally {+ holder.kill();+ }+ }, 15_000);++ test.skipIf(!isLinux)('does NOT reap on cmdline evidence when the lock belongs to another PID namespace', async () => {+ // #2840 class: a holder in another container shares the data dir; its+ // recorded PID maps to an unrelated process in OUR namespace. The pid_ns+ // mismatch must veto the reap even though the cmdline clearly differs.+ const squatter = Bun.spawn(['sleep', '60'], { stdout: 'ignore', stderr: 'ignore' });+ try {+ await waitForExec(squatter.pid, /sleep/);+ writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', { subcommand: 'serve', pidNs: 'pid:[1]' });++ await expect(acquireLock(TEST_DIR, { timeoutMs: 1200 })).rejects.toThrow(/already open through `gbrain serve`/);+ expect(existsSync(join(TEST_DIR, '.gbrain-lock'))).toBe(true);+ } finally {+ squatter.kill();+ }+ }, 15_000);++ test.skipIf(!isLinux)('never cmdline-reaps a LEGACY lock without namespace markers (fail-safe)', async () => {+ // Pre-marker locks carry no pid_ns: their recorded PID may belong to a+ // different namespace, so a cmdline mismatch proves nothing. ESRCH reaps+ // still apply; cmdline reaps must not.+ const squatter = Bun.spawn(['sleep', '60'], { stdout: 'ignore', stderr: 'ignore' });+ try {+ await waitForExec(squatter.pid, /sleep/);+ writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', { subcommand: 'serve', pidNs: null, bootId: null });++ await expect(acquireLock(TEST_DIR, { timeoutMs: 1200 })).rejects.toThrow(/already open through `gbrain serve`/);+ expect(existsSync(join(TEST_DIR, '.gbrain-lock'))).toBe(true);+ } finally {+ squatter.kill();+ }+ }, 15_000);++ test.skipIf(!isLinux)('never cmdline-reaps when boot_id is missing even if pid_ns matches (cross-host guard)', async () => {+ // pid_ns inode numbers can collide across hosts sharing a data dir, so on+ // Linux BOTH markers must be present and matching before cmdline evidence+ // is trusted.+ const squatter = Bun.spawn(['sleep', '60'], { stdout: 'ignore', stderr: 'ignore' });+ try {+ await waitForExec(squatter.pid, /sleep/);+ writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', { subcommand: 'serve', bootId: null });++ await expect(acquireLock(TEST_DIR, { timeoutMs: 1200 })).rejects.toThrow(/already open through `gbrain serve`/);+ expect(existsSync(join(TEST_DIR, '.gbrain-lock'))).toBe(true);+ } finally {+ squatter.kill();+ }+ }, 15_000);++ test('a lock held by THIS process is never classified as recycled', async () => {+ // Same-process re-acquire: the recorded PID is our own, so the cmdline+ // check must stand down even though `bun test` has no gbrain marker.+ writeHolderAt(TEST_DIR, process.pid, 'test holder');++ await expect(acquireLock(TEST_DIR, { timeoutMs: 1200 })).rejects.toThrow(/Timed out/);+ expect(existsSync(join(TEST_DIR, '.gbrain-lock'))).toBe(true);+ });++ test.skipIf(!canProbe)('concurrent reapers: exactly one reaps, the other never deletes the winner\u2019s fresh lock', async () => {+ // Race regression: two acquirers classify the same recycled-PID victim.+ // Without the atomic rename-aside claim, the slower reaper's rmSync can+ // delete the faster one's freshly installed lock — two writers, one dir.+ const squatter = Bun.spawn(['sleep', '60'], { stdout: 'ignore', stderr: 'ignore' });+ try {+ await waitForExec(squatter.pid, /sleep/);+ writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', { subcommand: 'serve' });++ const results = await Promise.allSettled([+ acquireLock(TEST_DIR, { timeoutMs: 5000 }),+ acquireLock(TEST_DIR, { timeoutMs: 5000 }),+ ]);+ const fulfilled = results.filter(r => r.status === 'fulfilled');+ const rejected = results.filter(r => r.status === 'rejected');+ // Exactly one reaps + acquires; the loser must time out against the+ // winner's live lock — never delete it.+ expect(fulfilled.length).toBe(1);+ expect(rejected.length).toBe(1);+ const lockFile = join(TEST_DIR, '.gbrain-lock', 'lock');+ expect(existsSync(lockFile)).toBe(true);+ const onDisk = JSON.parse(readFileSync(lockFile, 'utf-8'));+ expect(onDisk.pid).toBe(process.pid); // the winner's lock survived intact++ await releaseLock((fulfilled[0] as PromiseFulfilledResult<LockHandle>).value);+ } finally {+ squatter.kill();+ }+ }, 15_000);+});diff --git a/test/put-page-write-through-failure.test.ts b/test/put-page-write-through-failure.test.tsnew file mode 100644index 0000000000..532411130b--- /dev/null+++ b/test/put-page-write-through-failure.test.ts@@ -0,0 +1,111 @@+/**+ * put_page must not report success when the disk write-through fails.+ *+ * The DB row is a derived cache; the markdown file under a source's working+ * tree is the system of record (docs/architecture/system-of-record.md). If+ * `writePageThrough` can't produce that file — the write throws, or a guard+ * refuses it for a reason that isn't the deliberate "no repo configured at+ * all" case — `put_page` must reject the call instead of returning+ * `created_or_updated`, and a brand-new page's DB row must not survive as an+ * index-only orphan.+ */++import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { operations, OperationError } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { resetGateway } from '../src/core/ai/gateway.ts';++let engine: PGLiteEngine;+let tmpRoot: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+ resetGateway();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ resetGateway();+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-put-page-wt-'));+});++function makeCtx(overrides: Partial<OperationContext> = {}): OperationContext {+ return {+ engine,+ config: { engine: 'pglite' as const },+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: false,+ sourceId: 'default',+ ...overrides,+ };+}++const putPage = operations.find((o) => o.name === 'put_page')!;+const PAGE_CONTENT = '---\ntitle: T\ntype: note\n---\n\n# Body\n\nSome content.';++async function expectRejected(ctx: OperationContext, params: Record<string, unknown>): Promise<OperationError> {+ try {+ await putPage.handler(ctx, params);+ } catch (e) {+ expect(e).toBeInstanceOf(OperationError);+ return e as OperationError;+ }+ throw new Error('expected put_page to reject when write-through failed, but it reported success');+}++describe('put_page — write-through failure must not report success', () => {+ test('write-through throws (blocked parent dir) → put_page rejects and rolls back the new page', async () => {+ const sourceDir = path.join(tmpRoot, 'wt-fail-source');+ fs.mkdirSync(sourceDir, { recursive: true });+ await engine.executeRaw(+ `INSERT INTO sources (id, name, local_path, config) VALUES ('wt-fail', 'WT Fail', $1, '{}'::jsonb)`,+ [sourceDir],+ );+ // `notes` is a FILE, not a directory, so mkdir -p `notes/x` throws ENOTDIR+ // inside writePageThrough — the write-through-write-fails repro.+ fs.writeFileSync(path.join(sourceDir, 'notes'), 'blocker');++ const slug = 'notes/x';+ const err = await expectRejected(makeCtx({ sourceId: 'wt-fail' }), { slug, content: PAGE_CONTENT });+ expect(err.code).toBe('storage_error');++ // No orphan: the brand-new page must not survive with no markdown file.+ expect(await engine.getPage(slug, { sourceId: 'wt-fail' })).toBeNull();+ expect(fs.existsSync(path.join(sourceDir, 'notes.md'))).toBe(false);+ });++ test('write-through skip that is a refusal, not deliberate config (repo_not_found) → put_page rejects', async () => {+ const fileAsRepo = path.join(tmpRoot, 'not-a-dir');+ fs.writeFileSync(fileAsRepo, 'x');+ await engine.setConfig('sync.repo_path', fileAsRepo);++ const slug = 'inbox/repo-missing';+ const err = await expectRejected(makeCtx(), { slug, content: PAGE_CONTENT });+ expect(err.code).toBe('storage_error');+ expect(await engine.getPage(slug, { sourceId: 'default' })).toBeNull();+ });++ test('no sync.repo_path configured at all (DB-only by design) still succeeds', async () => {+ await engine.setConfig('sync.repo_path', '');+ const slug = 'inbox/db-only';+ const result = (await putPage.handler(makeCtx(), { slug, content: PAGE_CONTENT })) as {+ status: string;+ write_through?: { skipped?: string };+ };+ expect(result.status).toBe('created_or_updated');+ expect(result.write_through?.skipped).toBe('no_repo_configured');+ expect(await engine.getPage(slug, { sourceId: 'default' })).not.toBeNull();+ });+});diff --git a/test/regressions/v0_40_2_0-trajectory-backcompat.test.ts b/test/regressions/v0_40_2_0-trajectory-backcompat.test.tsindex 3d2f838873..610f2c5e0b 100644--- a/test/regressions/v0_40_2_0-trajectory-backcompat.test.ts+++ b/test/regressions/v0_40_2_0-trajectory-backcompat.test.ts@@ -60,6 +60,7 @@ describe('v0.40.2.0 back-compat — event rows ignored by metric callers', () =>// Pull all points (kind:'all' default) — includes the event row.const allPoints = await engine.findTrajectory({entitySlug: 'companies/acme-test',+ remote: false,});expect(allPoints.length).toBe(4);expect(allPoints.some(p => p.event_type === 'meeting')).toBe(true);@@ -68,6 +69,7 @@ describe('v0.40.2.0 back-compat — event rows ignored by metric callers', () =>const metricPoints = await engine.findTrajectory({entitySlug: 'companies/acme-test',kind: 'metric',+ remote: false,});expect(metricPoints.length).toBe(3);expect(metricPoints.every(p => p.event_type === null)).toBe(true);@@ -85,6 +87,7 @@ describe('v0.40.2.0 back-compat — event rows ignored by metric callers', () =>test('computeFounderScorecard ignores event rows in per-metric math', async () => {const allPoints = await engine.findTrajectory({entitySlug: 'companies/acme-test',+ remote: false,});const withEventRows = computeFounderScorecard({@@ -113,6 +116,7 @@ describe('v0.40.2.0 back-compat — event rows ignored by metric callers', () =>test('founder-scorecard math does not throw NaN on mixed input', async () => {const allPoints = await engine.findTrajectory({entitySlug: 'companies/acme-test',+ remote: false,});const scorecard = computeFounderScorecard({entitySlug: 'companies/acme-test',@@ -129,6 +133,7 @@ describe('v0.40.2.0 back-compat — event rows ignored by metric callers', () =>test('kind: "all" returns event row in chronological position', async () => {const points = await engine.findTrajectory({entitySlug: 'companies/acme-test',+ remote: false,});// Chronological order: 2026-01-01, 2026-04-01, 2026-05-15 (event), 2026-07-01expect(points.map(p => p.valid_from.toISOString().slice(0, 10))).toEqual([diff --git a/test/retrieval-quality-harness.test.ts b/test/retrieval-quality-harness.test.tsindex 7a86796527..67073e15be 100644--- a/test/retrieval-quality-harness.test.ts+++ b/test/retrieval-quality-harness.test.ts@@ -37,6 +37,17 @@ describe('scoreQuestion', () => {expect(scoreQuestion(q, ['a', 'b', 'c']).negative_clean).toBe(true);expect(scoreQuestion(q, ['a', 'bad', 'c']).negative_clean).toBe(false);});+ test('deduplicates pages before hit, reciprocal-rank, recall, and hard-negative cutoffs', () => {+ const positive: NamedThingQuestion = { family: 'title-substring', query: 'x', relevant: ['a'] };+ const scored = scoreQuestion(positive, ['x', 'x', 'a', 'a']);+ expect(scored.hit_at_3).toBe(true);+ expect(scored.reciprocal_rank).toBe(0.5);+ expect(scored.recall_at_k).toBe(1);+ expect(scored.recall_at_10).toBe(1);++ const negative: NamedThingQuestion = { family: 'hard-negative', query: 'x', forbidden: ['bad'] };+ expect(scoreQuestion(negative, ['x', 'x', 'y', 'bad']).negative_clean).toBe(false);+ });});describe('evaluateGate', () => {diff --git a/test/retrieval-reflex.test.ts b/test/retrieval-reflex.test.tsindex 6465f65e2a..175d6a64c5 100644--- a/test/retrieval-reflex.test.ts+++ b/test/retrieval-reflex.test.ts@@ -230,6 +230,49 @@ describe('context-engine assemble() — Retrieval Reflex integration', () => {});});+ test('turn delivered via `prompt` with empty `messages` still fires the reflex (codex-app-server path)', async () => {+ await withEnv(REFLEX_ON, async () => {+ await seed('people/alice-example', 'Alice Example', 'Alice is a founder.');+ const ce = createGBrainContextEngine({+ workspaceDir: '/tmp/rr-test-ws-prompt',+ resolveEntities: (candidates, opts) =>+ resolveEntitiesToPointers(engine, 'default', candidates, opts),+ });+ // Runtimes like the codex-app-server (2026.7.x) deliver the current turn+ // via `prompt` and leave `messages` empty. The reflex must still see it.+ const res = await ce.assemble({+ sessionId: 's-prompt',+ messages: [],+ prompt: 'what do you think about Alice Example?',+ });+ expect(res.systemPromptAddition).toContain('Brain pages mentioned this turn');+ expect(res.systemPromptAddition).toContain('people/alice-example');+ });+ });++ test('`prompt` is ignored when `messages` is non-empty (no double-count, back-compat)', async () => {+ await withEnv(REFLEX_ON, async () => {+ await seed('people/alice-example', 'Alice Example', 'Alice is a founder.');+ const seen: string[] = [];+ const ce = createGBrainContextEngine({+ workspaceDir: '/tmp/rr-test-ws-prompt-ignored',+ resolveEntities: (candidates, opts) => {+ seen.push(...candidates.map((c) => c.query));+ return resolveEntitiesToPointers(engine, 'default', candidates, opts);+ },+ });+ // `messages` carries the real turn; `prompt` names a DIFFERENT entity that+ // must never reach the resolver whenever `messages` is non-empty.+ const res = await ce.assemble({+ sessionId: 's-prompt-ignored',+ messages: [{ role: 'user', content: 'what do you think about Alice Example?' }],+ prompt: 'tell me about Bob Nonexistent',+ });+ expect(res.systemPromptAddition).toContain('people/alice-example');+ expect(seen.join(' ')).not.toContain('Bob Nonexistent');+ });+ });+test('no resolver available (PGLite, no serve/host) → no throw, live context still present', async () => {await withEnv(REFLEX_ON, async () => {const ce = createGBrainContextEngine({ workspaceDir: '/tmp/rr-test-ws-2' });diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex a739afafb2..7ae41f20d3 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -813,6 +813,15 @@ test('every CREATE INDEX column in PGLITE_SCHEMA_SQL is covered by CREATE TABLE// ─────────────────────────────────────────────────────────────────const COLUMN_EXEMPTIONS = new Set<string>([+ // takes.embedding: the takes table is migration-only (no CREATE TABLE in+ // PGLITE_SCHEMA_SQL / src/schema.sql), so there is no schema-blob forward+ // reference for the bootstrap to trip on. The column is created inline in+ // the takes CREATE TABLE and re-created by migration v126's handler with+ // the CONFIGURED embedding dimension (dynamic width — cannot be a static+ // blob column), and idx_takes_embedding_hnsw is created in the same+ // migration block. Fresh installs and upgrades both get the column + index+ // from the migration chain, never from the bootstrap.+ 'takes.embedding',// T7 — search_telemetry rank-1 drift columns (migration v111). search_telemetry// is created entirely by migration v57 (not in the schema blob), so the v57+v111// chain handles fresh + upgrade; no CREATE INDEX references these columns, sodiff --git a/test/schema-version-health.test.ts b/test/schema-version-health.test.tsnew file mode 100644index 0000000000..5eb5f28718--- /dev/null+++ b/test/schema-version-health.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from 'bun:test';+import { schemaVersionHealth } from '../src/core/schema-version-health.ts';++describe('schemaVersionHealth', () => {+ test('accepts only an exact schema match', () => {+ expect(schemaVersionHealth(130, 130)).toEqual({+ status: 'ok',+ message: 'Version 130 (latest: 130)',+ });+ });++ test('warns (AHEAD, #2036 semantics) when the database is newer than the client', () => {+ expect(schemaVersionHealth(130, 125)).toEqual({+ status: 'warn',+ message:+ "Version 130 is AHEAD of this client's latest known version (125). " ++ 'Another node migrated this DB past what this client knows — upgrade this client before writing.',+ });+ });++ test('retains the existing missing and behind guidance', () => {+ expect(schemaVersionHealth(0, 130).status).toBe('fail');+ expect(schemaVersionHealth(125, 130)).toEqual({+ status: 'warn',+ message: 'Version 125, latest is 130. Fix: gbrain apply-migrations --yes',+ });+ expect(schemaVersionHealth(125, 130, { remote: true })).toEqual({+ status: 'warn',+ message: 'Version 125, latest is 130. Run `gbrain apply-migrations --yes` on the host.',+ });+ });+});diff --git a/test/scope.test.ts b/test/scope.test.tsindex 4098e3969e..bff7a8975f 100644--- a/test/scope.test.ts+++ b/test/scope.test.ts@@ -5,6 +5,7 @@ import {ALLOWED_SCOPES,ALLOWED_SCOPES_LIST,assertAllowedScopes,+ filterAllowedScopes,InvalidScopeError,parseScopeString,type Scope,@@ -190,6 +191,24 @@ describe('assertAllowedScopes', () => {});});+describe('filterAllowedScopes', () => {+ test('keeps allowed and reports dropped unknowns', () => {+ const { allowed, dropped } = filterAllowedScopes([+ 'read', 'offline_access', 'write', 'openid', 'read',+ ]);+ expect(allowed).toEqual(['read', 'write']);+ expect(dropped).toEqual(['offline_access', 'openid']);+ });+ test('all-unknown yields empty allowed', () => {+ const { allowed, dropped } = filterAllowedScopes(['openid', 'offline_access']);+ expect(allowed).toEqual([]);+ expect(dropped).toEqual(['openid', 'offline_access']);+ });+ test('empty input yields empty both', () => {+ expect(filterAllowedScopes([])).toEqual({ allowed: [], dropped: [] });+ });+});+describe('parseScopeString', () => {test('splits space-separated', () => {expect(parseScopeString('read write admin')).toEqual(['read', 'write', 'admin']);diff --git a/test/search-alias-resolved-boost.test.ts b/test/search-alias-resolved-boost.test.tsindex 8235667add..5a17944ac8 100644--- a/test/search-alias-resolved-boost.test.ts+++ b/test/search-alias-resolved-boost.test.ts@@ -89,7 +89,7 @@ describe('alias_resolved boost stage', () => {});describe('KNOBS_HASH_VERSION', () => {- it('is 25 (20→21 recency fallback re-key #895; 21→22 result-stamp/injection epoch #1663 #3995 #3783 #4220; 22→23 excludePrivate posture fold #4352; 23→24 negative-offset cache-skip gap #4358 residual; 24→25 keywordOrFallback knob kof=; 25→26 salience/recency + intent_patterns fold #4415)', () => {+ it('is 26 (20→21 recency fallback re-key #895; 21→22 result-stamp/injection epoch #1663 #3995 #3783 #4220; 22→23 excludePrivate posture fold #4352; 23→24 negative-offset cache-skip gap #4358 residual; 24→25 keywordOrFallback knob kof= #3617; 25→26 salience/recency + intent_patterns fold #4415)', () => {// mw2: 21→22 result-stamp/injection epoch (#1663 #3995 #3783 #4220).// #4352 follow-up: 22→23 private-visibility posture fold (xp=).// #4358 residual: 23→24 negative-offset cache-skip gap.diff --git a/test/search/knobs-hash-reranker.test.ts b/test/search/knobs-hash-reranker.test.tsindex 0694e27281..7f898bc46e 100644--- a/test/search/knobs-hash-reranker.test.ts+++ b/test/search/knobs-hash-reranker.test.ts@@ -44,7 +44,7 @@ function baseKnobs(): ResolvedSearchKnobs {}describe('KNOBS_HASH_VERSION + version invariants', () => {- test('version is 24 (…; 21→22 result-stamp/injection epoch #1663 #3995 #3783 #4220; 22→23 excludePrivate posture fold #4352; 23→24 keywordOrFallback knob kof=; 25→26 salience/recency + intent_patterns fold #4415)', () => {+ test('version is 26 (…; 21→22 result-stamp/injection epoch #1663 #3995 #3783 #4220; 22→23 excludePrivate posture fold #4352; 23→24 negative-offset cache-skip gap #4358 residual; 24→25 keywordOrFallback knob kof= #3617; 25→26 salience/recency + intent_patterns fold #4415)', () => {// v0.35.0.0: 1→2 to fold reranker fields. v0.35.6.0: 2→3 to fold// floor_ratio. v0.36 wave: piggybacks on v=3 with 7 cross-modal knobs// (D2) PLUS column + provider context (D8/CDX-2 cross-column isolation).@@ -84,7 +84,7 @@ describe('KNOBS_HASH_VERSION + version invariants', () => {// #4352 follow-up: 22→23 excludePrivate posture fold (xp=) — replaces// the wholesale cache skip that disabled caching for remote callers.// #4358 residual: 23→24 negative-offset cache-skip gap.- // 24→25: kof= (keyword AND→OR fallback knob) joins the key.+ // 24→25 (#3617): kof= (keyword AND→OR fallback knob) joins the key.// 25→26: sal=/rec=/ipat= — salience/recency + intent_patterns fold (#4415).expect(KNOBS_HASH_VERSION).toBe(26);});diff --git a/test/search/title-retrieval-arm.test.ts b/test/search/title-retrieval-arm.test.tsindex 9afcfc6ab8..4d841c3ec5 100644--- a/test/search/title-retrieval-arm.test.ts+++ b/test/search/title-retrieval-arm.test.ts@@ -246,7 +246,7 @@ describe('searchKeyword — D2 AND→OR fallback', () => {});});-describe('hybridSearch — search.keywordOrFallback knob (v=15)', () => {+describe('hybridSearch — search.keywordOrFallback knob (v=25)', () => {// Title deliberately shares no token with the query so the D1 title arm// can't rescue the page — isolates the keyword arm's OR retry, which is// what the knob gates.diff --git a/test/serve-http-health.test.ts b/test/serve-http-health.test.tsindex d939296933..ae964da889 100644--- a/test/serve-http-health.test.ts+++ b/test/serve-http-health.test.ts@@ -2,7 +2,8 @@* Tests for probeHealth(), probeLiveness(), and HEALTH_TIMEOUT_MS in* src/commands/serve-http.ts.*- * v0.28.10 split: /health now calls probeLiveness (sql`SELECT 1`); the heavier+ * v0.28.10 split: /health now calls probeLiveness (engine.executeRaw('SELECT 1'));+ * the heavier* probeHealth (engine.getStats()) moved behind requireAdmin at* /admin/api/full-stats. Both share ProbeHealthResult so the route handlers* stay 2-line dispatches.@@ -18,7 +19,6 @@import { describe, test, expect } from 'bun:test';import { HEALTH_TIMEOUT_MS, probeHealth, probeLiveness } from '../src/commands/serve-http.ts';import type { BrainEngine } from '../src/core/engine.ts';-import type { SqlQuery } from '../src/core/oauth-provider.ts';/*** Minimal mock engine: only `getStats()` is exercised by probeHealth.@@ -29,14 +29,16 @@ function makeMockEngine(getStats: () => Promise<unknown>): BrainEngine {}/**- * Minimal mock sql tag: probeLiveness only awaits the result of `sql\`SELECT 1\``- * — the tag function's return value is what's raced, success/throw is what- * matters. We ignore the template strings and simulate a connection by calling- * the supplied factory.+ * Minimal liveness engine: probeLiveness only exercises executeRaw.*/-function makeMockSql(fn: () => Promise<unknown>): SqlQuery {- const tag: any = (_strings: TemplateStringsArray, ..._values: unknown[]) => fn();- return tag as SqlQuery;+function makeMockLivenessEngine(+ executeRaw: (+ sql: string,+ params?: unknown[],+ opts?: { signal?: AbortSignal },+ ) => Promise<unknown>,+): BrainEngine {+ return { executeRaw } as unknown as BrainEngine;}describe('HEALTH_TIMEOUT_MS', () => {@@ -90,8 +92,8 @@ describe('probeHealth', () => {describe('probeLiveness (v0.28.10)', () => {test('happy path: returns 200 + status:ok with NO engine-stats fields', async () => {- const sql = makeMockSql(async () => [{ '?column?': 1 }]);- const result = await probeLiveness(sql, 'postgres', '0.28.10', 100);+ const engine = makeMockLivenessEngine(async () => [{ '?column?': 1 }]);+ const result = await probeLiveness(engine, 'postgres', '0.28.10', 100);expect(result.ok).toBe(true);expect(result.status).toBe(200);if (result.ok) {@@ -107,12 +109,28 @@ describe('probeLiveness (v0.28.10)', () => {}});- test('timeout path: sql hangs → 503 with health_timeout description within 1s', async () => {- const sql = makeMockSql(() => new Promise(() => { /* never resolves */ }));+ test('timeout path: aborts the live query before returning 503', async () => {+ let querySignal: AbortSignal | undefined;+ let abortObserved = false;+ const engine = makeMockLivenessEngine((+ _sql: string,+ _params?: unknown[],+ opts?: { signal?: AbortSignal },+ ) => {+ querySignal = opts?.signal;+ return new Promise((_resolve, reject) => {+ querySignal?.addEventListener('abort', () => {+ abortObserved = true;+ reject(new DOMException('aborted', 'AbortError'));+ }, { once: true });+ });+ });const start = Date.now();- const result = await probeLiveness(sql, 'postgres', '0.28.10', 100);+ const result = await probeLiveness(engine, 'postgres', '0.28.10', 100);const elapsed = Date.now() - start;expect(elapsed).toBeLessThan(1000);+ expect(querySignal?.aborted).toBe(true);+ expect(abortObserved).toBe(true);expect(result.ok).toBe(false);expect(result.status).toBe(503);if (!result.ok) {@@ -123,9 +141,9 @@ describe('probeLiveness (v0.28.10)', () => {}});- test('db-error path: sql throws → 503 with database_failed description', async () => {- const sql = makeMockSql(() => Promise.reject(new Error('ECONNREFUSED')));- const result = await probeLiveness(sql, 'postgres', '0.28.10', 100);+ test('db-error path: query throws → 503 with database_failed description', async () => {+ const engine = makeMockLivenessEngine(() => Promise.reject(new Error('ECONNREFUSED')));+ const result = await probeLiveness(engine, 'postgres', '0.28.10', 100);expect(result.ok).toBe(false);expect(result.status).toBe(503);if (!result.ok) {@@ -135,12 +153,12 @@ describe('probeLiveness (v0.28.10)', () => {});test('timer-cleanup: 100 fast successful probes do not leak pending timers', async () => {- const sql = makeMockSql(async () => [{ '?column?': 1 }]);+ const engine = makeMockLivenessEngine(async () => [{ '?column?': 1 }]);// Snapshot active handles before; same after. If the finally-block// clearTimeout regressed, every probe would leak a 100ms-pending timer.const beforeHandles = (process as any)._getActiveHandles?.()?.length ?? 0;await Promise.all(- Array.from({ length: 100 }, () => probeLiveness(sql, 'postgres', '0.28.10', 100)),+ Array.from({ length: 100 }, () => probeLiveness(engine, 'postgres', '0.28.10', 100)),);// Allow microtask + process tick drain to let any leaked timers settle.await new Promise(r => setImmediate(r));diff --git a/test/smoke-test-worker.test.ts b/test/smoke-test-worker.test.tsnew file mode 100644index 0000000000..7c973b3503--- /dev/null+++ b/test/smoke-test-worker.test.ts@@ -0,0 +1,90 @@+import { afterEach, describe, expect, test } from 'bun:test';+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join, resolve } from 'path';+import { spawnSync } from 'child_process';++const REPO = resolve(import.meta.dir, '..');+const SCRIPT = join(REPO, 'scripts', 'smoke-test.sh');+const tempDirs: string[] = [];++function runSmoke(opts: { supervisorRunning: boolean; legacyPid?: number }) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-smoke-worker-'));+ tempDirs.push(dir);+ const fakeBun = join(dir, 'bun');+ const calls = join(dir, 'bun-calls.log');+ const workerStarted = join(dir, 'worker-started');+ const workerPid = join(dir, 'legacy-worker.pid');++ writeFileSync(fakeBun, `#!/bin/sh+printf '%s\\n' "$*" >> "$SMOKE_BUN_CALLS"+case " $* " in+ *" --help "*) exit 0 ;;+ *" doctor "*) printf '%s\\n' 'GBrain Health Check' 'Health score: 97'; exit 0 ;;+ *" jobs supervisor status --json "*)+ if [ "$SMOKE_SUPERVISOR_RUNNING" = 1 ]; then+ printf '%s\\n' '{"running":true,"detected_via":"pidfile"}'+ exit 0+ fi+ exit 1 ;;+ *" jobs work "*) : > "$SMOKE_WORKER_STARTED"; exit 0 ;;+esac+exit 0+`);+ chmodSync(fakeBun, 0o755);+ if (opts.legacyPid) writeFileSync(workerPid, `${opts.legacyPid}\n`);++ const result = spawnSync('bash', [SCRIPT], {+ cwd: REPO,+ encoding: 'utf8',+ timeout: 20_000,+ env: {+ ...process.env,+ HOME: dir,+ GBRAIN_BUN_PATH: fakeBun,+ GBRAIN_DIR_OVERRIDE: REPO,+ GBRAIN_DATABASE_URL: 'postgres://smoke.invalid/brain',+ GBRAIN_SMOKE_LOG: join(dir, 'smoke.log'),+ GBRAIN_SMOKE_WORKER_PID_FILE: workerPid,+ GBRAIN_BRAIN_PATH: dir,+ OPENAI_API_KEY: 'test-only-placeholder',+ SMOKE_BUN_CALLS: calls,+ SMOKE_WORKER_STARTED: workerStarted,+ SMOKE_SUPERVISOR_RUNNING: opts.supervisorRunning ? '1' : '0',+ },+ });+ return { ...result, calls, workerStarted, workerPid };+}++afterEach(() => {+ for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe('smoke-test worker health (#4175)', () => {+ test('a healthy native supervisor prevents a duplicate unmanaged worker', () => {+ const result = runSmoke({ supervisorRunning: true });++ expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);+ expect(result.stdout).toContain('health score: 97/100');+ expect(result.stderr).not.toContain('invalid option');+ expect(result.stdout).toContain('GBrain worker (supervisor-managed)');+ expect(readFileSync(result.calls, 'utf8')).toContain('jobs supervisor status --json');+ expect(existsSync(result.workerStarted)).toBe(false);+ expect(existsSync(result.workerPid)).toBe(false);+ }, 30_000);++ test('a missing worker fails with an explicit native repair and never starts one', () => {+ const result = runSmoke({ supervisorRunning: false });+ expect(result.status).toBe(1);+ expect(result.stdout).toContain('gbrain jobs supervisor start --detach');+ expect(existsSync(result.workerStarted)).toBe(false);+ expect(existsSync(result.workerPid)).toBe(false);+ }, 30_000);++ test('a supervisor plus a live legacy PID is reported as a duplicate', () => {+ const result = runSmoke({ supervisorRunning: true, legacyPid: process.pid });+ expect(result.status).toBe(1);+ expect(result.stdout).toContain('duplicate supervisor + legacy worker');+ expect(existsSync(result.workerStarted)).toBe(false);+ }, 30_000);+});diff --git a/test/sync-failures.test.ts b/test/sync-failures.test.tsindex 7acc834689..ef7cfa8260 100644--- a/test/sync-failures.test.ts+++ b/test/sync-failures.test.ts@@ -243,6 +243,22 @@ describe('classifyErrorCode — error message to code mapping', () => {expect(classifyErrorCode('invalid UTF-8: null byte at position 3770')).toBe('NULL_BYTES');});+ test('classifies RENAME_RECONCILE from the #3056 sentinel message (was UNKNOWN — #3479 review)', async () => {+ const { classifyErrorCode, renameReconcileErrorMessage } = await import('../src/core/sync.ts');+ expect(classifyErrorCode(+ renameReconcileErrorMessage('people/carol.md', 'people/carol', 'permission denied for table pages'),+ )).toBe('RENAME_RECONCILE');+ // Envelope-stable: the wrapped cause must not steal the classification —+ // the same sentinel class should not surface as STATEMENT_TIMEOUT one+ // run and DB_DUPLICATE_KEY the next just because the cause text varies.+ expect(classifyErrorCode(+ renameReconcileErrorMessage('people/carol.md', 'people/carol', 'canceling statement due to statement timeout'),+ )).toBe('RENAME_RECONCILE');+ expect(classifyErrorCode(+ renameReconcileErrorMessage('people/carol.md', undefined, 'duplicate key value violates unique constraint "pages_source_id_slug_key"'),+ )).toBe('RENAME_RECONCILE');+ });+test('classifies INVALID_UTF8', async () => {const { classifyErrorCode } = await import('../src/core/sync.ts');expect(classifyErrorCode('invalid UTF-8 sequence at position 500')).toBe('INVALID_UTF8');diff --git a/test/sync-include-hidden.test.ts b/test/sync-include-hidden.test.tsnew file mode 100644index 0000000000..0205c39cae--- /dev/null+++ b/test/sync-include-hidden.test.ts@@ -0,0 +1,128 @@+/**+ * `--include-hidden <glob>` — waives `pruneDir`'s leading-dot heuristic for+ * paths matching a user-supplied glob, without touching the default (which+ * must keep pruning `.git`, `.obsidian`, and every other dot-prefixed+ * directory unconditionally).+ *+ * Motivating case: a ledger convention (kazi-org/dira) that stores its+ * schema'd entries under `.dira/entries/`. Before this change no CLI flag,+ * `--include`/`--exclude` glob, or per-source config reached past the+ * dot-prefix prune — `classifySync` (drives `sync`) and+ * `isCollectibleForWalker` (drives `import`'s git-ls-files fast path, the+ * one every git-tracked source actually uses) both hard-excluded any path+ * with a dot-prefixed segment before any include/exclude glob was even+ * checked. `.dira/entries/*.md` was silently unsyncable and unimportable on+ * every git-tracked source, with no workaround.+ *+ * `isPathPruned` is the single function both classifiers now route through+ * (see its doc comment in core/sync.ts) — testing it directly here is+ * equivalent to testing both call sites without duplicating fixtures for+ * each, since a fix to one and not the other is exactly the drift bug this+ * refactor closes.+ */++import { describe, test, expect } from 'bun:test';+import { execSync } from 'child_process';+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { isSyncable, unsyncableReason, isPathPruned } from '../src/core/sync.ts';+import { collectSyncableFiles } from '../src/commands/import.ts';++function gitInit(dir: string): void {+ execSync('git init', { cwd: dir, stdio: 'pipe' });+ execSync('git config user.email "[email protected]"', { cwd: dir, stdio: 'pipe' });+ execSync('git config user.name "Test"', { cwd: dir, stdio: 'pipe' });+}++function gitCommitAll(dir: string): void {+ execSync('git add -A', { cwd: dir, stdio: 'pipe' });+ execSync('git commit -m "initial"', { cwd: dir, stdio: 'pipe' });+}++describe('isPathPruned — pure classifier used by both sync and import', () => {+ test('include-hidden-waives-dot-prune-when-glob-matches (fails on pre-fix main: includeHidden did not exist and every dot-segment path was unconditionally pruned)', () => {+ expect(isPathPruned('.dira/entries/cst-0001.md')).toBe(true);+ expect(isPathPruned('.dira/entries/cst-0001.md', ['.dira/**'])).toBe(false);+ expect(unsyncableReason('.dira/entries/cst-0001.md', { includeHidden: ['.dira/**'] })).toBe(null);+ expect(isSyncable('.dira/entries/cst-0001.md', { includeHidden: ['.dira/**'] })).toBe(true);+ });++ test('default-still-prunes-dot-dirs-without-include-hidden (regression guard: .git stays pruned when no flag is given)', () => {+ expect(isPathPruned('.git/notes.md')).toBe(true);+ expect(unsyncableReason('.git/notes.md')).toBe('pruned-dir');+ expect(isSyncable('.git/notes.md')).toBe(false);+ // Also unaffected by an unrelated --include-hidden pattern that doesn't match it.+ expect(unsyncableReason('.git/notes.md', { includeHidden: ['.dira/**'] })).toBe('pruned-dir');+ });++ test('a matching include-hidden glob does not waive generated/vendored exclusions', () => {+ // PRUNE_DIR_NAMES / *.raw are a different exclusion class from the+ // leading-dot heuristic and are never waivable by this flag.+ expect(isPathPruned('node_modules/foo/README.md', ['node_modules/**'])).toBe(true);+ expect(isPathPruned('vendor/pkg/note.md', ['vendor/**'])).toBe(true);+ expect(isPathPruned('people/pedro.raw/source.md', ['people/**'])).toBe(true);+ });++ test('include-hidden only waives the specific matching path, not every dot-dir', () => {+ expect(isPathPruned('.dira/entries/cst-0001.md', ['.dira/entries/**'])).toBe(false);+ expect(isPathPruned('.obsidian/workspace.md', ['.dira/entries/**'])).toBe(true);+ });+});++describe('collectSyncableFiles — import.ts entry point (git-ls-files fast path)', () => {+ let dir: string;++ function setup(): void {+ dir = mkdtempSync(join(tmpdir(), 'gbrain-include-hidden-'));+ gitInit(dir);+ mkdirSync(join(dir, '.dira', 'entries'), { recursive: true });+ writeFileSync(join(dir, '.dira', 'entries', 'dec-0001.md'), '---\ntype: note\ntitle: A\n---\n\nbody');+ mkdirSync(join(dir, 'brain'), { recursive: true });+ writeFileSync(join(dir, 'brain', 'plan.md'), '---\ntype: note\ntitle: B\n---\n\nbody');+ gitCommitAll(dir);+ }++ function teardown(): void {+ rmSync(dir, { recursive: true, force: true });+ }++ test('default: hidden-dir page absent, ordinary page present', () => {+ setup();+ try {+ const files = collectSyncableFiles(dir, { strategy: 'markdown' });+ expect(files.some((f) => f.endsWith('.dira/entries/dec-0001.md'))).toBe(false);+ expect(files.some((f) => f.endsWith('brain/plan.md'))).toBe(true);+ } finally {+ teardown();+ }+ });++ test('--include-hidden .dira/**: hidden-dir page now present, ordinary page still present', () => {+ setup();+ try {+ const files = collectSyncableFiles(dir, { strategy: 'markdown', includeHidden: ['.dira/**'] });+ expect(files.some((f) => f.endsWith('.dira/entries/dec-0001.md'))).toBe(true);+ expect(files.some((f) => f.endsWith('brain/plan.md'))).toBe(true);+ } finally {+ teardown();+ }+ });+});++describe('sync.ts delta path threads includeHidden (#4027 merge guard)', () => {+ // The hoisted syncOpts in src/commands/sync.ts is shared by the delta-path+ // isSyncable() filters AND the #3974 working-tree drift counter. It is also+ // where a master-merge can silently drop the flag: every+ // `isSyncable(path, syncOpts)` call keeps compiling and every+ // classifier-level test above stays green while --include-hidden parses and+ // does nothing. Pin the threading structurally (the classifier tests above+ // cover behavior; this covers the wiring the classifier can't see).+ test('the hoisted syncOpts literal carries includeHidden', () => {+ const src = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'sync.ts'), 'utf8');+ expect(src).toMatch(/const syncOpts = \{ strategy: opts\.strategy, includeHidden: opts\.includeHidden \}/);+ // The strategy-only form is the regression shape (pre-#4027 master): its+ // reappearance means a merge resolved the hoist without the threading.+ expect(src).not.toMatch(/const syncOpts = opts\.strategy \? \{ strategy: opts\.strategy \} : undefined/);+ });+});diff --git a/test/sync-rename-reconcile.serial.test.ts b/test/sync-rename-reconcile.serial.test.tsindex ff6e246f0c..5e4d2ea350 100644--- a/test/sync-rename-reconcile.serial.test.ts+++ b/test/sync-rename-reconcile.serial.test.ts@@ -25,7 +25,7 @@import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { execSync } from 'node:child_process';-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -277,4 +277,2211 @@ describe('#3056: rename fallback reconciles the stale old row', () => {);expect(remaining).toHaveLength(0);});++ test('#3479: an errorless unchanged-skip AT the new slug counts as materialized — the stale row reconciles without any write', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('people/carol')).not.toBeNull();++ // The destination row pre-exists AND its content_hash matches what the+ // renamed file would import to (forged via SQL to construct the shape;+ // in reality equal hashes mean byte-identical parsed content). The+ // import at the new path is then an errorless unchanged-skip at the NEW+ // slug — the one destMaterialized path where NOTHING is written.+ await engine.putPage('people/dana', {+ type: 'person', title: 'Dana occupier', compiled_truth: 'occupier body, untouched by the skip',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET content_hash =+ (SELECT content_hash FROM pages WHERE source_id = 'default' AND slug = 'people/carol')+ WHERE source_id = 'default' AND slug = 'people/dana'`,+ );++ execSync('git mv people/carol.md people/dana.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename carol to dana"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');++ // The stale old row reconciled away even though the skip wrote nothing...+ expect(await engine.getPage('people/carol')).toBeNull();+ // ...and the destination row is genuinely untouched (the skip was real).+ const dana = await engine.getPage('people/dana');+ expect(dana).not.toBeNull();+ expect(dana!.compiled_truth).toContain('occupier body');+ expect(await countPages()).toBe(1);+ });+});++describe('#3479 blocker 1: a permanent reconcile failure has a documented operator exit', () => {+ test('hard-blocks every --skip-failed run, names the gbrain delete remedy, and the remedy converges it', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const { loadSyncFailures } = await import('../src/core/sync-failure-ledger.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ await engine.putPage('people/dana', {+ type: 'person', title: 'Dana (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });+ execSync('git mv people/carol.md people/dana.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename carol to dana"', { cwd: repo, stdio: 'pipe' });++ // A PERMANENT delete failure (RLS denying DELETE, FK RESTRICT — an+ // environment where UPDATE still works but this DELETE never will):+ // every retry fails the same way. Capture stderr to pin that the+ // blocked message documents the operator exit, not just the retry.+ const origDelete = engine.deletePage.bind(engine);+ engine.deletePage = async () => { throw new Error('permission denied for table pages (injected permanent failure)'); };+ const stderrChunks: string[] = [];+ const origWrite = process.stderr.write.bind(process.stderr);+ const origConsoleError = console.error;+ process.stderr.write = ((chunk: unknown, ...rest: unknown[]) => {+ stderrChunks.push(String(chunk));+ return (origWrite as (...a: unknown[]) => boolean)(chunk, ...rest);+ }) as typeof process.stderr.write;+ console.error = (...args: unknown[]) => { stderrChunks.push(args.map(String).join(' ')); origConsoleError(...args); };+ let result;+ try {+ for (let i = 0; i < 3; i++) {+ const blocked = await performSync(engine, { repoPath: repo, ...SYNC_OPTS, skipFailed: true });+ // Structural: the sentinel hard-blocks EVEN with --skip-failed —+ // acknowledgeFailures explicitly skips sentinels, so without a+ // documented remedy this is a total sync outage.+ expect(blocked.status).toBe('blocked_by_failures');+ }+ const open = loadSyncFailures().filter(+ f => f.path === '<rename:people/dana.md>' && f.state === 'open',+ );+ expect(open).toHaveLength(1);+ expect(open[0].attempts).toBeGreaterThanOrEqual(3);++ // The documented remedy — exercised faithfully: `gbrain delete` is a+ // SOFT-delete (the row keeps its source_path until the purge phase),+ // and the environment's DELETE is STILL denied (the mock stays+ // active). Convergence therefore requires the reconcile to treat a+ // soft-deleted stale row as "nothing left to delete" instead of+ // re-attempting the hard delete that keeps failing here.+ expect(await engine.softDeletePage('people/carol', { sourceId: 'default' })).not.toBeNull();+ result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ } finally {+ process.stderr.write = origWrite;+ console.error = origConsoleError;+ engine.deletePage = origDelete;+ }+ const stderrText = stderrChunks.join('');+ expect(stderrText).toContain("'gbrain delete <stale-slug>'");+ // The error names the exact stale slug the remedy should target+ // (JSON-quoted — the format is machine-parsed by the orphan probe).+ expect(stderrText).toContain('stale row "people/carol" for "people/carol.md" not removed');+ expect(result.status).toBe('synced');+ const dana = await engine.getPage('people/dana');+ expect(dana).not.toBeNull();+ expect(dana!.compiled_truth).toContain('Carol is a person.');+ expect(loadSyncFailures().filter(+ f => f.path === '<rename:people/dana.md>' && f.state === 'open',+ )).toHaveLength(0);+ });+});++describe('#3479 blocker 2: an orphaned rename sentinel self-clears; a real duplicate never does', () => {+ test('force-push invalidates the pin: sentinel clears once the stale row is gone, stays open while it is real', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const { loadSyncFailures } = await import('../src/core/sync-failure-ledger.ts');+ const openRenameRows = () => loadSyncFailures().filter(+ f => f.path === '<rename:people/dana.md>' && f.state === 'open',+ );++ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ const preRenameCommit = execSync('git rev-parse HEAD', { cwd: repo, stdio: 'pipe' }).toString().trim();+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('people/carol')).not.toBeNull();++ // Rename with a failing reconcile → open sentinel, bookmark blocked.+ await engine.putPage('people/dana', {+ type: 'person', title: 'Dana (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });+ execSync('git mv people/carol.md people/dana.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename carol to dana"', { cwd: repo, stdio: 'pipe' });+ const origDelete = engine.deletePage.bind(engine);+ engine.deletePage = async () => { throw new Error('injected transient delete failure'); };+ try {+ const blocked = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(blocked.status).toBe('blocked_by_failures');+ } finally {+ engine.deletePage = origDelete;+ }+ expect(openRenameRows()).toHaveLength(1);++ // FORCE-PUSH: history is rewritten to BEFORE the rename (carol.md is+ // back in the tree, the rename commit is gone) and moves on with an+ // unrelated add — the rename never re-enters any diff, so the ordinary+ // convergence path can now never fire for it, and the banked pin is+ // invalidated. This is the reviewer's orphaning shape.+ execSync(`git reset --hard ${preRenameCommit}`, { cwd: repo, stdio: 'pipe' });+ writeFileSync(join(repo, 'people/dana.md'), personMd('Dana', 'A fresh, unrelated dana file.'));+ execSync('git add -A && git commit -m "fresh dana on rewritten history"', { cwd: repo, stdio: 'pipe' });++ // FAIL-CLOSED CONTROL: the stale duplicate row still resolves (carol.md+ // is untouched by the new diff), so the sentinel must survive however+ // many syncs run — auto-clearing here would silently drop the only+ // signal that a real duplicate exists.+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(openRenameRows()).toHaveLength(1);+ expect(await engine.getPage('people/carol')).not.toBeNull();++ // The duplicate disappears — via the operator's actual tool, `gbrain+ // delete` (a SOFT-delete: the row keeps its source_path). The sentinel+ // now guards nothing live: the next run — even a quiet up_to_date one,+ // the reviewer's exact probe shape — self-clears it.+ expect(await engine.softDeletePage('people/carol', { sourceId: 'default' })).not.toBeNull();+ const quiet = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(quiet.status).toBe('up_to_date');+ expect(openRenameRows()).toHaveLength(0);+ });+});++describe('#3479: rename sentinel error format round-trips', () => {+ test('parseRenameReconcileFrom inverts renameReconcileErrorMessage for awkward paths', async () => {+ const { renameReconcileErrorMessage, parseRenameReconcileFrom } =+ await import('../src/core/sync-failure-ledger.ts');+ const awkward = [+ 'people/carol.md',+ 'dir with spaces/x y.md',+ 'a(b)/weird):.md',+ // The delimiter-collision counterexample (#3479 codex review): a raw+ // interpolation would truncate this at its embedded ' not removed): '+ // and hand the orphan probe a WRONG path — JSON-quoting makes the+ // span self-delimiting.+ 'dir/a not removed): b.md',+ 'quotes "inside" and \\backslash\\.md',+ 'ユニコード/パス.md',+ ];+ for (const from of awkward) {+ for (const slug of ['people/carol', undefined]) {+ const err = renameReconcileErrorMessage(from, slug, 'boom: nested (cause) text not removed): decoy');+ expect(parseRenameReconcileFrom(err)).toBe(from);+ }+ }+ });++ test('anything else parses to undefined (fail-closed: never auto-clear on a misread)', async () => {+ const { parseRenameReconcileFrom } = await import('../src/core/sync-failure-ledger.ts');+ expect(parseRenameReconcileFrom('some legacy error text')).toBeUndefined();+ expect(parseRenameReconcileFrom('')).toBeUndefined();+ expect(parseRenameReconcileFrom('rename reconcile failed (stale row "x" for "unterminated): boom')).toBeUndefined();+ });++ test('the PRE-#3479 unquoted shape parses when unambiguous, and only then', async () => {+ const { renameReconcileErrorMessage, parseRenameReconcileFrom } =+ await import('../src/core/sync-failure-ledger.ts');+ // Anyone wedged by #3056 before upgrading carries this shape. Refusing to+ // read it leaves exactly those operators wedged forever (review: the fix+ // is incomplete for them).+ expect(parseRenameReconcileFrom(+ 'rename reconcile failed (stale row for people/x.md not removed): boom',+ )).toBe('people/x.md');+ // Ambiguity is the reason #3479 started JSON-encoding the slot: a raw+ // interpolation is undecidable once the delimiter appears twice, whether+ // it came from the path or from the cause. Both still fail closed.+ expect(parseRenameReconcileFrom(+ 'rename reconcile failed (stale row for weird not removed): path.md not removed): boom',+ )).toBeUndefined();+ expect(parseRenameReconcileFrom(+ 'rename reconcile failed (stale row for people/x.md not removed): cause not removed): tail',+ )).toBeUndefined();+ // An empty path slot names nothing to probe.+ expect(parseRenameReconcileFrom(+ 'rename reconcile failed (stale row for not removed): boom',+ )).toBeUndefined();+ // The current format is never read as legacy — the slug slot is in the way.+ const current = renameReconcileErrorMessage('people/y.md', 'people/y', 'boom');+ expect(parseRenameReconcileFrom(current)).toBe('people/y.md');+ const noSlug = renameReconcileErrorMessage('people/z.md', undefined, 'boom');+ expect(parseRenameReconcileFrom(noSlug)).toBe('people/z.md');+ });+});++describe('#3479: non-unique source_path — a soft-deleted row must not mask a live duplicate', () => {+ test('sentinel survives while ANY active row still carries the old path; reconcile removes every stale active one and spares the live row', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const { loadSyncFailures } = await import('../src/core/sync-failure-ledger.ts');+ const openRenameRows = () => loadSyncFailures().filter(+ f => f.path === '<rename:people/dana.md>' && f.state === 'open',+ );+ const repo = mkRepo({+ 'people/carol.md': personMd('Carol', 'Carol is a person.'),+ 'people/erin.md': personMd('Erin', 'Erin is a person.'),+ });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ // A SECOND row sharing source_path=people/carol.md (non-unique index):+ // one active, plus a soft-deleted decoy that a one-row resolve could+ // hand back first — masking the live duplicate behind a null getPage.+ await engine.putPage('people/carol-duplicate', {+ type: 'person', title: 'Carol (dup)', compiled_truth: 'second row for the same file',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/carol.md'+ WHERE source_id = 'default' AND slug = 'people/carol-duplicate'`,+ );+ // A LIVE row also sharing the old path — the bookkeeping a prior cheap+ // rename leaves behind (updateSlug never rewrites source_path). Its+ // backing file people/erin.md is in the working tree, so the widened+ // delete must NOT touch it (#3583 review, the data-loss blocker).+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/carol.md'+ WHERE source_id = 'default' AND slug = 'people/erin'`,+ );+ await engine.putPage('people/carol-decoy', {+ type: 'person', title: 'Carol (decoy)', compiled_truth: 'soft-deleted decoy sharing the path',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/carol.md'+ WHERE source_id = 'default' AND slug = 'people/carol-decoy'`,+ );+ expect(await engine.softDeletePage('people/carol-decoy', { sourceId: 'default' })).not.toBeNull();++ // Rename with a failing delete → open sentinel.+ await engine.putPage('people/dana', {+ type: 'person', title: 'Dana (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });+ execSync('git mv people/carol.md people/dana.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename carol to dana"', { cwd: repo, stdio: 'pipe' });+ const origDelete = engine.deletePage.bind(engine);+ engine.deletePage = async () => { throw new Error('injected transient delete failure'); };+ try {+ const blocked = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(blocked.status).toBe('blocked_by_failures');+ } finally {+ engine.deletePage = origDelete;+ }+ expect(openRenameRows()).toHaveLength(1);++ // Convergence must remove BOTH genuinely-stale active rows carrying the+ // old path — a single-row reconcile would leave one behind with the+ // rename already checkpointed, never to be retried. The LIVE erin row+ // (backed by people/erin.md in the working tree) must survive.+ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('people/carol')).toBeNull();+ expect(await engine.getPage('people/carol-duplicate')).toBeNull();+ const erin = await engine.getPage('people/erin');+ expect(erin).not.toBeNull();+ expect(erin!.compiled_truth).toContain('Erin is a person.');+ expect(openRenameRows()).toHaveLength(0);+ const dana = await engine.getPage('people/dana');+ expect(dana).not.toBeNull();+ expect(dana!.compiled_truth).toContain('Carol is a person.');+ });+});++describe('#3583 review: a live page sharing the stale source_path survives the reconcile', () => {+ test('a LEGACY row still carrying an old source_path is not deleted by a later occupied-destination rename', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/alpha.md': personMd('Alpha', 'Alpha original body.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('people/alpha')).not.toBeNull();++ // Ordinary cheap rename alpha -> beta. The cheap rename now repairs+ // source_path at the moment it lands (GATE13), so recreate the LEGACY+ // bookkeeping a pre-fix brain still carries: the live beta row naming+ // the OLD path. That legacy shape is the precondition that made the+ // widened source_path delete a data-loss bug (#3583 review).+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "cheap rename alpha to beta"', { cwd: repo, stdio: 'pipe' });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/beta'`,+ );+ const betaRows = await engine.executeRaw<{ source_path: string | null }>(+ `SELECT source_path FROM pages+ WHERE source_id = 'default' AND slug = 'people/beta' AND deleted_at IS NULL`,+ );+ expect(betaRows).toHaveLength(1);+ expect(betaRows[0].source_path).toBe('people/alpha.md');++ // An unrelated NEW file appears at the old path — two active rows now+ // share source_path=people/alpha.md.+ writeFileSync(join(repo, 'people/alpha.md'), personMd('Alpha II', 'A fresh, unrelated alpha.'));+ execSync('git add -A && git commit -m "new unrelated alpha"', { cwd: repo, stdio: 'pipe' });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('people/alpha')).not.toBeNull();+ expect(await engine.getPage('people/beta')).not.toBeNull();++ // Rename the recreated alpha into an OCCUPIED destination (the #3056+ // fallback this reconcile exists for). Only the recreated-alpha row is+ // genuinely stale; beta is a live page whose backing file is present in+ // the working tree.+ await engine.putPage('people/gamma', {+ type: 'person', title: 'Gamma occupier', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/gamma.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha into occupied gamma"', { cwd: repo, stdio: 'pipe' });+ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');++ // The destination carries the recreated file's content...+ const gamma = await engine.getPage('people/gamma');+ expect(gamma).not.toBeNull();+ expect(gamma!.compiled_truth).toContain('A fresh, unrelated alpha.');+ // ...the genuinely-stale row (recreated alpha, file gone) is removed...+ expect(await engine.getPage('people/alpha')).toBeNull();+ // ...and the LIVE beta page survives with its content intact.+ const beta = await engine.getPage('people/beta');+ expect(beta).not.toBeNull();+ expect(beta!.compiled_truth).toContain('Alpha original body.');++ // The very next sync is quiet and beta is still alive — the review's+ // loss was permanent precisely because no incremental sync healed it.+ const quiet = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(quiet.status).toBe('up_to_date');+ expect(await engine.getPage('people/beta')).not.toBeNull();+ });+});++const openDanaRows = async () => {+ const { loadSyncFailures } = await import('../src/core/sync-failure-ledger.ts');+ return loadSyncFailures().filter(+ f => f.path === '<rename:people/dana.md>' && f.state === 'open',+ );+};++/** Plant one open, ORPHANED `<rename:…>` sentinel (its old path has no+ * active row) — exactly what the self-heal sweep would clear, which is+ * why a preview must not run the sweep. */+async function plantOrphanedSentinel(): Promise<void> {+ const { recordFailures, renameSentinelPath, renameReconcileErrorMessage } =+ await import('../src/core/sync-failure-ledger.ts');+ recordFailures('default', [{+ path: renameSentinelPath('people/dana.md'),+ error: renameReconcileErrorMessage('people/dana-old.md', 'people/dana-old', 'injected wedge'),+ }], 'deadbeef');+}++describe('#3583 review: --dry-run must not rewrite the failure ledger', () => {++ test('quiet-repo dry run reports up_to_date and leaves the open sentinel untouched; the real run still self-heals it', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ await plantOrphanedSentinel();+ expect(await openDanaRows()).toHaveLength(1);++ // Byte-identical, not just semantically-open: a preview must not touch+ // the ledger file at all (a rewrite that happened to preserve the open+ // row would still pass a rows-only assertion).+ const { syncFailuresPath } = await import('../src/core/sync-failure-ledger.ts');+ const { readFileSync: readLedger } = await import('node:fs');+ const ledgerBefore = readLedger(syncFailuresPath(), 'utf-8');++ const dry = await performSync(engine, { repoPath: repo, ...SYNC_OPTS, dryRun: true });+ expect(dry.status).toBe('up_to_date');+ // The operator's only wedge signal survives the preview.+ expect(await openDanaRows()).toHaveLength(1);+ expect(readLedger(syncFailuresPath(), 'utf-8')).toBe(ledgerBefore);++ // Control: the same quiet run WITHOUT --dry-run self-heals the orphan.+ const real = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(real.status).toBe('up_to_date');+ expect(await openDanaRows()).toHaveLength(0);+ });++ test('totalChanges==0 sweep site: git advanced with no syncable changes — dry run preserves the row, the real run clears it', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ await plantOrphanedSentinel();+ expect(await openDanaRows()).toHaveLength(1);++ // Advance git HEAD with a change the markdown strategy filters out, so+ // the run reaches the totalChanges==0 early return (not the+ // HEAD-equality one).+ writeFileSync(join(repo, 'notes.txt'), 'not syncable under the markdown strategy');+ execSync('git add -A && git commit -m "non-syncable change"', { cwd: repo, stdio: 'pipe' });++ const dry = await performSync(engine, { repoPath: repo, ...SYNC_OPTS, dryRun: true });+ expect(dry.status).toBe('dry_run');+ expect(await openDanaRows()).toHaveLength(1);++ const real = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(real.status).toBe('up_to_date');+ expect(await openDanaRows()).toHaveLength(0);+ });++ test('performFullSync pre-gate probe: a full sync self-heals an orphaned sentinel', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });++ await plantOrphanedSentinel();+ expect(await openDanaRows()).toHaveLength(1);++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS, full: true });+ expect(result.status).toBe('first_sync');+ expect(await engine.getPage('people/carol')).not.toBeNull();+ expect(await openDanaRows()).toHaveLength(0);+ });+});++// A markdown file whose PATH derives no slug (emoji filename) imports+// under its frontmatter `slug:` (#598). Such a live row's slug is NOT+// path-derivable, so a tracked-file index built from resolveSlugForPath+// alone would miss it and misclassify the row as stale — the same+// data-loss shape as the ordinary cheap-rename case, one regime deeper.+// Mixed-case on purpose: importFromContent normalizes through+// validateSlug (lowercase), so the row is stored as `party-notes` — an+// index that carried the raw frontmatter casing would miss it and+// delete the live row all the same.+const exoticMd = [+ '---', 'type: person', 'title: Party Notes', 'slug: Party-Notes', '---',+ '', 'Party notes live here.',+].join('\n');++async function setupExoticScenario(): Promise<string> {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({+ '\u{1F389}.md': exoticMd,+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ const party = await engine.getPage('party-notes');+ expect(party).not.toBeNull();+ expect(party!.compiled_truth).toContain('Party notes live here.');++ // Manufacture the stale bookkeeping a prior cheap rename leaves behind:+ // the LIVE party-notes row (backed by the tracked emoji file) carries+ // the old path of the rename below. A genuinely-stale ghost row shares+ // the same path as the inverse control — it has no backing file and+ // MUST still be deleted.+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );++ // Occupied destination forces the fallback-to-add reconcile with+ // from=people/alpha.md.+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });+ return repo;+}++describe('#3583 review: frontmatter-fallback (CJK-wave) live rows survive the reconcile', () => {+ test('emoji-filename row with a frontmatter slug is spared; the stale ghost sharing the path is still deleted', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = await setupExoticScenario();++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');++ // The frontmatter-fallback row is LIVE (its emoji file is tracked and+ // still derives to party-notes through the import path) — it survives.+ const party = await engine.getPage('party-notes');+ expect(party).not.toBeNull();+ expect(party!.compiled_truth).toContain('Party notes live here.');++ // Inverse control: the ghost row sharing the same stale path has no+ // backing file — the widened reconcile still removes it.+ expect(await engine.getPage('people/ghost')).toBeNull();++ // And the rename itself converged.+ const beta = await engine.getPage('people/beta');+ expect(beta).not.toBeNull();+ expect(beta!.compiled_truth).toContain('Alpha is a person.');+ });++ test('sparse-checkout shape: the emoji file absent from the working tree still resolves through the git index blob', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = await setupExoticScenario();++ // Simulate a sparse/partial checkout: the file is tracked (in the git+ // index) but its working-tree copy is absent. The uncommitted disk+ // deletion never enters the commit diff, so sync does not see it as a+ // delete — but a naive on-disk read would now fail, and liveness must+ // fall through to the index blob.+ rmSync(join(repo, '\u{1F389}.md'));++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');++ const party = await engine.getPage('party-notes');+ expect(party).not.toBeNull();+ expect(party!.compiled_truth).toContain('Party notes live here.');+ expect(await engine.getPage('people/ghost')).toBeNull();+ });+});++// Post-review fix: trackedSlugIndex must enumerate the SAME set of files as+// collectSyncableFiles (tracked + untracked-not-ignored via+// `git ls-files --cached --others --exclude-standard`), not tracked-only+// (`git ls-files`). Before the fix, a fallback-regime file that was on disk+// and already imported by full sync — but never `git add`-ed — had a slug+// full sync knew about and trackedSlugIndex did not. Any rename reconcile+// running afterward would treat the missing index entry as proof of+// staleness and hard-delete the file's LIVE page.+describe('#3583 follow-up: an untracked (unstaged) fallback-regime file survives the reconcile', () => {+ async function setupUntrackedExoticScenario(): Promise<string> {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });++ // Write the frontmatter-fallback file WITHOUT staging or committing it.+ // `collectSyncableFiles`'s git-aware fast path (`--cached --others+ // --exclude-standard`) still imports it; a bare `git ls-files` would not+ // list it at all.+ writeFileSync(join(repo, '\u{1F389}.md'), exoticMd);++ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ const party = await engine.getPage('party-notes');+ expect(party).not.toBeNull();+ expect(party!.compiled_truth).toContain('Party notes live here.');++ // Same stale-bookkeeping shape as setupExoticScenario: force the LIVE+ // party-notes row onto the upcoming rename's `from` path so the+ // reconcile treats it as a candidate.+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });+ return repo;+ }++ test('an unstaged emoji-filename file that collectSyncableFiles already imported is not misclassified as stale', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = await setupUntrackedExoticScenario();++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');++ // The emoji file is real, on disk, still deriving to party-notes — it+ // was simply never `git add`-ed. It must survive the reconcile.+ const party = await engine.getPage('party-notes');+ expect(party).not.toBeNull();+ expect(party!.compiled_truth).toContain('Party notes live here.');++ // The rename itself still converged.+ const beta = await engine.getPage('people/beta');+ expect(beta).not.toBeNull();+ expect(beta!.compiled_truth).toContain('Alpha is a person.');+ });+});++// Scope note: "persistent state" here means the BRAIN's state (DB rows,+// checkpoints, the failure ledger). The internal `git pull` a preview runs+// without --no-pull mutates the operator's REPO and is longstanding+// upstream behavior with its own knob — out of this suite's scope.+describe('#3583 review: --dry-run must not mutate persistent brain state', () => {+ test('quiet named-source dry run leaves the last_sync_at heartbeat untouched; the real run bumps it', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ // The heartbeat UPDATE targets the sources row; create it the way+ // `gbrain sources add` would so the quiet-run UPDATE has a target.+ await engine.executeRaw(+ `INSERT INTO sources (id, name) VALUES ('default', 'default') ON CONFLICT (id) DO NOTHING`,+ );+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ await engine.executeRaw(+ `UPDATE sources SET last_sync_at = '2000-01-01T00:00:00Z' WHERE id = 'default'`,+ );+ const heartbeat = async (): Promise<string | undefined> => {+ const rows = await engine.executeRaw<{ t: string }>(+ `SELECT last_sync_at::text AS t FROM sources WHERE id = 'default'`,+ );+ return rows[0]?.t;+ };+ const pinned = await heartbeat();+ expect(pinned).toContain('2000-01-01');++ const dry = await performSync(engine, { repoPath: repo, ...SYNC_OPTS, dryRun: true });+ expect(dry.status).toBe('up_to_date');+ // A preview that bumps the freshness heartbeat masks real staleness+ // from doctor — it must stay pinned.+ expect(await heartbeat()).toBe(pinned);++ const real = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(real.status).toBe('up_to_date');+ expect(await heartbeat()).not.toBe(pinned);+ });++ test('a preview under a narrower strategy must not hard-delete the now-un-syncable page; the real run still does', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('people/carol')).not.toBeNull();++ // Modify + commit so the file enters manifest.modified; under+ // strategy=code it is then "modified but un-syncable" — the cleanup+ // class that used to be hard-deleted BEFORE the dry-run return.+ writeFileSync(join(repo, 'people/carol.md'), personMd('Carol', 'Carol updated body.'));+ execSync('git add -A && git commit -m "update carol"', { cwd: repo, stdio: 'pipe' });++ const dry = await performSync(engine, { repoPath: repo, ...SYNC_OPTS, strategy: 'code', dryRun: true });+ expect(dry.status).toBe('dry_run');+ expect(await engine.getPage('people/carol')).not.toBeNull();++ // Control: the real run keeps the pre-existing cleanup behavior.+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS, strategy: 'code' });+ expect(await engine.getPage('people/carol')).toBeNull();+ });+});++describe('#3583 review: orphan-sentinel self-heal probe/clear race', () => {+ test('an active row materializing between the two probes keeps the sentinel open', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ await plantOrphanedSentinel();+ expect(await openDanaRows()).toHaveLength(1);++ // Simulate a writer outside the sync lock (a raw import, restore_page)+ // committing an active row with the sentinel's old path IMMEDIATELY+ // after the first orphan probe returned "no active row". The second+ // probe must see it and keep the sentinel open — a single-probe sweep+ // cleared it while the duplicate existed.+ const origExecuteRaw = engine.executeRaw.bind(engine);+ let probeCalls = 0;+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw =+ (async (sql: string, params?: unknown[]) => {+ const res = await origExecuteRaw(sql, params);+ if (sql.includes('source_path = ANY')) {+ probeCalls++;+ if (probeCalls === 1) {+ await engine.putPage('people/dana-old-revenant', {+ type: 'person', title: 'Dana (revenant)',+ compiled_truth: 'materialized between probe and clear',+ }, { sourceId: 'default' });+ await origExecuteRaw(+ `UPDATE pages SET source_path = 'people/dana-old.md'+ WHERE source_id = 'default' AND slug = 'people/dana-old-revenant'`,+ );+ }+ }+ return res;+ }) as typeof engine.executeRaw;+ try {+ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('up_to_date');+ } finally {+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw = origExecuteRaw;+ }++ // The duplicate is real, so its sentinel survives...+ expect(await openDanaRows()).toHaveLength(1);+ // ...and the double-probe actually ran (this assertion fails on a+ // single-probe implementation even before the survival check does).+ expect(probeCalls).toBe(2);+ });+});++describe('#3583 review: an over-size-gate fallback-regime file suspends deletes instead of losing the row', () => {+ test('a live row whose emoji file grew past the import size gate is spared as unknown (and so is everything else)', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ // Import while the file is comfortably under the 5MB gate...+ const repo = mkRepo({+ '\u{1F389}.md': [+ '---', 'type: person', 'title: Party Notes', 'slug: Party-Notes', '---',+ '', 'Party notes live here.',+ ].join('\n'),+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('party-notes')).not.toBeNull();++ // ...then the file grows past the gate. Uncommitted on purpose: the+ // growth never enters the commit diff (no import attempt, no ledger+ // noise), but the liveness index reads the WORKING TREE — where the+ // file now sits over the gate. Concluding "no row possible" from the+ // current size would delete the row imported before the growth.+ const bigBody = 'x'.repeat(5_100_000);+ writeFileSync(join(repo, '\u{1F389}.md'), [+ '---', 'type: person', 'title: Party Notes', 'slug: Party-Notes', '---',+ '', bigBody,+ ].join('\n'));++ // Same stale-bookkeeping + ghost construction as the main exotic test.+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');++ // The live row survives — its slug could not be read, so staleness is+ // unprovable and the miss is spared, never deleted.+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // Deliberate, documented cost of the incomplete index: the genuinely+ // stale ghost is ALSO spared this run (no delete without proof).+ expect(await engine.getPage('people/ghost')).not.toBeNull();+ });++ test('R4_UNKNOWN_CLEARS_A_PRIOR_SENTINEL: an unprovable retry must not retire a rename an earlier run left open', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const { recordFailures, renameSentinelPath, renameReconcileErrorMessage, loadSyncFailures } =+ await import('../src/core/sync-failure-ledger.ts');+ const repo = mkRepo({+ '\u{1F389}.md': [+ '---', 'type: person', 'title: Party Notes', 'slug: Party-Notes', '---',+ '', 'Party notes live here.',+ ].join('\n'),+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ const anchorBefore = (await engine.executeRaw<{ last_commit: string }>(+ `SELECT last_commit FROM sources WHERE id = 'default'`,+ ))[0]?.last_commit;++ // An EARLIER run already failed to reconcile this very rename.+ recordFailures('default', [{+ path: renameSentinelPath('people/beta.md'),+ error: renameReconcileErrorMessage('people/alpha.md', 'people/ghost', 'injected prior denial'),+ }], 'deadbeef');++ // Now make the tracked-slug index incomplete, exactly as above.+ writeFileSync(join(repo, '\u{1F389}.md'), [+ '---', 'type: person', 'title: Party Notes', 'slug: Party-Notes', '---',+ '', 'x'.repeat(5_100_000),+ ].join('\n'));+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ // The sentinel is the operator's only record that this rename never+ // converged. 'unprovable' is not proof of convergence, so it survives...+ const stillOpen = loadSyncFailures().filter(+ f => f.path === renameSentinelPath('people/beta.md') && f.state === 'open',+ );+ expect(stillOpen).toHaveLength(1);+ // ...and it must NOT name an unprovable row as the stale one: that slug+ // feeds the operator remedy (`gbrain delete <slug>`), and an unprovable+ // row may be live — exactly the row this path refused to delete.+ expect(stillOpen[0]?.error).toContain('stale row ? for');+ for (const slug of ['party-notes', 'people/ghost', 'people/alpha']) {+ expect(stillOpen[0]?.error).not.toContain(`stale row "${slug}"`);+ }+ // ...the run does not report a clean sync...+ expect(result.status).not.toBe('synced');+ // ...the bookmark does not advance past the unresolved rename...+ const anchorAfter = (await engine.executeRaw<{ last_commit: string }>(+ `SELECT last_commit FROM sources WHERE id = 'default'`,+ ))[0]?.last_commit;+ expect(anchorAfter).toBe(anchorBefore);+ // ...and nothing was deleted without proof.+ expect(await engine.getPage('party-notes')).not.toBeNull();+ expect(await engine.getPage('people/ghost')).not.toBeNull();+ });+});++describe('#3583 review: both content states prove liveness — working tree AND index blob', () => {+ test('an uncommitted edit that removes the slug: line must not un-prove the imported row', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = await setupExoticScenario();++ // Uncommitted working-tree edit removes `slug:` — the WORKING TREE now+ // derives nothing, but the row was imported from the COMMITTED content,+ // which still names party-notes. Deleting on the working tree alone+ // loses the row.+ writeFileSync(join(repo, '\u{1F389}.md'), [+ '---', 'type: person', 'title: Party Notes', '---',+ '', 'Party notes live here (slug line temporarily removed).',+ ].join('\n'));++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // Proof stayed intact (the blob answered), so the true ghost is still deleted.+ expect(await engine.getPage('people/ghost')).toBeNull();+ });++ test('an extensionless exotic file imports under its frontmatter slug and must count as live', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const { importFromFile } = await import('../src/core/import-file.ts');+ const repo = mkRepo({+ '\u{1F389}': [+ '---', 'type: person', 'title: Party Notes', 'slug: Party-Notes', '---',+ '', 'Party notes live here.',+ ].join('\n'),+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ // Sync's walker does not import the extensionless file, but the direct+ // import path does — importFromFile has NO extension gate, and the path+ // derives no slug, so the frontmatter fallback fires.+ const imported = await importFromFile(+ engine, join(repo, '\u{1F389}'), '\u{1F389}', { sourceId: 'default', noEmbed: true },+ );+ expect(imported.status).toBe('imported');+ expect(await engine.getPage('party-notes')).not.toBeNull();++ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ });++ test('a tracked markdown symlink is never followed: its out-of-repo target cannot prove liveness', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const external = mkdtempSync(join(tmpdir(), 'gbrain-3583-external-'));+ repos.push(external);+ const externalTarget = join(external, 'outside.md');+ writeFileSync(externalTarget, [+ '---', 'type: person', 'title: Outside', 'slug: outside-probe', '---',+ '', 'This file is outside the repository.',+ ].join('\n'));+ const repo = mkRepo({ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.') });+ symlinkSync(externalTarget, join(repo, '\u{1F389}.md'));+ execSync('git add -A', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "add symlink"', { cwd: repo, stdio: 'pipe' });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ // A row named by the TARGET's frontmatter slug, wearing the stale path+ // of the rename below. Import refuses symlinks, so no in-repo file can+ // legitimately back this row — the index must treat the symlink as its+ // blob (the target path text, which derives nothing) and let the row+ // be reconciled, NOT follow the link out of the repository and spare it.+ await engine.putPage('outside-probe', {+ type: 'person', title: 'Outside (stale)', compiled_truth: 'no in-repo backing file',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'outside-probe'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('outside-probe')).toBeNull();+ });++ test('absent working copy plus unmerged index makes the fallback index incomplete and spares every miss', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = await setupExoticScenario();++ // Replace the emoji file's stage-0 index entry with unmerged stage-1/2+ // entries and remove the working copy: neither content state is+ // readable, so no slug can be proven and NOTHING may be deleted.+ const stageZero = execSync('git ls-files -s -- "\u{1F389}.md"', {+ cwd: repo, stdio: 'pipe',+ }).toString();+ const blob = stageZero.trim().split(/\s+/)[1];+ expect(blob).toBeTruthy();+ execSync('git update-index --force-remove -- "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });+ execSync('git update-index --index-info', {+ cwd: repo,+ stdio: ['pipe', 'pipe', 'pipe'],+ input:+ `100644 ${blob} 1\t\u{1F389}.md\n` ++ `100644 ${blob} 2\t\u{1F389}.md\n`,+ });+ rmSync(join(repo, '\u{1F389}.md'));++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // Incomplete index: even the true ghost is spared this run.+ expect(await engine.getPage('people/ghost')).not.toBeNull();+ });++ test('unreachable checkpoint rows survive dry-run and are cleared by the real run', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const { loadOpCheckpoint, recordCompleted, syncFingerprint } =+ await import('../src/core/op-checkpoint.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ const anchor = execSync('git rev-parse HEAD', { cwd: repo, stdio: 'pipe' }).toString().trim();++ writeFileSync(join(repo, 'people/old-line.md'), personMd('Old line', 'old history'));+ execSync('git add -A && git commit -m "old line"', { cwd: repo, stdio: 'pipe' });+ const unreachableTarget =+ execSync('git rev-parse HEAD', { cwd: repo, stdio: 'pipe' }).toString().trim();+ // Rewind to the anchor and diverge — the recorded target becomes+ // unreachable from the new history line (temp repo, nothing of value+ // is discarded).+ execSync(`git reset --hard ${anchor}`, { cwd: repo, stdio: 'pipe' });+ writeFileSync(join(repo, 'people/new-line.md'), personMd('New line', 'new history'));+ execSync('git add -A && git commit -m "new line"', { cwd: repo, stdio: 'pipe' });++ const fingerprint = syncFingerprint({ sourceId: 'default', lastCommit: anchor });+ const pathsKey = { op: 'sync', fingerprint };+ const targetKey = { op: 'sync-target', fingerprint };+ await recordCompleted(engine, pathsKey, ['people/already-done.md']);+ await recordCompleted(engine, targetKey, [unreachableTarget]);++ const dry = await performSync(engine, { repoPath: repo, ...SYNC_OPTS, dryRun: true });+ expect(dry.status).toBe('dry_run');+ expect(await loadOpCheckpoint(engine, pathsKey)).toEqual(['people/already-done.md']);+ expect(await loadOpCheckpoint(engine, targetKey)).toEqual([unreachableTarget]);++ const real = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(real.status).toBe('synced');+ expect(await loadOpCheckpoint(engine, pathsKey)).toEqual([]);+ expect(await loadOpCheckpoint(engine, targetKey)).toEqual([]);+ });+});++describe('#3583 review: a writer landing AFTER the second probe gets its sentinel restored', () => {+ test('clear-then-verify detects the post-probe row and re-records the sentinel', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ await plantOrphanedSentinel();+ expect(await openDanaRows()).toHaveLength(1);++ // Both orphan probes see "no active row" — the writer lands only AFTER+ // the second probe returned, i.e. after the double-probe verdict is+ // final and the clear is committed. The post-clear verify probe must+ // detect the row and RESTORE the sentinel.+ const origExecuteRaw = engine.executeRaw.bind(engine);+ let probeCalls = 0;+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw =+ (async (sql: string, params?: unknown[]) => {+ const res = await origExecuteRaw(sql, params);+ if (sql.includes('source_path = ANY')) {+ probeCalls++;+ if (probeCalls === 2) {+ await engine.putPage('people/dana-old-late-writer', {+ type: 'person', title: 'Dana (late writer)',+ compiled_truth: 'materialized after the second probe',+ }, { sourceId: 'default' });+ await origExecuteRaw(+ `UPDATE pages SET source_path = 'people/dana-old.md'+ WHERE source_id = 'default' AND slug = 'people/dana-old-late-writer'`,+ );+ }+ }+ return res;+ }) as typeof engine.executeRaw;+ try {+ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('up_to_date');+ } finally {+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw = origExecuteRaw;+ }++ // Probe #1 and #2 (orphan verdict) + probe #3 (post-clear verify).+ expect(probeCalls).toBe(3);+ expect(await engine.getPage('people/dana-old-late-writer')).not.toBeNull();+ // The duplicate is real again — the verify probe restored its sentinel.+ expect(await openDanaRows()).toHaveLength(1);+ });+});++describe('#3583 review: HEAD keeps proving liveness through a STAGED uncommitted edit', () => {+ test('staging the slug-line removal changes the working tree AND the staging index — HEAD still spares the row', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = await setupExoticScenario();++ // Remove the slug: line AND stage it (no commit): the working tree and+ // the staging-index blob now both derive nothing — only HEAD still+ // carries the slug the imported row was created from.+ writeFileSync(join(repo, '\u{1F389}.md'), [+ '---', 'type: person', 'title: Party Notes', '---',+ '', 'Party notes live here (slug line removed and STAGED).',+ ].join('\n'));+ execSync('git add -- "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // Proof intact through HEAD — the true ghost is still deleted.+ expect(await engine.getPage('people/ghost')).toBeNull();+ });+});++describe('#3583 review: the failure-gate clear paths also verify-and-restore', () => {+ test('incremental gate: a writer landing after the orphan verdict gets its sentinel restored post-gate', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ await plantOrphanedSentinel();+ expect(await openDanaRows()).toHaveLength(1);++ // A COMMITTED unrelated change routes the run through the import path+ // and the failure GATE (not the quiet-run sweep) — the gate's clear of+ // the orphaned sentinel used to skip post-clear verification entirely.+ writeFileSync(join(repo, 'people/newfile.md'), personMd('New', 'New person.'));+ execSync('git add -A && git commit -m "unrelated addition"', { cwd: repo, stdio: 'pipe' });++ const origExecuteRaw = engine.executeRaw.bind(engine);+ let probeCalls = 0;+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw =+ (async (sql: string, params?: unknown[]) => {+ const res = await origExecuteRaw(sql, params);+ if (sql.includes('source_path = ANY')) {+ probeCalls++;+ if (probeCalls === 2) {+ // After the double-probe verdict is final, before the gate clears.+ await engine.putPage('people/dana-old-gate-writer', {+ type: 'person', title: 'Dana (gate writer)',+ compiled_truth: 'materialized between the gate verdict and the clear',+ }, { sourceId: 'default' });+ await origExecuteRaw(+ `UPDATE pages SET source_path = 'people/dana-old.md'+ WHERE source_id = 'default' AND slug = 'people/dana-old-gate-writer'`,+ );+ }+ }+ return res;+ }) as typeof engine.executeRaw;+ try {+ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ } finally {+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw = origExecuteRaw;+ }++ expect(await engine.getPage('people/dana-old-gate-writer')).not.toBeNull();+ // The post-gate verify probe restored the sentinel.+ expect(await openDanaRows()).toHaveLength(1);+ });++ test('a verify probe that THROWS after the clear restores every cleared sentinel (fail-closed), verbatim', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const { recordFailures, renameSentinelPath, renameReconcileErrorMessage } =+ await import('../src/core/sync-failure-ledger.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ // Plant the orphan TWICE so attempts climbs to 2 — the restore must+ // reproduce the row verbatim, not restart the streak at attempts 1.+ const plant = () => recordFailures('default', [{+ path: renameSentinelPath('people/dana.md'),+ error: renameReconcileErrorMessage('people/dana-old.md', 'people/dana-old', 'injected wedge'),+ }], 'deadbeef');+ plant();+ plant();+ const before = (await openDanaRows())[0];+ expect(before).toBeDefined();+ expect(before!.attempts).toBe(2);++ // Both orphan probes succeed (empty) → clear commits; the post-clear+ // VERIFY probe (third matching SELECT) throws. Fail-closed means every+ // cleared sentinel comes back.+ const origExecuteRaw = engine.executeRaw.bind(engine);+ let probeCalls = 0;+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw =+ (async (sql: string, params?: unknown[]) => {+ if (sql.includes('source_path = ANY')) {+ probeCalls++;+ if (probeCalls === 3) throw new Error('injected verify-probe outage');+ }+ return origExecuteRaw(sql, params);+ }) as typeof engine.executeRaw;+ try {+ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('up_to_date');+ } finally {+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw = origExecuteRaw;+ }++ expect(probeCalls).toBe(3);+ const rows = await openDanaRows();+ expect(rows).toHaveLength(1);+ // Verbatim restore: streak metadata survives the round trip.+ expect(rows[0]!.attempts).toBe(2);+ expect(rows[0]!.first_seen).toBe(before!.first_seen);+ expect(rows[0]!.commit).toBe(before!.commit);+ });+});++describe('#3583 review: the anchor commit keeps proving liveness when HEAD moved past it', () => {+ test('a single commit that removes the slug: line AND carries the colliding rename must not delete the row imported at the anchor', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({+ '\u{1F389}.md': exoticMd,+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('party-notes')).not.toBeNull();++ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });++ // ONE commit does both: the emoji file loses its slug: line (its+ // re-import will fail with "produces no usable slug") AND the rename+ // that triggers the reconcile lands. Working tree, staging index, and+ // HEAD all show the slugless content — only the ANCHOR commit (what+ // the brain actually reflects) still proves the row.+ writeFileSync(join(repo, '\u{1F389}.md'), [+ '---', 'type: person', 'title: Party Notes', '---',+ '', 'Party notes live here (slug line removed at HEAD).',+ ].join('\n'));+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git add -A && git commit -m "remove slug and rename in one commit"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ // The emoji file's re-import fails (no usable slug), so the run blocks —+ // and the reconcile that ran within it must NOT have deleted the row.+ expect(result.status).toBe('blocked_by_failures');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // The true ghost is still gone: the anchor state answered, proof intact.+ expect(await engine.getPage('people/ghost')).toBeNull();+ });+});++describe('#3583 review: a throwing bookmark advance can no longer lose a sentinel', () => {+ test('the orphan sweep sits outside the gate: advance() throwing leaves the sentinel untouched', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ await plantOrphanedSentinel();+ expect(await openDanaRows()).toHaveLength(1);++ // A committed change routes the run through the gate; the injected+ // failure makes the bookmark advance throw AFTER the gate's internal+ // record/clear pass. The orphaned sentinel must survive: its clear+ // lives OUTSIDE the gate now, and is never reached on a throw.+ writeFileSync(join(repo, 'people/newfile.md'), personMd('New', 'New person.'));+ execSync('git add -A && git commit -m "unrelated addition"', { cwd: repo, stdio: 'pipe' });++ const origExecuteRaw = engine.executeRaw.bind(engine);+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw =+ (async (sql: string, params?: unknown[]) => {+ if (sql.includes('UPDATE sources SET last_commit')) {+ throw new Error('injected advance outage');+ }+ return origExecuteRaw(sql, params);+ }) as typeof engine.executeRaw;+ let threw = false;+ try {+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ } catch {+ threw = true;+ } finally {+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw = origExecuteRaw;+ }+ expect(threw).toBe(true);++ // Fail-closed: nothing cleared, nothing lost.+ expect(await openDanaRows()).toHaveLength(1);+ });+});++describe('#3583 review: the anchor tree is enumerated on its own paths, not looked up through current ones', () => {+ test('renaming the exotic file itself (while dropping its slug) must not lose the anchor-imported row', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({+ '\u{1F389}.md': exoticMd,+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('party-notes')).not.toBeNull();++ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });++ // ONE commit renames the exotic file to a NEW exotic path, drops its+ // slug: line, and carries the colliding rename. The anchor's content+ // for the row now lives at the OLD path — a liveness pass that only+ // queries the anchor through CURRENT paths misses it entirely (and+ // still believes its index is complete).+ execSync('git mv "\u{1F389}.md" "\u{2728}.md"', { cwd: repo, stdio: 'pipe' });+ writeFileSync(join(repo, '\u{2728}.md'), [+ '---', 'type: person', 'title: Party Notes', '---',+ '', 'Party notes live here (renamed and slug line dropped).',+ ].join('\n'));+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git add -A && git commit -m "rename exotic file, drop slug, rename alpha"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ // The exotic file's re-import fails (no usable slug at its new path),+ // so the run blocks — and the reconcile inside it must NOT have+ // deleted the anchor-imported row.+ expect(result.status).toBe('blocked_by_failures');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // The anchor tree answered, proof stays intact: the ghost is still gone.+ expect(await engine.getPage('people/ghost')).toBeNull();+ });+});++describe('#3583 review: GATE6 — the three anchor-enumeration refutations', () => {+ test('a row carried by ANOTHER rename in the diff (ordinary path renamed to a slugless exotic path) survives', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({+ 'notes/party.md': personMd('Party', 'Party content lives here.'),+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('notes/party')).not.toBeNull();++ // Stale bookkeeping from a prior cheap rename + the usual ghost/occupier.+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'notes/party'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });++ // ONE commit renames notes/party.md to an exotic path (derives no slug,+ // carries no frontmatter slug — its re-import will fail) AND carries the+ // colliding alpha rename. No current path, blob, or anchor FALLBACK+ // state names notes/party anymore — only the rename pair itself proves+ // the content is still tracked.+ execSync('git mv notes/party.md "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "carry party to an exotic path; rename alpha"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('blocked_by_failures');+ expect(await engine.getPage('notes/party')).not.toBeNull();+ expect(await engine.getPage('people/ghost')).toBeNull();+ });++ test('a leading-space filename survives NUL-delimited listing intact (no trim corruption, no decoy read)', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({+ // Sorts FIRST in every listing — the entry a trimmed NUL-joined+ // string corrupts. Its decoy (same name minus the space) carries a+ // DIFFERENT slug; a corrupted read would register the decoy's slug+ // twice and never party-notes.+ ' \u{1F389}.md': [+ '---', 'type: person', 'title: Party Notes', 'slug: Party-Notes', '---',+ '', 'Party notes live here.',+ ].join('\n'),+ '\u{1F389}.md': [+ '---', 'type: person', 'title: Decoy', 'slug: decoy-notes', '---',+ '', 'Decoy content.',+ ].join('\n'),+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('party-notes')).not.toBeNull();+ expect(await engine.getPage('decoy-notes')).not.toBeNull();++ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta (stale)', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ expect(await engine.getPage('people/ghost')).toBeNull();+ });++ test('a content filter configured for a fallback-regime file makes anchor-blob proof unprovable (spared, not trusted)', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = await setupExoticScenario();+ // Even an IDENTITY filter flips the verdict: `cat-file --filters`+ // reconstructs historical blobs with TODAY's filter definitions, so a+ // drifted smudge filter can hand back content whose slug differs from+ // what was imported — a successful read is not evidence of absence.+ writeFileSync(join(repo, '.gitattributes'), '*.md filter=ident\n');+ execSync('git config filter.ident.clean cat', { cwd: repo, stdio: 'pipe' });+ execSync('git config filter.ident.smudge cat', { cwd: repo, stdio: 'pipe' });+ execSync('git add .gitattributes && git commit -m "add filter"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // The filter makes the anchor evidence unprovable → the index is+ // incomplete → even the true ghost is spared this run (documented cost).+ expect(await engine.getPage('people/ghost')).not.toBeNull();+ });+});++describe('#3583 review: GATE7 — exclude-filtered carriers and filter-name impersonation', () => {+ test('excluded carried rename is still part of the full diff proof', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({+ 'notes/party.md': personMd('Party', 'Party content lives here.'),+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('notes/party')).not.toBeNull();++ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'notes/party'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta occupier', compiled_truth: 'occupies destination',+ }, { sourceId: 'default' });++ execSync('git mv notes/party.md "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "carry excluded party; rename alpha"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, {+ repoPath: repo,+ ...SYNC_OPTS,+ exclude: ['\u{1F389}.md'],+ });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('notes/party')).not.toBeNull();+ expect(await engine.getPage('people/ghost')).toBeNull();+ });++ test('a configured filter literally named unspecified cannot impersonate no filter', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({+ '\u{1F389}.md': exoticMd,+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ const anchor = execSync('git rev-parse HEAD', { cwd: repo, stdio: 'pipe' }).toString().trim();+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('party-notes')).not.toBeNull();++ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta occupier', compiled_truth: 'occupies destination',+ }, { sourceId: 'default' });++ writeFileSync(join(repo, '\u{1F389}.md'), [+ '---', 'type: person', 'title: Party Notes', '---',+ '', 'Slug line removed in the current tree.',+ ].join('\n'));+ writeFileSync(join(repo, '.gitattributes'), '*.md filter=unspecified\n');+ execSync('git config filter.unspecified.clean cat', { cwd: repo, stdio: 'pipe' });+ execSync(`git config filter.unspecified.smudge "sed '/^slug:/d'"`, { cwd: repo, stdio: 'pipe' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git add -A && git commit -m "drift ambiguous filter and rename"', { cwd: repo, stdio: 'pipe' });++ const attr = execSync('git check-attr filter -- "\u{1F389}.md"', {+ cwd: repo, stdio: 'pipe',+ }).toString().trim();+ expect(attr).toEndWith(': filter: unspecified');+ const filteredAnchor = execSync(`git cat-file --filters "${anchor}:\u{1F389}.md"`, {+ cwd: repo, stdio: 'pipe',+ }).toString();+ expect(filteredAnchor).not.toContain('slug: Party-Notes');++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('blocked_by_failures');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // The impersonating filter IS detected (the filter ATTRIBUTE is+ // specified for the path — check-attr --all lists it regardless of+ // its magic-looking value), so anchor evidence is unprovable and the+ // index incomplete — even the true ghost is spared this run, the same+ // documented cost as any filtered fallback path. (party-notes above+ // additionally survives through the RAW anchor blob, which still+ // carries the slug the drifted smudge strips.)+ expect(await engine.getPage('people/ghost')).not.toBeNull();+ });+});++describe('#3583 review: GATE8 — a REMOVED filter driver cannot impersonate no filter', () => {+ test('deleting filter.<name>.* config while .gitattributes still names it keeps the historically-smudged row alive', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ // The raw blob carries NO slug — the smudge filter INJECTS it at+ // checkout, so the row sync imports exists ONLY through the filter+ // conversion. mkRepo commits BEFORE the driver is configured, so the+ // committed blob is the raw form.+ const rawExotic = [+ '---', 'type: person', 'title: Party Notes', '---',+ '', 'Party notes live here.',+ ].join('\n');+ const repo = mkRepo({+ '\u{1F389}.md': rawExotic,+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ '.gitattributes': '*.md filter=unspecified\n',+ });+ execSync(`git config filter.unspecified.clean "sed '/^slug: Party-Notes$/d'"`, { cwd: repo, stdio: 'pipe' });+ execSync(`git config filter.unspecified.smudge "awk 'NR==2{print \\"slug: Party-Notes\\"}1'"`, { cwd: repo, stdio: 'pipe' });+ // Materialize the smudged working tree (checkout runs the smudge).+ rmSync(join(repo, '\u{1F389}.md'));+ execSync('git checkout -- "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });+ expect(readFileSync(join(repo, '\u{1F389}.md'), 'utf8')).toContain('slug: Party-Notes');++ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('party-notes')).not.toBeNull();++ // The operator (or a fresh clone) loses the LOCAL driver config; the+ // committed .gitattributes entry stays behind. Re-checkout leaves the+ // raw, slugless content in the working tree.+ execSync('git config --remove-section filter.unspecified', { cwd: repo, stdio: 'pipe' });+ rmSync(join(repo, '\u{1F389}.md'));+ execSync('git checkout -- "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });+ expect(readFileSync(join(repo, '\u{1F389}.md'), 'utf8')).not.toContain('slug: Party-Notes');+ // The exact ambiguity: check-attr still reports the magic-looking+ // token, and the driver lookup that used to "disambiguate" it finds+ // nothing (config --get-regexp exits non-zero).+ const attr = execSync('git check-attr filter -- "\u{1F389}.md"', {+ cwd: repo, stdio: 'pipe',+ }).toString().trim();+ expect(attr).toEndWith(': filter: unspecified');+ expect(() => execSync(`git config --get-regexp '^filter\\.unspecified\\.'`, {+ cwd: repo, stdio: 'pipe',+ })).toThrow();++ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta occupier', compiled_truth: 'occupies destination',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });++ // No current git surface (worktree, staging, HEAD, anchor raw OR+ // anchor filter-converted — the driver is gone) carries the slug the+ // historical smudge injected. Only the still-specified filter+ // attribute proves the evidence is unprovable.+ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // Unprovable evidence spares every miss, including the true ghost+ // (the same documented conservative cost as any filtered path).+ expect(await engine.getPage('people/ghost')).not.toBeNull();+ });+});++describe('#3583 review: GATE9 — attribute mutations after the import cannot erase the anchor-time filter', () => {+ test('resetting the attribute to !filter still leaves the anchor-imported row alive (anchor attrs consulted via --source)', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ // Same historical-smudge construction as GATE8: the raw blob has no+ // slug, the smudge injects it, and the imported row exists only+ // through the anchor-time conversion.+ const rawExotic = [+ '---', 'type: person', 'title: Party Notes', '---',+ '', 'Party notes live here.',+ ].join('\n');+ const repo = mkRepo({+ '\u{1F389}.md': rawExotic,+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ '.gitattributes': '*.md filter=probe\n',+ });+ execSync(`git config filter.probe.clean "sed '/^slug: Party-Notes$/d'"`, { cwd: repo, stdio: 'pipe' });+ execSync(`git config filter.probe.smudge "awk 'NR==2{print \\"slug: Party-Notes\\"}1'"`, { cwd: repo, stdio: 'pipe' });+ rmSync(join(repo, '\u{1F389}.md'));+ execSync('git checkout -- "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });+ expect(readFileSync(join(repo, '\u{1F389}.md'), 'utf8')).toContain('slug: Party-Notes');++ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('party-notes')).not.toBeNull();++ // The attribute is RESET to force-unspecified — the driver stays+ // configured, but today's check-attr --all output for the path is+ // EMPTY. Only the anchor commit's attributes still name the filter.+ writeFileSync(join(repo, '.gitattributes'), '*.md !filter\n');+ execSync('git add .gitattributes && git commit -m "reset filter attribute"', { cwd: repo, stdio: 'pipe' });+ rmSync(join(repo, '\u{1F389}.md'));+ execSync('git checkout -- "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });+ expect(readFileSync(join(repo, '\u{1F389}.md'), 'utf8')).not.toContain('slug: Party-Notes');+ const attrToday = execSync('git check-attr --all -- "\u{1F389}.md"', {+ cwd: repo, stdio: 'pipe',+ }).toString();+ expect(attrToday).toBe('');++ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta occupier', compiled_truth: 'occupies destination',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // Anchor-time filter detected via --source → evidence unprovable →+ // every miss spared, the ghost included (documented cost).+ expect(await engine.getPage('people/ghost')).not.toBeNull();+ });++ test('a filter active only for a PAST interval (attr removal already absorbed by an earlier sync) still downgrades the proof', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ // Same historical-smudge construction, but the attribute reset is+ // absorbed by an INTERMEDIATE sync: by the time the rename reconcile+ // runs, BOTH endpoints (today's attributes and the current anchor's)+ // are clean — only an interior epoch of the history names the filter+ // the imported row's content came through.+ const rawExotic = [+ '---', 'type: person', 'title: Party Notes', '---',+ '', 'Party notes live here.',+ ].join('\n');+ const repo = mkRepo({+ '\u{1F389}.md': rawExotic,+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ '.gitattributes': '*.md filter=probe\n',+ });+ execSync(`git config filter.probe.clean "sed '/^slug: Party-Notes$/d'"`, { cwd: repo, stdio: 'pipe' });+ execSync(`git config filter.probe.smudge "awk 'NR==2{print \\"slug: Party-Notes\\"}1'"`, { cwd: repo, stdio: 'pipe' });+ rmSync(join(repo, '\u{1F389}.md'));+ execSync('git checkout -- "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('party-notes')).not.toBeNull();++ writeFileSync(join(repo, '.gitattributes'), '*.md !filter\n');+ // An ordinary edit rides along so the intermediate sync has syncable+ // work and ADVANCES the anchor past the reset commit. The adds are+ // TARGETED: `git add -A` here would sweep the still-smudged working+ // copy of the exotic file into the commit as a slug-carrying blob+ // (the clean filter no longer strips it), collapsing the scenario.+ writeFileSync(join(repo, 'people/alpha.md'), personMd('Alpha', 'Alpha is a person. Edited.'));+ execSync('git add .gitattributes people/alpha.md && git commit -m "reset filter attribute; edit alpha"', { cwd: repo, stdio: 'pipe' });+ const resetCommit = execSync('git rev-parse HEAD', { cwd: repo, stdio: 'pipe' }).toString().trim();+ rmSync(join(repo, '\u{1F389}.md'));+ execSync('git checkout -- "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });+ expect(readFileSync(join(repo, '\u{1F389}.md'), 'utf8')).not.toContain('slug: Party-Notes');+ const mid = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(mid.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // Scenario precondition: the anchor now sits AT the reset commit, so+ // both endpoint attribute states (today + anchor) are clean.+ const anchorRows = await engine.executeRaw<{ last_commit: string }>(+ `SELECT last_commit FROM sources WHERE id = 'default'`,+ );+ expect(anchorRows[0]?.last_commit).toBe(resetCommit);++ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta occupier', compiled_truth: 'occupies destination',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ expect(await engine.getPage('people/ghost')).not.toBeNull();+ });+});++describe('#3583 review: GATE10 — historical path-specific attributes survive a rename of the file', () => {+ test('a reachable filter epoch on the pre-rename path must downgrade proof for the anchor-time path', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const rawExotic = [+ '---', 'type: person', 'title: Party Notes', '---',+ '', 'Party notes live here.',+ ].join('\n');+ const repo = mkRepo({+ '🎉.md': rawExotic,+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ '.gitattributes': '🎉.md filter=probe\n',+ });+ execSync(`git config filter.probe.clean "sed '/^slug: Party-Notes$/d'"`, { cwd: repo, stdio: 'pipe' });+ execSync(`git config filter.probe.smudge "awk 'NR==2{print \\"slug: Party-Notes\\"}1'"`, { cwd: repo, stdio: 'pipe' });+ rmSync(join(repo, '🎉.md'));+ execSync('git checkout -- "🎉.md"', { cwd: repo, stdio: 'pipe' });+ expect(readFileSync(join(repo, '🎉.md'), 'utf8')).toContain('slug: Party-Notes');+ const importCommit = execSync('git rev-parse HEAD', { cwd: repo, stdio: 'pipe' })+ .toString().trim();++ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('party-notes')).not.toBeNull();++ // Remove the filter and materialize the raw, slugless blob before the+ // file moves. The old-path filter epoch remains reachable from HEAD.+ writeFileSync(join(repo, '.gitattributes'), '*.md !filter\n');+ rmSync(join(repo, '🎉.md'));+ execSync('git checkout -- "🎉.md"', { cwd: repo, stdio: 'pipe' });+ expect(readFileSync(join(repo, '🎉.md'), 'utf8')).not.toContain('slug: Party-Notes');+ execSync('git mv "🎉.md" "✨.md"', { cwd: repo, stdio: 'pipe' });+ execSync('git add .gitattributes && git commit -m "reset filter and move exotic file"', {+ cwd: repo, stdio: 'pipe',+ });+ const movedCommit = execSync('git rev-parse HEAD', { cwd: repo, stdio: 'pipe' })+ .toString().trim();++ // Absorb the move while excluding its destination. This advances the+ // sync anchor without re-importing the now-slugless fallback file.+ await performSync(engine, {+ repoPath: repo,+ ...SYNC_OPTS,+ exclude: ['✨.md'],+ });+ const anchorRows = await engine.executeRaw<{ last_commit: string }>(+ `SELECT last_commit FROM sources WHERE id = 'default'`,+ );+ expect(anchorRows[0]?.last_commit).toBe(movedCommit);+ expect(await engine.getPage('party-notes')).not.toBeNull();++ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta occupier', compiled_truth: 'occupies destination',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });++ // Pin the defect mechanism: the epoch enumeration finds both+ // attribute-changing commits, but a PER-PATH check keyed to the+ // anchor path (✨.md) is empty at every epoch, while the same import+ // epoch proves a filter immediately under the HISTORICAL path+ // (🎉.md). Only a repo-wide epoch check can see it.+ const epochOutput = execSync(+ `git log --format=%H HEAD ${movedCommit} -- .gitattributes ':(glob)**/.gitattributes'`,+ { cwd: repo, stdio: 'pipe' },+ ).toString().trim();+ const epochs = epochOutput.split('\n').filter(Boolean);+ expect(epochs).toContain(importCommit);+ expect(epochs).toContain(movedCommit);+ for (const epoch of epochs) {+ expect(execSync(`git check-attr --source=${epoch} --all -- "✨.md"`, {+ cwd: repo, stdio: 'pipe',+ }).toString()).toBe('');+ }+ const oldPathAtImport = execSync(+ `git check-attr --source=${importCommit} --all -- "🎉.md"`,+ { cwd: repo, stdio: 'pipe' },+ ).toString();+ expect(oldPathAtImport).toContain('filter: probe');++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // The repo-wide historical downgrade spares every miss, the true+ // ghost included (documented conservative cost).+ expect(await engine.getPage('people/ghost')).not.toBeNull();+ });+});++describe('#3583 review: GATE11 — filter epochs invisible to the default history walk', () => {+ test('a filter epoch on a side branch discarded by a merge (-s ours) still downgrades the proof', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const rawExotic = [+ '---', 'type: person', 'title: Party Notes', '---',+ '', 'Party notes live here.',+ ].join('\n');+ // Base commit has NO attributes file at all.+ const repo = mkRepo({+ '\u{1F389}.md': rawExotic,+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ // The filter lives only on an experiment branch; the sync that imports+ // the row runs while THAT branch is checked out.+ const mainBranch = execSync('git branch --show-current', { cwd: repo, stdio: 'pipe' })+ .toString().trim();+ execSync('git switch -qc filtered-side', { cwd: repo, stdio: 'pipe' });+ writeFileSync(join(repo, '.gitattributes'), '*.md filter=probe\n');+ execSync('git add .gitattributes && git commit -m "side: enable filter"', { cwd: repo, stdio: 'pipe' });+ const sideCommit = execSync('git rev-parse HEAD', { cwd: repo, stdio: 'pipe' }).toString().trim();+ execSync(`git config filter.probe.clean "sed '/^slug: Party-Notes$/d'"`, { cwd: repo, stdio: 'pipe' });+ execSync(`git config filter.probe.smudge "awk 'NR==2{print \\"slug: Party-Notes\\"}1'"`, { cwd: repo, stdio: 'pipe' });+ rmSync(join(repo, '\u{1F389}.md'));+ execSync('git checkout -- "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });+ expect(readFileSync(join(repo, '\u{1F389}.md'), 'utf8')).toContain('slug: Party-Notes');+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('party-notes')).not.toBeNull();++ // The experiment is DISCARDED at the merge: `-s ours` keeps the main+ // tree (no attributes file), so the merge is TREESAME to the kept+ // parent and the default path-simplified walk prunes the side line.+ execSync(`git switch -q ${mainBranch}`, { cwd: repo, stdio: 'pipe' });+ execSync('git merge -q -s ours filtered-side -m "discard filter experiment"', { cwd: repo, stdio: 'pipe' });+ rmSync(join(repo, '\u{1F389}.md'));+ execSync('git checkout -- "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });+ expect(readFileSync(join(repo, '\u{1F389}.md'), 'utf8')).not.toContain('slug: Party-Notes');+ // An ordinary edit so the intermediate sync advances the anchor.+ writeFileSync(join(repo, 'people/alpha.md'), personMd('Alpha', 'Alpha is a person. Edited.'));+ execSync('git add people/alpha.md && git commit -m "edit alpha"', { cwd: repo, stdio: 'pipe' });+ const postMergeCommit = execSync('git rev-parse HEAD', { cwd: repo, stdio: 'pipe' }).toString().trim();+ const mid = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(mid.status).toBe('synced');+ const anchorRows = await engine.executeRaw<{ last_commit: string }>(+ `SELECT last_commit FROM sources WHERE id = 'default'`,+ );+ expect(anchorRows[0]?.last_commit).toBe(postMergeCommit);+ expect(await engine.getPage('party-notes')).not.toBeNull();++ // Pin the defect mechanism: the default walk omits the side epoch,+ // --full-history keeps it.+ const defaultLog = execSync(+ `git log --format=%H HEAD ${postMergeCommit} -- .gitattributes ':(glob)**/.gitattributes'`,+ { cwd: repo, stdio: 'pipe' },+ ).toString();+ expect(defaultLog).not.toContain(sideCommit);+ const fullLog = execSync(+ `git log --full-history --format=%H HEAD ${postMergeCommit} -- .gitattributes ':(glob)**/.gitattributes'`,+ { cwd: repo, stdio: 'pipe' },+ ).toString();+ expect(fullLog).toContain(sideCommit);++ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta occupier', compiled_truth: 'occupies destination',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ expect(await engine.getPage('people/ghost')).not.toBeNull();+ });++ test('a shallow clone makes attribute history unprovable: no fallback-anchor delete on truncated history', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ // Full source repo: an attributes-free history whose ghost WOULD be+ // deletable — then a shallow re-clone truncates the history the epoch+ // enumeration needs, and every fallback anchor proof degrades.+ const src = mkRepo({+ '\u{1F389}.md': exoticMd,+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ execSync('git commit --allow-empty -m "second commit for depth"', { cwd: src, stdio: 'pipe' });+ const shallow = mkdtempSync(join(tmpdir(), 'gbrain-3056-shallow-'));+ repos.push(shallow);+ execSync(`git clone --no-local --depth 1 "file://${src}" "${shallow}"`, { stdio: 'pipe' });+ execSync('git config user.email "[email protected]" && git config user.name "Test"', {+ cwd: shallow, stdio: 'pipe',+ });+ expect(execSync('git rev-parse --is-shallow-repository', { cwd: shallow, stdio: 'pipe' })+ .toString().trim()).toBe('true');++ await performSync(engine, { repoPath: shallow, ...SYNC_OPTS });+ expect(await engine.getPage('party-notes')).not.toBeNull();++ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'party-notes'`,+ );+ await engine.putPage('people/ghost', {+ type: 'person', title: 'Ghost (stale)', compiled_truth: 'no backing file anywhere',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'people/ghost'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta occupier', compiled_truth: 'occupies destination',+ }, { sourceId: 'default' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: shallow, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: shallow, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: shallow, ...SYNC_OPTS });+ expect(result.status).toBe('synced');+ expect(await engine.getPage('party-notes')).not.toBeNull();+ // Truncated history is unprovable history: the ghost is spared too.+ expect(await engine.getPage('people/ghost')).not.toBeNull();+ });+});++describe('#3583 review: GATE13 — a cheap rename repairs its bookkeeping when it lands', () => {+ test('a cheap rename repairs source_path at the moment it lands, and the row survives a full sync', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('people/alpha')).not.toBeNull();++ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repo, stdio: 'pipe' });+ const inc = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(inc.status).toBe('synced');+ expect(await engine.getPage('people/beta')).not.toBeNull();+ expect(await engine.getPage('people/alpha')).toBeNull();+ // The root fix: the cheap rename no longer leaves source_path behind+ // (updateSlug moves the row; the unchanged-content reimport is a+ // no-write skip that would never have repaired it).+ const bookkeeping = await engine.executeRaw<{ source_path: string | null }>(+ `SELECT source_path FROM pages WHERE source_id = 'default' AND slug = 'people/beta'`,+ );+ expect(bookkeeping[0]?.source_path).toBe('people/beta.md');++ const full = await performSync(engine, { repoPath: repo, ...SYNC_OPTS, full: true });+ expect(full.status).not.toBe('blocked_by_failures');+ expect(await engine.getPage('people/beta')).not.toBeNull();+ });++});++describe('#3583 review: GATE13 — chunker_version is acknowledged only by a completed re-chunk', () => {+ test('a chunker-version-gate dry run leaves chunker_version untouched', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const repo = mkRepo({ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ await engine.executeRaw(+ `UPDATE sources SET chunker_version = 'gate13-stale' WHERE id = 'default'`,+ );+ const preview = await performSync(engine, { repoPath: repo, ...SYNC_OPTS, dryRun: true });+ expect(preview.status).toBe('dry_run');+ const version = await engine.executeRaw<{ chunker_version: string | null }>(+ `SELECT chunker_version FROM sources WHERE id = 'default'`,+ );+ expect(version[0]?.chunker_version).toBe('gate13-stale');+ });++ test('a BLOCKED forced re-chunk keeps the version stale, so the retry actually re-runs', async () => {+ const { CHUNKER_VERSION } = await import('../src/core/chunkers/code.ts');+ const { performSync } = await import('../src/commands/sync.ts');+ const goodAlpha = personMd('Alpha', 'Alpha is a person.');+ const repo = mkRepo({ 'people/alpha.md': goodAlpha });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ await engine.executeRaw(+ `UPDATE sources SET chunker_version = 'gate13-stale' WHERE id = 'default'`,+ );+ // Corrupt the tracked working copy so the forced full re-chunk fails.+ // Invalid YAML frontmatter, NOT a NUL byte: #3998 NUL-sanitizes page+ // bodies at write time, so a NUL now ingests cleanly instead of failing.+ writeFileSync(join(repo, 'people/alpha.md'), '---\ntitle: [unclosed\n---\ngarbage\n');+ const blocked = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(blocked.status).toBe('blocked_by_failures');+ const staleVersion = await engine.executeRaw<{ chunker_version: string | null }>(+ `SELECT chunker_version FROM sources WHERE id = 'default'`,+ );+ // The failed re-chunk must NOT be acknowledged...+ expect(staleVersion[0]?.chunker_version).toBe('gate13-stale');++ // ...so once the operator repairs the file, the retry actually+ // re-runs the re-chunk instead of reporting up_to_date.+ writeFileSync(join(repo, 'people/alpha.md'), goodAlpha);+ const retry = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(retry.status).not.toBe('up_to_date');+ const ackedVersion = await engine.executeRaw<{ chunker_version: string | null }>(+ `SELECT chunker_version FROM sources WHERE id = 'default'`,+ );+ expect(ackedVersion[0]?.chunker_version).toBe(String(CHUNKER_VERSION));+ expect(await engine.getPage('people/alpha')).not.toBeNull();+ });+});++describe('#3583 review: GATE14 — the cheap-rename bookkeeping repair is source-exact', () => {++ test('the bookkeeping repair never crosses sources: an unscoped sync leaves an identical (slug, source_path) row in another source alone', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const bare = { noPull: true, noEmbed: true, noExtract: true } as const;+ // Source "other" naturally carries the SAME legacy pair the default+ // source is about to repair: slug people/beta, source_path+ // people/alpha.md.+ const repoOther = mkRepo({ 'people/beta.md': personMd('Beta Other', 'Beta in the other source.') });+ await engine.executeRaw(+ `INSERT INTO sources (id, name, config, created_at)+ VALUES ('other', 'other', '{}'::jsonb, now()) ON CONFLICT (id) DO NOTHING`,+ );+ const otherSync = await performSync(engine, { repoPath: repoOther, ...bare, sourceId: 'other' });+ expect(otherSync.status).not.toBe('blocked_by_failures');+ const otherSeed = await engine.executeRaw<{ n: number | string }>(+ `SELECT count(*)::int AS n FROM pages WHERE source_id = 'other' AND slug = 'people/beta'`,+ );+ expect(Number(otherSeed[0]?.n)).toBe(1);+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'other' AND slug = 'people/beta'`,+ );++ // The default-source rename runs WITHOUT a sourceId (the bare path).+ // Pin the bare path's dynamic source resolution to the DEFAULT source+ // (tier 5, sources.default — otherwise the sole-non-default-source+ // convenience tier routes the run into 'other'), so the run coheres+ // with updateSlug's own no-opts scope ('default') — the pair the+ // repair UPDATE must match.+ const repoDefault = mkRepo({ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.') });+ await engine.setConfig('sources.default', 'default');+ await performSync(engine, { repoPath: repoDefault, ...bare });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repoDefault, stdio: 'pipe' });+ execSync('git commit -m "rename alpha to beta"', { cwd: repoDefault, stdio: 'pipe' });+ const renameRun = await performSync(engine, { repoPath: repoDefault, ...bare });+ expect(renameRun.status).toBe('synced');++ // The default row is repaired...+ const defaultRow = await engine.executeRaw<{ source_path: string | null }>(+ `SELECT source_path FROM pages WHERE source_id = 'default' AND slug = 'people/beta'`,+ );+ expect(defaultRow[0]?.source_path).toBe('people/beta.md');+ // ...and the OTHER source's bookkeeping is untouched: rewriting it made+ // that source's later fallback reconcile probe the wrong path, find+ // nothing, and advance without its rename sentinel (gate 14).+ const otherRow = await engine.executeRaw<{ source_path: string | null }>(+ `SELECT source_path FROM pages WHERE source_id = 'other' AND slug = 'people/beta'`,+ );+ expect(otherRow[0]?.source_path).toBe('people/alpha.md');+ });++});++describe('#3583 review: FUGU — the carried-rename spare survives a decoy row displacing the DB resolve', () => {+ test('a decoy row sharing the carrying rename\'s from-path cannot strip the path-derived slug from the spare set', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ // The GATE6 sequence — a row carried by ANOTHER rename to a slugless+ // exotic path — plus one DECOY: an unrelated row whose stale+ // bookkeeping names the carrying rename's from-path. A single-slug+ // DB resolve for notes/party.md returns the DECOY's slug and+ // displaces the path-derived notes/party from the spare set; the+ // carried row then loses its protection and is hard-deleted.+ const repo = mkRepo({+ 'notes/party.md': personMd('Party', 'Party content lives here.'),+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),+ });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('notes/party')).not.toBeNull();++ // Stale bookkeeping: the carried row names alpha's path (its+ // candidate-admission ticket for the colliding rename)...+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'people/alpha.md'+ WHERE source_id = 'default' AND slug = 'notes/party'`,+ );+ // ...and the DECOY names the carrying rename's from-path.+ await engine.putPage('people/decoy', {+ type: 'person', title: 'Decoy', compiled_truth: 'stale bookkeeping pointing at party',+ }, { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE pages SET source_path = 'notes/party.md'+ WHERE source_id = 'default' AND slug = 'people/decoy'`,+ );+ await engine.putPage('people/beta', {+ type: 'person', title: 'Beta occupier', compiled_truth: 'occupies the destination slug',+ }, { sourceId: 'default' });++ execSync('git mv notes/party.md "\u{1F389}.md"', { cwd: repo, stdio: 'pipe' });+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });+ execSync('git commit -m "carry party to an exotic path; rename alpha"', { cwd: repo, stdio: 'pipe' });++ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(result.status).toBe('blocked_by_failures');+ // The carried row survives — the spare set holds the path-derived+ // slug REGARDLESS of what the DB resolve returned for the path.+ expect(await engine.getPage('notes/party')).not.toBeNull();+ });+});++describe('#3583 review: GATE24 — the post-purge sweep site converges in one run', () => {+ test('a sentinel whose stale row the purge itself removes clears in the SAME full sync', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ // The one self-heal call site the earlier coverage work left unexercised+ // (blocker 3 named it). The pre-gate probe cannot clear this sentinel:+ // at that point the stale row is still ACTIVE and still carries the old+ // path, so the sentinel is legitimately open. Only the sweep that runs+ // AFTER the purge removed that row can close it — and it has to, or a+ // full sync (the operator's usual reset move) leaves the wedge open for+ // a whole extra run.+ const repo = mkRepo({+ 'people/carol.md': personMd('Carol', 'Carol is a person.'),+ 'people/dana-old.md': personMd('Dana Old', 'Dana Old is a person.'),+ });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(await engine.getPage('people/dana-old')).not.toBeNull();++ // The file leaves git, so the row becomes a genuine purge candidate…+ execSync('git rm -q people/dana-old.md && git commit -m "delete dana-old"', { cwd: repo, stdio: 'pipe' });+ // …and the sentinel names that same old path, so it is NOT orphaned yet.+ await plantOrphanedSentinel();+ expect(await openDanaRows()).toHaveLength(1);++ const full = await performSync(engine, { repoPath: repo, ...SYNC_OPTS, full: true });+ expect(full.status).not.toBe('blocked_by_failures');+ // The purge took the stale row…+ expect(await engine.getPage('people/dana-old')).toBeNull();+ // …and the post-purge sweep closed the wedge in the same run.+ expect(await openDanaRows()).toHaveLength(0);+ expect(await engine.getPage('people/carol')).not.toBeNull();+ });+});++describe('#3583 review: GATE25 — the upgrade path for someone already wedged by #3056', () => {+ test('a PRE-#3479 legacy sentinel self-heals on the first run after upgrading', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const { recordFailures, renameSentinelPath, loadSyncFailures } =+ await import('../src/core/sync-failure-ledger.ts');+ // The review flagged this as unverified and, on the previous head, as an+ // incomplete fix: the self-heal read only the JSON-quoted format, so a+ // ledger row written by the PRE-#3479 code could never be parsed, never+ // be proven orphaned, and never clear — a permanent doctor FAIL for+ // exactly the operators the self-heal was written for. This is the+ // upgrade simulation: the ledger row is byte-for-byte what the old code+ // wrote, and the run is the new code.+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });++ const legacyPath = 'people/dana-old.md';+ recordFailures('default', [{+ path: renameSentinelPath('people/dana.md'),+ // Verbatim pre-#3479 shape: no slug slot, path interpolated raw.+ error: `rename reconcile failed (stale row for ${legacyPath} not removed): injected wedge`,+ }], 'deadbeef');+ const openBefore = loadSyncFailures().filter(+ f => f.path === '<rename:people/dana.md>' && f.state === 'open',+ );+ expect(openBefore).toHaveLength(1);+ // No active row carries that path, so the sentinel is genuinely orphaned.+ const carriers = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pages+ WHERE source_id = 'default' AND source_path = $1 AND deleted_at IS NULL`,+ [legacyPath],+ );+ expect(Number(carriers[0]?.n ?? 0)).toBe(0);++ const quiet = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(quiet.status).toBe('up_to_date');+ expect(loadSyncFailures().filter(+ f => f.path === '<rename:people/dana.md>' && f.state === 'open',+ )).toHaveLength(0);+ });++ test('an AMBIGUOUS legacy sentinel is still left open — fail-closed survives the widening', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const { recordFailures, renameSentinelPath, loadSyncFailures } =+ await import('../src/core/sync-failure-ledger.ts');+ // Same upgrade, but the raw interpolation is undecidable (the delimiter+ // appears twice). Widening the parser must not turn "cannot tell" into a+ // clear — that is the failure mode #3479 introduced JSON encoding for.+ const repo = mkRepo({ 'people/carol.md': personMd('Carol', 'Carol is a person.') });+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ recordFailures('default', [{+ path: renameSentinelPath('people/eve.md'),+ error: 'rename reconcile failed (stale row for a not removed): b.md not removed): injected wedge',+ }], 'deadbeef');++ const quiet = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });+ expect(quiet.status).toBe('up_to_date');+ expect(loadSyncFailures().filter(+ f => f.path === '<rename:people/eve.md>' && f.state === 'open',+ )).toHaveLength(1);+ });});diff --git a/test/synthesize-chunk-budget.test.ts b/test/synthesize-chunk-budget.test.tsindex 0ad160960c..3457287153 100644--- a/test/synthesize-chunk-budget.test.ts+++ b/test/synthesize-chunk-budget.test.ts@@ -1,5 +1,5 @@/**- * computeChunkCharBudget — MODEL_CONTEXT_TOKENS resolution.+ * computeChunkCharBudget — official recipe/model context resolution.** Pins two things:* 1. Current-generation models resolve their real context budget instead@@ -12,6 +12,7 @@*/import { describe, test, expect } from 'bun:test';+import { resolveChatContextTokens } from '../src/core/ai/model-resolver.ts';import { computeChunkCharBudget } from '../src/core/cycle/synthesize.ts';// Mirror the module's constants (deliberately duplicated: a silent change to@@ -23,6 +24,23 @@ const budgetFor = (contextTokens: number) =>Math.floor(contextTokens * HEADROOM_RATIO * CHARS_PER_TOKEN);describe('computeChunkCharBudget — model resolution', () => {+ test('official model resolver exposes recipe context metadata', () => {+ expect(resolveChatContextTokens('deepseek:deepseek-v4-flash')).toBe(1_000_000);+ expect(resolveChatContextTokens('deepseek:deepseek-v4-pro')).toBe(1_000_000);+ expect(resolveChatContextTokens('anthropic:claude-opus-4-7')).toBe(1_000_000);+ expect(resolveChatContextTokens('anthropic:claude-sonnet-4-6')).toBe(200_000);+ // openai recipe declares the gpt-5.6 family window (GA 2026-07-09).+ expect(resolveChatContextTokens('openai:gpt-5')).toBe(1_050_000);+ expect(computeChunkCharBudget('openai:gpt-5', null)).toBe(budgetFor(1_050_000));+ });++ test('DeepSeek v4 models use the 1M context declared by the official recipe', () => {+ for (const model of ['deepseek:deepseek-v4-flash', 'deepseek:deepseek-v4-pro']) {+ expect(computeChunkCharBudget(model, null)).toBe(budgetFor(1_000_000));+ expect(computeChunkCharBudget(model, null)).not.toBe(UNKNOWN_BUDGET);+ }+ });+test('current-generation 1M-context models get their real budget, not the fallback', () => {for (const model of ['claude-sonnet-5', 'claude-fable-5', 'claude-opus-5', 'claude-opus-4-8']) {expect(computeChunkCharBudget(model, null)).toBe(budgetFor(1_000_000));@@ -42,8 +60,14 @@ describe('computeChunkCharBudget — model resolution', () => {});test('unknown models fall back to the conservative 180K budget', () => {- expect(computeChunkCharBudget('openai:gpt-5', null)).toBe(UNKNOWN_BUDGET);expect(computeChunkCharBudget('some-custom-model', null)).toBe(UNKNOWN_BUDGET);+ expect(computeChunkCharBudget('unknown-provider:custom-model', null)).toBe(UNKNOWN_BUDGET);+ });++ test('existing known Anthropic model budgets do not regress', () => {+ expect(computeChunkCharBudget('anthropic:claude-sonnet-5', null)).toBe(budgetFor(1_000_000));+ expect(computeChunkCharBudget('anthropic:claude-sonnet-4-6', null)).toBe(budgetFor(200_000));+ expect(computeChunkCharBudget('anthropic:claude-haiku-4-5-20251001', null)).toBe(budgetFor(200_000));});test('config override wins over the map', () => {diff --git a/test/takes-engine.test.ts b/test/takes-engine.test.tsindex 8bf1bbe8b3..7474d7faff 100644--- a/test/takes-engine.test.ts+++ b/test/takes-engine.test.ts@@ -6,6 +6,7 @@*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { embedStaleTakes } from '../src/core/embed-takes.ts';let engine: PGLiteEngine;let alicePageId: number;@@ -392,3 +393,34 @@ describe('countStaleTakes + listStaleTakes', () => {expect(stale[0]).toHaveProperty('claim');});});++describe('take embedding writes', () => {+ test('persists a take vector and removes it from the stale set', async () => {+ const [take] = await engine.listTakes({ page_id: alicePageId, active: true, limit: 1 });+ expect(take).toBeDefined();+ const dims = Number(await engine.getConfig('embedding_dimensions')) || 1536;++ const updated = await engine.updateTakeEmbeddings([{+ take_id: take!.id,+ embedding: new Float32Array(dims).fill(0.25),+ }]);++ expect(updated).toBe(1);+ expect(await engine.countStaleTakes()).toBeGreaterThanOrEqual(0);+ const stored = await engine.getTakeEmbeddings([take!.id]);+ expect(stored.get(take!.id)?.length).toBe(dims);+ });++ test('embedding pass writes provider vectors and activates vector search', async () => {+ const dims = Number(await engine.getConfig('embedding_dimensions')) || 1536;+ const result = await embedStaleTakes(engine, {+ batchSize: 2,+ embedFn: async (texts) => texts.map(() => new Float32Array(dims).fill(0.5)),+ });++ expect(result.failures).toBe(0);+ expect(result.embedded).toBeGreaterThan(0);+ const hits = await engine.searchTakesVector(new Float32Array(dims).fill(0.5), { limit: 10 });+ expect(hits.length).toBeGreaterThan(0);+ });+});diff --git a/test/think-pipeline.serial.test.ts b/test/think-pipeline.serial.test.tsindex 7e28d25a1e..4444aca39f 100644--- a/test/think-pipeline.serial.test.ts+++ b/test/think-pipeline.serial.test.ts@@ -519,6 +519,19 @@ describe('runThink — #1698 explicit-model hard error', () => {});describe('runThink + persistSynthesis — #1698 never persist empty', () => {+ test('#3734: question embedder is called for vector takes retrieval', async () => {+ let embeddedQuestion: string | undefined;+ await runThink(engine, {+ question: 'Which claims matter?',+ embedQuestion: async (question) => {+ embeddedQuestion = question;+ return new Float32Array(4).fill(0.25);+ },+ stubResponse: { answer: 'has content', citations: [], gaps: [] },+ });+ expect(embeddedQuestion).toBe('Which claims matter?');+ });+test('empty-but-valid-JSON answer → synthesisOk false → persist-skip signal', async () => {const result = await runThink(engine, {question: 'empty answer test',diff --git a/test/think-trajectory-injection.test.ts b/test/think-trajectory-injection.test.tsindex 9a29547ac3..4df5d2afa3 100644--- a/test/think-trajectory-injection.test.ts+++ b/test/think-trajectory-injection.test.ts@@ -87,6 +87,7 @@ describe('runThink — trajectory injection happy path', () => {test('temporal intent → trajectory block appears in user message', async () => {const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'When did Marco last switch jobs?',client,});@@ -99,6 +100,7 @@ describe('runThink — trajectory injection happy path', () => {test('"other" intent → no trajectory block', async () => {const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'Summarize the deal pipeline',client,});@@ -112,6 +114,7 @@ describe('runThink — kill switches', () => {test('withTrajectory: false bypasses injection even for temporal intent', async () => {const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'When did Marco last switch jobs?',client,withTrajectory: false,@@ -126,6 +129,7 @@ describe('runThink — kill switches', () => {);const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'When did Marco last switch jobs?',client,});@@ -145,6 +149,7 @@ describe('runThink — empty trajectory short-circuits', () => {});const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'When did empty last visit?',client,});@@ -168,6 +173,7 @@ describe('runThink — graceful degradation', () => {try {const { client, captured } = captureClient();const result = await runThink(engine, {+ remote: false,question: 'When did Marco last switch jobs?',client,});@@ -189,6 +195,7 @@ describe('runThink — trajectory points count exposed via warnings', () => {test('successful injection records TRAJECTORY_INJECTED_*_POINTS warning', async () => {const { client } = captureClient();const result = await runThink(engine, {+ remote: false,question: 'When did Marco last switch jobs?',client,});@@ -218,6 +225,7 @@ describe('runThink — calibration-mode trajectory placement', () => {test('default mode: trajectory block lands AFTER retrieved blocks, BEFORE instruction', async () => {const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'When did Marco last switch jobs?',client,// No withCalibration → default-mode prompt assembly.@@ -266,6 +274,7 @@ describe('runThink — calibration-mode trajectory placement', () => {const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'When did Marco last switch jobs?',client,withCalibration: true,@@ -303,6 +312,7 @@ describe('runThink — calibration-mode trajectory placement', () => {// shape is unchanged from the v0.36 baseline.const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'Summarize the deal pipeline',client,withCalibration: true,@@ -351,6 +361,7 @@ describe('runThink — resolution_source != fallback_slugify gate', () => {const { client, captured } = captureClient();await runThink(engine, {+ remote: false,question: 'When did I last meet zelda?',client,});diff --git a/test/track1-save-time-entity-resolution.test.ts b/test/track1-save-time-entity-resolution.test.tsnew file mode 100644index 0000000000..087d8140b1--- /dev/null+++ b/test/track1-save-time-entity-resolution.test.ts@@ -0,0 +1,152 @@+/**+ * Save-time entity resolution — hook contract only.+ *+ * The read-time cascade (including alias_exact) already ships on master+ * via #3730. This file covers the write-path caller that the original+ * #4052 PR added, rewritten onto that shipped vocabulary. It does not+ * re-test resolve.ts.+ */+import { describe, expect, spyOn, test } from 'bun:test';+import { BudgetExhausted } from '../src/core/budget/budget-tracker.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { ExtractedFact } from '../src/core/facts/extract.ts';+import type { ResolveResult } from '../src/core/entities/resolve.ts';+import * as resolve from '../src/core/entities/resolve.ts';+import {+ formatSaveTimeResolutionCounts,+ resolveExtractedEntitiesForSave,+} from '../src/core/entities/resolve-on-save.ts';++function fact(entity_slug: string | null, text = 'a fact'): ExtractedFact {+ return {+ fact: text,+ kind: 'event',+ entity_slug,+ source: 'test',+ source_session: null,+ confidence: 1,+ notability: 'medium',+ };+}++function stubResolve(+ impl: (raw: string) => Promise<ResolveResult | null>,+): ReturnType<typeof spyOn> {+ return spyOn(resolve, 'resolveEntitySlugWithSource').mockImplementation(+ async (_engine, _sourceId, raw) => impl(raw),+ );+}++describe('save-time resolution vocabulary', () => {+ test('logs shipped alias_exact, never alias_match or alias_redirect', () => {+ expect(formatSaveTimeResolutionCounts({+ alias_exact: 2,+ fallback_slugify: 1,+ })).toBe('{"alias_exact":2,"fallback_slugify":1}');+ const rendered = formatSaveTimeResolutionCounts({+ exact_page: 1,+ alias_exact: 1,+ fuzzy_match: 1,+ fallback_slugify: 1,+ });+ expect(rendered).toContain('alias_exact');+ expect(rendered).not.toContain('alias_match');+ expect(rendered).not.toContain('alias_redirect');+ });+});++describe('resolveExtractedEntitiesForSave', () => {+ const engine = {} as BrainEngine;++ test('rewrites slugs, preserves null, and counts fallback_slugify', async () => {+ const spy = stubResolve(async (raw) => {+ if (raw === 'Brian') {+ return { slug: 'people/brian-example', source: 'alias_exact' };+ }+ if (raw === 'Unlisted Person') {+ return { slug: 'unlisted-person', source: 'fallback_slugify' };+ }+ return { slug: raw, source: 'fallback_slugify' };+ });+ try {+ const facts = [+ fact('Brian'),+ fact('Unlisted Person'),+ fact(null),+ ];+ const stats = await resolveExtractedEntitiesForSave(engine, 'default', facts);+ expect(facts.map((row) => row.entity_slug)).toEqual([+ 'people/brian-example',+ 'unlisted-person',+ null,+ ]);+ expect(stats.counts).toEqual({+ alias_exact: 1,+ fallback_slugify: 1,+ });+ expect(stats.fallback_slugify_count).toBe(1);+ expect(stats.resolution_errors).toBe(0);+ expect(spy).toHaveBeenCalledTimes(2);+ } finally {+ spy.mockRestore();+ }+ });++ test('best-effort resolver failure keeps the raw value', async () => {+ const spy = stubResolve(async (raw) => {+ if (raw === 'Unlisted Person') throw new Error('resolver unavailable');+ return { slug: 'people/brian-example', source: 'alias_exact' };+ });+ const errors: Array<{ raw: string; message: string }> = [];+ try {+ const facts = [fact('Brian'), fact('Unlisted Person')];+ const stats = await resolveExtractedEntitiesForSave(+ engine,+ 'default',+ facts,+ (raw, message) => errors.push({ raw, message }),+ );+ expect(facts.map((row) => row.entity_slug)).toEqual([+ 'people/brian-example',+ 'Unlisted Person',+ ]);+ expect(stats.resolution_errors).toBe(1);+ expect(stats.fallback_slugify_count).toBe(0);+ expect(errors).toEqual([+ { raw: 'Unlisted Person', message: 'resolver unavailable' },+ ]);+ } finally {+ spy.mockRestore();+ }+ });++ test('BudgetExhausted from resolution propagates and is not a resolution error', async () => {+ const spy = stubResolve(async () => {+ throw new BudgetExhausted('resolver budget exhausted', {+ reason: 'cost',+ spent: 2,+ cap: 1,+ });+ });+ try {+ const facts = [fact('Brian')];+ await expect(resolveExtractedEntitiesForSave(engine, 'default', facts))+ .rejects.toBeInstanceOf(BudgetExhausted);+ expect(facts[0].entity_slug).toBe('Brian');+ } finally {+ spy.mockRestore();+ }+ });++ test('abort from resolution propagates', async () => {+ const spy = stubResolve(async () => {+ throw Object.assign(new Error('aborted'), { name: 'AbortError' });+ });+ try {+ await expect(resolveExtractedEntitiesForSave(engine, 'default', [fact('Brian')]))+ .rejects.toMatchObject({ name: 'AbortError' });+ } finally {+ spy.mockRestore();+ }+ });+});