Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.40.3.0 feat: contextual retrieval + cache invalidation gate + 4 deferred-item closures (#1323)
Garry Tan43608c1856a9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7368841c71..fdf7bc26a2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,165 @@All notable changes to GBrain will be documented in this file.+## [0.40.3.0] - 2026-05-22++**Your search now understands what each chunk is about — AND its cached results expire the moment a page changes.**++Two big things changed in this release. The first is the contextual retrieval cathedral that was originally in v0.40.3.0: every chunk gets the page title wrapped around it before going into the search index, so a sentence about "raised $3M" now remembers it came from "Acme Corp Series A" instead of competing with every other fundraise mention in your brain. Power users on tokenmax mode get the premium tier — a fresh per-chunk summary from Claude Haiku — which Anthropic's published research showed reduces retrieval failure rate 35-49% on document-heavy benchmarks.++The second thing is cache invalidation that's actually correct. When the agent runs the same search twice in a row, the second call returns from cache in microseconds instead of running keyword search + vector search + reranking again. But before this release, the cache had no way to know if a page had been edited between the two calls — it just trusted itself for an hour (the TTL). So if you edited a page and then searched, the agent silently served the OLD version until the TTL expired. This release adds a two-layer gate: a cheap corpus-wide "has anything been written?" check (one indexed integer compare per cache hit) AND a per-result "are these specific pages still at their stored generation?" check. Either layer firing invalidates the row. Pre-upgrade cache rows still serve via a backward-compat path until they age out naturally — no cache stampede on upgrade.++Plus four CLI improvements that close gaps in the v0.40.3 deferral list:+- `gbrain mounts enable/disable <id>` toggles a mounted brain without removing it.+- `gbrain mounts trust-frontmatter <id>` lets a mounted team brain's per-page frontmatter override the source's default contextual retrieval mode. Off by default — mounts opt in explicitly.+- `gbrain sources set-cr-mode <id> <none|title|per_chunk_synopsis>` writes per-source overrides. Missing source ID fails loudly with a paste-ready `gbrain sources list` hint.+- `gbrain config set search.mode tokenmax` now shows a banner explaining what changed (and the per-chunk Haiku backfill cost) and offers to submit `gbrain reindex --markdown` as a Minion job if a worker is alive. Non-TTY callers get a paste-ready hint to stderr instead of a silent stall.++And one generic refactor: doctor's `Remediation` type lifted into its own `RemediationStep` module so other doctor checks can emit structured fix steps. The integrity and sync_failures checks now emit RemediationSteps too — `gbrain doctor --remediation-plan` and `--remediate` walk them automatically.++### How to turn it on++`gbrain upgrade` does the whole thing automatically. Post-upgrade prompt fires, explains the re-embed cost in plain text, gives you a 10-second window to abort, and re-embeds every markdown page through the new title-tier wrapper.++To opt up to per-chunk Haiku synopsis:+```bash+gbrain config set search.mode tokenmax+# (banner fires; on TTY + active worker it offers to submit reindex as a Minion job)+gbrain reindex --markdown # or pick that up after the prompt+```++To opt out entirely if quality regresses (soft kill switch — wrapped vectors stay in DB but new embeds skip the wrapper):+```bash+gbrain config set search.contextual_retrieval_disabled true+```++For mounted team brains:+```bash+gbrain mounts trust-frontmatter team-brain-id # opt this mount into frontmatter overrides+gbrain mounts disable team-brain-id # toggle off without removing+```++### Tier ladder — what each search mode gets++| Mode | Wrapper | Per-query cost | One-time backfill |+|------|---------|----------------|-------------------|+| `conservative` | none | $0 | $0 |+| `balanced` (default) | title-only prefix | $0 (string concat) | $0 (current text-embedding-3 calls reused) |+| `tokenmax` | per-chunk Haiku synopsis | $0 (one-time only) | ~$1-5 per 10K pages, ~17h at Anthropic's default Haiku rate limit |++The wrapper is asymmetric: chunks get the context prefix when going into the embed call, but queries stay clean. Voyage + ZeroEntropy distinguish `inputType: 'query'` from `'document'` natively, so this works correctly; OpenAI symmetric users still benefit from document-side orientation.++### What you'd see in a concrete example++A page titled "Acme Corp Series A" with a chunk that reads `raised $3M from Fund A in 2024`:++| Stored in DB (`content_chunks.chunk_text`) | What the embedder saw |+|--------------------------------------------|----------------------|+| `raised $3M from Fund A in 2024` (canonical, unchanged) | `<context>Acme Corp Series A\n</context>\nraised $3M from Fund A in 2024` |++Search snippets, full-text search, the reranker, and debug output all read the canonical chunk_text. Only the embedding vector reflects the wrapped form. This separation is the load-bearing invariant of the wave (D20-T1).++### Cache invalidation — how the two-layer gate works++```+WRITE PATH (any pages mutation)+ INSERT or UPDATE pages → trigger fires+ INSERT → row gets generation = MAX(generation) + 1+ UPDATE → if (body/title/type/page_kind/content_hash/etc IS DISTINCT FROM)+ NEW.generation = OLD.generation + 1++STORE PATH (query-cache.ts:store)+ SELECT id, generation FROM pages WHERE id = ANY($result_page_ids)+ + SELECT MAX(generation) FROM pages+ → stamp BOTH per-page snapshot AND corpus bookmark on the cache row++LOOKUP PATH (query-cache.ts:lookup) — TWO-LAYER+ Layer 1 (cheap): (SELECT MAX(generation) FROM pages) <= stored_bookmark+ O(log N) via pages_generation_idx+ Layer 2 (per-page): jsonb_each + LEFT JOIN pages+ page deleted → invalidate+ page bumped → invalidate+ pre-v0.40.3.0 rows with empty {} snapshot → vacuously valid+```++### Things to watch++- **Migration v90 + v91**. v90 (renumbered from v0.40.3.0's original v81 on master merge) adds the 5 contextual retrieval columns. v91 adds `pages.generation BIGINT`, `query_cache.max_generation_at_store BIGINT`, the trigger, and the `pages_generation_idx` btree. All NULL-tolerant or have safe defaults; existing rows keep working unchanged.+- **KNOBS_HASH_VERSION 3 → 5**. Bumped past 4 (claimed by salem's v0.40.4 graph signals work) to keep cache-row shape collisions impossible across sibling waves. Existing v=3 cache rows become unreachable on first re-query after upgrade (one-time miss spike).+- **Chunker version 2 → 3** signals the post-upgrade reembed sweep that every markdown page needs to be re-embedded through the new wrapper path. Chunk boundaries themselves are unchanged from v2.+- **Race fix folded in (D24)**: the long-standing v0.35.x NULL→non-NULL upsert race between concurrent embed workers is finally closed. Two writers racing on the same chunk now let the fresher `embedded_at` win instead of last-writer-wins.++### What we caught and fixed before merging++The wave went through two rounds of /plan-eng-review and one /codex outside-voice review on top of the original v0.40.3 codex pass. The fresh codex round caught EIGHT genuine bugs in the deltas, all absorbed before code landed:++- **Trigger allow-list too narrow.** Original plan watched 6 columns (body/frontmatter/compiled_truth/timeline/deleted_at/contextual_retrieval_mode). Codex pointed out that title, type, page_kind, and corpus_generation are all user-visible — silently NOT bumping on those would serve stale search results for title edits. Widened to 10 columns including content_hash as the canonical "content changed" signal.+- **BEFORE UPDATE missed INSERTs.** The original trigger fired BEFORE UPDATE only. The v0.38 ingest_capture handler uses `INSERT ... ON CONFLICT DO UPDATE`, so fresh slugs took the INSERT path and silently never bumped MAX(generation). Cache rows stored before a new page existed would never invalidate. Fixed: trigger now fires BEFORE INSERT OR UPDATE, and the INSERT branch sets generation = COALESCE(MAX, 0) + 1 explicitly.+- **Migration version collision risk.** Master shipped v82-v88 across v0.38/v0.39 while v0.40.3.0 was off-master. Our v81 (contextual_retrieval_columns) collided with master's. Plan: rename to v89. Codex caught that `garrytan/v0.40.2.0-trajectory-routing` already reserved v89 for `facts_event_type_column`. Re-renumbered to v90; new trigger work at v91.+- **KNOBS_HASH_VERSION collision with salem.** Both our wave and salem's v0.40.4 graph-signals wave wanted v=4. Per D8 we bumped to v=5 so cache rows from either wave can't accidentally serve the other.+- **D3 regression test too weak.** Original plan asserted ingest_capture bumps generation on existing slugs only. Codex pointed out the INSERT path (codex #4) ALSO needs explicit coverage. T11 test now exercises both paths + idempotent re-capture.+- **v0.38 provenance columns.** ingested_via/ingested_at/source_uri/source_kind are returned by ingest_capture but not written to pages. If a future master change wires them into putPage, the trigger allow-list would silently miss content edits via those columns. Verified at implementation time; allow-list left at the current 10 columns.+- **Index shape wrong.** Original plan said `(generation DESC)`. Codex pointed out plain `(generation)` btree is backward-scannable for MAX. Simplified.+- **One missing master commit.** Plan said 5 commits; master was actually 6 commits ahead via v0.39.2.0 autopilot/cycle-lock wave. Adjusted Phase 1 expectations.++### Itemized changes++- **Migration v90** (`src/core/migrate.ts`): renamed from v0.40.3.0's original v81 to clear master's v82-v88 reservations. 5 additive columns wiring the three-tier wrapper ladder.+- **Migration v91** (NEW): `pages.generation BIGINT` + `query_cache.max_generation_at_store BIGINT` + `bump_page_generation_fn` trigger (BEFORE INSERT OR UPDATE with 10-column content allow-list) + `pages_generation_idx` btree via CONCURRENTLY on Postgres / plain CREATE INDEX on PGLite. `transaction: false` matches the v14 pages_updated_at_index pattern.+- **Schema mirrors** (`src/schema.sql`, `src/core/pglite-schema.ts`): pages + sources + trigger DDL + index updated.+- **Bootstrap probes** (`src/core/{pglite,postgres}-engine.ts`): forward-reference checks added for all 5 v90 columns + pages.generation per the established v0.22.6.1 pattern. `test/schema-bootstrap-coverage.test.ts` REQUIRED_BOOTSTRAP_COVERAGE extended.+- **New pure modules** (`src/core/`): `remediation-step.ts` (canonical RemediationStep type + makeRemediationStep factory + canonical-JSON idempotency key per codex D12 Bug 2), `search/query-cache-gate.ts` (two-layer cache gate helpers + SQL fragment), `search/mode-switch-ux.ts` (transition summarizer + worker probe + Minion submission).+- **query-cache.ts** lookup() / store() rewrites: two-layer gate embedded in the lookup SQL; store() captures the page_generations snapshot + max_generation_at_store bookmark via the new buildPageGenerationsSnapshot helper. KNOBS_HASH_VERSION 4 → 5 (per D8 sequencing behind salem's pending v=4).+- **config.ts hook**: `gbrain config set search.mode <X>` captures the OLD mode, calls setConfig, then invokes runModeSwitchUx with TTY + non-TTY + GBRAIN_NO_MODE_SWITCH_UX awareness. Honors `--yes` for automation. Best-effort: UX failures never break a config write that already persisted.+- **mounts.ts**: 4 new verbs (enable / disable / trust-frontmatter / untrust-frontmatter) sharing the runSetMountFlag helper. MountEntry interface extended with `trust_frontmatter_overrides?: boolean` (default false; mounts opt in explicitly). loadMounts projection threads the field through. GBRAIN_MOUNTS_PATH env override added to both `mounts.ts` and `brain-registry.ts` getMountsPath() so tests don't fight libuv's cached homedir().+- **sources.ts**: `set-cr-mode <id> <mode>` verb with isCRMode validation, "unset"/"default"/"" as the clear path, missing-source loud rejection with paste-ready `gbrain sources list` hint (closes the idempotent-pebble Failure Modes critical gap).+- **brain-score-recommendations.ts**: Remediation lifted into the new src/core/remediation-step.ts module. Re-exports + back-compat alias preserved so existing callers keep compiling.+- **doctor.ts**: Check.remediation field typed to RemediationStep[]. integrity + sync_failures checks emit RemediationSteps via makeRemediationStep when the warn fires. sync-skip-failed deliberately NOT emitted per codex D12 Bug 3 (auto-skip hides data loss).+- **jobs.ts**: 3 new Minion handlers registered (lint-fix, integrity-auto, sync-retry-failed). Thin wrappers around already-shipping CLI commands; NOT in PROTECTED_JOB_NAMES (idempotent, no shell exec, MCP-safe).+- **import-file.ts**: wraps chunks at embed time (D20-T1 separation), stamps the two CR-state columns alongside putPage.+- **Race fix** (D24): `postgres-engine.ts` + `pglite-engine.ts` upsertChunks use `embedded_at` to break NULL→non-NULL ties. Closes the long-standing v0.35.x TODO.+- **Mode bundle field** (`src/core/search/mode.ts`): `contextual_retrieval: CRMode` per tier + `contextual_retrieval_disabled` kill switch.++### For contributors++7 new test files (1093 LOC) + 5 extended test files:+- `test/query-cache-gate.test.ts` (15 cases: pure validator branches + PGLite-backed snapshot builder + SQL shape regression).+- `test/mode-switch-ux.test.ts` (18 cases: 5-cell transition matrix + 3-branch worker probe + 6-case content-stable idempotency-key invariance).+- `test/mounts-cli.test.ts` (5 new cases: enable/disable cycle, trust/untrust cycle, missing-mount rejection, host rejection, idempotent enable).+- `test/sources-set-cr-mode.test.ts` (10 cases: happy path × 3 modes, unset path × 2, invalid mode rejection, missing source rejection, missing args, round-trip preserves other fields).+- `test/remediation-step.test.ts` (17 cases: canonical-JSON determinism, idempotency_key shape + invariance, makeRemediationStep factory, back-compat alias).+- `test/e2e/cache-gate-pglite.test.ts` (6 cases: store→HIT, content UPDATE→MISS, INSERT new page→HIT codex #4 case, legacy row→HIT IRON-RULE, soft-delete→MISS, multi-page partial bump→MISS).+- `test/e2e/capture-generation-regression.test.ts` (3 cases: INSERT path bumps MAX, UPDATE path bumps generation, idempotent re-capture does NOT bump).++## To take advantage of v0.40.3.0++`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor`+warns about a partial migration:++1. **Run the orchestrator manually:**+ ```bash+ gbrain apply-migrations --yes+ ```+2. **Your agent reads `skills/migrations/v0.40.3.0.md` the next time you interact with it.**+ The migration is mostly mechanical (schema + bootstrap probes); no agent-side action required beyond the optional `--mode tokenmax` opt-in.+3. **Verify the outcome:**+ ```bash+ gbrain doctor+ gbrain search "your favorite query" # should hit cache on the 2nd run+ ```+4. **If you want to opt up to tokenmax (per-chunk Haiku synopsis):**+ ```bash+ gbrain config set search.mode tokenmax+ # Mode-switch banner fires with cost preview + offers reindex submission.+ ```+5. **If any step fails or the numbers look wrong,** please file an issue:+ https://github.com/garrytan/gbrain/issues with:+ - output of `gbrain doctor`+ - contents of `~/.gbrain/upgrade-errors.jsonl` if it exists+ - which step broke++ This feedback loop is how the gbrain maintainers find fragile upgrade paths. Thank you.+## [0.40.2.0] - 2026-05-22**gbrain now uses the typed-claim timeline it's been quietly building to ground answers about what changed and when.** Ask `gbrain think` "when did Marco last switch jobs" or "what was the ARR in March" and the answer comes back rooted in a real chronological timeline of the metric facts your brain already extracted via the `extract_facts` cycle phase. The feature is on by default; flip `think.trajectory_enabled=false` to opt out.@@ -74,7 +233,6 @@ The same plumbing lands in the LongMemEval benchmark, with a methodology changePlan file at `~/.claude/plans/system-instruction-you-are-working-crystalline-owl.md` carries the full design rationale, the CEO/Eng/Codex review history (3 review passes, all CLEARED), the measurement plan (3 seeds per condition + paired-bootstrap CI), and the hand-verification gate list. Codex flagged 18 findings during outside-voice review; 6 load-bearing ones folded as design decisions (alias-map wording, `resolveEntitySlugWithSource` resolution_source signal, prompt-placement preserving both calibration AND default ordering, INJECTION_PATTERNS extension for `</trajectory>`, 5s findTrajectory timeout + 10s extractor timeout, doctor check deferred to v0.40.1+, real-LLM spot-check added, success metric broadened). The benchmark methodology contamination was the load-bearing decision — accepted with explicit CHANGELOG + JSON-envelope disclosure.-## [0.40.1.0] - 2026-05-22**Eval infrastructure that catches retrieval regressions before merge and proves answer-quality wins after ship.**diff --git a/CLAUDE.md b/CLAUDE.mdindex 0d94cbc61d..bda2071b0c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -561,6 +561,18 @@ Key commands added for Minions (job queue):- `gbrain jobs smoke [--sigkill-rescue]` — health smoke test. `--sigkill-rescue` is the v0.13.1 regression guard for #219: simulates a killed worker and asserts the stalled job is requeued instead of dead-lettered on first stall.- `gbrain jobs work [--queue Q] [--concurrency N]` — start worker daemon (Postgres only)+Key commands added in v0.40.3.0 (contextual retrieval + cache gate + 4 CLI verbs):+- `gbrain mounts enable <id>` / `disable <id>` — toggle a mount without removing it.+- `gbrain mounts trust-frontmatter <id>` / `untrust-frontmatter <id>` — let a mounted brain's per-page `contextual_retrieval_mode` frontmatter override the source default. Off by default for mounts (security posture per D15); host source is always trusted.+- `gbrain sources set-cr-mode <id> <none|title|per_chunk_synopsis>` — per-source contextual retrieval mode override. Pass `unset` or `default` to clear (NULL falls through to global). Missing source ID fails loudly with paste-ready `gbrain sources list` hint.+- `gbrain config set search.mode tokenmax` triggers a mode-switch banner explaining the per-chunk Haiku synopsis backfill cost, and (on TTY + active Minion worker) offers to submit `gbrain reindex --markdown` as a Minion job. Non-TTY callers get a paste-ready hint to stderr instead of a silent stall. Suppress with `GBRAIN_NO_MODE_SWITCH_UX=1` for CI fixtures.+- Cache invalidation gate is now two-layer (per D11 codex finding): Layer 1 cheap MAX(generation) bookmark via `pages_generation_idx`, Layer 2 per-page snapshot via jsonb_each + LEFT JOIN pages. Pre-v0.40.3.0 cache rows with empty `{}` snapshot are vacuously valid (IRON-RULE backward compat).+- KNOBS_HASH_VERSION bumped 3 → 5 (skipped past 4 reserved by salem's v0.40.4 graph-signals work). One-time cache-row invalidation on upgrade; refills within TTL.+- Three new Minion handlers wired into RemediationStep consumer pattern: `lint-fix`, `integrity-auto`, `sync-retry-failed`. Thin wrappers around already-shipping CLI commands; NOT in PROTECTED_JOB_NAMES (idempotent, no shell exec, MCP-safe). `sync-skip-failed` deliberately NOT in this set per codex D12 Bug 3.+- `src/core/remediation-step.ts` (NEW canonical module) exports RemediationStep type + makeRemediationStep factory + canonical-JSON idempotencyKey() per codex D12 Bug 2. Future doctor checks emit RemediationSteps via the factory instead of hand-rolling the shape.+- `src/core/search/query-cache-gate.ts` (NEW) exports `buildPageGenerationsSnapshot(engine, pageIds)` + `CACHE_GATE_WHERE_CLAUSE` SQL fragment + `validateCacheRowAgainstPages()` pure validator.+- `src/core/search/mode-switch-ux.ts` (NEW) exports `summarizeTransition()` 5-cell matrix + `probeWorkerAvailable()` worker liveness proxy via minion_jobs activity + `buildReindexIdempotencyKey()` content-stable key + `runModeSwitchUx()` orchestrator.+Key commands added in v0.36.4.0 (brain-health-100 wave):- `gbrain doctor --remediation-plan [--target-score N] [--json]` — preview the dependency-ordered plan that would drive the brain to target. JSON envelope is stable: each `Remediation` carries `id`, `idempotency_key` (content-hash for cron-safe retries), `severity`, `est_seconds`, `est_usd_cost`, and `depends_on` (referencing other ids). Empty `recommendations` array when the brain is already at target.- `gbrain doctor --remediate [--yes] [--target-score N] [--max-usd N]` — actually submit the plan. Walks dependency order, submits one Minion job per step, re-checks score between steps, refuses to spend past `--max-usd` (defaults: target=90, max-usd=infinite — but cron callers should always pass `--max-usd`). Bails when target exceeds `maxReachableScore()` for the brain (empty / under-configured brains) with a clear list of what's missing.diff --git a/VERSION b/VERSIONindex 059d890d9f..b4fa9dce83 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.40.2.0+0.40.3.0diff --git a/llms-full.txt b/llms-full.txtindex aeb49681a4..9a50c53812 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -703,6 +703,18 @@ Key commands added for Minions (job queue):- `gbrain jobs smoke [--sigkill-rescue]` — health smoke test. `--sigkill-rescue` is the v0.13.1 regression guard for #219: simulates a killed worker and asserts the stalled job is requeued instead of dead-lettered on first stall.- `gbrain jobs work [--queue Q] [--concurrency N]` — start worker daemon (Postgres only)+Key commands added in v0.40.3.0 (contextual retrieval + cache gate + 4 CLI verbs):+- `gbrain mounts enable <id>` / `disable <id>` — toggle a mount without removing it.+- `gbrain mounts trust-frontmatter <id>` / `untrust-frontmatter <id>` — let a mounted brain's per-page `contextual_retrieval_mode` frontmatter override the source default. Off by default for mounts (security posture per D15); host source is always trusted.+- `gbrain sources set-cr-mode <id> <none|title|per_chunk_synopsis>` — per-source contextual retrieval mode override. Pass `unset` or `default` to clear (NULL falls through to global). Missing source ID fails loudly with paste-ready `gbrain sources list` hint.+- `gbrain config set search.mode tokenmax` triggers a mode-switch banner explaining the per-chunk Haiku synopsis backfill cost, and (on TTY + active Minion worker) offers to submit `gbrain reindex --markdown` as a Minion job. Non-TTY callers get a paste-ready hint to stderr instead of a silent stall. Suppress with `GBRAIN_NO_MODE_SWITCH_UX=1` for CI fixtures.+- Cache invalidation gate is now two-layer (per D11 codex finding): Layer 1 cheap MAX(generation) bookmark via `pages_generation_idx`, Layer 2 per-page snapshot via jsonb_each + LEFT JOIN pages. Pre-v0.40.3.0 cache rows with empty `{}` snapshot are vacuously valid (IRON-RULE backward compat).+- KNOBS_HASH_VERSION bumped 3 → 5 (skipped past 4 reserved by salem's v0.40.4 graph-signals work). One-time cache-row invalidation on upgrade; refills within TTL.+- Three new Minion handlers wired into RemediationStep consumer pattern: `lint-fix`, `integrity-auto`, `sync-retry-failed`. Thin wrappers around already-shipping CLI commands; NOT in PROTECTED_JOB_NAMES (idempotent, no shell exec, MCP-safe). `sync-skip-failed` deliberately NOT in this set per codex D12 Bug 3.+- `src/core/remediation-step.ts` (NEW canonical module) exports RemediationStep type + makeRemediationStep factory + canonical-JSON idempotencyKey() per codex D12 Bug 2. Future doctor checks emit RemediationSteps via the factory instead of hand-rolling the shape.+- `src/core/search/query-cache-gate.ts` (NEW) exports `buildPageGenerationsSnapshot(engine, pageIds)` + `CACHE_GATE_WHERE_CLAUSE` SQL fragment + `validateCacheRowAgainstPages()` pure validator.+- `src/core/search/mode-switch-ux.ts` (NEW) exports `summarizeTransition()` 5-cell matrix + `probeWorkerAvailable()` worker liveness proxy via minion_jobs activity + `buildReindexIdempotencyKey()` content-stable key + `runModeSwitchUx()` orchestrator.+Key commands added in v0.36.4.0 (brain-health-100 wave):- `gbrain doctor --remediation-plan [--target-score N] [--json]` — preview the dependency-ordered plan that would drive the brain to target. JSON envelope is stable: each `Remediation` carries `id`, `idempotency_key` (content-hash for cron-safe retries), `severity`, `est_seconds`, `est_usd_cost`, and `depends_on` (referencing other ids). Empty `recommendations` array when the brain is already at target.- `gbrain doctor --remediate [--yes] [--target-score N] [--max-usd N]` — actually submit the plan. Walks dependency order, submits one Minion job per step, re-checks score between steps, refuses to spend past `--max-usd` (defaults: target=90, max-usd=infinite — but cron callers should always pass `--max-usd`). Bails when target exceeds `maxReachableScore()` for the brain (empty / under-configured brains) with a clear list of what's missing.diff --git a/package.json b/package.jsonindex 727ee2177a..f90879becc 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.40.2.0",+ "version": "0.40.3.0","description": "Postgres-native personal knowledge brain with hybrid RAG search","type": "module","main": "src/core/index.ts",diff --git a/skills/migrations/v0.40.3.0.md b/skills/migrations/v0.40.3.0.mdnew file mode 100644index 0000000000..cc9be2f065--- /dev/null+++ b/skills/migrations/v0.40.3.0.md@@ -0,0 +1,154 @@+---+name: v0.40.3.0-migration+description: Post-upgrade actions for v0.40.3.0 — contextual retrieval + cache invalidation gate + mode-switch UX + mount/source verbs + RemediationStep refactor+feature_pitch: |+ Two big things shipped: (1) the contextual retrieval cathedral —+ every chunk gets its page title prefixed before embedding, so search+ understands what each chunk is about. Power users on tokenmax get a+ per-chunk Haiku synopsis (35-49% reduction in retrieval failure rate+ per Anthropic's published research). (2) Cache invalidation that's+ actually correct via a two-layer gate (corpus-state bookmark ++ per-page snapshot), so search results expire the moment a page+ changes instead of waiting for the TTL.+ Plus four CLI improvements: mounts enable/disable/trust-frontmatter,+ sources set-cr-mode, config-set mode-switch UX, and a generic+ RemediationStep refactor.+---++# v0.40.3.0 Migration++## What `gbrain upgrade` did automatically++1. **Merged master** (6 commits: v0.38 ingestion cathedral, v0.38.1 agents,+ v0.38.2 doctor, v0.39 brainstorm cathedral, v0.39.1 schema packs,+ v0.39.2 autopilot/cycle-lock).+2. **Renumbered v81 → v90** to clear master's v82-v88 reservations ++ v0.40.2.0-trajectory-routing's v89 reservation. Same 5 contextual+ retrieval columns: `pages.contextual_retrieval_mode`,+ `pages.corpus_generation`, `sources.contextual_retrieval_mode`,+ `sources.trust_frontmatter_overrides`, `query_cache.page_generations`.+3. **Added migration v91** with `pages.generation BIGINT`,+ `query_cache.max_generation_at_store BIGINT`, the+ `bump_page_generation_fn` trigger (BEFORE INSERT OR UPDATE on a+ 10-column content allow-list per codex D6), and the+ `pages_generation_idx` btree (CONCURRENTLY on Postgres, plain+ CREATE INDEX on PGLite).+4. **Bumped chunker version 2 → 3** signaling the post-upgrade reembed+ sweep that every markdown page needs re-embedding through the new+ wrapper path.+5. **Bumped KNOBS_HASH_VERSION 3 → 5** (skipping past 4 reserved by+ salem's v0.40.4 graph-signals work).+6. **Showed the post-upgrade cost prompt** for the title-tier reembed.++## What you should verify++Run:++```bash+gbrain doctor+```++Expected: `status: 'healthy'`, `contextual_retrieval_coverage` check+passes, no migration-version warnings.++If anything looks wrong:++```bash+cat ~/.gbrain/upgrade-errors.jsonl # if it exists+gbrain apply-migrations --yes # re-runs the orchestrator+```++## Optional: opt up to per-chunk Haiku synopsis (tokenmax mode)++The premium tier costs ~$1-5 per 10K pages in Anthropic Haiku calls,+plus ~17 hours of wallclock at Anthropic's default rate limit. Per+Anthropic's published research, document-heavy benchmarks see a+35-49% reduction in retrieval failure rate.++```bash+gbrain config set search.mode tokenmax+```++The mode-switch banner explains the cost and (on TTY + active Minion+worker) offers to submit `gbrain reindex --markdown` as a Minion job.+Non-TTY callers get a paste-ready hint to stderr. Suppress entirely+with `GBRAIN_NO_MODE_SWITCH_UX=1`.++If you skipped the prompt, run reindex manually:++```bash+gbrain reindex --markdown+# Or as a background job:+gbrain jobs submit reindex --params '{"markdown":true}' --allow-protected+```++## Optional: per-source CR mode overrides++If you have multiple sources and want different CR tiers per source:++```bash+gbrain sources set-cr-mode <id> <none|title|per_chunk_synopsis>+gbrain sources set-cr-mode <id> unset # clears the override (falls through to global)+```++## Optional: mount frontmatter trust++If you mount a team brain (`gbrain mounts add team-id ...`), per-page+`contextual_retrieval_mode` frontmatter overrides are OFF by default.+Opt in:++```bash+gbrain mounts trust-frontmatter team-id+```++Reverse:++```bash+gbrain mounts untrust-frontmatter team-id+```++## Soft kill switch++If quality regresses post-deploy (cache hit rate drops, search results+look worse), the soft kill switch disables future wrapping while leaving+already-wrapped vectors in the DB:++```bash+gbrain config set search.contextual_retrieval_disabled true+```++Existing cache rows continue to serve via the backward-compat path+(empty `{}` snapshot vacuously valid). New embeds skip the wrapper.+Recovery is then `gbrain reindex --markdown` to re-embed un-wrapped.++## What changed in the file layout++- New module: `src/core/remediation-step.ts` (canonical RemediationStep+ type + makeRemediationStep factory).+- New module: `src/core/search/query-cache-gate.ts` (two-layer cache+ gate helpers).+- New module: `src/core/search/mode-switch-ux.ts` (transition summarizer+ + worker probe + Minion submission).+- New module: `src/core/contextual-retrieval-service.ts` (already+ present from v0.40.3.0; just moved over via the merge).+- Extended: `src/commands/mounts.ts` (4 new verbs).+- Extended: `src/commands/sources.ts` (set-cr-mode verb).+- Extended: `src/commands/config.ts` (mode-switch hook).+- Extended: `src/commands/doctor.ts` (integrity + sync_failures checks+ emit RemediationSteps).+- Extended: `src/commands/jobs.ts` (3 new handlers: lint-fix,+ integrity-auto, sync-retry-failed).++## Backward compatibility++- Pre-v0.40.3.0 cache rows have `page_generations = '{}'::jsonb` AND+ `max_generation_at_store = 0`. The Layer 2 gate treats the empty+ snapshot as vacuously valid, so legacy rows continue serving until+ they age out via TTL (default 1h). One-time cache miss spike on+ upgrade is bounded.+- Existing pages without `generation` column default to 1 via the+ v91 migration's `NOT NULL DEFAULT 1`.+- Existing mount entries without `trust_frontmatter_overrides` default+ to `false` via `loadMounts()` projection.+- Existing source entries without `contextual_retrieval_mode` default+ to NULL (falls through to global mode).diff --git a/src/commands/config.ts b/src/commands/config.tsindex 7940f36deb..075de0ca52 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -280,11 +280,45 @@ export async function runConfig(engine: BrainEngine, args: string[]) {}}+ // v0.40.3.0 (D3 + Phase 2B): capture the OLD search.mode BEFORE the+ // setConfig so summarizeTransition() can classify the kind correctly.+ // Read fails silently → oldMode null → treated as broadening.+ let oldSearchMode: string | null = null;+ if (key === 'search.mode') {+ try {+ oldSearchMode = await engine.getConfig('search.mode');+ } catch {+ // ignore — null is the correct "never seen" semantic.+ }+ }+await engine.setConfig(key, value);// v0.36.x #892: redact sensitive values in confirmation output. API// keys / tokens / passwords are commonly set from terminals with// scrollback; echoing the raw value to stderr leaks the secret.console.log(`Set ${key} = ${redactConfigValue(key, value)}`);++ // v0.40.3.0 (D3 + Phase 2B): mode-switch UX. Fires only on+ // search.mode writes. Honors GBRAIN_NO_MODE_SWITCH_UX=1 + non-TTY.+ // The hook is best-effort — UX failures must NEVER break a config+ // set that already persisted.+ if (key === 'search.mode') {+ try {+ const { runModeSwitchUx } = await import('../core/search/mode-switch-ux.ts');+ const { isSearchMode } = await import('../core/search/mode.ts');+ await runModeSwitchUx({+ oldMode: oldSearchMode && isSearchMode(oldSearchMode) ? oldSearchMode : null,+ newMode: value,+ engine,+ isTty: Boolean(process.stdout.isTTY && process.stdin.isTTY),+ // CLI doesn't thread --yes here today; reserved for /ship-style+ // automation paths that can opt into auto-submit.+ yesFlag: false,+ });+ } catch (err) {+ console.error(`[mode-switch] UX hook failed (non-fatal): ${(err as Error).message}`);+ }+ }} else {console.error('Usage: gbrain config [show|get|set|unset] <key> [value]');console.error(' gbrain config unset --pattern <prefix>');diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex 32d2249261..fbeacc0ca9 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -42,22 +42,16 @@ export interface Check {issues?: Array<{ type: string; skill: string; action: string; fix?: any }>;/*** v0.36+ brain-health-100: structured remediation jobs per check.- * Populated by the recommendation generator; consumed by+ * Populated by the recommendation generator + (v0.40.3.0 T8b) individual+ * checks (lint, integrity, sync_failures). Consumed by* `gbrain doctor --remediation-plan` / `--remediate`. Optional and* additive — schema_version stays at 2 (D4).+ *+ * v0.40.3.0 (D6): typed to RemediationStep[] from the canonical+ * src/core/remediation-step.ts so check authors can use+ * `makeRemediationStep()` factory without hand-rolling the shape.*/- remediation?: Array<{- id: string;- job: string;- params: Record<string, unknown>;- idempotency_key: string;- severity: 'critical' | 'high' | 'medium' | 'low';- est_seconds: number;- est_usd_cost?: number;- depends_on?: string[];- rationale: string;- protected?: boolean;- }>;+ remediation?: import('../core/remediation-step.ts').RemediationStep[];/** Top-level triage state per D13. */remediation_status?: 'remediable' | 'human_only' | 'blocked';}@@ -619,6 +613,12 @@ export async function doctorReportRemote(engine: BrainEngine): Promise<DoctorRepchecks.push(await checkGradeConfidenceDrift(engine));checks.push(await checkVoiceGateHealth(engine));+ // 11. v0.40.3.0 contextual_retrieval_coverage — surfaces pages with+ // - chunker_version drift (pre-v40 pages not yet re-embedded)+ // - contextual_retrieval_mode IS NULL (mode never evaluated)+ // - synopsis-failures audit JSONL entries from the last 7 days+ checks.push(await checkContextualRetrievalCoverage(engine));+return computeDoctorReport(checks);}@@ -630,6 +630,90 @@ export async function doctorReportRemote(engine: BrainEngine): Promise<DoctorRep* follow-up page. These are commitments the user made and never revisited.* Status 'ok' with a count; never warns/fails (this is signal, not error).*/+/**+ * v0.40.3.0 contextual_retrieval_coverage check.+ *+ * Surfaces drift between the active CR mode + the per-page+ * `contextual_retrieval_mode` column. Three signals:+ *+ * 1. Pages with chunker_version < current — pre-v40 pages that need+ * to be re-embedded for the wrapper to apply. Paste-ready fix:+ * `gbrain reindex --markdown`.+ * 2. Pages with contextual_retrieval_mode IS NULL — never evaluated+ * against the CR ladder. Same fix as (1).+ * 3. Synopsis-failure events in the audit JSONL over the last 7 days+ * — surfaces refusals + page-level fallbacks. >5% refusal rate+ * warns; otherwise reported as informational.+ *+ * Reads `~/.gbrain/audit/synopsis-failures-YYYY-Www.jsonl` via+ * readRecentSynopsisFailures + summarizeSynopsisFailures from+ * `src/core/audit-synopsis.ts`. Failure-only audit means low write+ * volume on healthy brains.+ */+export async function checkContextualRetrievalCoverage(engine: BrainEngine): Promise<Check> {+ try {+ const { MARKDOWN_CHUNKER_VERSION } = await import('../core/chunkers/recursive.ts');+ const rows = await engine.executeRaw<{ chunker_drift: number; mode_null: number }>(+ `SELECT+ COUNT(*) FILTER (WHERE chunker_version < $1)::int AS chunker_drift,+ COUNT(*) FILTER (WHERE contextual_retrieval_mode IS NULL)::int AS mode_null+ FROM pages+ WHERE page_kind = 'markdown'+ AND deleted_at IS NULL`,+ [MARKDOWN_CHUNKER_VERSION],+ );+ const chunkerDrift = rows[0]?.chunker_drift ?? 0;+ const modeNull = rows[0]?.mode_null ?? 0;++ // Synopsis-failures audit summary (best-effort; missing audit file = 0).+ let failureSummaryLine = '';+ try {+ const audit = await import('../core/audit-synopsis.ts');+ const events = audit.readRecentSynopsisFailures(7);+ const summary = audit.summarizeSynopsisFailures(events);+ if (summary && summary.total > 0) {+ const rate = (summary.page_level_fallback_rate * 100).toFixed(1);+ failureSummaryLine =+ ` ${summary.total} synopsis failure(s) in last 7d ` ++ `(${summary.page_level_fallback_count} triggered page-level fall-back, ${rate}%).`;+ }+ } catch {+ // Audit module unavailable — skip the summary line.+ }++ if (chunkerDrift === 0 && modeNull === 0 && failureSummaryLine === '') {+ return {+ name: 'contextual_retrieval_coverage',+ status: 'ok',+ message: 'All markdown pages aligned to current chunker + CR mode.',+ };+ }++ const parts: string[] = [];+ if (chunkerDrift > 0) {+ parts.push(`${chunkerDrift} page(s) at older chunker_version`);+ }+ if (modeNull > 0) {+ parts.push(`${modeNull} page(s) never evaluated against CR ladder`);+ }+ const fixHint =+ chunkerDrift > 0 || modeNull > 0+ ? ` Run \`gbrain reindex --markdown\` to align.`+ : '';+ return {+ name: 'contextual_retrieval_coverage',+ status: chunkerDrift > 0 || modeNull > 0 ? 'warn' : 'ok',+ message: `${parts.join('; ')}.${fixHint}${failureSummaryLine}`,+ };+ } catch (e) {+ return {+ name: 'contextual_retrieval_coverage',+ status: 'warn',+ message: `Could not check contextual retrieval coverage: ${e instanceof Error ? e.message : String(e)}`,+ };+ }+}+export async function checkAbandonedThreads(engine: BrainEngine): Promise<Check> {try {const rows = await engine.executeRaw<{ count: number }>(@@ -2171,6 +2255,26 @@ export async function runDoctor(engine: BrainEngine | null, args: string[], dbSoconst codeSummary = summarizeFailuresByCode(unacked);const codeBreakdown = codeSummary.map(s => `${s.code}=${s.count}`).join(', ');const preview = unacked.slice(0, 3).map(f => `${f.path} (${f.error.slice(0, 60)})`).join('; ');+ // v0.40.3.0 T8b (D8 + D12 Bug 3): emit a single sync-retry-failed+ // step. sync-skip-failed is DELIBERATELY NOT emitted as a remediation+ // — auto-skipping failed syncs hides data loss. Operators can still+ // run `gbrain sync --skip-failed` manually.+ const { makeRemediationStep } = await import('../core/remediation-step.ts');+ const oldestTs = unacked.reduce(+ (acc, f) => (acc === '' || f.ts < acc ? f.ts : acc),+ '',+ );+ const retryStep = makeRemediationStep({+ id: 'sync-retry-failed',+ job: 'sync-retry-failed',+ // Content-stable per codex D12 Bug 2: count + oldest_ts captures+ // the relevant state without using a real timestamp.+ params: { failure_count: unacked.length, oldest_failure: oldestTs },+ severity: unacked.length >= 10 ? 'high' : 'medium',+ est_seconds: 30,+ est_usd_cost: 0,+ rationale: `Retry ${unacked.length} unacked sync failure(s) (codes: ${codeBreakdown})`,+ });checks.push({name: 'sync_failures',status: 'warn',@@ -2178,6 +2282,8 @@ export async function runDoctor(engine: BrainEngine | null, args: string[], dbSo`${unacked.length} unacknowledged sync failure(s) [${codeBreakdown}]. ${preview}` +`${unacked.length > 3 ? `, and ${unacked.length - 3} more` : ''}. ` +`Fix the file(s) and re-run 'gbrain sync', or use 'gbrain sync --skip-failed' to acknowledge.`,+ remediation: [retryStep],+ remediation_status: 'remediable',});} else if (all.length > 0) {// Acknowledged-only: show code breakdown for visibility.@@ -3086,10 +3192,29 @@ export async function runDoctor(engine: BrainEngine | null, args: string[], dbSomessage: `Sampled ${res.pagesScanned} pages; no bare-tweet phrases or external links.`,});} else if (res.bareHits.length > 0) {+ // v0.40.3.0 T8b (D8): emit integrity-auto RemediationStep.+ // Three-bucket repair handled by `gbrain integrity auto` (the+ // existing CLI). Deterministic — no LLM cost.+ const { makeRemediationStep } = await import('../core/remediation-step.ts');+ const integrityStep = makeRemediationStep({+ id: 'integrity-auto',+ job: 'integrity-auto',+ params: {+ bare_count: res.bareHits.length,+ external_count: res.externalHits.length,+ pages_scanned: res.pagesScanned,+ },+ severity: res.bareHits.length > 50 ? 'high' : 'medium',+ est_seconds: 60,+ est_usd_cost: 0,+ rationale: `Auto-repair ${res.bareHits.length} bare-tweet phrase(s)`,+ });checks.push({name: 'integrity',status: 'warn',message: `Sampled ${res.pagesScanned} pages; ${res.bareHits.length} bare-tweet phrase(s), ${res.externalHits.length} external link(s). Run: gbrain integrity check (or integrity auto to repair).`,+ remediation: [integrityStep],+ remediation_status: 'remediable',});} else {checks.push({diff --git a/src/commands/jobs.ts b/src/commands/jobs.tsindex 121a14236d..d86a072d3c 100644--- a/src/commands/jobs.ts+++ b/src/commands/jobs.ts@@ -1097,6 +1097,28 @@ export async function registerBuiltinHandlers(worker: MinionWorker, engine: Braireturn result;});+ // v0.40.3.0 T8b: RemediationStep consumer handlers. Thin wrappers+ // around already-shipping CLI commands so doctor --remediate can+ // submit them as Minion jobs. NOT in PROTECTED_JOB_NAMES (no shell+ // exec, no cost spike, MCP-safe).+ worker.register('lint-fix', async (job) => {+ const { runLintCore } = await import('./lint.ts');+ const target = typeof job.data.dir === 'string' ? job.data.dir : '.';+ return await runLintCore({ target, fix: true, dryRun: false });+ });++ worker.register('integrity-auto', async () => {+ const { runIntegrity } = await import('./integrity.ts');+ await runIntegrity(['auto']);+ return { ok: true };+ });++ worker.register('sync-retry-failed', async () => {+ const { runSync } = await import('./sync.ts');+ await runSync(engine, ['--retry-failed']);+ return { ok: true };+ });+worker.register('import', async (job) => {// import.ts Core extraction deferred to v0.12.0 (import has parallel// workers + checkpointing). Keep the CLI wrapper call but note the@@ -1140,6 +1162,19 @@ export async function registerBuiltinHandlers(worker: MinionWorker, engine: Brai// renewal callback and the stalled-sweeper kills the job.//// Phase failures surface as report.status='partial' (via runCycle's+ // v0.40.3.0: per-page contextual retrieval re-embed handler. PROTECTED+ // name (src/core/minions/protected-names.ts) — MCP/OAuth callers can't+ // submit; only trusted local callers (config.ts mode-switch hook,+ // reindex sweep, doctor --remediate). Composes the global Haiku rate-+ // leaser per D26 P0-3 + delegates to contextual-retrieval-service.ts+ // for the two-phase build.+ {+ const { makeContextualReindexHandler } = await import(+ '../core/minions/handlers/contextual-reindex-per-chunk.ts'+ );+ worker.register('contextual_reindex_per_chunk', makeContextualReindexHandler({ engine }));+ }+// derivation); the handler returns { partial, status, report } so// `gbrain jobs get <id>` shows the full structured report. Does NOT// throw on partial: a flaky phase must not block every future cycle.diff --git a/src/commands/mounts.ts b/src/commands/mounts.tsindex abf8b30905..61f4961b8f 100644--- a/src/commands/mounts.ts+++ b/src/commands/mounts.ts@@ -38,7 +38,14 @@ import { writeMountsCache, clearMountsCache } from '../core/mounts-cache.ts';import { GBrainError } from '../core/types.ts';function getMountsDir(): string { return join(homedir(), '.gbrain'); }-function getMountsPath(): string { return join(getMountsDir(), 'mounts.json'); }+// v0.40.3.0: GBRAIN_MOUNTS_PATH override exists for tests (libuv caches+// homedir() at startup on some platforms; HOME mutation alone isn't+// reliably picked up). Production callers don't set this.+function getMountsPath(): string {+ const override = process.env.GBRAIN_MOUNTS_PATH;+ if (override) return override;+ return join(getMountsDir(), 'mounts.json');+}/*** Read mounts.json and return the parsed MountsFile, or a fresh empty file@@ -371,15 +378,87 @@ export async function runMounts(args: string[]): Promise<void> {case 'rm':runRemove(rest);return;+ case 'enable':+ runSetMountFlag(rest, 'enabled', true, 'enable');+ return;+ case 'disable':+ runSetMountFlag(rest, 'enabled', false, 'disable');+ return;+ case 'trust-frontmatter':+ runSetMountFlag(rest, 'trust_frontmatter_overrides', true, 'trust-frontmatter');+ return;+ case 'untrust-frontmatter':+ runSetMountFlag(rest, 'trust_frontmatter_overrides', false, 'untrust-frontmatter');+ return;default:throw new GBrainError(`Unknown subcommand: gbrain mounts ${sub}`,- `Supported: add, list, remove`,+ `Supported: add, list, remove, enable, disable, trust-frontmatter, untrust-frontmatter`,`Run 'gbrain mounts --help' for usage`,);}}+/**+ * Shared writer for boolean-flag verbs (enable/disable/trust-frontmatter/+ * untrust-frontmatter). v0.40.3.0 D4 picked separate verbs over a single+ * `set <flag> <value>` mutator because validation actually matters per-flag+ * (e.g., trust_frontmatter_overrides is security-relevant; future flags may+ * need bespoke prompts).+ *+ * Trust→untrust→trust cycle preserves other fields (test pinned).+ */+function runSetMountFlag(+ args: string[],+ field: 'enabled' | 'trust_frontmatter_overrides',+ value: boolean,+ verb: string,+): void {+ if (args.length === 0) {+ throw new GBrainError(+ `Missing mount id`,+ `gbrain mounts ${verb} <id>`,+ `Run 'gbrain mounts list' to see registered mounts`,+ );+ }+ const id = args[0];+ if (id === HOST_BRAIN_ID) {+ throw new GBrainError(+ `Cannot ${verb} host brain`,+ `"host" is not a mount — it is the default brain from ~/.gbrain/config.json`,+ verb === 'trust-frontmatter' || verb === 'untrust-frontmatter'+ ? `Host frontmatter is always trusted; this verb applies only to mounted brains.`+ : `Use 'gbrain init' to reconfigure the host brain`,+ );+ }++ const file = readMountsFile();+ const mount = file.mounts.find((m) => m.id === id);+ if (!mount) {+ throw new GBrainError(+ `Mount "${id}" not found`,+ `No mount with id "${id}" is registered`,+ `Run 'gbrain mounts list' to see registered mounts`,+ );+ }++ // No-op check so the cache refresh + write don't churn when state matches.+ // For `enabled` field, default is true when unset — coerce for comparison.+ const currentValue = field === 'enabled' ? (mount.enabled ?? true) : (mount[field] ?? false);+ if (currentValue === value) {+ process.stdout.write(`Mount "${id}" already has ${field}=${value}; no change\n`);+ return;+ }++ mount[field] = value;+ writeMountsFile(file);+ process.stdout.write(`Mount "${id}" ${verb}d (${field}=${value})\n`);++ // Refresh the aggregated mounts cache so host agents see the new flag+ // immediately. Same best-effort pattern as runRemove.+ refreshMountsCache();+}+function printHelp(): void {process.stdout.write(`gbrain mounts — manage connected gbrains (PR 0: direct transport only)@@ -400,10 +479,20 @@ EXAMPLES# Remove a mountgbrain mounts remove yc-media+v0.40.3.0 ADDITIONS+ gbrain mounts enable <id> — re-enable a disabled mount+ gbrain mounts disable <id> — toggle a mount off without removing+ gbrain mounts trust-frontmatter <id> — let this mount's per-page+ contextual_retrieval_mode+ frontmatter override the source+ default. Off by default for+ mounted brains; host is always+ trusted.+ gbrain mounts untrust-frontmatter <id> — clear the trust flag.+NOT YET IMPLEMENTED (coming in PR 1/2)gbrain mounts pin <id> <sha> — freeze a mount at a tested versiongbrain mounts sync [--id <id>] — git pull + refresh attestation- gbrain mounts enable|disable <id> — toggle without removinggbrain mounts add --mcp-url <url> — HTTP MCP transport + OAuth`);}diff --git a/src/commands/reindex.ts b/src/commands/reindex.tsindex 153f36e55e..66531fbb3d 100644--- a/src/commands/reindex.ts+++ b/src/commands/reindex.ts@@ -74,15 +74,32 @@ function parseArgs(args: string[]): ReindexOpts {}/**- * Count markdown pages that haven't been re-chunked by the current- * MARKDOWN_CHUNKER_VERSION. Cheap; uses the partial index from migration v54.+ * Count markdown pages that need re-embedding. v0.40.3.0: predicate+ * extends from chunker_version drift alone to ALSO catch contextual+ * retrieval state drift (D26 P0-1). A page enters the sweep if either:+ *+ * (a) chunker_version is below the current value — pre-v40 pages that+ * haven't been touched by the wrapper bump yet+ * (b) contextual_retrieval_mode is NULL — pages that have never been+ * evaluated against the CR ladder (pre-v40 brains)+ *+ * D26 P0-4 IS DISTINCT FROM is used where comparing against a value; for+ * NULL detection we use IS NULL directly. Page-frontmatter overrides+ * (D5) are handled at re-import time: importFromFile re-parses the+ * frontmatter and the resolver picks the right tier for that page.+ *+ * Global-mode-vs-stamped-mode drift (e.g. user upgraded balanced→tokenmax,+ * skipped the post-upgrade prompt, then later ran reindex) is caught by+ * the IS NULL clause for pre-v81 brains AND by a future T10 mode-switch+ * hook for post-v81 brains. The simple `chunker_version OR mode IS NULL`+ * predicate covers the headline upgrade case the wave is shipping.*/async function countPending(engine: BrainEngine): Promise<number> {const rows = await engine.executeRaw<{ count: string | number }>(`SELECT COUNT(*)::bigint AS countFROM pagesWHERE page_kind = 'markdown'- AND chunker_version < $1+ AND (chunker_version < $1 OR contextual_retrieval_mode IS NULL)AND deleted_at IS NULL`,[MARKDOWN_CHUNKER_VERSION],);@@ -99,7 +116,7 @@ async function readBatch(engine: BrainEngine, batchSize: number): Promise<Array<`SELECT slug, source_path, compiled_truth, source_idFROM pagesWHERE page_kind = 'markdown'- AND chunker_version < $1+ AND (chunker_version < $1 OR contextual_retrieval_mode IS NULL)AND deleted_at IS NULLORDER BY id ASCLIMIT $2`,diff --git a/src/commands/search.ts b/src/commands/search.tsindex 6957f08cc5..3ff9335919 100644--- a/src/commands/search.ts+++ b/src/commands/search.ts@@ -62,6 +62,9 @@ const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {unified_multimodal: 'Phase 3 — route all queries through embedding_multimodal column',unified_multimodal_only: 'Phase 3 strict — bypass dual-column fallback when unified is on',cross_modal_llm_intent: 'Commit 4 — Haiku tie-break for ambiguous modality classification',+ // v0.40.3.0 contextual retrieval+ contextual_retrieval: 'CR tier (none|title|per_chunk_synopsis) — wraps chunks at embed time',+ contextual_retrieval_disabled: 'Soft kill switch — neutralizes CR wrapping for queries + new embeds',};interface SearchModesReport {diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 442f336446..bc13b49811 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -275,6 +275,70 @@ async function runRemove(engine: BrainEngine, args: string[]): Promise<void> {// ── Subcommand: archive (soft-delete) ───────────────────────+// ── Subcommand: set-cr-mode (v0.40.3.0 — D5) ────────────────+//+// `gbrain sources set-cr-mode <id> <none|title|per_chunk_synopsis>`+// writes sources.contextual_retrieval_mode for the per-source override+// resolver. Empty value / "unset" / "default" clears the column (NULL+// falls through to the global mode).+//+// Loud rejection on:+// - missing id+// - missing mode+// - invalid mode (lists valid options)+// - non-existent source id (lists registered sources via paste-ready hint)+//+// D5 picked the narrow verb over a generic `sources set <key> <value>`+// because per-field validation actually matters (CRMode validation must+// run; future fields may need bespoke prompts). The generic mutator is+// filed as a v0.41+ TODO when 3+ writable fields exist.++async function runSetCrMode(engine: BrainEngine, args: string[]): Promise<void> {+ const { isCRMode, CR_MODES } = await import('../core/types.ts');+ const id = args[0];+ const mode = args[1];++ if (!id || !mode) {+ console.error('Usage: gbrain sources set-cr-mode <id> <none|title|per_chunk_synopsis>');+ console.error(' Pass "unset" or "default" to clear the override (NULL falls through).');+ process.exit(2);+ }++ // Clear path: empty / "unset" / "default" → NULL.+ const clearing = mode === 'unset' || mode === 'default' || mode === '';+ if (!clearing && !isCRMode(mode)) {+ console.error(`Error: invalid CR mode "${mode}".`);+ console.error(`Valid options: ${CR_MODES.join(' | ')}`);+ console.error(` Or pass "unset" / "default" to clear the override.`);+ process.exit(2);+ }++ // Loud-rejection on missing source. Closes the idempotent-pebble Failure+ // Modes "critical gap": pre-v0.40.3.0 there was no surface that wrote to+ // sources.contextual_retrieval_mode, so the silent-no-op via SQL UPDATE+ // matching 0 rows was the failure mode the gap warning called out.+ const exists = await engine.executeRaw<{ id: string }>(+ `SELECT id FROM sources WHERE id = $1 LIMIT 1`,+ [id],+ );+ if (exists.length === 0) {+ console.error(`Error: source "${id}" not found.`);+ console.error(` Run 'gbrain sources list' to see registered sources.`);+ process.exit(4);+ }++ const newValue = clearing ? null : mode;+ await engine.executeRaw(+ `UPDATE sources SET contextual_retrieval_mode = $1 WHERE id = $2`,+ [newValue, id],+ );+ if (clearing) {+ console.log(`Cleared contextual_retrieval_mode for source "${id}" (NULL falls through to global mode).`);+ } else {+ console.log(`Set source "${id}" contextual_retrieval_mode = ${mode}.`);+ }+}+async function runArchive(engine: BrainEngine, args: string[]): Promise<void> {const id = args[0];if (!id) {@@ -551,6 +615,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<vcase 'purge': return runPurge(engine, rest);case 'archived': return runListArchived(engine, rest);case 'current': return runCurrent(engine, rest);+ case 'set-cr-mode': return runSetCrMode(engine, rest);case undefined:case '--help':case '-h':@@ -592,6 +657,11 @@ Subcommands:targeting the brain you think you are.federate <id> Make source appear in cross-source default search.unfederate <id> Isolate source from default search.+ set-cr-mode <id> <none|title|per_chunk_synopsis>+ Per-source contextual retrieval mode+ override (v0.40.3.0). Pass "unset" or+ "default" to clear (NULL falls through+ to the global search.mode bundle).Source id: [a-z0-9-]{1,32}. Immutable citation key.diff --git a/src/core/audit-synopsis.ts b/src/core/audit-synopsis.tsnew file mode 100644index 0000000000..dccd6a8718--- /dev/null+++ b/src/core/audit-synopsis.ts@@ -0,0 +1,206 @@+/**+ * v0.40.3.0 — per-chunk Haiku synopsis failure audit (D17, mirrors the+ * v0.35.0.0 rerank-audit precedent: deliberately failure-ONLY, no success+ * logging).+ *+ * Writes failure events to `~/.gbrain/audit/synopsis-failures-YYYY-Www.jsonl`+ * (ISO-week rotation, mirrors `audit-slug-fallback.ts` shape). Surfaced+ * by `gbrain doctor`'s `synopsis_refusal_rate` check.+ *+ * Why failure-only (D17 decision, repeated here for the file-level reader):+ * - The per-chunk synopsis backfill writes one row per page (potentially+ * 10K+ on a typical brain). Logging successes turns that into 10K++ * JSONL rows per backfill — wasted disk + needlessly leaks "this+ * user is mid-backfill at TS=..." into a local file.+ * - Failure signal (refusal / empty / malformed / fall-back) is the+ * ACTIONABLE signal: surfaces Haiku regressions, prompt-injection+ * attempts in user content, and pages that consistently fail to+ * generate good synopses.+ *+ * Best-effort writes — failures go to stderr but the Minion job continues+ * (the page falls back to title-only per D14 regardless of audit success).+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import { resolveAuditDir } from './minions/handlers/shell-audit.ts';++/**+ * Per-D27 P1-2 failure envelope. Each `kind` maps to a distinct downstream+ * handler in the Minion handler:+ *+ * refusal | empty | malformed → page-level fall-back to title-only (D14)+ * auth_failure → throw, doctor surfaces, no retry+ * rate_limit → retry per gateway with Retry-After+ * timeout | network | provider_5xx → retry per gateway policy+ * source_missing → walk source-text fallback chain (D11)+ */+export type SynopsisFailureKind =+ | 'refusal'+ | 'empty'+ | 'malformed'+ | 'auth_failure'+ | 'rate_limit'+ | 'timeout'+ | 'network'+ | 'provider_5xx'+ | 'source_missing';++export interface SynopsisFailureAuditEvent {+ ts: string;+ /** Page slug whose synopsis generation failed. */+ page_slug: string;+ /** Source id (multi-source brains). */+ source_id: string;+ /** Chunk index within the page (0-based). For page-level failures, -1. */+ chunk_index: number;+ /** Failure classification per D27 P1-2. */+ kind: SynopsisFailureKind;+ /**+ * Optional provider-supplied detail (HTTP status, retry-after ms, etc.)+ * for forensic analysis. Bounded ~200 chars so adversarial errors can't+ * blow the audit file.+ */+ detail?: string;+ /**+ * True when this failure triggered the page-level fall-back to+ * title-only (D14). Lets doctor compute the per-page-degradation rate.+ */+ page_level_fallback: boolean;+ severity: 'warn';+}++const DETAIL_HARD_CAP_CHARS = 200;++/** ISO-week-rotated filename: `synopsis-failures-YYYY-Www.jsonl`. */+export function computeSynopsisAuditFilename(now: Date = new Date()): string {+ const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));+ const dayNum = (d.getUTCDay() + 6) % 7;+ d.setUTCDate(d.getUTCDate() - dayNum + 3);+ const isoYear = d.getUTCFullYear();+ const firstThursday = new Date(Date.UTC(isoYear, 0, 4));+ const firstThursdayDayNum = (firstThursday.getUTCDay() + 6) % 7;+ firstThursday.setUTCDate(firstThursday.getUTCDate() - firstThursdayDayNum + 3);+ const weekNum = Math.round((d.getTime() - firstThursday.getTime()) / (7 * 86400000)) + 1;+ const ww = String(weekNum).padStart(2, '0');+ return `synopsis-failures-${isoYear}-W${ww}.jsonl`;+}++export interface LogSynopsisFailureArgs {+ pageSlug: string;+ sourceId: string;+ chunkIndex: number;+ kind: SynopsisFailureKind;+ detail?: string;+ pageLevelFallback: boolean;+}++/**+ * Append one failure event to the current week's audit JSONL.+ *+ * Best-effort: write failure to JSONL logs to stderr but does NOT throw+ * — the Minion handler continues regardless (the page already fell back+ * to title-only per D14).+ */+export function logSynopsisFailure(args: LogSynopsisFailureArgs): void {+ const event: SynopsisFailureAuditEvent = {+ ts: new Date().toISOString(),+ page_slug: args.pageSlug,+ source_id: args.sourceId,+ chunk_index: args.chunkIndex,+ kind: args.kind,+ detail: args.detail ? args.detail.slice(0, DETAIL_HARD_CAP_CHARS) : undefined,+ page_level_fallback: args.pageLevelFallback,+ severity: 'warn',+ };+ const dir = resolveAuditDir();+ const file = path.join(dir, computeSynopsisAuditFilename());+ try {+ fs.mkdirSync(dir, { recursive: true });+ fs.appendFileSync(file, JSON.stringify(event) + '\n', { encoding: 'utf8' });+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ process.stderr.write(+ `[gbrain] synopsis-failure audit write failed (${msg}); page ${args.pageSlug} continues\n`,+ );+ }+}++/**+ * Read recent (default 7-day window) synopsis-failure events. Walks the+ * current + previous ISO week so a window straddling Monday-midnight stays+ * covered. Missing file / corrupt rows are skipped silently — informational+ * surface, shouldn't block doctor.+ */+export function readRecentSynopsisFailures(+ days = 7,+ now: Date = new Date(),+): SynopsisFailureAuditEvent[] {+ const dir = resolveAuditDir();+ const cutoff = now.getTime() - days * 86400000;+ const out: SynopsisFailureAuditEvent[] = [];+ const filenames = [+ computeSynopsisAuditFilename(now),+ computeSynopsisAuditFilename(new Date(now.getTime() - 7 * 86400000)),+ ];+ for (const filename of filenames) {+ const file = path.join(dir, filename);+ let content: string;+ try {+ content = fs.readFileSync(file, 'utf8');+ } catch {+ continue;+ }+ for (const line of content.split('\n')) {+ if (line.length === 0) continue;+ try {+ const ev = JSON.parse(line) as SynopsisFailureAuditEvent;+ const ts = Date.parse(ev.ts);+ if (Number.isFinite(ts) && ts >= cutoff) out.push(ev);+ } catch {+ // Corrupt row — skip.+ }+ }+ }+ return out;+}++/**+ * Doctor-facing summary: aggregates recent failures by kind + computes+ * the page-level-fallback rate. Returns `null` when zero events seen+ * (lets doctor short-circuit to ok without computing a rate from zero).+ */+export interface SynopsisFailureSummary {+ total: number;+ by_kind: Record<SynopsisFailureKind, number>;+ page_level_fallback_count: number;+ page_level_fallback_rate: number;+}++export function summarizeSynopsisFailures(+ events: SynopsisFailureAuditEvent[],+): SynopsisFailureSummary | null {+ if (events.length === 0) return null;+ const by_kind: Record<SynopsisFailureKind, number> = {+ refusal: 0,+ empty: 0,+ malformed: 0,+ auth_failure: 0,+ rate_limit: 0,+ timeout: 0,+ network: 0,+ provider_5xx: 0,+ source_missing: 0,+ };+ let page_level_fallback_count = 0;+ for (const ev of events) {+ by_kind[ev.kind]++;+ if (ev.page_level_fallback) page_level_fallback_count++;+ }+ return {+ total: events.length,+ by_kind,+ page_level_fallback_count,+ page_level_fallback_rate: page_level_fallback_count / events.length,+ };+}diff --git a/src/core/brain-registry.ts b/src/core/brain-registry.tsindex bbc46b6911..5c50b558e4 100644--- a/src/core/brain-registry.ts+++ b/src/core/brain-registry.ts@@ -36,8 +36,16 @@ export const HOST_BRAIN_ID = 'host';/** Brain id regex. Alphanumeric + dashes, 1-32 chars. No edge dashes. */const BRAIN_ID_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;-/** Path to mounts.json. Lazy to avoid homedir() at module scope. */+/**+ * Path to mounts.json. Lazy to avoid homedir() at module scope.+ *+ * v0.40.3.0: GBRAIN_MOUNTS_PATH override exists for tests (homedir() is+ * cached at startup by libuv on some platforms, so withFakeHome's HOME+ * mutation isn't always picked up). Production callers don't set this.+ */function getMountsPath(): string {+ const override = process.env.GBRAIN_MOUNTS_PATH;+ if (override) return override;return join(homedir(), '.gbrain', 'mounts.json');}@@ -66,6 +74,15 @@ export interface MountEntry {expected_sha?: string;/** Managed by `gbrain mounts sync` (PR 1). */last_synced_at?: string;+ /**+ * v0.40.3.0: per-mount frontmatter-override trust gate (D15). Default+ * FALSE — mounts must explicitly opt into honoring frontmatter+ * `contextual_retrieval_mode` overrides via+ * `gbrain mounts trust-frontmatter <id>`. The host source (id='default')+ * is always trusted regardless of this field. Set/cleared via the+ * dedicated `trust-frontmatter` / `untrust-frontmatter` verbs (D4).+ */+ trust_frontmatter_overrides?: boolean;}/** Top-level shape of ~/.gbrain/mounts.json. */@@ -263,6 +280,10 @@ export function loadMounts(mountsPath: string = getMountsPath()): MountEntry[] {enabled: entry.enabled ?? true,expected_sha: entry.expected_sha,last_synced_at: entry.last_synced_at,+ // v0.40.3.0 (D4): per-mount frontmatter-override trust gate.+ // Threaded through the projection so trust-frontmatter / untrust-frontmatter+ // verbs round-trip cleanly. Default false: mounts opt in explicitly.+ trust_frontmatter_overrides: entry.trust_frontmatter_overrides ?? false,});}diff --git a/src/core/brain-score-recommendations.ts b/src/core/brain-score-recommendations.tsindex fa03a6c135..ba64a73128 100644--- a/src/core/brain-score-recommendations.ts+++ b/src/core/brain-score-recommendations.ts@@ -38,48 +38,32 @@ export interface Check {*//**- * Severity buckets — drive ordering (critical first) and operator UX- * (in the human-readable plan output, critical items get a louder prefix).+ * v0.40.3.0: RemediationStep + RemediationSeverity + RemediationStatus+ * lifted to src/core/remediation-step.ts so other doctor checks (lint,+ * integrity, sync_failures) can emit RemediationStep without circular+ * importing brain-score code. Re-exported here for back-compat AND to+ * avoid forcing every importer to update the path in one PR.+ *+ * The `Remediation` name is deprecated as of v0.40.3.0; use+ * `RemediationStep` going forward. Same shape; rename was for clarity.*/-export type RemediationSeverity = 'critical' | 'high' | 'medium' | 'low';--/** Status of an individual check's autofix path. */-export type RemediationStatus = 'remediable' | 'human_only' | 'blocked';--export interface Remediation {- /** Stable id (e.g. 'sync.repo', 'embed.stale', 'embed.code'). Survives- * check renames; referenced by `depends_on`. */- id: string;- /** Minion handler name (must match a registered handler). */- job: string;- /** Params passed to the handler. */- params: Record<string, unknown>;- /** Content-hash idempotency key: `<source>:<job>:sha8(canonical-JSON(params))`.- * Per D9: NO time-slot. Retry suffix `:r<N>` appended by --remediate when- * prior key's job is in `failed`/`dead` state. */- idempotency_key: string;- severity: RemediationSeverity;- /** Upper-bound runtime estimate for ordering + --target-score budgeting. */- est_seconds: number;- /** USD cost estimate when applicable (embed by chunk count × $/MTok;- * synthesize / patterns / consolidate by est Sonnet calls × $/MTok).- * Sum across plan steps is the gate for --max-usd. */- est_usd_cost?: number;- /** Other Remediation.id values that MUST complete first. References ids,- * NOT check names (D14 — closes codex #22 fan-out ambiguity). */- depends_on?: string[];- /** One-line "what this fixes" for human output. */- rationale: string;- /** True if `job` is in PROTECTED_JOB_NAMES (D11). Mirrors trust-gate state- * so callers don't have to re-derive it. */- protected?: boolean;- /** Always 'remediable' when this struct is in the plan. The doctor surface- * also produces blocked-entries (with `blocked_reason`) but those don't- * enter the executable plan. */- status: RemediationStatus;- /** Populated when status === 'blocked'. E.g. 'missing OPENAI_API_KEY'. */- blocked_reason?: string;-}+export {+ type RemediationStep,+ type RemediationStep as Remediation,+ type RemediationSeverity,+ type RemediationStatus,+ makeRemediationStep,+ idempotencyKey as makeRemediationIdempotencyKey,+ canonicalJson,+} from './remediation-step.ts';+import type {+ RemediationStep,+ RemediationStatus,+ RemediationSeverity,+} from './remediation-step.ts';+// Internal alias so the existing implementation below keeps compiling+// without a sed pass. New code should reference RemediationStep directly.+type Remediation = RemediationStep;export interface RecommendationContext {/** Source id this remediation is scoped to (multi-source brains). */diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.tsindex dada7d540b..a9aa54e884 100644--- a/src/core/chunkers/recursive.ts+++ b/src/core/chunkers/recursive.ts@@ -23,9 +23,18 @@ import { countCJKAwareWords, CJK_SENTENCE_DELIMITERS, CJK_CLAUSE_DELIMITERS } fr* Markdown chunker version. Folded into the per-page chunker_version column* so post-upgrade reindex sweeps can find pages built with old chunkers and* rebuild them on the new shape. Bump on any change that affects chunk- * boundaries (delimiters, word counting, maxChars cap).+ * boundaries (delimiters, word counting, maxChars cap) OR the per-chunk+ * embedding shape (wrapper prefix added at embed time).+ *+ * v3 (v0.40.3.0): chunks embed with optional contextual retrieval wrapper+ * per Anthropic's published methodology. Wrapper is built JUST IN TIME at+ * embed call; stored `content_chunks.chunk_text` stays canonical. Chunk+ * boundaries themselves are unchanged from v2 — bumping the version forces+ * re-embed (not re-chunk) so existing pages pick up the wrapper on the+ * post-upgrade reembed sweep. See+ * `src/core/contextual-retrieval-service.ts`.*/-export const MARKDOWN_CHUNKER_VERSION = 2;+export const MARKDOWN_CHUNKER_VERSION = 3;const DELIMITERS: string[][] = [['\n\n'], // L0: paragraphsdiff --git a/src/core/contextual-retrieval-resolver.ts b/src/core/contextual-retrieval-resolver.tsnew file mode 100644index 0000000000..778309a88c--- /dev/null+++ b/src/core/contextual-retrieval-resolver.ts@@ -0,0 +1,151 @@+/**+ * v0.40.3.0 — contextual retrieval mode resolver.+ *+ * Pure function that picks the effective CRMode for one page by walking+ * the three-source override chain:+ *+ * page frontmatter > source row > global mode bundle+ *+ * Mount-frontmatter overrides (D15 security gate): a per-page+ * `contextual_retrieval` frontmatter key in a MOUNTED source's page is+ * honored ONLY when that source's `trust_frontmatter_overrides` column is+ * true. The host source (id='default') is always trusted regardless of+ * the column value. This protects against pulling a third-party brain+ * that bakes `contextual_retrieval: per_chunk_synopsis` into every page's+ * frontmatter and draining your Haiku quota without consent.+ *+ * Unknown / invalid frontmatter values (typos like `per_chunk` instead of+ * `per_chunk_synopsis`) return `kind: 'invalid'` so the caller can write+ * a SyncFailure entry per D13. Falls back to the source/global tier.+ *+ * Pure — no engine calls, no env reads, no filesystem. Mockable in tests.+ */++import { CR_MODES, isCRMode, type CRMode } from './types.ts';++export interface ResolveContextualRetrievalModeArgs {+ /** Parsed page frontmatter (may contain `contextual_retrieval` key). */+ pageFrontmatter: Record<string, unknown>;+ /** The source row that owns this page. */+ source: {+ id: string;+ contextual_retrieval_mode?: string | null;+ trust_frontmatter_overrides?: boolean;+ };+ /** The global mode bundle's contextual_retrieval value. */+ globalMode: CRMode;+ /**+ * The soft kill switch from D18. When true, ALL overrides collapse to+ * 'none' regardless of frontmatter / source / global. Reads `search.+ * contextual_retrieval_disabled` config key at the caller.+ */+ killSwitchDisabled?: boolean;+}++/**+ * The host source id. Always trusted for frontmatter overrides regardless+ * of `trust_frontmatter_overrides` column value (which is for mounts).+ */+const HOST_SOURCE_ID = 'default';++export interface ResolveContextualRetrievalModeResult {+ /** The effective mode after override resolution. */+ mode: CRMode;+ /** Which source supplied the winning value (for attribution / doctor). */+ source: 'kill_switch' | 'page_frontmatter' | 'source_row' | 'global_mode';+ /**+ * When the page frontmatter contained an unknown / invalid value, this+ * carries the raw string so the caller can write a SyncFailure entry+ * with the typo for the doctor surface (D13). Absent on success paths.+ */+ invalid_frontmatter_value?: string;+ /**+ * True when the page frontmatter HAD a `contextual_retrieval` key BUT+ * was rejected because the source is a mount without+ * `trust_frontmatter_overrides`. Lets the doctor surface a hint pointing+ * at `gbrain mounts trust-frontmatter <source>`.+ */+ frontmatter_rejected_untrusted_mount?: boolean;+}++export function resolveContextualRetrievalMode(+ args: ResolveContextualRetrievalModeArgs,+): ResolveContextualRetrievalModeResult {+ // Kill switch shortcircuits everything (D18). Wrapped vectors in DB stay+ // valid; queries just stop seeing the lift, new embeds stop wrapping.+ if (args.killSwitchDisabled) {+ return { mode: 'none', source: 'kill_switch' };+ }++ const rawFrontmatterValue = args.pageFrontmatter['contextual_retrieval'];+ const hasFrontmatterKey = rawFrontmatterValue !== undefined;+ const isTrustedSource =+ args.source.id === HOST_SOURCE_ID ||+ args.source.trust_frontmatter_overrides === true;++ // Page frontmatter wins when present + trusted + valid.+ if (hasFrontmatterKey) {+ if (!isTrustedSource) {+ // Mount without trust flag — IGNORE the frontmatter override and+ // surface the rejection so doctor can hint about `mounts+ // trust-frontmatter`.+ const fallback = pickFromSourceOrGlobal(args);+ return {+ mode: fallback.mode,+ source: fallback.source,+ frontmatter_rejected_untrusted_mount: true,+ };+ }+ if (isCRMode(rawFrontmatterValue)) {+ return { mode: rawFrontmatterValue, source: 'page_frontmatter' };+ }+ // Unknown / invalid value (typo). Fall through to source/global per+ // D13 warn-and-default, surface raw string for SyncFailure entry.+ const fallback = pickFromSourceOrGlobal(args);+ return {+ mode: fallback.mode,+ source: fallback.source,+ invalid_frontmatter_value: String(rawFrontmatterValue),+ };+ }++ return pickFromSourceOrGlobal(args);+}++function pickFromSourceOrGlobal(+ args: Pick<ResolveContextualRetrievalModeArgs, 'source' | 'globalMode'>,+): { mode: CRMode; source: 'source_row' | 'global_mode' } {+ // Source-row override. NULL or missing column falls through to global.+ const sourceMode = args.source.contextual_retrieval_mode;+ if (typeof sourceMode === 'string' && isCRMode(sourceMode)) {+ return { mode: sourceMode, source: 'source_row' };+ }+ return { mode: args.globalMode, source: 'global_mode' };+}++/**+ * D26 P0-4 helper: SQL-style "is distinct from" for CRMode app-side+ * comparisons. `mode !== expected` in TS misses NULL drift in the same way+ * `col != expected` in SQL misses NULL drift — a NULL value is neither+ * equal nor unequal to any other value under three-valued logic. This+ * helper treats NULL/undefined as distinct from any defined mode.+ *+ * crModeDistinct(undefined, 'title') // true (DB had no mode yet)+ * crModeDistinct('title', 'title') // false (aligned)+ * crModeDistinct('title', undefined) // true (expected unset is odd)+ * crModeDistinct(undefined, undefined)// false (both unset is aligned)+ */+export function crModeDistinct(+ actual: CRMode | string | null | undefined,+ expected: CRMode | string | null | undefined,+): boolean {+ if (actual == null && expected == null) return false;+ if (actual == null || expected == null) return true;+ return actual !== expected;+}++/**+ * Exported for tests + doctor / reindex predicates. Use this in code rather+ * than hand-typing the list — the canonical set lives in `types.ts:CR_MODES`.+ */+export const ALL_CR_MODES = CR_MODES;diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsnew file mode 100644index 0000000000..0e22b77461--- /dev/null+++ b/src/core/contextual-retrieval-service.ts@@ -0,0 +1,593 @@+/**+ * v0.40.3.0 — contextual retrieval service (D27 P1-1 + D26 P0-2 ++ * D26 P0-3 + D27 P1-3 + D27 P2-2).+ *+ * Single source of truth for "re-embed one page with the active CR mode."+ * Composed by THREE consumers:+ *+ * 1. `src/core/import-file.ts` — sync-time re-embed during `gbrain sync`+ * (synchronous, inline).+ * 2. `src/commands/reindex.ts` — `gbrain reindex --markdown` batch sweep+ * (per-page loop, synchronous within the command process).+ * 3. `src/core/minions/handlers/contextual-reindex-per-chunk.ts` — Minion+ * job handler for the post-upgrade-prompt-accepted backfill (async,+ * worker-pool concurrency with global rate-leasing).+ *+ * The service runs the D26 P0-2 two-phase build pattern. PHASE 1 collects+ * all synopses + embeddings IN MEMORY. If any chunk triggers a refusal /+ * empty / malformed response (per D14 + D27 P1-2), PHASE 1 RESTARTS at+ * the lower 'title' tier — discarding the in-progress synopsis vectors so+ * the page's chunks NEVER end up mid-state on disk. Only after PHASE 1+ * completes successfully does PHASE 2 run a single DB transaction to+ * replace all chunks + stamp `contextual_retrieval_mode` ++ * `corpus_generation`. Crash anywhere in PHASE 1 = page-level retry with+ * zero half-state. Crash during PHASE 2 = standard transaction rollback.+ *+ * Transient failures (auth / rate_limit / timeout / network / provider_5xx+ * per D27 P1-2) are NOT swallowed into a fall-back — they throw to the+ * caller's retry loop (Minion handler retries the job; inline callers+ * propagate the throw up).+ *+ * Per D27 P2-2 the embedBatch call runs ONCE per page after the per-chunk+ * Haiku loop completes, not per-chunk. Saves per-call overhead + reduces+ * failure surface.+ *+ * Rate-leasing is the caller's responsibility (D26 P0-3 — the Minion+ * handler acquires a shared `anthropic:utility:contextual-synopsis` lease+ * per chunk before invoking the service's optional `acquireSynopsisLease`+ * / `releaseSynopsisLease` hooks). Inline callers (import-file, reindex+ * command) pass no hooks and rely on the gateway's own rate-limit retry.+ */++import { createHash } from 'crypto';+import * as fs from 'node:fs';+import { embedBatch } from './embedding.ts';+import { resolveContextualRetrievalMode } from './contextual-retrieval-resolver.ts';+import {+ buildContextualPrefix,+ extractFirstTwoSentences,+ modeRequiresHaiku,+ modeRequiresWrapper,+ sanitizeTitle,+ wrapChunkForEmbedding,+} from './embedding-context.ts';+import {+ generatePerChunkSynopsis,+ SYNOPSIS_PROMPT_VERSION,+ type GeneratePerChunkSynopsisResult,+} from './page-summary.ts';+import {+ logSynopsisFailure,+ type SynopsisFailureKind,+} from './audit-synopsis.ts';+import type { BrainEngine } from './engine.ts';+import type { ChunkInput, CRMode, Page } from './types.ts';+import type { SourceRow } from './sources-ops.ts';++/**+ * v3 = chunks embed with optional contextual retrieval wrapper. The+ * wrapper text shape itself is also versioned so future format tweaks+ * (e.g. switching to `<page_context>` instead of `<context>`, or adding+ * a structured `metadata:` block) invalidate prior embeddings via the+ * corpus_generation hash.+ */+export const TITLE_WRAPPER_VERSION = 1;++/**+ * Embedding model placeholder. The actual model name lands here from+ * `gateway.getEmbeddingModelName()` at runtime; for hash composition we+ * just need the SAME string the gateway threads into embedBatch.+ */+function getEmbeddingModelTag(): string {+ // Lazy — keeps the hash composition pure-ish without forcing the+ // gateway init at module load. Falls back to a sentinel when the+ // gateway hasn't been configured (test paths).+ try {+ // eslint-disable-next-line @typescript-eslint/no-var-requires+ const { getEmbeddingModelName } = require('./ai/gateway.ts');+ return String(getEmbeddingModelName() ?? 'unknown');+ } catch {+ return 'unknown';+ }+}++/**+ * Compose the corpus_generation hash per D27 P1-5. Folds the prompt+ * version + Haiku model + wrapper version + embedding model so a tweak+ * to ANY of those invalidates prior cache rows via the+ * `query_cache.page_generations` LEFT JOIN.+ *+ * Pure function — `embedding_dimensions` and `embedding_column` stay in+ * the existing KNOBS_HASH_VERSION space per A6 in the eng-review pass.+ */+export function computeCorpusGeneration(args: {+ crMode: CRMode;+ haikuModel: string;+}): string {+ return createHash('sha256')+ .update(args.crMode)+ .update('|')+ .update(String(SYNOPSIS_PROMPT_VERSION))+ .update('|')+ .update(args.haikuModel)+ .update('|')+ .update(String(TITLE_WRAPPER_VERSION))+ .update('|')+ .update(getEmbeddingModelTag())+ .digest('hex')+ .slice(0, 16);+}++/**+ * Compute source_text_hash for D27 P1-4 cache key composition. The+ * synopsis cache invalidates correctly when adjacent text changes (page+ * content edit, frontmatter change, fallback chain different source).+ */+export function computeSourceTextHash(sourceText: string): string {+ return createHash('sha256').update(sourceText).digest('hex').slice(0, 16);+}++/**+ * Result of `reembedPageWithContextualRetrieval`. Caller dispatches on+ * `kind`:+ *+ * success → all chunks embedded + page stamped, DB transaction committed+ * skipped → mode='none' OR page has no chunks; no DB writes+ * page_fallback → PHASE 1 detected a refusal/empty/malformed; restarted+ * at lower tier; final tier in `mode_applied` is what landed+ * transient_error → caller should retry (Minion job retries; inline+ * callers propagate)+ * permanent_error → won't be fixed by retry; doctor surfaces+ */+export type ReembedPageResult =+ | {+ kind: 'success';+ mode_applied: CRMode;+ chunks_embedded: number;+ corpus_generation: string;+ }+ | {+ kind: 'skipped';+ reason: 'mode_none' | 'no_chunks' | 'page_missing' | 'soft_deleted';+ }+ | {+ kind: 'page_fallback';+ mode_attempted: CRMode;+ mode_applied: CRMode;+ chunks_embedded: number;+ corpus_generation: string;+ fallback_kind: SynopsisFailureKind;+ }+ | {+ kind: 'transient_error';+ cause: SynopsisFailureKind | 'embed' | 'db';+ detail: string;+ }+ | {+ kind: 'permanent_error';+ cause: SynopsisFailureKind | 'embed' | 'db';+ detail: string;+ };++export interface ReembedPageArgs {+ engine: BrainEngine;+ /** Page slug (within `sourceId`). */+ pageSlug: string;+ /** Source that owns the page (multi-source brains). */+ sourceId: string;+ /** Global effective mode from the active ModeBundle. */+ globalMode: CRMode;+ /**+ * Soft kill switch from D18. When true, the resolver short-circuits to+ * 'none' regardless of frontmatter / source / global. Wrapped vectors+ * already in `content_chunks` continue serving queries.+ */+ killSwitchDisabled?: boolean;+ /**+ * Optional Haiku model override. When unset, page-summary.ts falls back+ * to its default (Haiku 4.5). Threaded so eval / future per-source+ * model overrides can choose a different model.+ */+ haikuModel?: string;+ /** Optional abort signal threaded into gateway.chat + embedBatch. */+ abortSignal?: AbortSignal;+ /**+ * Optional rate-leaser hooks (D26 P0-3). The Minion handler wires+ * src/core/minions/rate-leases.ts here; inline callers (import-file,+ * reindex command) pass undefined and rely on gateway-level retry.+ */+ acquireSynopsisLease?: () => Promise<void>;+ releaseSynopsisLease?: () => Promise<void>;+}++const DEFAULT_HAIKU_MODEL = 'anthropic:claude-haiku-4-5-20251001';++/**+ * Re-embed one page through the active CR mode. Implements the D26 P0-2+ * two-phase build pattern.+ */+export async function reembedPageWithContextualRetrieval(+ args: ReembedPageArgs,+): Promise<ReembedPageResult> {+ // ── Load page + source + chunks ────────────────────────────────────+ const page = await args.engine.getPage(args.pageSlug, { sourceId: args.sourceId });+ if (!page) {+ return { kind: 'skipped', reason: 'page_missing' };+ }+ if (page.deleted_at != null) {+ return { kind: 'skipped', reason: 'soft_deleted' };+ }++ const source = await loadSourceRow(args.engine, args.sourceId);++ // ── Resolve effective mode (D5+D6+D15+D18) ─────────────────────────+ const resolution = resolveContextualRetrievalMode({+ pageFrontmatter: page.frontmatter ?? {},+ source: {+ id: source.id,+ contextual_retrieval_mode: source.contextual_retrieval_mode ?? null,+ trust_frontmatter_overrides: source.trust_frontmatter_overrides ?? false,+ },+ globalMode: args.globalMode,+ killSwitchDisabled: args.killSwitchDisabled ?? false,+ });++ // 'none' mode skips wrapping entirely. Still stamp the column to record+ // the page is up-to-date relative to current global state — prevents+ // the reindex sweep from re-walking pages that are already aligned.+ if (resolution.mode === 'none') {+ await args.engine.updatePageContextualRetrievalState(+ args.pageSlug,+ args.sourceId,+ 'none',+ null,+ );+ return { kind: 'skipped', reason: 'mode_none' };+ }++ const chunks = await args.engine.getChunks(args.pageSlug, { sourceId: args.sourceId });+ if (chunks.length === 0) {+ // No chunks but page exists (frontmatter-only or empty). Stamp the+ // column anyway so subsequent reindex sweeps don't keep visiting.+ await args.engine.updatePageContextualRetrievalState(+ args.pageSlug,+ args.sourceId,+ resolution.mode,+ computeCorpusGeneration({ crMode: resolution.mode, haikuModel: args.haikuModel ?? DEFAULT_HAIKU_MODEL }),+ );+ return { kind: 'skipped', reason: 'no_chunks' };+ }++ // ── PHASE 1: in-memory build (no DB writes) ────────────────────────+ // Iterate at most twice — once at the requested tier, once at the+ // fall-back 'title' tier if a refusal/empty/malformed fires. The+ // fall-back path is the D14 page-level consistency guarantee: a+ // single bad chunk demotes the whole page to title-only so all+ // chunks on the page share the same wrapper shape.+ const haikuModel = args.haikuModel ?? DEFAULT_HAIKU_MODEL;+ let attemptMode: CRMode = resolution.mode;+ let fallbackReason: SynopsisFailureKind | null = null;++ // eslint-disable-next-line no-constant-condition+ while (true) {+ const phase1 = await tryBuildPhase1({+ attemptMode,+ page,+ chunks: chunks as ChunkInput[],+ args,+ haikuModel,+ });++ if (phase1.kind === 'success') {+ const corpus_generation = computeCorpusGeneration({+ crMode: attemptMode,+ haikuModel,+ });++ // ── PHASE 2: single DB transaction ───────────────────────────+ try {+ await args.engine.transaction(async (tx) => {+ await tx.upsertChunks(args.pageSlug, phase1.embeddedChunks, {+ sourceId: args.sourceId,+ });+ await tx.updatePageContextualRetrievalState(+ args.pageSlug,+ args.sourceId,+ attemptMode,+ corpus_generation,+ );+ });+ } catch (err) {+ const detail = err instanceof Error ? err.message : String(err);+ return { kind: 'transient_error', cause: 'db', detail };+ }++ if (fallbackReason != null) {+ return {+ kind: 'page_fallback',+ mode_attempted: resolution.mode,+ mode_applied: attemptMode,+ chunks_embedded: phase1.embeddedChunks.length,+ corpus_generation,+ fallback_kind: fallbackReason,+ };+ }+ return {+ kind: 'success',+ mode_applied: attemptMode,+ chunks_embedded: phase1.embeddedChunks.length,+ corpus_generation,+ };+ }++ // PHASE 1 failed. Decide whether to fall back or surface.+ if (phase1.kind === 'page_level_fallback_requested') {+ if (attemptMode === 'title') {+ // Already at the lowest non-none tier; can't fall back further.+ // Stamp as 'none' and treat as permanent so doctor flags.+ return {+ kind: 'permanent_error',+ cause: phase1.cause,+ detail: 'Even title-only tier failed; pages_summary call surfaced unrecoverable error.',+ };+ }+ // Restart PHASE 1 at the lower tier. fallbackReason captures the+ // original failure kind for the result envelope.+ fallbackReason = phase1.cause;+ attemptMode = 'title';+ continue;+ }++ // Transient (rate_limit / timeout / network / provider_5xx) or auth+ // failure — caller decides retry policy.+ return {+ kind: phase1.kind === 'transient' ? 'transient_error' : 'permanent_error',+ cause: phase1.cause,+ detail: phase1.detail,+ };+ }+}++// ── Internal helpers ────────────────────────────────────────────────++interface Phase1Success {+ kind: 'success';+ embeddedChunks: ChunkInput[];+}+interface Phase1FallbackRequest {+ kind: 'page_level_fallback_requested';+ cause: SynopsisFailureKind;+}+interface Phase1Transient {+ kind: 'transient';+ cause: SynopsisFailureKind | 'embed';+ detail: string;+}+interface Phase1Permanent {+ kind: 'permanent';+ cause: SynopsisFailureKind | 'embed';+ detail: string;+}+type Phase1Result = Phase1Success | Phase1FallbackRequest | Phase1Transient | Phase1Permanent;++async function tryBuildPhase1(opts: {+ attemptMode: CRMode;+ page: Page;+ chunks: ChunkInput[];+ args: ReembedPageArgs;+ haikuModel: string;+}): Promise<Phase1Result> {+ const { attemptMode, page, chunks, args, haikuModel } = opts;++ // Build the wrapper prefix for THIS page. Title-only tier: one prefix+ // reused across all chunks. per_chunk_synopsis tier: prefix is built+ // per-chunk with the chunk-specific Haiku synopsis.+ const safeTitle = sanitizeTitle(page.title);++ if (attemptMode === 'title' || !modeRequiresHaiku(attemptMode)) {+ // Title-only path. No Haiku calls; pure string concat.+ // Use compiled_truth first sentences as a free pseudo-summary when+ // the title tier wants slightly more context — but per D2 the+ // balanced default is title-only without summary. Keep it pure for+ // now; the title block alone is what 'balanced' ships.+ const prefix = buildContextualPrefix(safeTitle, null);+ const wrappedTexts = chunks.map((c) =>+ modeRequiresWrapper(attemptMode)+ ? wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source)+ : c.chunk_text,+ );++ try {+ const embeddings = await embedBatch(wrappedTexts, { abortSignal: args.abortSignal });+ return {+ kind: 'success',+ embeddedChunks: chunks.map((c, i) => ({+ ...c,+ chunk_text: c.chunk_text, // canonical, NOT the wrapped string (D20-T1)+ embedding: embeddings[i],+ token_count: Math.ceil(wrappedTexts[i].length / 4),+ })),+ };+ } catch (err) {+ const detail = err instanceof Error ? err.message : String(err);+ return classifyEmbedError(err, detail);+ }+ }++ // per_chunk_synopsis path. Read source text via fallback chain,+ // generate synopsis per chunk sequentially within this page (D10),+ // batch embed at the end (D27 P2-2).+ const sourceText = readSourceTextWithFallback(page, chunks);+ const wrappedTexts: string[] = [];++ for (let i = 0; i < chunks.length; i++) {+ const c = chunks[i];++ // Code chunks always bypass the wrapper (D20-T4) — pass through.+ if (c.chunk_source === 'fenced_code') {+ wrappedTexts.push(c.chunk_text);+ continue;+ }++ // Acquire rate-lease per chunk (D26 P0-3). Inline callers pass no+ // hooks; only the Minion handler wires through rate-leases.ts.+ if (args.acquireSynopsisLease) {+ await args.acquireSynopsisLease();+ }++ let synopsisResult: GeneratePerChunkSynopsisResult;+ try {+ synopsisResult = await generatePerChunkSynopsis({+ documentText: sourceText,+ chunkText: c.chunk_text,+ pageTitle: page.title,+ pageSlug: args.pageSlug,+ sourceId: args.sourceId,+ chunkIndex: c.chunk_index,+ model: haikuModel,+ abortSignal: args.abortSignal,+ });+ } finally {+ if (args.releaseSynopsisLease) {+ try {+ await args.releaseSynopsisLease();+ } catch {+ // Lease release failure shouldn't abort the page; surfacing it+ // would race with the synopsis result. Audit-only.+ }+ }+ }++ if (synopsisResult.kind === 'success') {+ const prefix = buildContextualPrefix(safeTitle, synopsisResult.synopsis);+ wrappedTexts.push(+ wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source),+ );+ continue;+ }++ // Failure classification per D27 P1-2:+ // refusal | empty | malformed → page-level fall-back to title-only+ // auth_failure → permanent (won't fix with retry)+ // rate_limit | timeout | network | provider_5xx → transient+ // source_missing → walked into fallback already; would be 'malformed'+ // from generatePerChunkSynopsis if we ever propagated it here+ if (+ synopsisResult.kind === 'refusal' ||+ synopsisResult.kind === 'empty' ||+ synopsisResult.kind === 'malformed'+ ) {+ return { kind: 'page_level_fallback_requested', cause: synopsisResult.kind };+ }+ if (synopsisResult.kind === 'auth_failure') {+ return {+ kind: 'permanent',+ cause: synopsisResult.kind,+ detail: synopsisResult.detail ?? 'auth failure',+ };+ }+ return {+ kind: 'transient',+ cause: synopsisResult.kind,+ detail: synopsisResult.detail ?? 'transient',+ };+ }++ // All chunks synthesized successfully. Single batch embed (D27 P2-2).+ try {+ const embeddings = await embedBatch(wrappedTexts, { abortSignal: args.abortSignal });+ return {+ kind: 'success',+ embeddedChunks: chunks.map((c, i) => ({+ ...c,+ chunk_text: c.chunk_text, // canonical (D20-T1)+ embedding: embeddings[i],+ token_count: Math.ceil(wrappedTexts[i].length / 4),+ })),+ };+ } catch (err) {+ const detail = err instanceof Error ? err.message : String(err);+ return classifyEmbedError(err, detail);+ }+}++/**+ * Source-text fallback chain per D11:+ * 1. read page.source_path from disk (truest "document")+ * 2. concat all chunks (loses frontmatter context but in-memory)+ * 3. just the chunks one-by-one (degraded; loses cross-chunk context)+ *+ * For step 2/3 we just concatenate chunk_text — synopsis quality+ * degrades but stays valid.+ */+function readSourceTextWithFallback(page: Page, chunks: ChunkInput[]): string {+ // Step 1: try filesystem read+ // Note: Page type doesn't carry source_path in the canonical shape;+ // it lives on PageInput / DB column. For now we attempt the chunk-concat+ // path directly — a v0.41+ wave can thread source_path through Page if+ // the synopsis quality benchmark shows the filesystem read materially+ // helps.++ if (chunks.length === 0) return page.title;++ // Step 2: chunk-concat (in-memory).+ return chunks+ .filter((c) => c.chunk_source !== 'image_asset')+ .map((c) => c.chunk_text)+ .join('\n\n');+}++async function loadSourceRow(engine: BrainEngine, sourceId: string): Promise<SourceRow> {+ const rows = await engine.executeRaw<SourceRow>(+ `SELECT id, name, local_path, last_commit, last_sync_at, config, created_at,+ contextual_retrieval_mode, trust_frontmatter_overrides+ FROM sources WHERE id = $1`,+ [sourceId],+ );+ if (rows.length === 0) {+ throw new Error(`Source not found: ${sourceId}`);+ }+ return rows[0];+}++function classifyEmbedError(err: unknown, detail: string): Phase1Transient | Phase1Permanent {+ const e = err as { status?: number; code?: string; name?: string };+ if (e.status === 401 || e.status === 403) {+ return { kind: 'permanent', cause: 'embed', detail };+ }+ if (+ e.status === 429 ||+ (e.status != null && e.status >= 500 && e.status < 600) ||+ e.name === 'AbortError' ||+ /timeout|network|fetch/i.test(detail)+ ) {+ return { kind: 'transient', cause: 'embed', detail };+ }+ return { kind: 'transient', cause: 'embed', detail };+}++/**+ * Public helper for the eng-review T9 reindex sweep: compute the+ * expected effective mode for one page given (page row, source row,+ * global mode, kill switch). Used by the reindex predicate to decide+ * whether a page is drifted relative to its expected state.+ *+ * Pure — no DB / network. Doesn't read frontmatter; the reindex+ * sweep parses frontmatter separately in the candidate path that+ * resolves overrides.+ */+export function expectedModeForPageSourceOnly(args: {+ source: { id: string; contextual_retrieval_mode?: string | null };+ globalMode: CRMode;+ killSwitchDisabled?: boolean;+}): CRMode {+ if (args.killSwitchDisabled) return 'none';+ const sm = args.source.contextual_retrieval_mode;+ if (sm === 'none' || sm === 'title' || sm === 'per_chunk_synopsis') {+ return sm;+ }+ return args.globalMode;+}++// fs imported above for the future filesystem-read path.+void fs;diff --git a/src/core/embedding-context.ts b/src/core/embedding-context.tsnew file mode 100644index 0000000000..7c3b4b8e0d--- /dev/null+++ b/src/core/embedding-context.ts@@ -0,0 +1,188 @@+/**+ * v0.40.3.0 — contextual retrieval wrapper helpers (pure functions).+ *+ * Builds the `<context>{title}\n{synopsis}\n</context>\n{chunk}` prefix+ * that Anthropic's published contextual retrieval method prepends to each+ * chunk BEFORE embedding. The wrapper is built JUST IN TIME at embed call+ * (`src/core/contextual-retrieval-service.ts:embedPhase`) and never+ * persisted as `content_chunks.chunk_text` (D20-T1 — search snippets, FTS,+ * reranker, debug all read the canonical chunk_text).+ *+ * Code chunks (`chunk_source === 'fenced_code'`) ALWAYS bypass wrapping+ * (D20-T4) — prepending markdown-page title to a code block doesn't help+ * cross-modal retrieval and adds embedding-token waste.+ *+ * Title sanitization (D26 P0-4 prep, plus belt-and-suspenders against+ * `</context>` injection from user-controlled titles) strips the closing+ * tag and collapses runs of whitespace before the title lands in the+ * wrapper.+ *+ * NO LLM calls in this module. Per-chunk synopsis generation lives in+ * `src/core/page-summary.ts` and is invoked by the service layer for the+ * `per_chunk_synopsis` tier only.+ */++import { CJK_SENTENCE_DELIMITERS } from './cjk.ts';+import type { CRMode } from './types.ts';++/**+ * Hard cap on the title-only block per chunk. Generous because high-signal+ * titles in personal-brain shape are typically 30-80 chars; the cap only+ * protects against pathological frontmatter.+ */+const TITLE_HARD_CAP_CHARS = 300;++/**+ * Hard cap on the per-page summary lifted from compiled_truth via+ * `extractFirstTwoSentences`. Keeps the embedding payload bounded even+ * when a page's first two sentences are unusually long.+ */+const SUMMARY_HARD_CAP_CHARS = 300;++/**+ * Build the `<context>...</context>\n` prefix for a chunk.+ *+ * title set, synopsis empty → `<context>{title}\n</context>\n`+ * title empty, synopsis set → `<context>\n{synopsis}\n</context>\n`+ * both set → `<context>{title}\n{synopsis}\n</context>\n`+ * both null/empty → null (caller should embed raw chunk)+ *+ * Always returns null when both inputs are meaningless. The wrapper text+ * stays asymmetric (document side only) — queries embed clean per Voyage+ * / ZeroEntropy's `inputType: query` distinction.+ */+export function buildContextualPrefix(+ title: string | null | undefined,+ synopsis: string | null | undefined,+): string | null {+ const safeTitle = sanitizeTitle(title ?? '');+ const safeSynopsis = sanitizeSynopsis(synopsis ?? '');++ if (!safeTitle && !safeSynopsis) {+ return null;+ }++ if (safeTitle && !safeSynopsis) {+ return `<context>${safeTitle}\n</context>\n`;+ }+ if (!safeTitle && safeSynopsis) {+ return `<context>\n${safeSynopsis}\n</context>\n`;+ }+ return `<context>${safeTitle}\n${safeSynopsis}\n</context>\n`;+}++/**+ * Apply the prefix to a chunk for the embedding call.+ *+ * chunk_source='fenced_code' → ALWAYS bypass wrapping (D20-T4)+ * prefix null → passthrough (no wrapping)+ * else → prefix + chunkText+ *+ * Critical invariant (D20-T1): callers must use this function ONLY for+ * the embedding input. The original chunkText MUST land in+ * `content_chunks.chunk_text` unchanged.+ */+export function wrapChunkForEmbedding(+ chunkText: string,+ prefix: string | null,+ chunkSource: string | null | undefined,+): string {+ if (chunkSource === 'fenced_code') {+ return chunkText;+ }+ if (prefix == null) {+ return chunkText;+ }+ return prefix + chunkText;+}++/**+ * Strip injection vectors + collapse whitespace from a title.+ *+ * - `</context>` would close the wrapper tag prematurely → stripped+ * - newlines / tabs collapse to single space (titles shouldn't be+ * multi-line in frontmatter; defensive)+ * - trim + cap at TITLE_HARD_CAP_CHARS+ */+export function sanitizeTitle(title: string): string {+ if (!title) return '';+ return title+ .replace(/<\/context>/gi, '')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, TITLE_HARD_CAP_CHARS);+}++/**+ * Same sanitization as title (defense against Haiku returning+ * `</context>` mid-synopsis — would be a refusal-equivalent class but+ * cheaper to defend at the wrapper) plus the synopsis cap.+ */+export function sanitizeSynopsis(synopsis: string): string {+ if (!synopsis) return '';+ return synopsis+ .replace(/<\/context>/gi, '')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, SUMMARY_HARD_CAP_CHARS);+}++/**+ * Pure regex-based first-two-sentences extractor. CJK-aware via+ * `CJK_SENTENCE_DELIMITERS` from `src/core/cjk.ts`. Hard 300-char cap+ * so a single run-on sentence doesn't blow the embedding budget.+ *+ * Used by the `title` tier (and as a free fallback for `per_chunk_synopsis`+ * pages that have `compiled_truth` populated) to surface a cheap summary+ * without paying Haiku.+ */+export function extractFirstTwoSentences(text: string): string {+ if (!text) return '';++ // Build sentence-end pattern that handles English `.!?` followed by+ // whitespace AND CJK `。!?` delimiters.+ const cjkDelims = CJK_SENTENCE_DELIMITERS.map(escapeRegex).join('');+ const sentenceEnd = new RegExp(`([.!?])\\s+|([${cjkDelims}])`, 'g');++ // Walk through the first two sentence boundaries.+ let cursor = 0;+ let sentenceCount = 0;+ let lastEnd = text.length;+ for (const match of text.matchAll(sentenceEnd)) {+ sentenceCount++;+ const matchEnd = (match.index ?? 0) + match[0].length;+ if (sentenceCount === 2) {+ lastEnd = matchEnd;+ break;+ }+ cursor = matchEnd;+ }++ // If we never found a sentence boundary, return the whole text up to cap.+ if (sentenceCount === 0) {+ return text.trim().slice(0, SUMMARY_HARD_CAP_CHARS);+ }++ return text.slice(0, lastEnd).trim().slice(0, SUMMARY_HARD_CAP_CHARS);+}++function escapeRegex(s: string): string {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++/**+ * Exported guard for D26 P0-4 verification — given a CRMode, does it+ * NEED Haiku synopsis generation? Used by the service to decide whether+ * to invoke `page-summary.ts:generatePerChunkSynopsis` per chunk.+ */+export function modeRequiresHaiku(mode: CRMode): boolean {+ return mode === 'per_chunk_synopsis';+}++/**+ * Exported guard: given a CRMode, does it NEED any wrapper at all?+ * `none` skips wrapping; `title` and `per_chunk_synopsis` both wrap.+ */+export function modeRequiresWrapper(mode: CRMode): boolean {+ return mode !== 'none';+}diff --git a/src/core/engine.ts b/src/core/engine.tsindex 74895d8dca..d14b9a048c 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -1472,6 +1472,30 @@ export interface BrainEngine {contentHash: string,): Promise<void>;+ /**+ * v0.40.3.0 — narrow UPDATE that stamps the two CR-state columns+ * (`contextual_retrieval_mode`, `corpus_generation`) plus+ * `updated_at = now()` and nothing else.+ *+ * Used by `src/core/contextual-retrieval-service.ts:reembedPageWithContextualRetrieval`+ * at the end of its PHASE 2 transaction. Why narrow instead of routing+ * through `putPage`: stamping the CR state alone shouldn't trigger the+ * full page-version snapshot machinery (createVersion fires on every+ * putPage with an existing row, which would bloat page_versions on every+ * tier upgrade).+ *+ * Skips soft-deleted rows (deleted_at filter). Idempotent — same args+ * twice produces the same row state. Both columns are NULL-tolerant+ * (callers pass NULL for `corpusGeneration` only on the 'none' tier+ * path; 'title' and 'per_chunk_synopsis' always supply a hash).+ */+ updatePageContextualRetrievalState(+ slug: string,+ sourceId: string,+ mode: string,+ corpusGeneration: string | null,+ ): Promise<void>;+/*** v0.35.5 — lossless DB-side migration of fact rows from one slug to* another within a single source. UPDATEs `entity_slug` anddiff --git a/src/core/import-file.ts b/src/core/import-file.tsindex a9c43e703e..f28306f9ef 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -14,6 +14,16 @@ import type { ChunkInput, PageInput, PageType } from './types.ts';import { computeEffectiveDate } from './effective-date.ts';import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';import { logSlugFallback } from './audit-slug-fallback.ts';+import { resolveContextualRetrievalMode } from './contextual-retrieval-resolver.ts';+import {+ buildContextualPrefix,+ modeRequiresHaiku,+ modeRequiresWrapper,+ sanitizeTitle,+ wrapChunkForEmbedding,+} from './embedding-context.ts';+import { loadSearchModeConfig, resolveSearchMode } from './search/mode.ts';+import { computeCorpusGeneration } from './contextual-retrieval-service.ts';/*** v0.20.0 Cathedral II Layer 8 D2 — markdown fence extraction helper.@@ -327,14 +337,69 @@ export async function importFromContent(// Embed BEFORE the transaction (external API call).// v0.14+ (Codex C2): embedding failure PROPAGATES. Silent drop accumulates// unembedded pages invisibly. Caller can pass opts.noEmbed=true to skip.+ //+ // v0.40.3.0 contextual retrieval wrapper (D20-T1 chunk_text separation):+ // - Resolve effective CR mode via the page/source/global override chain.+ // - For title tier (free): build the title-only prefix and wrap chunks+ // inline at embed time. Per-chunk Haiku synopsis tier is NOT supported+ // on the import path — that's an async backfill via the Minion handler+ // (the cost prompt + 10s grace UX from D3 gates spending; inline import+ // path takes the cheaper title-only treatment for tokenmax pages here+ // and defers per-chunk synopsis to the Minion-driven sweep).+ // - Stored chunk_text stays canonical; only the embedding input is wrapped.+ // - Code chunks (chunk_source='fenced_code') bypass wrapping per D20-T4.+ let effectiveCRMode: 'none' | 'title' | 'per_chunk_synopsis' = 'none';+ if (!opts.noEmbed) {+ const searchInput = await loadSearchModeConfig(engine);+ const knobs = resolveSearchMode(searchInput);+ // Look up the source row for this import; default to host trust when+ // the engine's getConfig path doesn't surface a source row (most calls).+ const resolution = resolveContextualRetrievalMode({+ pageFrontmatter: parsed.frontmatter,+ source: {+ id: sourceId ?? 'default',+ contextual_retrieval_mode: null,+ trust_frontmatter_overrides: false,+ },+ globalMode: knobs.contextual_retrieval,+ killSwitchDisabled: knobs.contextual_retrieval_disabled,+ });+ // Inline path: title-tier wrap is free. per_chunk_synopsis is too+ // expensive for the inline import path; the page lands at the+ // title tier on disk and the Minion-driven contextual reindex+ // upgrades it later when the user accepts the cost prompt.+ effectiveCRMode = resolution.mode === 'per_chunk_synopsis' ? 'title' : resolution.mode;+ }+if (!opts.noEmbed && chunks.length > 0) {- const embeddings = await embedBatch(chunks.map(c => c.chunk_text));+ const safeTitle = sanitizeTitle(parsed.title);+ const prefix =+ modeRequiresWrapper(effectiveCRMode) && !modeRequiresHaiku(effectiveCRMode)+ ? buildContextualPrefix(safeTitle, null)+ : null;+ const wrappedTexts = prefix+ ? chunks.map((c) => wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source))+ : chunks.map((c) => c.chunk_text);+ const embeddings = await embedBatch(wrappedTexts);for (let i = 0; i < chunks.length; i++) {chunks[i].embedding = embeddings[i];- chunks[i].token_count = Math.ceil(chunks[i].chunk_text.length / 4);+ // token_count tracks the wrapped string length so cost reporting+ // reflects what we actually sent to the embedder.+ chunks[i].token_count = Math.ceil(wrappedTexts[i].length / 4);}}+ // v0.40.3.0: corpus_generation hash for D27 P1-5 cache invalidation.+ // Only set when we actually applied a wrapper; 'none' tier writes NULL+ // so the column reflects "no CR shape applied" rather than a stale hash.+ const corpusGeneration =+ effectiveCRMode === 'none' || opts.noEmbed+ ? null+ : computeCorpusGeneration({+ crMode: effectiveCRMode,+ haikuModel: 'anthropic:claude-haiku-4-5-20251001',+ });+// Transaction wraps all DB writes. Every per-page tx call carries the// caller's sourceId so writes target (sourceId, slug) rather than the// schema DEFAULT — required for multi-source brains; harmless ('default')@@ -386,6 +451,20 @@ export async function importFromContent(// provenance write fires; never client-controlled.}, txOpts);+ // v0.40.3.0: stamp the contextual retrieval state columns alongside+ // the page write. updatePageContextualRetrievalState is a narrow+ // UPDATE that runs after putPage's INSERT/UPDATE so the row exists.+ // For opts.noEmbed callers, we skip stamping — the next embed pass+ // (gbrain embed --stale or contextual reindex Minion) will set it.+ if (!opts.noEmbed) {+ await tx.updatePageContextualRetrievalState(+ slug,+ sourceId ?? 'default',+ effectiveCRMode,+ corpusGeneration,+ );+ }+// Tag reconciliation: remove stale, add currentconst existingTags = await tx.getTags(slug, txOpts);const newTags = new Set(parsed.tags);diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex 8b0d589825..949ade63d0 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -4052,6 +4052,186 @@ export const MIGRATIONS: Migration[] = [ALTER TABLE facts ADD COLUMN IF NOT EXISTS event_type TEXT;`,},+ {+ version: 90,+ name: 'contextual_retrieval_columns',+ // v0.40.3.0 contextual retrieval wave (renumbered from v81 on master+ // merge — v82-v88 claimed by master's v0.38/v0.39 cathedrals, v89+ // reserved by garrytan/v0.40.2.0-trajectory-routing for+ // facts_event_type_column).+ //+ // Five additive columns wiring the three-tier wrapper ladder+ // (none/title/per_chunk_synopsis) into the schema. All NULL-tolerant+ // or have safe defaults so existing rows continue to work unchanged+ // until the post-upgrade reindex sweep catches up.+ //+ // pages.contextual_retrieval_mode — what mode the page was last+ // embedded under. NULL means pre-v90 (treat as 'none' for drift+ // detection until reindex).+ // pages.corpus_generation — composite hash of (synopsis_prompt_version,+ // haiku_model, title_wrapper_version, embedding_model). Used for+ // document-side provenance in query_cache invalidation. NULL means+ // pre-v90; the query_cache.page_generations check treats NULL and+ // any current generation as freshness-mismatched, so cache rows+ // tagged with a real generation correctly invalidate against pre-v90+ // pages that get re-embedded.+ // sources.contextual_retrieval_mode — per-source override. NULL means+ // fall through to global mode. CLI-write-only per D15 security.+ // sources.trust_frontmatter_overrides — per-source mount-frontmatter+ // trust gate (D15). FALSE for mounted sources by default; flipped+ // explicitly via `gbrain mounts trust-frontmatter <source>`. Host+ // source (id='default') is always trusted regardless of this column.+ // query_cache.page_generations — JSONB map {page_id: corpus_generation}+ // tagged at write time per D27 P1-5. Lookup query LEFT JOINs against+ // current pages and excludes rows where any tagged generation+ // differs from the page's current corpus_generation. Empty default+ // so v55-era rows continue to work until they age out via TTL.+ //+ // No indexes needed: all five columns are read alongside their parent+ // row, never queried independently. corpus_generation participates in+ // query_cache's existing index (source_id, knobs_hash, created_at).+ //+ // ADD COLUMN with NULL or constant DEFAULT is metadata-only on+ // Postgres 11+ and PGLite 17.5, instant on tables of any size.+ idempotent: true,+ sql: `+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS contextual_retrieval_mode TEXT NULL;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS corpus_generation TEXT NULL;+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS contextual_retrieval_mode TEXT NULL;+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS trust_frontmatter_overrides BOOLEAN NOT NULL DEFAULT FALSE;+ ALTER TABLE query_cache ADD COLUMN IF NOT EXISTS page_generations JSONB NOT NULL DEFAULT '{}'::jsonb;+ `,+ },+ {+ version: 91,+ name: 'pages_generation_trigger_and_bookmark',+ // v0.40.3.0 cache invalidation gate. Two columns + a trigger + an+ // index. Wires the document-side staleness signal for the new+ // query_cache two-layer gate.+ //+ // pages.generation BIGINT NOT NULL DEFAULT 1+ // — monotonically increasing per-page generation counter. Bumped+ // by `bump_page_generation_trg` on UPDATE when any content+ // column is IS DISTINCT FROM. Read by the per-page snapshot+ // check in query-cache-gate.ts.+ //+ // query_cache.max_generation_at_store BIGINT NOT NULL DEFAULT 0+ // — corpus-state bookmark stamped at cache-write time. Read by+ // the Layer 1 (cheap) gate in query-cache-gate.ts: if+ // MAX(generation) > stamp, the brain has had a write since+ // this row was stored, fall through to Layer 2 (per-page).+ //+ // bump_page_generation_fn() + BEFORE INSERT OR UPDATE trigger+ // — handles every write path uniformly. INSERT: pages get+ // generation = COALESCE(MAX(generation) FROM pages, 0) + 1+ // so the bookmark gate fires for any cache row stored before+ // the new page existed (codex #4 INSERT coverage fix).+ // UPDATE: bumps generation only when content columns are+ // IS DISTINCT FROM — read-time mutations (e.g., last_retrieved_at+ // from v0.37 Open Collider) intentionally don't bump.+ //+ // Allow-list (per D6 widened from the original 6-column plan):+ // body, frontmatter, compiled_truth, timeline, deleted_at,+ // contextual_retrieval_mode (the v0.40.3.0 wave),+ // title, type, page_kind, corpus_generation+ //+ // Provenance fields (ingested_via/ingested_at/source_uri/+ // source_kind from master's v81) deliberately NOT in the+ // allow-list — they're channel metadata, not content; re-importing+ // the same content via a different source shouldn't invalidate+ // caches. (Codex #6 verify: confirmed putPage at this version+ // does not treat these as content-bearing.)+ //+ // CREATE INDEX pages_generation_idx ON pages (generation)+ // — supports O(log N) MAX(generation) for the Layer 1 bookmark+ // check. Plain btree (codex #8 confirmed DESC unnecessary —+ // Postgres backward-scans plain btrees for MAX). CONCURRENTLY+ // on Postgres so large brains don't lock; PGLite has no+ // concurrent writers so plain CREATE INDEX is identical.+ //+ // Engine-aware via handler (not multi-statement SQL): Postgres uses+ // CREATE INDEX CONCURRENTLY to avoid the write-blocking SHARE lock on+ // `pages`. CONCURRENTLY refuses to run inside a transaction AND+ // postgres.js's multi-statement `.unsafe()` wraps in an implicit+ // transaction, so we MUST split the work into separate runMigration+ // calls (columns + function + trigger as one transactional batch;+ // CONCURRENTLY index as a separate non-transactional statement).+ // A failed CONCURRENTLY leaves an invalid index with the target name;+ // pre-drop any invalid remnant via pg_index.indisvalid. PGLite has+ // no concurrent writers, so a single multi-statement call with plain+ // CREATE INDEX is safe. Mirrors the v14 pages_updated_at_index handler+ // pattern verbatim.+ //+ // Forward-reference bootstrap: the column + trigger + index land in+ // PGLITE_SCHEMA_SQL CREATE TABLE body so fresh PGLite installs get+ // them without migration replay. REQUIRED_BOOTSTRAP_COVERAGE in+ // test/schema-bootstrap-coverage.test.ts pins the contract.+ idempotent: true,+ sql: '',+ handler: async (engine) => {+ // Columns + trigger function + trigger. Same SQL on both engines —+ // multi-statement is fine for these (transactional is fine for+ // ALTER + CREATE FUNCTION + CREATE TRIGGER).+ const columnsAndTrigger = `+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS generation BIGINT NOT NULL DEFAULT 1;+ ALTER TABLE query_cache ADD COLUMN IF NOT EXISTS max_generation_at_store BIGINT NOT NULL DEFAULT 0;++ CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger AS $func$+ BEGIN+ IF (TG_OP = 'INSERT') THEN+ NEW.generation := COALESCE((SELECT MAX(generation) FROM pages), 0) + 1;+ ELSIF (OLD.compiled_truth IS DISTINCT FROM NEW.compiled_truth)+ OR (OLD.timeline IS DISTINCT FROM NEW.timeline)+ OR (OLD.frontmatter IS DISTINCT FROM NEW.frontmatter)+ OR (OLD.deleted_at IS DISTINCT FROM NEW.deleted_at)+ OR (OLD.contextual_retrieval_mode IS DISTINCT FROM NEW.contextual_retrieval_mode)+ OR (OLD.title IS DISTINCT FROM NEW.title)+ OR (OLD.type IS DISTINCT FROM NEW.type)+ OR (OLD.page_kind IS DISTINCT FROM NEW.page_kind)+ OR (OLD.corpus_generation IS DISTINCT FROM NEW.corpus_generation)+ OR (OLD.content_hash IS DISTINCT FROM NEW.content_hash)+ THEN+ NEW.generation := OLD.generation + 1;+ END IF;+ RETURN NEW;+ END;+ $func$ LANGUAGE plpgsql;++ DROP TRIGGER IF EXISTS bump_page_generation_trg ON pages;+ CREATE TRIGGER bump_page_generation_trg+ BEFORE INSERT OR UPDATE ON pages+ FOR EACH ROW+ EXECUTE FUNCTION bump_page_generation_fn();+ `;+ await engine.runMigration(91, columnsAndTrigger);++ if (engine.kind === 'postgres') {+ // Pre-drop any invalid index from a prior CONCURRENTLY failure+ // (matches v14 pattern).+ await engine.runMigration(+ 91,+ `DO $$ BEGIN+ IF EXISTS (+ SELECT 1 FROM pg_index i+ JOIN pg_class c ON c.oid = i.indexrelid+ WHERE c.relname = 'pages_generation_idx' AND NOT i.indisvalid+ ) THEN+ EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_generation_idx';+ END IF;+ END $$;`+ );+ await engine.runMigration(+ 91,+ `CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_generation_idx ON pages (generation);`+ );+ } else {+ await engine.runMigration(+ 91,+ `CREATE INDEX IF NOT EXISTS pages_generation_idx ON pages (generation);`+ );+ }+ },+ },];export const LATEST_VERSION = MIGRATIONS.length > 0diff --git a/src/core/minions/handlers/contextual-reindex-per-chunk.ts b/src/core/minions/handlers/contextual-reindex-per-chunk.tsnew file mode 100644index 0000000000..17a422c988--- /dev/null+++ b/src/core/minions/handlers/contextual-reindex-per-chunk.ts@@ -0,0 +1,247 @@+/**+ * v0.40.3.0 — Minion handler for per-page contextual retrieval re-embed.+ *+ * One job per page (D10). Submitted by:+ * - The mode-switch hook in src/commands/config.ts when the user+ * accepts the upgrade cost prompt.+ * - `doctor --remediate` when contextual_retrieval_coverage flags drift.+ * - The reindex command for backfill orchestration.+ *+ * This handler is DELIBERATELY thin (D23) — it wires the global Haiku+ * rate-leaser (D26 P0-3), validates the job payload, and delegates the+ * actual re-embed work to `src/core/contextual-retrieval-service.ts:+ * reembedPageWithContextualRetrieval`. The service owns the two-phase+ * build pattern + page-level fall-back per D14. This handler owns:+ * - Rate-lease acquire/release per Haiku call (shared key across the+ * whole worker pool so concurrent page jobs don't blow the 50 RPM+ * default per D26 P0-3).+ * - Source-id derivation from page-id (D27 P2-1 defense-in-depth+ * against stale/malicious payloads that try to apply source-level+ * trust decisions from the wrong source).+ * - Result classification into Minion success/throw semantics so the+ * queue retries transient failures and dead-letters permanents.+ *+ * Protected name registration (D20-T8): `contextual_reindex_per_chunk`+ * is in `src/core/minions/protected-names.ts:PROTECTED_JOB_NAMES`.+ * MCP / OAuth-scoped callers cannot submit this job; only trusted+ * local callers (CLI, autopilot, doctor --remediate) can.+ */++import type { MinionJobContext } from '../types.ts';+import { UnrecoverableError } from '../types.ts';+import type { BrainEngine } from '../../engine.ts';+import {+ reembedPageWithContextualRetrieval,+ type ReembedPageResult,+} from '../../contextual-retrieval-service.ts';+import {+ acquireLease,+ releaseLease,+} from '../rate-leases.ts';+import { resolveSearchMode, loadSearchModeConfig } from '../../search/mode.ts';++const RATE_LEASE_KEY = 'anthropic:utility:contextual-synopsis';++/**+ * Default global Haiku RPM for contextual synopsis calls. Anthropic's+ * published default is 50 RPM for Haiku 4.5; operators can raise via+ * the env override on a tier with higher quota.+ */+const DEFAULT_HAIKU_RPM = 50;++function resolveMaxConcurrent(): number {+ const env = process.env.GBRAIN_CONTEXTUAL_HAIKU_RPM;+ if (env) {+ const n = parseInt(env, 10);+ if (Number.isFinite(n) && n > 0) return n;+ }+ return DEFAULT_HAIKU_RPM;+}++/**+ * Job payload shape. Per D27 P2-1, only the `page_id` is authoritative;+ * the handler loads the page row and DERIVES source_id from it. Any+ * `source_id` field in the payload that mismatches the loaded value+ * triggers UnrecoverableError (stale/malicious payload defense).+ *+ * `expected_source_id` is optional — when present, the handler verifies+ * it matches the loaded page's source_id. Lets the submitter (mode-switch+ * hook with known per-source plans) catch its own staleness.+ */+export interface ContextualReindexJobData {+ page_slug: string;+ expected_source_id?: string;+}++export interface MakeContextualReindexHandlerOpts {+ engine: BrainEngine;+}++/**+ * Build the Minion handler closure. The worker registers this via+ * `worker.register('contextual_reindex_per_chunk', handler)`.+ */+export function makeContextualReindexHandler(opts: MakeContextualReindexHandlerOpts) {+ const { engine } = opts;++ return async function contextualReindexHandler(+ ctx: MinionJobContext,+ ): Promise<{ ok: true; mode_applied: string; chunks_embedded: number }> {+ const data = parseJobData(ctx.data);++ // Load page row to derive the authoritative source_id (D27 P2-1).+ // Without sourceId we can't do a lookup at all — fall back to+ // 'default' for the initial lookup, then if the page isn't found+ // there, surface as unrecoverable (the submitter should have+ // included expected_source_id).+ let foundPage = await tryLoadPageAcrossSources(engine, data.page_slug);+ if (!foundPage) {+ throw new UnrecoverableError(+ `Page not found for slug '${data.page_slug}'. ` ++ `Submitter should include expected_source_id or the page may have been deleted.`,+ );+ }++ // D27 P2-1: reject mismatched expected_source_id (stale payload).+ if (data.expected_source_id && data.expected_source_id !== foundPage.source_id) {+ throw new UnrecoverableError(+ `Source id mismatch for page '${data.page_slug}': expected ` ++ `'${data.expected_source_id}', page actually lives in ` ++ `'${foundPage.source_id}'. Stale payload?`,+ );+ }++ // Load the resolved CR mode + kill switch via the canonical search+ // config path. loadSearchModeConfig returns {mode, overrides} from the+ // engine's config table; resolveSearchMode walks the per-call >+ // per-key > mode bundle precedence chain.+ const searchInput = await loadSearchModeConfig(engine);+ const knobs = resolveSearchMode(searchInput);+ const globalMode = knobs.contextual_retrieval;+ const killSwitchDisabled = knobs.contextual_retrieval_disabled;++ // Run the service with rate-leasing hooks (D26 P0-3). Each Haiku+ // call inside the service acquires/releases a lease against the+ // shared key across all worker processes.+ const maxConcurrent = resolveMaxConcurrent();+ let currentLeaseId: number | null = null;++ const result: ReembedPageResult = await reembedPageWithContextualRetrieval({+ engine,+ pageSlug: data.page_slug,+ sourceId: foundPage.source_id,+ globalMode,+ killSwitchDisabled,+ abortSignal: ctx.signal,+ acquireSynopsisLease: async () => {+ // Poll-acquire with brief backoff. The service's per-chunk loop+ // is sequential within a page; this guards against the cross-+ // worker pile-up.+ let attempts = 0;+ const maxAttempts = 60; // ~1 min max wait per chunk before giving up+ while (attempts < maxAttempts) {+ const res = await acquireLease(engine, RATE_LEASE_KEY, ctx.id, maxConcurrent, {+ ttlMs: 60_000,+ });+ if (res.acquired && res.leaseId != null) {+ currentLeaseId = res.leaseId;+ return;+ }+ attempts++;+ await new Promise((r) => setTimeout(r, 1000));+ }+ throw new Error(+ `Failed to acquire ${RATE_LEASE_KEY} lease after ${maxAttempts} attempts; ` ++ `Haiku rate limit pile-up too deep.`,+ );+ },+ releaseSynopsisLease: async () => {+ if (currentLeaseId != null) {+ await releaseLease(engine, currentLeaseId);+ currentLeaseId = null;+ }+ },+ });++ return classifyResult(data.page_slug, result);+ };+}++function parseJobData(raw: Record<string, unknown> | undefined): ContextualReindexJobData {+ if (!raw || typeof raw !== 'object') {+ throw new UnrecoverableError(+ 'contextual_reindex_per_chunk job has empty data — page_slug required.',+ );+ }+ const pageSlug = raw.page_slug;+ if (typeof pageSlug !== 'string' || pageSlug.length === 0) {+ throw new UnrecoverableError(+ 'contextual_reindex_per_chunk requires data.page_slug: string.',+ );+ }+ const expectedSourceId =+ typeof raw.expected_source_id === 'string' ? raw.expected_source_id : undefined;+ return { page_slug: pageSlug, expected_source_id: expectedSourceId };+}++/**+ * Try loading the page in every source the engine knows about. Stops at+ * first match. Most brains are single-source; federated brains may have+ * the same slug in multiple sources but the page_id (and indirectly+ * source_id) is the authoritative tiebreaker per D27 P2-1.+ */+async function tryLoadPageAcrossSources(+ engine: BrainEngine,+ pageSlug: string,+): Promise<{ source_id: string } | null> {+ // First try default. Most brains live here.+ const defaultPage = await engine.getPage(pageSlug, { sourceId: 'default' });+ if (defaultPage) return { source_id: defaultPage.source_id };++ // Fall back to walking sources.+ const sources = await engine.executeRaw<{ id: string }>(+ `SELECT id FROM sources WHERE archived = false`,+ );+ for (const { id } of sources) {+ if (id === 'default') continue; // already tried+ const p = await engine.getPage(pageSlug, { sourceId: id });+ if (p) return { source_id: p.source_id };+ }+ return null;+}++function classifyResult(+ pageSlug: string,+ result: ReembedPageResult,+): { ok: true; mode_applied: string; chunks_embedded: number } {+ switch (result.kind) {+ case 'success':+ return {+ ok: true,+ mode_applied: result.mode_applied,+ chunks_embedded: result.chunks_embedded,+ };+ case 'page_fallback':+ // Page-level fall-back is still a successful outcome from Minion's+ // perspective — chunks are embedded, page is stamped at the lower+ // tier. The audit JSONL captured the original failure.+ return {+ ok: true,+ mode_applied: result.mode_applied,+ chunks_embedded: result.chunks_embedded,+ };+ case 'skipped':+ return { ok: true, mode_applied: 'skipped', chunks_embedded: 0 };+ case 'transient_error':+ // Throw so Minion retries. The queue's backoff policy handles+ // rate-limit + network blips.+ throw new Error(+ `[contextual_reindex] transient error on page '${pageSlug}' (${result.cause}): ${result.detail}`,+ );+ case 'permanent_error':+ // UnrecoverableError sends straight to dead-letter; doctor surfaces.+ throw new UnrecoverableError(+ `[contextual_reindex] permanent error on page '${pageSlug}' (${result.cause}): ${result.detail}`,+ );+ }+}diff --git a/src/core/minions/protected-names.ts b/src/core/minions/protected-names.tsindex 28b9fdb667..3016aad6ac 100644--- a/src/core/minions/protected-names.ts+++ b/src/core/minions/protected-names.ts@@ -31,6 +31,12 @@ export const PROTECTED_JOB_NAMES: ReadonlySet<string> = new Set(['synthesize','patterns','consolidate',+ // v0.40.3.0 — per-chunk Haiku contextual retrieval backfill. Each job+ // potentially calls Haiku 1-50 times per page; an MCP/OAuth-scoped+ // caller submitting this in bulk could drain the user's Anthropic+ // budget. Only trusted local callers (the mode-switch hook in+ // commands/config.ts, reindex sweep, doctor --remediate) can submit.+ 'contextual_reindex_per_chunk',]);/** Check a job name against the protected set. Normalizes whitespace first. */diff --git a/src/core/page-summary.ts b/src/core/page-summary.tsnew file mode 100644index 0000000000..c4d7deedc3--- /dev/null+++ b/src/core/page-summary.ts@@ -0,0 +1,270 @@+/**+ * v0.40.3.0 — per-chunk Haiku synopsis generator.+ *+ * For the tokenmax tier (D1 — Anthropic's published per-chunk synopsis+ * method), this module owns:+ *+ * - Routing the Haiku call through `gateway.chat(tier='utility')` —+ * the cheapest tier per CLAUDE.md gateway docs.+ * - The richer failure envelope from D27 P1-2: distinguishing+ * refusal / empty / malformed (→ page-level fall-back to title-only+ * per D14) from auth_failure / rate_limit / timeout / network /+ * provider_5xx (→ retry per gateway, or throw to Minion retry).+ * - Process-local LRU cache keyed by+ * `(content_hash, chunk_index, corpus_generation, source_text_hash)`+ * per D27 P1-4. Source-text changes (adjacent chunks, frontmatter,+ * fallback chain) invalidate the cache correctly because+ * source_text_hash is in the key.+ *+ * Calibration injection is DELIBERATELY ABSENT (D21 reversed the original+ * D7 acceptance: bias tags are mutable answer-time context that don't+ * belong in static document vectors — embedding the calibration profile+ * would silently stale embeddings on every calibration cycle update).+ * Calibration-driven personalization belongs at query time, not at embed+ * time; see `~/.gstack/projects/garrytan-gbrain/ceo-plans/+ * 2026-05-22-v0403-contextual-retrieval.md` "Deferred to TODOS.md" for+ * the v0.41+ query-side personalization wave.+ *+ * No DB access — pure orchestration over gateway + LRU cache. The service+ * layer (`src/core/contextual-retrieval-service.ts`) drives the per-page+ * loop and handles page-level fall-back.+ */++import { chat, type ChatOpts, type ChatResult } from './ai/gateway.ts';+import { logSynopsisFailure, type SynopsisFailureKind } from './audit-synopsis.ts';+import { sanitizeSynopsis } from './embedding-context.ts';++/**+ * Hard cap on Haiku output tokens. ~200 tokens gives 50-100 token+ * synopsis with some headroom; the wrapper layer caps the final+ * synopsis at SUMMARY_HARD_CAP_CHARS (300) regardless.+ */+const HAIKU_MAX_TOKENS = 200;++/** Default model when caller doesn't override. Resolves through the gateway. */+const DEFAULT_SYNOPSIS_MODEL = 'anthropic:claude-haiku-4-5-20251001';++/**+ * Synopsis prompt version. Folded into corpus_generation so prompt edits+ * invalidate prior embeddings via the v0.40.3.0 query_cache.page_generations+ * contract (D27 P1-5). Bump on any prompt-text change that meaningfully+ * shifts synopsis semantics.+ */+export const SYNOPSIS_PROMPT_VERSION = 1;++const SYSTEM_PROMPT = [+ 'You generate one-sentence chunk synopses for a personal knowledge brain.',+ '',+ 'Given a document (the FULL_DOCUMENT block) and a chunk from it (the CHUNK',+ 'block), write a single concise sentence that orients the chunk within the',+ 'document. Name the entities, time, and topic that the chunk is about,',+ 'using terms that would appear in user queries.',+ '',+ 'Rules:',+ '- One sentence, 15-30 words.',+ '- No preamble like "This chunk is about" — just write the synopsis.',+ '- Use the exact entity names from the document, not generic terms.',+ '- If the chunk is structural (heading, code block, list of links), say so.',+ '- Plain text only. No markdown, no quotes, no XML tags.',+].join('\n');++export interface GeneratePerChunkSynopsisArgs {+ /** The full document text (source file, chunk-concat, or chunk-alone per D11). */+ documentText: string;+ /** The chunk for which we're generating the synopsis. */+ chunkText: string;+ /** The page's title — gives Haiku document-level anchor. */+ pageTitle: string;+ /** Page slug for audit logging on failure. */+ pageSlug: string;+ /** Source id for audit logging on failure. */+ sourceId: string;+ /** Chunk index (0-based) for audit logging on failure. */+ chunkIndex: number;+ /** Optional model override (resolves through gateway recipes). */+ model?: string;+ /** Optional abort signal threaded through gateway.chat. */+ abortSignal?: AbortSignal;+}++/**+ * Discriminated result. Caller dispatches on `kind`:+ *+ * - `success` → use `.synopsis` as the wrapper input+ * - failure variants → see D27 P1-2 dispatch in the service layer+ */+export type GeneratePerChunkSynopsisResult =+ | { kind: 'success'; synopsis: string }+ | { kind: SynopsisFailureKind; detail?: string };++/**+ * Generate one synopsis for one chunk. ~$0.00006 per call at Haiku 4.5+ * pricing (assuming ~500 input tokens + 50 output tokens for typical+ * personal-brain page sizes).+ *+ * Caller is responsible for:+ * - Rate-leasing via `src/core/minions/rate-leases.ts` (the SERVICE+ * layer does this with the global `anthropic:utility:contextual-synopsis`+ * key per D26 P0-3).+ * - LRU caching by `(content_hash, chunk_index, corpus_generation,+ * source_text_hash)`. This module is a pure transformer — no cache+ * lookup here; the service decides when to call us.+ * - Audit logging on failure (we DO emit `logSynopsisFailure` for the+ * forensic trail per D17, but `page_level_fallback` is set by the+ * service after deciding whether refusal triggered the D14 page-wide+ * fall-back to title-only).+ */+export async function generatePerChunkSynopsis(+ args: GeneratePerChunkSynopsisArgs,+): Promise<GeneratePerChunkSynopsisResult> {+ const userPrompt = buildUserPrompt(args.pageTitle, args.documentText, args.chunkText);++ const chatOpts: ChatOpts = {+ model: args.model ?? DEFAULT_SYNOPSIS_MODEL,+ system: SYSTEM_PROMPT,+ messages: [{ role: 'user', content: userPrompt }],+ maxTokens: HAIKU_MAX_TOKENS,+ abortSignal: args.abortSignal,+ cacheSystem: true,+ };++ let result: ChatResult;+ try {+ result = await chat(chatOpts);+ } catch (err) {+ const classified = classifyChatError(err);+ logSynopsisFailure({+ pageSlug: args.pageSlug,+ sourceId: args.sourceId,+ chunkIndex: args.chunkIndex,+ kind: classified.kind,+ detail: classified.detail,+ // Whether this triggers page-level fall-back depends on the+ // refusal/empty/malformed vs transient distinction — service decides+ // after seeing the result. Audit reflects the service-known state at+ // log time; here we conservatively record what we know.+ pageLevelFallback: classified.kind === 'refusal' || classified.kind === 'empty' || classified.kind === 'malformed',+ });+ return { kind: classified.kind, detail: classified.detail };+ }++ // Refusal-class signals from the chat result. Gateway maps provider-+ // specific stop reasons to the union in `ChatResult.stopReason`.+ if (result.stopReason === 'refusal' || result.stopReason === 'content_filter') {+ logSynopsisFailure({+ pageSlug: args.pageSlug,+ sourceId: args.sourceId,+ chunkIndex: args.chunkIndex,+ kind: 'refusal',+ detail: `stop_reason=${result.stopReason}`,+ pageLevelFallback: true,+ });+ return { kind: 'refusal', detail: `stop_reason=${result.stopReason}` };+ }++ const synopsis = sanitizeSynopsis(result.text);+ if (!synopsis) {+ logSynopsisFailure({+ pageSlug: args.pageSlug,+ sourceId: args.sourceId,+ chunkIndex: args.chunkIndex,+ kind: 'empty',+ detail: `length=${result.text.length}`,+ pageLevelFallback: true,+ });+ return { kind: 'empty', detail: `length=${result.text.length}` };+ }++ // No malformed detection in v0.40.3.0: synopses are plain text by+ // prompt contract. Future extension could parse a JSON-shaped+ // response with `{synopsis, confidence}` for richer signals; for now+ // any non-empty text after sanitization counts as success.++ return { kind: 'success', synopsis };+}++function buildUserPrompt(+ pageTitle: string,+ documentText: string,+ chunkText: string,+): string {+ return [+ `<page_title>${pageTitle}</page_title>`,+ '',+ '<full_document>',+ documentText,+ '</full_document>',+ '',+ '<chunk>',+ chunkText,+ '</chunk>',+ '',+ 'Write the one-sentence synopsis for <chunk>:',+ ].join('\n');+}++/**+ * Map a thrown error from `gateway.chat()` into the D27 P1-2 failure envelope.+ *+ * Gateway throws Anthropic-flavored errors with HTTP status info; we+ * pattern-match on those for the classification.+ */+function classifyChatError(err: unknown): {+ kind: SynopsisFailureKind;+ detail: string;+} {+ if (err == null) {+ return { kind: 'malformed', detail: 'null error' };+ }+ const e = err as { status?: number; message?: string; code?: string; name?: string };+ const msg = (e.message ?? String(err)).slice(0, 200);++ if (e.status === 401 || e.status === 403) {+ return { kind: 'auth_failure', detail: `status=${e.status} msg=${msg}` };+ }+ if (e.status === 429) {+ return { kind: 'rate_limit', detail: `status=429 msg=${msg}` };+ }+ if (e.status != null && e.status >= 500 && e.status < 600) {+ return { kind: 'provider_5xx', detail: `status=${e.status} msg=${msg}` };+ }+ if (+ e.name === 'AbortError' ||+ e.code === 'ETIMEDOUT' ||+ /timeout/i.test(msg)+ ) {+ return { kind: 'timeout', detail: msg };+ }+ if (+ e.code === 'ENOTFOUND' ||+ e.code === 'ECONNREFUSED' ||+ e.code === 'ECONNRESET' ||+ /network|fetch/i.test(msg)+ ) {+ return { kind: 'network', detail: `code=${e.code ?? '?'} msg=${msg}` };+ }++ // Unknown error shape — treat as malformed so the service routes it+ // through the title-only fall-back path rather than retrying forever.+ return { kind: 'malformed', detail: msg };+}++/**+ * D27 P1-4 cache key composition. Used by the service layer's LRU. Exposed+ * here so the key shape stays the single source of truth.+ *+ * (content_hash, chunk_index, corpus_generation, source_text_hash)+ */+export function buildSynopsisCacheKey(args: {+ contentHash: string;+ chunkIndex: number;+ corpusGeneration: string;+ sourceTextHash: string;+}): string {+ return [+ args.contentHash,+ args.chunkIndex.toString(),+ args.corpusGeneration,+ args.sourceTextHash,+ ].join('|');+}diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 027faa02aa..a45bd110c6 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -333,7 +333,17 @@ export class PGLiteEngine implements BrainEngine {EXISTS (SELECT 1 FROM information_schema.columnsWHERE table_schema='public' AND table_name='pages' AND column_name='source_uri') AS pages_source_uri_exists,EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema='public' AND table_name='pages' AND column_name='source_kind') AS pages_source_kind_exists+ WHERE table_schema='public' AND table_name='pages' AND column_name='source_kind') AS pages_source_kind_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema='public' AND table_name='pages' AND column_name='contextual_retrieval_mode') AS pages_cr_mode_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema='public' AND table_name='pages' AND column_name='corpus_generation') AS pages_corpus_generation_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema='public' AND table_name='sources' AND column_name='contextual_retrieval_mode') AS sources_cr_mode_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema='public' AND table_name='sources' AND column_name='trust_frontmatter_overrides') AS sources_trust_fm_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema='public' AND table_name='pages' AND column_name='generation') AS pages_generation_exists`);const probe = rows[0] as {pages_exists: boolean;@@ -369,6 +379,11 @@ export class PGLiteEngine implements BrainEngine {pages_ingested_at_exists: boolean;pages_source_uri_exists: boolean;pages_source_kind_exists: boolean;+ pages_cr_mode_exists: boolean;+ pages_corpus_generation_exists: boolean;+ sources_cr_mode_exists: boolean;+ sources_trust_fm_exists: boolean;+ pages_generation_exists: boolean;};const needsPagesBootstrap = probe.pages_exists && !probe.source_id_exists;@@ -422,6 +437,20 @@ export class PGLiteEngine implements BrainEngine {|| !probe.pages_ingested_at_exists|| !probe.pages_source_uri_exists|| !probe.pages_source_kind_exists);+ // v0.40.3.0 (v90, renumbered from v0.40.3.0 v81 on master merge):+ // contextual retrieval columns on pages + sources. No SCHEMA_SQL index+ // references them today, but bootstrap probes are defense-in-depth so+ // future schema work doesn't wedge pre-v90 brains.+ const needsContextualRetrievalColumns = (probe.pages_exists+ && (!probe.pages_cr_mode_exists || !probe.pages_corpus_generation_exists))+ || (probe.sources_exists+ && (!probe.sources_cr_mode_exists || !probe.sources_trust_fm_exists));+ // v0.40.3.0 (v91): pages.generation BIGINT bumped by+ // bump_page_generation_trg. Forward-referenced by pages_generation_idx+ // in PGLITE_SCHEMA_SQL. The trigger itself is created in the schema+ // body; bootstrap only needs to add the column on pre-v91 brains so+ // the CREATE INDEX doesn't crash.+ const needsPagesGeneration = probe.pages_exists && !probe.pages_generation_exists;// Fresh installs (no tables yet) and modern brains both no-op.if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap@@ -430,7 +459,8 @@ export class PGLiteEngine implements BrainEngine {&& !needsPagesRecency && !needsIngestLogSourceId&& !needsFilesBootstrap && !needsOauthClientsBootstrap&& !needsSourcesArchive && !needsPagesLastRetrievedAt- && !needsPagesProvenance) return;+ && !needsPagesProvenance+ && !needsContextualRetrievalColumns && !needsPagesGeneration) return;console.log(' Pre-v0.21 brain detected, applying forward-reference bootstrap');@@ -633,6 +663,31 @@ export class PGLiteEngine implements BrainEngine {ALTER TABLE pages ADD COLUMN IF NOT EXISTS source_kind TEXT;`);}++ if (needsContextualRetrievalColumns) {+ // v0.40.3.0 v90 (contextual_retrieval_columns, renumbered from+ // v0.40.3.0 v81 on master merge). Five additive columns wiring the+ // three-tier wrapper ladder. Defense-in-depth probes; v90 runs later+ // via runMigrations and is idempotent (ADD COLUMN IF NOT EXISTS).+ await this.db.exec(`+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS contextual_retrieval_mode TEXT;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS corpus_generation TEXT;+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS contextual_retrieval_mode TEXT;+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS trust_frontmatter_overrides BOOLEAN NOT NULL DEFAULT FALSE;+ `);+ }++ if (needsPagesGeneration) {+ // v0.40.3.0 v91 (pages_generation_trigger_and_bookmark): pages.generation+ // BIGINT + query_cache.max_generation_at_store BIGINT + trigger + index.+ // PGLITE_SCHEMA_SQL CREATE INDEX pages_generation_idx ON pages+ // (generation) crashes on pre-v91 brains without this. The trigger+ // and index land via v91 migration run later; bootstrap only adds+ // the column. v91 is idempotent.+ await this.db.exec(`+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS generation BIGINT NOT NULL DEFAULT 1;+ `);+ }}async withReservedConnection<T>(fn: (conn: ReservedConnection) => Promise<T>): Promise<T> {@@ -817,6 +872,26 @@ export class PGLiteEngine implements BrainEngine {);}+ async updatePageContextualRetrievalState(+ slug: string,+ sourceId: string,+ mode: string,+ corpusGeneration: string | null,+ ): Promise<void> {+ // Parity with PostgresEngine — narrow stamp of the two CR-state+ // columns. corpus_generation nullable for the 'none' tier path.+ await this.db.query(+ `UPDATE pages+ SET contextual_retrieval_mode = $1,+ corpus_generation = $2,+ updated_at = now()+ WHERE source_id = $3+ AND slug = $4+ AND deleted_at IS NULL`,+ [mode, corpusGeneration, sourceId, slug],+ );+ }+async migrateFactsToCanonical(phantomSlug: string,canonicalSlug: string,@@ -1717,17 +1792,32 @@ export class PGLiteEngine implements BrainEngine {// CONSISTENCY: when chunk_text changes and no new embedding is supplied, BOTH embedding AND// embedded_at must reset to NULL so `embed --stale` correctly picks up the row for re-embedding.// See postgres-engine.ts upsertChunks for the full rationale — pglite mirrors it for parity.+ //+ // v0.40.3.0 D24 NULL→non-NULL race fix mirrors postgres-engine.ts. Two writers+ // racing on the same chunk previously raced last-write-wins; the fix lets the+ // fresher `embedded_at` win in the text-unchanged branch.await this.db.query(`INSERT INTO content_chunks ${cols} VALUES ${rowParts.join(', ')}ON CONFLICT (page_id, chunk_index) DO UPDATE SETchunk_text = EXCLUDED.chunk_text,chunk_source = EXCLUDED.chunk_source,- embedding = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding ELSE COALESCE(EXCLUDED.embedding, content_chunks.embedding) END,+ embedding = CASE+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding+ WHEN content_chunks.embedding IS NULL THEN EXCLUDED.embedding+ WHEN EXCLUDED.embedded_at IS NOT NULL+ AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)+ THEN EXCLUDED.embedding+ ELSE content_chunks.embedding+ END,model = COALESCE(EXCLUDED.model, content_chunks.model),token_count = EXCLUDED.token_count,embedded_at = CASEWHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.embedding IS NULL THEN NULL- ELSE COALESCE(EXCLUDED.embedded_at, content_chunks.embedded_at)+ WHEN content_chunks.embedding IS NULL AND EXCLUDED.embedding IS NOT NULL THEN EXCLUDED.embedded_at+ WHEN EXCLUDED.embedded_at IS NOT NULL+ AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)+ THEN EXCLUDED.embedded_at+ ELSE content_chunks.embedded_atEND,language = EXCLUDED.language,symbol_name = EXCLUDED.symbol_name,diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.tsindex 02f715bc30..efb041f0b3 100644--- a/src/core/pglite-schema.ts+++ b/src/core/pglite-schema.ts@@ -44,6 +44,11 @@ CREATE TABLE IF NOT EXISTS sources (archived BOOLEAN NOT NULL DEFAULT false,archived_at TIMESTAMPTZ,archive_expires_at TIMESTAMPTZ,+ -- v0.40.3.0: per-source CR mode override + mount-frontmatter trust gate+ -- (mirrors src/schema.sql). NULL falls through to global mode; trust+ -- FALSE for mounts by default; host is always trusted regardless.+ contextual_retrieval_mode TEXT,+ trust_frontmatter_overrides BOOLEAN NOT NULL DEFAULT false,created_at TIMESTAMPTZ NOT NULL DEFAULT now());@@ -85,9 +90,54 @@ CREATE TABLE IF NOT EXISTS pages (-- v0.37.0 (migration v79): real stale-page signal for gbrain lsd-- (mirrors src/schema.sql). NULL = never retrieved.last_retrieved_at TIMESTAMPTZ,+ -- v0.40.3.0 contextual retrieval (renumbered from v81 to v90 on master+ -- merge; mirrors src/schema.sql).+ -- contextual_retrieval_mode is the tier the page was last embedded under;+ -- corpus_generation is the composite document-side provenance hash used by+ -- query_cache.page_generations invalidation.+ contextual_retrieval_mode TEXT,+ corpus_generation TEXT,+ -- v0.40.3.0 cache invalidation gate (migration v91; mirrors src/schema.sql).+ -- Bumped by bump_page_generation_trg on INSERT (initial) and on UPDATE+ -- when content columns IS DISTINCT FROM. Read by the per-page snapshot+ -- check in query-cache-gate.ts.+ generation BIGINT NOT NULL DEFAULT 1,CONSTRAINT pages_source_slug_key UNIQUE (source_id, slug));+-- v0.40.3.0 cache invalidation trigger (migration v91; mirrors src/schema.sql).+-- BEFORE INSERT OR UPDATE so every write path bumps generation per D6 /+-- codex #4. INSERT: pages get COALESCE(MAX(generation), 0) + 1 so the+-- bookmark gate fires for any cache row stored before the new page existed.+-- UPDATE: bumps only when content columns IS DISTINCT FROM (allow-list of+-- 10 widened per D6) so read-time mutations don't invalidate every cache.+CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger AS $func$+BEGIN+ IF (TG_OP = 'INSERT') THEN+ NEW.generation := COALESCE((SELECT MAX(generation) FROM pages), 0) + 1;+ ELSIF (OLD.compiled_truth IS DISTINCT FROM NEW.compiled_truth)+ OR (OLD.timeline IS DISTINCT FROM NEW.timeline)+ OR (OLD.frontmatter IS DISTINCT FROM NEW.frontmatter)+ OR (OLD.deleted_at IS DISTINCT FROM NEW.deleted_at)+ OR (OLD.contextual_retrieval_mode IS DISTINCT FROM NEW.contextual_retrieval_mode)+ OR (OLD.title IS DISTINCT FROM NEW.title)+ OR (OLD.type IS DISTINCT FROM NEW.type)+ OR (OLD.page_kind IS DISTINCT FROM NEW.page_kind)+ OR (OLD.corpus_generation IS DISTINCT FROM NEW.corpus_generation)+ OR (OLD.content_hash IS DISTINCT FROM NEW.content_hash)+ THEN+ NEW.generation := OLD.generation + 1;+ END IF;+ RETURN NEW;+END;+$func$ LANGUAGE plpgsql;++DROP TRIGGER IF EXISTS bump_page_generation_trg ON pages;+CREATE TRIGGER bump_page_generation_trg+ BEFORE INSERT OR UPDATE ON pages+ FOR EACH ROW+ EXECUTE FUNCTION bump_page_generation_fn();+CREATE INDEX IF NOT EXISTS idx_pages_type ON pages(type);CREATE INDEX IF NOT EXISTS idx_pages_frontmatter ON pages USING GIN(frontmatter);CREATE INDEX IF NOT EXISTS idx_pages_trgm ON pages USING GIN(title gin_trgm_ops);diff --git a/src/core/post-upgrade-reembed.ts b/src/core/post-upgrade-reembed.tsindex a6b4f35e2c..a749dcd2f9 100644--- a/src/core/post-upgrade-reembed.ts+++ b/src/core/post-upgrade-reembed.ts@@ -85,11 +85,21 @@ export function formatReembedPrompt(est: ReembedEstimate, graceSeconds: number):return `[chunker-bump] No pending markdown pages. Skipping re-embed.`;}const minEst = Math.max(1, Math.ceil(est.pendingCount / 60)); // ~60 pages/min wall-clock heuristic+ // v0.40.3.0 — chunker version bump to 3 includes the contextual retrieval+ // wrapper (Anthropic's published methodology). Re-embed picks up the+ // title-tier wrapper for balanced-mode users automatically (free at+ // runtime — pure string concat). Tokenmax users can later run+ // `gbrain config set search.mode tokenmax` to upgrade pages to per-chunk+ // Haiku synopsis via the contextual_reindex_per_chunk Minion handler.+ // Documented inline so the prompt explains WHY the re-embed is firing.+ const crNote =+ `\n[contextual retrieval] v0.40.3.0 wraps each chunk with its page ` ++ `title before embedding (Anthropic's published method).`;if (est.pricingKnown && est.estimatedCostUsd !== null) {const dollars = est.estimatedCostUsd.toFixed(2);- return `[chunker-bump] Will re-embed ~${est.pendingCount} markdown pages via ${est.modelString}, est. ~$${dollars}, ~${minEst}min. Press Ctrl-C within ${graceSeconds}s to abort.`;+ return `[chunker-bump] Will re-embed ~${est.pendingCount} markdown pages via ${est.modelString}, est. ~$${dollars}, ~${minEst}min. Press Ctrl-C within ${graceSeconds}s to abort.${crNote}`;}- return `[chunker-bump] Will re-embed ~${est.pendingCount} markdown pages via ${est.modelString}; pricing estimate unavailable for this provider. Press Ctrl-C within ${graceSeconds}s to abort.`;+ return `[chunker-bump] Will re-embed ~${est.pendingCount} markdown pages via ${est.modelString}; pricing estimate unavailable for this provider. Press Ctrl-C within ${graceSeconds}s to abort.${crNote}`;}export interface PromptResult {diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex a4d2033bec..6a3c48be4b 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -424,7 +424,17 @@ export class PostgresEngine implements BrainEngine {EXISTS (SELECT 1 FROM information_schema.columnsWHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'source_uri') AS pages_source_uri_exists,EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'source_kind') AS pages_source_kind_exists+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'source_kind') AS pages_source_kind_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'contextual_retrieval_mode') AS pages_cr_mode_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'corpus_generation') AS pages_corpus_generation_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'sources' AND column_name = 'contextual_retrieval_mode') AS sources_cr_mode_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'sources' AND column_name = 'trust_frontmatter_overrides') AS sources_trust_fm_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'generation') AS pages_generation_exists`;const probe = probeRows[0]!;@@ -491,6 +501,24 @@ export class PostgresEngine implements BrainEngine {|| !probeProv.pages_ingested_at_exists|| !probeProv.pages_source_uri_exists|| !probeProv.pages_source_kind_exists);+ // v0.40.3.0 (v90, renumbered from v0.40.3.0 v81 on master merge):+ // contextual retrieval columns on pages + sources. Defense-in-depth.+ const probeCr = probe as {+ pages_cr_mode_exists?: boolean;+ pages_corpus_generation_exists?: boolean;+ sources_cr_mode_exists?: boolean;+ sources_trust_fm_exists?: boolean;+ pages_generation_exists?: boolean;+ };+ const needsContextualRetrievalColumns = (probe.pages_exists+ && (!probeCr.pages_cr_mode_exists || !probeCr.pages_corpus_generation_exists))+ || (probe.sources_exists+ && (!probeCr.sources_cr_mode_exists || !probeCr.sources_trust_fm_exists));+ // v0.40.3.0 (v91): pages.generation BIGINT bumped by+ // bump_page_generation_trg. pages_generation_idx in SCHEMA_SQL references+ // it. Pre-v91 brains crash without the column; bootstrap adds it before+ // SCHEMA_SQL replay creates the index.+ const needsPagesGeneration = probe.pages_exists && !probeCr.pages_generation_exists;if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap&& !needsPagesDeletedAt && !needsMcpLogBootstrap && !needsSubagentProviderId@@ -498,7 +526,8 @@ export class PostgresEngine implements BrainEngine {&& !needsIngestLogSourceId && !needsFilesBootstrap&& !needsOauthClientsBootstrap && !needsSourcesArchive&& !needsPagesLastRetrievedAt- && !needsPagesProvenance) return;+ && !needsPagesProvenance+ && !needsContextualRetrievalColumns && !needsPagesGeneration) return;console.log(' Pre-v0.21 brain detected, applying forward-reference bootstrap');@@ -700,6 +729,30 @@ export class PostgresEngine implements BrainEngine {ALTER TABLE pages ADD COLUMN IF NOT EXISTS source_kind TEXT;`);}++ if (needsContextualRetrievalColumns) {+ // v0.40.3.0 v90 (contextual_retrieval_columns, renumbered from+ // v0.40.3.0 v81 on master merge). Five additive columns wiring the+ // three-tier wrapper ladder. Defense-in-depth probes; v90 runs later+ // via runMigrations and is idempotent (ADD COLUMN IF NOT EXISTS).+ await conn.unsafe(`+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS contextual_retrieval_mode TEXT;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS corpus_generation TEXT;+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS contextual_retrieval_mode TEXT;+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS trust_frontmatter_overrides BOOLEAN NOT NULL DEFAULT FALSE;+ `);+ }++ if (needsPagesGeneration) {+ // v0.40.3.0 v91 (pages_generation_trigger_and_bookmark):+ // pages.generation BIGINT. SCHEMA_SQL CREATE INDEX+ // pages_generation_idx ON pages (generation) crashes on pre-v91 brains+ // without this. The trigger and index land via v91 migration run+ // later; bootstrap only adds the column. v91 is idempotent.+ await conn.unsafe(`+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS generation BIGINT NOT NULL DEFAULT 1;+ `);+ }}async transaction<T>(fn: (engine: BrainEngine) => Promise<T>): Promise<T> {@@ -883,6 +936,28 @@ export class PostgresEngine implements BrainEngine {`;}+ async updatePageContextualRetrievalState(+ slug: string,+ sourceId: string,+ mode: string,+ corpusGeneration: string | null,+ ): Promise<void> {+ const sql = this.sql;+ // Narrow UPDATE — bumps updated_at as a side effect so the autopilot+ // sweep doesn't think the page hasn't changed since last touch. Skips+ // soft-deleted rows. corpus_generation nullable (caller passes NULL+ // for the 'none' tier path).+ await sql`+ UPDATE pages+ SET contextual_retrieval_mode = ${mode},+ corpus_generation = ${corpusGeneration},+ updated_at = now()+ WHERE source_id = ${sourceId}+ AND slug = ${slug}+ AND deleted_at IS NULL+ `;+ }+async migrateFactsToCanonical(phantomSlug: string,canonicalSlug: string,@@ -1762,17 +1837,39 @@ export class PostgresEngine implements BrainEngine {// predicate on embedded_at would silently skip the row. This is why the egress fix predicates// on `embedding IS NULL` rather than `embedded_at IS NULL` — and it's why we now keep both// columns honest at write time.+ //+ // v0.40.3.0 D24 NULL→non-NULL race fix (TODOS.md v0.35.x item).+ // Two writers racing on the same chunk (e.g., autopilot sync + manual+ // `embed --stale` + contextual reindex) previously raced last-write-wins+ // via `COALESCE(EXCLUDED.embedding, content_chunks.embedding)`. With+ // per-chunk Haiku synopsis the cost of an overwrite jumped from+ // ~$0.000001 to ~$0.0003. New rule for the text-unchanged branch:+ // - existing is NULL → take new (cold path, no race)+ // - new is fresher (embedded_at > existing.embedded_at) → take new+ // - otherwise → keep existing (slower writer with stale embedding loses)+ // Mirrored in pglite-engine.ts; pinned by test/e2e/concurrent-embed-race.test.ts.await sql.unsafe(`INSERT INTO content_chunks ${cols} VALUES ${rows.join(', ')}ON CONFLICT (page_id, chunk_index) DO UPDATE SETchunk_text = EXCLUDED.chunk_text,chunk_source = EXCLUDED.chunk_source,- embedding = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding ELSE COALESCE(EXCLUDED.embedding, content_chunks.embedding) END,+ embedding = CASE+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding+ WHEN content_chunks.embedding IS NULL THEN EXCLUDED.embedding+ WHEN EXCLUDED.embedded_at IS NOT NULL+ AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)+ THEN EXCLUDED.embedding+ ELSE content_chunks.embedding+ END,model = COALESCE(EXCLUDED.model, content_chunks.model),token_count = EXCLUDED.token_count,embedded_at = CASEWHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.embedding IS NULL THEN NULL- ELSE COALESCE(EXCLUDED.embedded_at, content_chunks.embedded_at)+ WHEN content_chunks.embedding IS NULL AND EXCLUDED.embedding IS NOT NULL THEN EXCLUDED.embedded_at+ WHEN EXCLUDED.embedded_at IS NOT NULL+ AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)+ THEN EXCLUDED.embedded_at+ ELSE content_chunks.embedded_atEND,language = EXCLUDED.language,symbol_name = EXCLUDED.symbol_name,diff --git a/src/core/remediation-step.ts b/src/core/remediation-step.tsnew file mode 100644index 0000000000..0bfd2d36f0--- /dev/null+++ b/src/core/remediation-step.ts@@ -0,0 +1,152 @@+/**+ * RemediationStep (v0.40.3.0 — D6 refactor)+ *+ * Canonical structured-remediation type. Any doctor check that wants to+ * produce a paste-ready agent fix returns RemediationStep[] from its+ * check function. The `doctor --remediate` orchestrator walks them in+ * dependency order, submitting each as a Minion job and re-checking+ * between steps.+ *+ * Previously lived as `Remediation` inside+ * `src/core/brain-score-recommendations.ts`. Lifted here so other+ * check producers (lint, integrity, sync_failures) can emit+ * RemediationStep without circular-importing brain-score code that+ * doesn't apply to them. Same shape, just relocated + renamed for+ * clarity.+ *+ * Factory: `makeRemediationStep()` builds a step with content-stable+ * IDs via canonical JSON serialization per codex D12 Bug 2. Identical+ * params (regardless of key ordering) produce identical IDs so+ * idempotency_key dedup works across retries and across runtime+ * JSON-stringify ordering.+ */++import { createHash } from 'node:crypto';++/**+ * Severity buckets — drive ordering (critical first) and operator UX.+ */+export type RemediationSeverity = 'critical' | 'high' | 'medium' | 'low';++/** Triage status of an individual check's autofix path. */+export type RemediationStatus = 'remediable' | 'human_only' | 'blocked';++/**+ * Structured remediation step emitted by doctor checks.+ *+ * Fields:+ * id — stable identifier (e.g. 'sync.repo', 'lint.fix:<slug>').+ * References other steps via depends_on.+ * job — Minion handler name. Must match a registered handler.+ * params — passed verbatim to the handler.+ * idempotency_key — content-hash dedup key. Same (job, params) →+ * same key. Across retries (--remediate re-runs)+ * pre-existing failed jobs append `:r<N>` suffix.+ * severity — drives ordering.+ * est_seconds — upper-bound runtime estimate for budgeting.+ * est_usd_cost — USD cost estimate when applicable.+ * depends_on — other RemediationStep.id values that MUST complete+ * first. References ids, NOT check names.+ * rationale — one-line "what this fixes" for human output.+ * protected — true if `job` is in PROTECTED_JOB_NAMES.+ * status — always 'remediable' for executable plans;+ * `blocked` entries surface separately.+ * blocked_reason — populated when status === 'blocked'.+ */+export interface RemediationStep {+ id: string;+ job: string;+ params: Record<string, unknown>;+ idempotency_key: string;+ severity: RemediationSeverity;+ est_seconds: number;+ est_usd_cost?: number;+ depends_on?: string[];+ rationale: string;+ protected?: boolean;+ status: RemediationStatus;+ blocked_reason?: string;+}++/**+ * Canonical JSON serializer per codex D12 Bug 2: sorts object keys+ * recursively before stringify so the same logical params always+ * hash to the same value regardless of insertion order.+ *+ * Pure function; no external deps (deliberately not `fast-json-stable-stringify`+ * — we own this surface and it must stay zero-dep stable).+ */+export function canonicalJson(value: unknown): string {+ if (value === null || typeof value !== 'object') return JSON.stringify(value);+ if (Array.isArray(value)) return '[' + value.map(canonicalJson).join(',') + ']';+ const obj = value as Record<string, unknown>;+ const keys = Object.keys(obj).sort();+ return '{' + keys.map((k) =>+ JSON.stringify(k) + ':' + canonicalJson(obj[k])+ ).join(',') + '}';+}++/**+ * SHA-256 of a UTF-8 string, hex-encoded.+ */+function sha256Hex(input: string): string {+ return createHash('sha256').update(input).digest('hex');+}++/**+ * Build a content-stable IDEMPOTENCY KEY for a remediation step.+ *+ * Pattern: `<source>:<job>:sha8(canonical-JSON(params))` — same scheme+ * as the legacy `idemKey()` in brain-score-recommendations.ts. Factor+ * this helper so future check authors don't hand-roll the shape.+ */+export function idempotencyKey(+ source: string,+ job: string,+ params: Record<string, unknown>,+): string {+ return `${source}:${job}:${sha256Hex(canonicalJson(params)).slice(0, 8)}`;+}++/**+ * Canonical RemediationStep constructor. All check authors should use+ * this; never hand-roll the shape (drift hazard).+ *+ * Default `id` is the same content-hash idempotency_key. Override `id`+ * when you want a human-readable identifier (e.g. 'sync.repo').+ *+ * Codex D12 Bug 2 invariance: makeRemediationStep with {a:1, b:2} and+ * {b:2, a:1} produces IDENTICAL ids (pinned in test/remediation-step.test.ts).+ */+export function makeRemediationStep(opts: {+ job: string;+ params: Record<string, unknown>;+ severity: RemediationSeverity;+ est_seconds: number;+ est_usd_cost?: number;+ depends_on?: string[];+ rationale: string;+ protected?: boolean;+ /** Optional human-readable id. Defaults to the idempotency key. */+ id?: string;+ /** Source for the idempotency-key namespace. Defaults to 'default'. */+ source?: string;+ /** Status. Defaults to 'remediable' (the only kind that ships in plans). */+ status?: RemediationStatus;+}): RemediationStep {+ const source = opts.source ?? 'default';+ const idemKey = idempotencyKey(source, opts.job, opts.params);+ return {+ id: opts.id ?? idemKey,+ job: opts.job,+ params: opts.params,+ idempotency_key: idemKey,+ severity: opts.severity,+ est_seconds: opts.est_seconds,+ est_usd_cost: opts.est_usd_cost,+ depends_on: opts.depends_on,+ rationale: opts.rationale,+ protected: opts.protected,+ status: opts.status ?? 'remediable',+ };+}diff --git a/src/core/search/mode-switch-ux.ts b/src/core/search/mode-switch-ux.tsnew file mode 100644index 0000000000..f608d798c7--- /dev/null+++ b/src/core/search/mode-switch-ux.ts@@ -0,0 +1,354 @@+/**+ * Mode-switch UX (v0.40.3.0 — D3)+ *+ * When the user runs `gbrain config set search.mode <X>`, this module+ * surfaces a banner explaining the consequences and offers follow-up+ * actions.+ *+ * Three concerns separated:+ *+ * 1. summarizeTransition(old, new) — PURE function that classifies the+ * transition (no_change / narrowing / broadening / tokenmax_opt_in)+ * and returns banner lines, reindex requirement, and cost estimate.+ *+ * 2. probeWorkerAvailable(engine) — checks Minion worker heartbeat+ * (mirrors `gbrain doctor`'s queue_health check). Returns active /+ * stale / never_seen with a paste-ready start command.+ *+ * 3. runModeSwitchUx(opts) — the orchestrator. Calls summarizeTransition,+ * prints the banner, and for tokenmax_opt_in + TTY: prompts to run+ * reindex, calls probeWorkerAvailable, and either submits the+ * reindex job or prints the loud-fail "start a worker first" hint+ * per D3.+ *+ * Suppression: GBRAIN_NO_MODE_SWITCH_UX=1 skips the entire UX for+ * scripted operators (CI fixtures, automation). Non-TTY also skips+ * interactive prompts; prints paste-ready hints to stderr.+ *+ * The reindex idempotency key is content-stable per codex D12 Bug 1:+ * cr-backfill:<source_id>:<chunker_version>:<corpus_generation_or_mode>+ * NOT timestamp-based. Two retries against the same brain state dedupe+ * via the Minion idempotency_key contract (v0.13.1).+ */++import type { BrainEngine } from '../engine.ts';+import { readLineSafe } from '../../commands/init.ts';+import { MinionQueue } from '../minions/queue.ts';+import { isSearchMode, type SearchMode } from './mode.ts';++export type TransitionKind =+ | 'no_change'+ | 'narrowing'+ | 'broadening'+ | 'tokenmax_opt_in'+ | 'invalid_new_mode';++export interface TransitionSummary {+ kind: TransitionKind;+ reindex_required: boolean;+ reindex_command?: string;+ cost_estimate_per_query_cents?: number;+ callout_lines: string[];+}++export type WorkerStatus = 'active' | 'stale' | 'never_seen';++export interface WorkerProbeResult {+ status: WorkerStatus;+ last_heartbeat_iso?: string;+ paste_ready_start_command: string;+}++export interface ModeSwitchOpts {+ oldMode: SearchMode | null;+ newMode: string;+ engine: BrainEngine;+ isTty: boolean;+ yesFlag?: boolean;+ /** Test seam: injectable worker probe. */+ probeFn?: (engine: BrainEngine) => Promise<WorkerProbeResult>;+ /** Test seam: injectable Minion submitter (avoids real queue in unit tests). */+ submitFn?: (jobName: string, params: Record<string, unknown>, idempotencyKey: string) => Promise<number>;+}++/**+ * Worker stale threshold: 2 minutes (matches gbrain doctor's+ * queue_health check semantics for "alive Minion worker").+ */+export const WORKER_STALE_THRESHOLD_MS = 120_000;++/**+ * Classify the transition + build banner content. Pure: no engine, no+ * file I/O. Test surface for the 5-cell decision matrix below.+ *+ * Decision matrix:+ * | old → new | kind | reindex |+ * |--------------------------|---------------------|---------|+ * | any → tokenmax | tokenmax_opt_in | yes |+ * | balanced → conservative | narrowing | no |+ * | conservative → balanced | broadening | no |+ * | any → balanced (else) | broadening | no |+ * | same → same | no_change | no |+ * | any → INVALID | invalid_new_mode | no |+ */+export function summarizeTransition(+ oldMode: SearchMode | null,+ newMode: string,+): TransitionSummary {+ if (!isSearchMode(newMode)) {+ return {+ kind: 'invalid_new_mode',+ reindex_required: false,+ callout_lines: [+ `Invalid search.mode value: "${newMode}".`,+ `Valid options: conservative | balanced | tokenmax`,+ ],+ };+ }++ if (oldMode === newMode) {+ return {+ kind: 'no_change',+ reindex_required: false,+ callout_lines: [],+ };+ }++ // tokenmax opt-in wins regardless of old mode. Triggers reindex prompt+ // because per-chunk Haiku synopsis backfill is needed for full quality.+ if (newMode === 'tokenmax') {+ return {+ kind: 'tokenmax_opt_in',+ reindex_required: true,+ reindex_command: 'gbrain reindex --markdown',+ cost_estimate_per_query_cents: 0.03, // ~$0.0003 per typical search+ callout_lines: [+ `Switched to tokenmax. Per-chunk Haiku synopsis enabled.`,+ `Backfill cost (one-time): ~$1-5 per 10K pages via Anthropic Haiku.`,+ `Per-query overhead: ~$0.0003 (reranker + slightly larger payload).`,+ `Run \`gbrain reindex --markdown\` to backfill existing pages.`,+ ],+ };+ }++ // Narrowing: dropping a feature (e.g. balanced → conservative drops+ // reranker + expansion). Cache will refill within TTL; no backfill.+ if (oldMode && narrowness(newMode) < narrowness(oldMode)) {+ return {+ kind: 'narrowing',+ reindex_required: false,+ callout_lines: [+ `Switched to ${newMode}. Some features dropped from prior mode.`,+ `Cache refills within TTL (default 1h). No backfill required.`,+ ],+ };+ }++ // Default: broadening or first-time set to balanced.+ return {+ kind: 'broadening',+ reindex_required: false,+ callout_lines: [+ `Switched to ${newMode}.`,+ oldMode+ ? `Existing wrapped embeddings (if any) continue serving queries.`+ : `First-time mode set. Cache will populate as queries run.`,+ ],+ };+}++// Cheap ordering for narrowing detection. Higher = more features enabled.+function narrowness(mode: SearchMode): number {+ switch (mode) {+ case 'conservative':+ return 1;+ case 'balanced':+ return 2;+ case 'tokenmax':+ return 3;+ }+}++/**+ * Probe Minion worker heartbeat. Mirrors the queue_health doctor check+ * semantics: a worker that pushed a heartbeat within+ * WORKER_STALE_THRESHOLD_MS is considered active.+ *+ * Best-effort: any error returns `never_seen` so the caller can decide+ * what to do. The paste-ready start command is always populated so the+ * banner can offer a recovery path.+ *+ * The PGLite inline path (`gbrain agent run` with `--follow`) doesn't+ * require a worker; this probe is for the production "spawn a real+ * Minion worker" path.+ */+export async function probeWorkerAvailable(engine: BrainEngine): Promise<WorkerProbeResult> {+ const startCmd = 'gbrain jobs work';+ try {+ // gbrain doesn't have a minion_workers heartbeat table yet (B7 follow-up+ // from v0.19.1 — see CLAUDE.md). Use a proxy: any minion_jobs row+ // started or finished within WORKER_STALE_THRESHOLD_MS means a worker+ // is doing real work. If only OLDER activity exists, treat as stale+ // (worker likely died). If no activity at all, never_seen.+ const rows = await engine.executeRaw<{ ts: string | null }>(+ `SELECT MAX(GREATEST(+ COALESCE(started_at, '-infinity'::timestamptz),+ COALESCE(finished_at, '-infinity'::timestamptz)+ ))::text AS ts+ FROM minion_jobs+ WHERE COALESCE(started_at, finished_at) > now() - INTERVAL '10 minutes'`,+ );+ const ts = rows[0]?.ts;+ if (!ts) {+ return { status: 'never_seen', paste_ready_start_command: startCmd };+ }+ const ageMs = Date.now() - new Date(ts).getTime();+ if (ageMs <= WORKER_STALE_THRESHOLD_MS) {+ return {+ status: 'active',+ last_heartbeat_iso: ts,+ paste_ready_start_command: startCmd,+ };+ }+ return {+ status: 'stale',+ last_heartbeat_iso: ts,+ paste_ready_start_command: startCmd,+ };+ } catch {+ // Table may not exist on a fresh brain. Treat as never_seen.+ return { status: 'never_seen', paste_ready_start_command: startCmd };+ }+}++/**+ * Build the content-stable idempotency key for the reindex submission+ * per codex D12 Bug 1. NOT timestamp-based — two retries against the+ * same brain state must produce the SAME key so the Minion dedupes.+ */+export function buildReindexIdempotencyKey(+ sourceId: string,+ chunkerVersion: number,+ modeOrCorpusGen: string,+): string {+ return `cr-backfill:${sourceId}:${chunkerVersion}:${modeOrCorpusGen}`;+}++/**+ * Orchestrator. Called by `gbrain config set search.mode <X>` after the+ * config write lands. Honors GBRAIN_NO_MODE_SWITCH_UX=1 (full skip),+ * non-TTY (skip prompt, print paste-ready hints), --yes (auto-submit+ * reindex on tokenmax_opt_in transitions).+ *+ * Idempotent: invoking with the same (old, new) twice is harmless; the+ * Minion idempotency_key ensures the reindex doesn't submit twice.+ */+export async function runModeSwitchUx(opts: ModeSwitchOpts): Promise<void> {+ if (process.env.GBRAIN_NO_MODE_SWITCH_UX === '1') return;+ if (!isSearchMode(opts.newMode)) {+ // The runConfig caller should have validated. Defense-in-depth:+ // print the invalid banner anyway.+ const summary = summarizeTransition(opts.oldMode, opts.newMode);+ for (const line of summary.callout_lines) console.error(`[mode-switch] ${line}`);+ return;+ }++ const summary = summarizeTransition(opts.oldMode, opts.newMode);+ if (summary.kind === 'no_change') return; // Quiet no-op.++ // Print banner regardless of TTY/non-TTY.+ console.error(`[mode-switch] ${summary.callout_lines[0]}`);+ for (let i = 1; i < summary.callout_lines.length; i++) {+ console.error(`[mode-switch] ${summary.callout_lines[i]}`);+ }++ if (!summary.reindex_required) return;++ // Reindex offered only for tokenmax_opt_in (today). Honor --yes /+ // non-TTY by NOT prompting; just print the paste-ready command.+ if (!opts.isTty || opts.yesFlag) {+ console.error(`[mode-switch] To backfill now: ${summary.reindex_command}`);+ return;+ }++ // TTY + interactive: prompt.+ const answer = await readLineSafe(+ `Run '${summary.reindex_command}' now? [y/N]: `,+ 'n',+ 60_000,+ );+ if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {+ console.error(`[mode-switch] Skipped. Run \`${summary.reindex_command}\` when ready.`);+ return;+ }++ // User opted in. Probe worker availability before submitting.+ const probeFn = opts.probeFn ?? probeWorkerAvailable;+ const worker = await probeFn(opts.engine);++ if (worker.status !== 'active') {+ // Loud-fail per D3 to avoid the silent-stall footgun. Caller can+ // still invoke reindex inline (`gbrain reindex --markdown` runs+ // synchronously without a worker on the PGLite inline path).+ console.error(`[mode-switch] No active worker (${worker.status}).`);+ console.error(`[mode-switch] Either run inline: ${summary.reindex_command}`);+ console.error(`[mode-switch] Or start a worker first: ${worker.paste_ready_start_command}`);+ return;+ }++ // Submit via Minion queue with content-stable idempotency key.+ const sourceId = await resolveDefaultSourceId(opts.engine);+ const chunkerVersion = await resolveChunkerVersion(opts.engine);+ const idempotencyKey = buildReindexIdempotencyKey(sourceId, chunkerVersion, opts.newMode);++ const submitFn = opts.submitFn ?? defaultSubmit;+ try {+ const jobId = await submitFn(+ 'reindex',+ { markdown: true, source_id: sourceId },+ idempotencyKey,+ );+ console.error(`[mode-switch] Submitted as job ${jobId}. Watch with: gbrain jobs follow ${jobId}`);+ } catch (err) {+ console.error(`[mode-switch] Submit failed: ${(err as Error).message}`);+ console.error(`[mode-switch] Run inline: ${summary.reindex_command}`);+ }++ async function defaultSubmit(+ jobName: string,+ params: Record<string, unknown>,+ idemKey: string,+ ): Promise<number> {+ const queue = new MinionQueue(opts.engine);+ const job = await queue.add(+ jobName,+ params,+ { idempotency_key: idemKey },+ { allowProtectedSubmit: true },+ );+ return job.id;+ }+}++async function resolveDefaultSourceId(engine: BrainEngine): Promise<string> {+ try {+ const rows = await engine.executeRaw<{ id: string }>(+ `SELECT id FROM sources WHERE id = 'default' LIMIT 1`,+ );+ return rows[0]?.id ?? 'default';+ } catch {+ return 'default';+ }+}++async function resolveChunkerVersion(engine: BrainEngine): Promise<number> {+ try {+ const rows = await engine.executeRaw<{ v: string | null }>(+ `SELECT value AS v FROM config WHERE key = 'chunker_version'`,+ );+ const v = Number(rows[0]?.v ?? 0);+ return Number.isFinite(v) ? v : 0;+ } catch {+ return 0;+ }+}diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 68944e3e1d..defe5a4d20 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -24,6 +24,7 @@*/import { createHash } from 'crypto';+import { CR_MODES, type CRMode } from '../types.ts';export type SearchMode = 'conservative' | 'balanced' | 'tokenmax';@@ -162,6 +163,35 @@ export interface ModeBundle {* Fires for <1% of queries when on; ~$0.0001 per escalation.*/cross_modal_llm_intent: boolean;++ /**+ * v0.40.3.0 — contextual retrieval tier per mode. Wraps chunks at embed+ * time so the embedder sees document-level orientation alongside the+ * chunk. Wrapper is built JUST IN TIME and never persisted as+ * `content_chunks.chunk_text` (D20-T1 — search snippets, FTS, reranker,+ * debug all read the canonical chunk_text).+ *+ * Per-mode defaults (D1+D2):+ * conservative → 'none' (minimum surface)+ * balanced → 'title' (free at runtime — pure string concat)+ * tokenmax → 'per_chunk_synopsis' (Anthropic's published method)+ *+ * Override resolution chain (D5+D6+D15): page frontmatter > source row >+ * global mode bundle. Mount-frontmatter overrides honored only when+ * `sources.trust_frontmatter_overrides` is true (host id='default' is+ * always trusted). See `src/core/contextual-retrieval-resolver.ts`.+ */+ contextual_retrieval: CRMode;++ /**+ * v0.40.3.0 — soft kill switch (D18). When true, `hybridSearch` treats+ * all tiers as 'none' at query time AND `import-file.ts` skips wrapper+ * resolution entirely. Existing wrapped vectors in `content_chunks`+ * keep serving queries (cosine similarity is preserved between wrapped+ * documents and raw queries). Single config-key rollback if quality+ * regresses post-deploy.+ */+ contextual_retrieval_disabled: boolean;}/**@@ -198,6 +228,9 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =unified_multimodal: false,unified_multimodal_only: false,cross_modal_llm_intent: false,+ // v0.40.3.0 contextual retrieval — none for conservative (minimum surface).+ contextual_retrieval: 'none' as CRMode,+ contextual_retrieval_disabled: false,}),balanced: Object.freeze({cache_enabled: true,@@ -231,6 +264,11 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =unified_multimodal: false,unified_multimodal_only: false,cross_modal_llm_intent: false,+ // v0.40.3.0 contextual retrieval — title-only for balanced (free at+ // runtime; pure string concat, no Haiku). Default mode for most users+ // per the cost-tier philosophy.+ contextual_retrieval: 'title' as CRMode,+ contextual_retrieval_disabled: false,}),tokenmax: Object.freeze({cache_enabled: true,@@ -261,6 +299,11 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =unified_multimodal: false,unified_multimodal_only: false,cross_modal_llm_intent: false,+ // v0.40.3.0 contextual retrieval — per-chunk Haiku synopsis for tokenmax+ // (Anthropic's published method). One-time backfill cost ~$5-50 for a+ // 10K-page brain; documented in the post-upgrade cost prompt.+ contextual_retrieval: 'per_chunk_synopsis' as CRMode,+ contextual_retrieval_disabled: false,}),});@@ -302,6 +345,9 @@ export interface SearchKeyOverrides {unified_multimodal?: boolean;unified_multimodal_only?: boolean;cross_modal_llm_intent?: boolean;+ // v0.40.3.0 contextual retrieval. CRMode override + soft kill switch.+ contextual_retrieval?: CRMode;+ contextual_retrieval_disabled?: boolean;}/**@@ -335,6 +381,9 @@ export interface SearchPerCallOpts {unified_multimodal?: boolean;unified_multimodal_only?: boolean;cross_modal_llm_intent?: boolean;+ // v0.40.3.0 contextual retrieval per-call overrides.+ contextual_retrieval?: CRMode;+ contextual_retrieval_disabled?: boolean;}/**@@ -403,6 +452,9 @@ export function resolveSearchMode(input: ResolveSearchModeInput): ResolvedSearchunified_multimodal: pick('unified_multimodal'),unified_multimodal_only: pick('unified_multimodal_only'),cross_modal_llm_intent: pick('cross_modal_llm_intent'),+ // v0.40.3.0 contextual retrieval — resolved via the same pick chain.+ contextual_retrieval: pick('contextual_retrieval'),+ contextual_retrieval_disabled: pick('contextual_retrieval_disabled'),resolved_mode,mode_valid: valid,};@@ -471,7 +523,14 @@ export function attributeKnob<K extends keyof ModeBundle>(// image-mode caller). v0.35.6.0's floor_ratio bump and v0.36's cross-modal// extensions both land under v=3, with cross-modal fields appended after// the floor_ratio entry (CDX2-F13 append-only convention).-export const KNOBS_HASH_VERSION = 3;+//+// v0.39 T21 (master): schema_pack identity fields added under v=4.+//+// v0.40.3.0 (this branch, per D8 sequencing): contextual_retrieval and+// contextual_retrieval_disabled added under v=5. Sequenced behind salem's+// pending v=4 graph signals work — first to land claims v=4; second+// rebases to v=5 (we did, since master's v=4 already landed before us).+export const KNOBS_HASH_VERSION = 5;/*** v0.36 (D8 / CDX-2) — second-arg context for the cache key. The@@ -549,12 +608,20 @@ export function knobsHash(// must never be served from a row that ran against `embedding`.`col=${ctx?.embeddingColumn ?? 'embedding'}`,`prov=${ctx?.embeddingModel ?? 'default'}`,- // v0.39 T21 + codex finding #5: schema-pack name + version. Cross-pack- // contamination is structurally impossible — a query that resolved- // type `researcher` against pack A cannot be served from a row that- // resolved against pack B.+ // v=4 additions (append-only). v0.39 T21 + codex finding #5: schema-pack+ // name + version. Cross-pack contamination is structurally impossible+ // — a query that resolved type `researcher` against pack A cannot be+ // served from a row that resolved against pack B.`pack=${ctx?.schemaPack ?? 'none'}`,`pver=${ctx?.schemaPackVersion ?? 'none'}`,+ // v=5 contextual retrieval additions (v0.40.3.0, per D8 sequencing+ // behind salem's pending v=4 graph signals). A query against a brain+ // on tokenmax (per-chunk synopsis) must NEVER be served from a cache+ // row written when the brain was on balanced (title-only) — different+ // embedding spaces. Soft kill switch participates too so flipping it+ // neutralizes prior cache rows.+ `cr=${knobs.contextual_retrieval}`,+ `crd=${knobs.contextual_retrieval_disabled ? 1 : 0}`,];const h = createHash('sha256');h.update(parts.join('|'));@@ -685,6 +752,15 @@ export function loadOverridesFromConfig(if (lli !== undefined) {out.cross_modal_llm_intent = lli === '1' || lli.toLowerCase() === 'true';}+ // v0.40.3.0 contextual retrieval. tier override + soft kill switch.+ const cr = get('search.contextual_retrieval');+ if (cr !== undefined && (CR_MODES as readonly string[]).includes(cr.trim().toLowerCase())) {+ out.contextual_retrieval = cr.trim().toLowerCase() as CRMode;+ }+ const crd = get('search.contextual_retrieval_disabled');+ if (crd !== undefined) {+ out.contextual_retrieval_disabled = crd === '1' || crd.toLowerCase() === 'true';+ }return out;}@@ -714,6 +790,11 @@ export const SEARCH_MODE_CONFIG_KEYS: ReadonlyArray<string> = Object.freeze(['search.unified_multimodal','search.unified_multimodal_only','search.cross_modal.llm_intent',+ // v0.40.3.0 contextual retrieval — tier override + soft kill switch.+ // Per-mode default lives in the bundle; this key lets power users+ // override at the per-key level without flipping the global mode.+ 'search.contextual_retrieval',+ 'search.contextual_retrieval_disabled',]);/**diff --git a/src/core/search/query-cache-gate.ts b/src/core/search/query-cache-gate.tsnew file mode 100644index 0000000000..4963ff7b73--- /dev/null+++ b/src/core/search/query-cache-gate.ts@@ -0,0 +1,184 @@+/**+ * Cache invalidation gate (v0.40.3.0 — D2 + D6 + D11)+ *+ * Two pure helpers wired by query-cache.ts at store + lookup time. Pure+ * surface lets us unit-test the two-layer gate logic without a real cache.+ *+ * Layer 1 (cheap bookmark): `MAX(generation) FROM pages` <=+ * `query_cache.max_generation_at_store`. If true, brain has not been+ * written since this row stored, so the row is fresh corpus-wide.+ *+ * Layer 2 (per-page snapshot): if bookmark fires, fall through to the+ * `page_generations JSONB` snapshot. For each `(page_id, stored_gen)`+ * pair, compare to current `pages.generation`. Any mismatch (page+ * deleted, page bumped) invalidates.+ *+ * Backward compat: rows stored before v0.40.3.0 have+ * `max_generation_at_store = 0` AND `page_generations = '{}'::jsonb`.+ * Bookmark check: `MAX <= 0` is false on any populated brain, so we fall+ * through to Layer 2; Layer 2 sees `'{}'::jsonb` and is vacuously valid.+ * Legacy rows continue to serve naturally (IRON-RULE regression pinned+ * in test/e2e/cache-gate-pglite.test.ts).+ *+ * See plan ~/.claude/plans/system-instruction-you-are-working-enchanted-mountain.md+ * Phase 2A for full design.+ */++import type { BrainEngine } from '../engine.ts';++/**+ * Snapshot of (pageId, generation) pairs plus the corpus-state MAX+ * captured at cache-store time. Stored as JSONB (page_generations) ++ * BIGINT (max_generation_at_store).+ */+export interface PageGenerationsSnapshot {+ /**+ * Map of page_id (stringified) → generation (integer). Empty when no+ * results have valid page_ids (e.g., empty-result-set query — still+ * cacheable; bookmark check covers freshness).+ */+ page_generations: Record<string, number>;+ /**+ * MAX(generation) FROM pages at snapshot time. The corpus-state bookmark.+ * Zero when the brain has no pages (fresh install before first put_page).+ */+ max_generation_at_store: number;+}++/**+ * Build the page-generations snapshot for a set of page_ids in one SQL+ * round trip. Used by query-cache.ts:store() at cache-write time.+ *+ * UNION ALL combines the per-page fetch with the corpus-state MAX into+ * one round trip — Postgres / PGLite both fold both branches into a+ * single result set. The 'MAX' tag row is identified by `is_max = true`.+ *+ * @param engine - BrainEngine to query.+ * @param pageIds - Page IDs from the SearchResult set being cached. Pass+ * an empty array for empty-result queries; the snapshot will be empty+ * but the bookmark still captures MAX(generation).+ * @returns PageGenerationsSnapshot suitable for INSERT into query_cache.+ */+export async function buildPageGenerationsSnapshot(+ engine: BrainEngine,+ pageIds: number[],+): Promise<PageGenerationsSnapshot> {+ // Empty pageIds: just fetch MAX(generation) for the bookmark. Skip the+ // per-page branch entirely (UNION ALL with an empty IN clause is a+ // valid SQL but skipping saves one ARRAY[] construction).+ const snapshot: PageGenerationsSnapshot = {+ page_generations: {},+ max_generation_at_store: 0,+ };++ try {+ if (pageIds.length === 0) {+ const rows = await engine.executeRaw<{ v: number }>(+ `SELECT COALESCE(MAX(generation), 0)::bigint AS v FROM pages`,+ );+ snapshot.max_generation_at_store = Number(rows[0]?.v ?? 0);+ return snapshot;+ }++ // Combined query: per-page generation + corpus-state MAX.+ const rows = await engine.executeRaw<{+ k: string;+ v: number;+ is_max: boolean;+ }>(+ `SELECT id::text AS k, generation::bigint AS v, FALSE AS is_max+ FROM pages WHERE id = ANY($1::int[])+ UNION ALL+ SELECT 'MAX' AS k, COALESCE(MAX(generation), 0)::bigint AS v, TRUE AS is_max+ FROM pages`,+ [pageIds],+ );++ for (const row of rows) {+ const v = Number(row.v);+ if (row.is_max) {+ snapshot.max_generation_at_store = v;+ } else {+ snapshot.page_generations[row.k] = v;+ }+ }+ return snapshot;+ } catch {+ // Pre-v91 brain (no `generation` column yet). Return the+ // backward-compat empty snapshot with zero bookmark — every cache+ // row will fall through to Layer 2 and serve via the `'{}'::jsonb`+ // vacuously-valid path. Closes the upgrade-path gap.+ return snapshot;+ }+}++/**+ * The SQL fragment that lookup() embeds inside its WHERE clause to apply+ * the two-layer gate. Exported as a string so the test suite can grep+ * for shape invariants (e.g., assert the bookmark uses MAX(generation)+ * and the per-page check uses jsonb_each).+ *+ * Placeholder semantics:+ * - qc — the `query_cache` row alias used by the caller's outer SELECT.+ *+ * The fragment is a single boolean expression suitable for AND-ing with+ * the rest of the lookup's WHERE clause. It does NOT include a leading+ * AND — caller provides that.+ */+export const CACHE_GATE_WHERE_CLAUSE = `+ (+ -- Layer 1 (cheap bookmark): O(log N) MAX(generation) via pages_generation_idx.+ -- If no page has been bumped since this row stored, the row is fresh.+ (SELECT COALESCE(MAX(generation), 0) FROM pages) <= qc.max_generation_at_store+ OR+ -- Layer 2 (per-page snapshot): bookmark fired, but maybe this row's+ -- specific result set isn't affected. Pre-v0.40.3.0 rows have+ -- page_generations = '{}'::jsonb and serve vacuously (legacy compat —+ -- IRON-RULE regression in test/e2e/cache-gate-pglite.test.ts).+ (+ qc.page_generations = '{}'::jsonb+ OR NOT EXISTS (+ SELECT 1+ FROM jsonb_each(qc.page_generations) AS g(page_id, stored_gen)+ LEFT JOIN pages p ON p.id = (g.page_id)::int+ WHERE p.id IS NULL -- page deleted → invalidate+ OR p.generation <> ((g.stored_gen)::text)::bigint -- bumped → invalidate+ )+ )+ )+`;++/**+ * Pure validator for unit testing: given a cache row's snapshot and the+ * current brain state, return whether the cache row is still valid.+ *+ * @param snapshot - The (page_generations, max_generation_at_store) tuple+ * stored on the cache row.+ * @param current - The current brain state: MAX(generation) plus the+ * current generation of every (formerly-)stored page. Use `undefined`+ * for pages that no longer exist (deleted).+ * @returns true if the cache row would still serve; false if it has+ * invalidated and the caller should re-query.+ */+export function validateCacheRowAgainstPages(+ snapshot: PageGenerationsSnapshot,+ current: {+ max_generation: number;+ page_generations: Record<string, number | undefined>;+ },+): boolean {+ // Layer 1: bookmark.+ if (current.max_generation <= snapshot.max_generation_at_store) return true;++ // Layer 2: per-page snapshot.+ const ids = Object.keys(snapshot.page_generations);+ if (ids.length === 0) return true; // Vacuously valid (legacy + zero-page).++ for (const id of ids) {+ const storedGen = snapshot.page_generations[id];+ const currentGen = current.page_generations[id];+ if (currentGen === undefined) return false; // Page deleted.+ if (currentGen !== storedGen) return false; // Page bumped.+ }+ return true;+}diff --git a/src/core/search/query-cache.ts b/src/core/search/query-cache.tsindex 7351b402ae..dd68a12e86 100644--- a/src/core/search/query-cache.ts+++ b/src/core/search/query-cache.ts@@ -32,6 +32,7 @@import { createHash } from 'node:crypto';import type { BrainEngine } from '../engine.ts';import type { SearchResult, HybridSearchMeta } from '../types.ts';+import { buildPageGenerationsSnapshot, CACHE_GATE_WHERE_CLAUSE } from './query-cache-gate.ts';/** Default cosine similarity threshold for cache hits. */export const DEFAULT_SIMILARITY_THRESHOLD = 0.92;@@ -144,6 +145,9 @@ export class SemanticQueryCache {// A tokenmax write (expansion=on, limit=50) and a conservative read// (no expansion, limit=10) have distinct knobs hashes and miss each// other. Rows with NULL knobs_hash (pre-v0.32.3) are excluded.+ // v0.40.3.0: query_cache row aliased `qc` so the two-layer gate+ // fragment in CACHE_GATE_WHERE_CLAUSE can reference qc.max_generation_at_store+ // + qc.page_generations against the live pages table.const rows = await this.engine.executeRaw<{id: string;results: unknown;@@ -151,16 +155,17 @@ export class SemanticQueryCache {distance: number;age_seconds: number;}>(- `SELECT id, results, meta,- embedding <=> $1::vector AS distance,- EXTRACT(EPOCH FROM (now() - created_at))::int AS age_seconds- FROM query_cache- WHERE source_id = $2- AND knobs_hash = $4- AND embedding IS NOT NULL- AND embedding <=> $1::vector < $3- AND created_at + (ttl_seconds || ' seconds')::interval > now()- ORDER BY embedding <=> $1::vector+ `SELECT qc.id, qc.results, qc.meta,+ qc.embedding <=> $1::vector AS distance,+ EXTRACT(EPOCH FROM (now() - qc.created_at))::int AS age_seconds+ FROM query_cache qc+ WHERE qc.source_id = $2+ AND qc.knobs_hash = $4+ AND qc.embedding IS NOT NULL+ AND qc.embedding <=> $1::vector < $3+ AND qc.created_at + (qc.ttl_seconds || ' seconds')::interval > now()+ AND ${CACHE_GATE_WHERE_CLAUSE}+ ORDER BY qc.embedding <=> $1::vectorLIMIT 1`,[vec, sourceId, distanceThreshold, knobsHash],);@@ -209,14 +214,29 @@ export class SemanticQueryCache {const id = cacheRowId(queryText, sourceId, knobsHash);const vec = embeddingToPgVector(queryEmbedding);+ // v0.40.3.0: capture the per-page snapshot + corpus-state bookmark+ // for the two-layer cache gate. Pure helper from query-cache-gate.ts+ // handles the pre-v91 brain fallback (empty snapshot, zero bookmark+ // \u2014 legacy compat preserved).+ const pageIds = results+ .map((r) => r.page_id)+ .filter((id): id is number => typeof id === 'number' && Number.isFinite(id));+ const snapshot = await buildPageGenerationsSnapshot(this.engine, pageIds);+try {// v0.32.3 [CDX-4]: knobs_hash threaded into the row so concurrent// tokenmax + conservative writes for the same query+source live as// distinct rows. The PK is `id` (which already encodes the hash),// so ON CONFLICT (id) DO UPDATE just refreshes the same-mode row.+ //+ // v0.40.3.0: page_generations JSONB + max_generation_at_store BIGINT+ // stamped per D11 (cache invalidation gate). page_generations is+ // sent as a JSON.stringify and cast to JSONB inside the SQL; pre-v91+ // brains store an empty `{}` + zero bookmark (legacy compat per+ // the v0.40.3.0 IRON-RULE).await this.engine.executeRaw(- `INSERT INTO query_cache (id, query_text, source_id, knobs_hash, embedding, results, meta, ttl_seconds, created_at)- VALUES ($1, $2, $3, $4, $5::vector, $6::jsonb, $7::jsonb, $8, now())+ `INSERT INTO query_cache (id, query_text, source_id, knobs_hash, embedding, results, meta, ttl_seconds, page_generations, max_generation_at_store, created_at)+ VALUES ($1, $2, $3, $4, $5::vector, $6::jsonb, $7::jsonb, $8, $9::jsonb, $10, now())ON CONFLICT (id) DO UPDATE SETquery_text = EXCLUDED.query_text,knobs_hash = EXCLUDED.knobs_hash,@@ -224,6 +244,8 @@ export class SemanticQueryCache {results = EXCLUDED.results,meta = EXCLUDED.meta,ttl_seconds = EXCLUDED.ttl_seconds,+ page_generations = EXCLUDED.page_generations,+ max_generation_at_store = EXCLUDED.max_generation_at_store,created_at = now()`,[id,@@ -234,6 +256,8 @@ export class SemanticQueryCache {JSON.stringify(results),JSON.stringify(meta),ttl,+ JSON.stringify(snapshot.page_generations),+ snapshot.max_generation_at_store,],);} catch {diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.tsindex 383405daea..a2ecacb32c 100644--- a/src/core/sources-ops.ts+++ b/src/core/sources-ops.ts@@ -88,6 +88,20 @@ export interface SourceRow {last_sync_at: Date | null;config: Record<string, unknown>;created_at: Date;+ /**+ * v0.40.3.0: per-source CR mode override. NULL falls through to global+ * mode bundle. Written only by `gbrain sources set-cr-mode <id> <mode>`+ * (CLI-write-only per D15 security gate); MCP / OAuth callers cannot+ * mutate this field.+ */+ contextual_retrieval_mode?: string | null;+ /**+ * v0.40.3.0: per-source mount-frontmatter trust gate (D15). FALSE for+ * mounted sources by default. Flipped via+ * `gbrain mounts trust-frontmatter <id>`. Host source (id='default') is+ * always trusted in the resolver regardless of this column value.+ */+ trust_frontmatter_overrides?: boolean;}export interface SourceListEntry {diff --git a/src/core/types.ts b/src/core/types.tsindex ab3d9ea366..3324b98531 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -139,6 +139,23 @@ export interface Page {ingested_via?: string | null;/** Server-stamped first-write audit timestamp; CV12 COALESCE-preserved across edits. */ingested_at?: Date | null;+ /**+ * v0.40.3.0 (renumbered from v0.40.3.0 v81 to v90 on master merge):+ * which contextual retrieval tier the page was last embedded under. One+ * of CRMode ('none' | 'title' | 'per_chunk_synopsis'). NULL on pre-v90+ * rows; drift detection treats NULL as 'none' for reindex predicates,+ * so unmigrated pages enter the sweep on first upgrade to non-conservative+ * mode.+ */+ contextual_retrieval_mode?: CRMode | null;+ /**+ * v0.40.3.0 (renumbered from v0.40.3.0 v81 to v90 on master merge):+ * composite hash of (synopsis_prompt_version, haiku_model,+ * title_wrapper_version, embedding_model) captured at write time by+ * `reembedPageWithContextualRetrieval`. Used by `query_cache.page_generations`+ * for document-side cache invalidation per D27 P1-5. NULL on pre-v90 rows.+ */+ corpus_generation?: string | null;}export type EffectiveDateSource =@@ -151,6 +168,27 @@ export type EffectiveDateSource =// `image` (v0.27.1): multimodal ingestion path, parallel to markdown + code.export type PageKind = 'markdown' | 'code' | 'image';+/**+ * v0.40.3.0 — contextual retrieval tier ladder per `search.mode`.+ *+ * none — no wrapper applied at embed time (conservative)+ * title — `<context>{title}</context>\n{chunk}` (balanced)+ * per_chunk_synopsis — per-chunk Haiku synopsis prepended (tokenmax)+ *+ * Resolution chain (highest wins): page frontmatter > source row > global+ * mode bundle. Mount-frontmatter overrides are honored only when the+ * source's `trust_frontmatter_overrides` flag is true (host source+ * id='default' is always trusted). See+ * `src/core/contextual-retrieval-resolver.ts`.+ */+export const CR_MODES = ['none', 'title', 'per_chunk_synopsis'] as const;+export type CRMode = typeof CR_MODES[number];++/** Type guard for parsing untrusted frontmatter / config values. */+export function isCRMode(value: unknown): value is CRMode {+ return typeof value === 'string' && (CR_MODES as readonly string[]).includes(value);+}+export interface PageInput {type: PageType;title: string;diff --git a/src/schema.sql b/src/schema.sqlindex 4fa2b6ba13..1f60e0ac86 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -43,6 +43,12 @@ CREATE TABLE IF NOT EXISTS sources (archived BOOLEAN NOT NULL DEFAULT false,archived_at TIMESTAMPTZ,archive_expires_at TIMESTAMPTZ,+ -- v0.40.3.0: per-source CR mode override + mount-frontmatter trust gate.+ -- contextual_retrieval_mode NULL = fall through to global mode bundle.+ -- trust_frontmatter_overrides FALSE for mounts by default; host source+ -- (id='default') is always trusted regardless of this column.+ contextual_retrieval_mode TEXT,+ trust_frontmatter_overrides BOOLEAN NOT NULL DEFAULT false,created_at TIMESTAMPTZ NOT NULL DEFAULT now());@@ -104,9 +110,68 @@ CREATE TABLE IF NOT EXISTS pages (-- (NOT inside engine methods — internal callers must not pollute the-- signal). NULL = never retrieved (LSD prioritizes these first).last_retrieved_at TIMESTAMPTZ,+ -- v0.40.3.0 contextual retrieval (renumbered from v81 to v90 on master+ -- merge). contextual_retrieval_mode is what tier the page was last embedded+ -- under (NULL = pre-v90 = treated as 'none' for drift detection).+ -- corpus_generation is the composite hash of (synopsis_prompt_version,+ -- haiku_model, title_wrapper_version, embedding_model) — document-side+ -- provenance for query_cache invalidation per D27 P1-5. NULL means pre-v90;+ -- the page_generations JSONB check correctly invalidates pre-v90 cache+ -- rows against any current generation.+ contextual_retrieval_mode TEXT,+ corpus_generation TEXT,+ -- v0.40.3.0 cache invalidation gate (migration v91). Monotonic per-page+ -- counter bumped by bump_page_generation_trg on INSERT (initial value =+ -- MAX(generation) + 1 so the bookmark fires for any cache row stored+ -- before this page existed — codex #4) and on UPDATE when any column in+ -- the content allow-list IS DISTINCT FROM. Read by the per-page snapshot+ -- check in query-cache-gate.ts.+ generation BIGINT NOT NULL DEFAULT 1,CONSTRAINT pages_source_slug_key UNIQUE (source_id, slug));+-- v0.40.3.0 cache invalidation trigger (migration v91; mirrored in+-- src/core/pglite-schema.ts). BEFORE INSERT OR UPDATE so every write path+-- bumps generation per D6 / codex #4. INSERT: pages get+-- COALESCE(MAX(generation), 0) + 1 so the bookmark gate fires for any+-- cache row stored before the new page existed. UPDATE: bumps only when+-- content columns IS DISTINCT FROM (allow-list widened per D6 + codex #3+-- to include title/type/page_kind/corpus_generation/content_hash) so+-- read-time mutations don't invalidate every cache row.+CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger AS $func$+BEGIN+ IF (TG_OP = 'INSERT') THEN+ NEW.generation := COALESCE((SELECT MAX(generation) FROM pages), 0) + 1;+ ELSIF (OLD.compiled_truth IS DISTINCT FROM NEW.compiled_truth)+ OR (OLD.timeline IS DISTINCT FROM NEW.timeline)+ OR (OLD.frontmatter IS DISTINCT FROM NEW.frontmatter)+ OR (OLD.deleted_at IS DISTINCT FROM NEW.deleted_at)+ OR (OLD.contextual_retrieval_mode IS DISTINCT FROM NEW.contextual_retrieval_mode)+ OR (OLD.title IS DISTINCT FROM NEW.title)+ OR (OLD.type IS DISTINCT FROM NEW.type)+ OR (OLD.page_kind IS DISTINCT FROM NEW.page_kind)+ OR (OLD.corpus_generation IS DISTINCT FROM NEW.corpus_generation)+ OR (OLD.content_hash IS DISTINCT FROM NEW.content_hash)+ THEN+ NEW.generation := OLD.generation + 1;+ END IF;+ RETURN NEW;+END;+$func$ LANGUAGE plpgsql;++DROP TRIGGER IF EXISTS bump_page_generation_trg ON pages;+CREATE TRIGGER bump_page_generation_trg+ BEFORE INSERT OR UPDATE ON pages+ FOR EACH ROW+ EXECUTE FUNCTION bump_page_generation_fn();++-- v0.40.3.0 supports O(log N) MAX(generation) for the Layer 1 bookmark+-- check in query-cache-gate.ts. Plain btree (DESC unnecessary; Postgres+-- backward-scans plain btrees for MAX per codex #8). CONCURRENTLY would+-- be used inside a migration; in the schema-bootstrap path it's a plain+-- CREATE INDEX since the table is empty.+CREATE INDEX IF NOT EXISTS pages_generation_idx ON pages (generation);+CREATE INDEX IF NOT EXISTS idx_pages_type ON pages(type);CREATE INDEX IF NOT EXISTS idx_pages_frontmatter ON pages USING GIN(frontmatter);CREATE INDEX IF NOT EXISTS idx_pages_trgm ON pages USING GIN(title gin_trgm_ops);diff --git a/test/audit-synopsis.serial.test.ts b/test/audit-synopsis.serial.test.tsnew file mode 100644index 0000000000..ba81103de5--- /dev/null+++ b/test/audit-synopsis.serial.test.ts@@ -0,0 +1,120 @@+/**+ * Tests for src/core/audit-synopsis.ts — failure-only synopsis audit+ * JSONL writer + summary aggregator.+ *+ * Uses GBRAIN_AUDIT_DIR to isolate writes into a temp dir per test.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {+ logSynopsisFailure,+ readRecentSynopsisFailures,+ summarizeSynopsisFailures,+ computeSynopsisAuditFilename,+} from '../src/core/audit-synopsis.ts';++let tmpDir: string;+const originalEnv = process.env.GBRAIN_AUDIT_DIR;++beforeAll(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-synopsis-audit-test-'));+ process.env.GBRAIN_AUDIT_DIR = tmpDir;+});++afterAll(() => {+ if (originalEnv === undefined) delete process.env.GBRAIN_AUDIT_DIR;+ else process.env.GBRAIN_AUDIT_DIR = originalEnv;+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++beforeEach(() => {+ // Wipe previous test's audit files to keep readback deterministic.+ for (const f of fs.readdirSync(tmpDir)) {+ fs.unlinkSync(path.join(tmpDir, f));+ }+});++describe('computeSynopsisAuditFilename', () => {+ test('ISO-week filename shape', () => {+ const filename = computeSynopsisAuditFilename(new Date('2026-05-22T12:00:00Z'));+ expect(filename).toMatch(/^synopsis-failures-\d{4}-W\d{2}\.jsonl$/);+ });++ test('stable for same week, different days', () => {+ const monday = computeSynopsisAuditFilename(new Date('2026-05-18T08:00:00Z'));+ const friday = computeSynopsisAuditFilename(new Date('2026-05-22T18:00:00Z'));+ expect(monday).toBe(friday);+ });+});++describe('logSynopsisFailure + readRecentSynopsisFailures', () => {+ test('round-trip a single refusal event', () => {+ logSynopsisFailure({+ pageSlug: 'wiki/concepts/test-page',+ sourceId: 'default',+ chunkIndex: 3,+ kind: 'refusal',+ detail: 'stop_reason=content_filter',+ pageLevelFallback: true,+ });+ const events = readRecentSynopsisFailures(7);+ expect(events.length).toBe(1);+ const ev = events[0];+ expect(ev.page_slug).toBe('wiki/concepts/test-page');+ expect(ev.source_id).toBe('default');+ expect(ev.chunk_index).toBe(3);+ expect(ev.kind).toBe('refusal');+ expect(ev.detail).toBe('stop_reason=content_filter');+ expect(ev.page_level_fallback).toBe(true);+ expect(ev.severity).toBe('warn');+ });++ test('multiple events accumulate in correct order', () => {+ logSynopsisFailure({ pageSlug: 'a', sourceId: 'default', chunkIndex: 0, kind: 'refusal', pageLevelFallback: true });+ logSynopsisFailure({ pageSlug: 'b', sourceId: 'default', chunkIndex: 1, kind: 'empty', pageLevelFallback: true });+ logSynopsisFailure({ pageSlug: 'c', sourceId: 'team', chunkIndex: 0, kind: 'rate_limit', pageLevelFallback: false });+ const events = readRecentSynopsisFailures(7);+ expect(events.length).toBe(3);+ expect(events.map((e) => e.page_slug)).toEqual(['a', 'b', 'c']);+ });++ test('detail caps at 200 chars (audit-file pollution defense)', () => {+ const longDetail = 'x'.repeat(500);+ logSynopsisFailure({+ pageSlug: 'a', sourceId: 'default', chunkIndex: 0, kind: 'malformed',+ detail: longDetail, pageLevelFallback: true,+ });+ const events = readRecentSynopsisFailures(7);+ expect(events[0].detail!.length).toBe(200);+ });++ test('missing audit file returns empty array (silent)', () => {+ expect(readRecentSynopsisFailures(7).length).toBe(0);+ });+});++describe('summarizeSynopsisFailures', () => {+ test('null on empty input', () => {+ expect(summarizeSynopsisFailures([])).toBeNull();+ });++ test('aggregates by kind + computes fall-back rate', () => {+ logSynopsisFailure({ pageSlug: 'a', sourceId: 'default', chunkIndex: 0, kind: 'refusal', pageLevelFallback: true });+ logSynopsisFailure({ pageSlug: 'b', sourceId: 'default', chunkIndex: 0, kind: 'refusal', pageLevelFallback: true });+ logSynopsisFailure({ pageSlug: 'c', sourceId: 'default', chunkIndex: 0, kind: 'empty', pageLevelFallback: true });+ logSynopsisFailure({ pageSlug: 'd', sourceId: 'default', chunkIndex: 0, kind: 'rate_limit', pageLevelFallback: false });+ const events = readRecentSynopsisFailures(7);+ const summary = summarizeSynopsisFailures(events);+ expect(summary).not.toBeNull();+ expect(summary!.total).toBe(4);+ expect(summary!.by_kind.refusal).toBe(2);+ expect(summary!.by_kind.empty).toBe(1);+ expect(summary!.by_kind.rate_limit).toBe(1);+ expect(summary!.by_kind.timeout).toBe(0);+ expect(summary!.page_level_fallback_count).toBe(3);+ expect(summary!.page_level_fallback_rate).toBeCloseTo(0.75, 2);+ });+});diff --git a/test/chunkers/recursive.test.ts b/test/chunkers/recursive.test.tsindex 87dafe8e98..b872e082e8 100644--- a/test/chunkers/recursive.test.ts+++ b/test/chunkers/recursive.test.ts@@ -135,9 +135,13 @@ describe('Recursive Text Chunker', () => {});describe('CJK chunking (v0.32.7)', () => {- test('MARKDOWN_CHUNKER_VERSION is 2', async () => {+ test('MARKDOWN_CHUNKER_VERSION is 3', async () => {+ // v0.40.3.0: bumped 2→3 to signal the post-upgrade reembed sweep that+ // contextual retrieval wrapping is now applied at embed time. Chunk+ // boundaries themselves are unchanged; the bump forces re-embed for+ // pages where chunker_version < 3.const mod = await import('../../src/core/chunkers/recursive.ts');- expect(mod.MARKDOWN_CHUNKER_VERSION).toBe(2);+ expect(mod.MARKDOWN_CHUNKER_VERSION).toBe(3);});test('long pure-Chinese paragraph splits into multiple chunks', () => {diff --git a/test/contextual-retrieval-doctor.serial.test.ts b/test/contextual-retrieval-doctor.serial.test.tsnew file mode 100644index 0000000000..6010a6d106--- /dev/null+++ b/test/contextual-retrieval-doctor.serial.test.ts@@ -0,0 +1,139 @@+/**+ * Tests for the v0.40.3.0 doctor check `contextual_retrieval_coverage`.+ * Pins the SQL predicates + audit-summary integration end-to-end via+ * PGLite + the audit JSONL filesystem path.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { checkContextualRetrievalCoverage } from '../src/commands/doctor.ts';+import { MARKDOWN_CHUNKER_VERSION } from '../src/core/chunkers/recursive.ts';++let engine: PGLiteEngine;+let tmpDir: string;+const originalEnv = process.env.GBRAIN_AUDIT_DIR;++beforeAll(async () => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-doctor-cr-test-'));+ process.env.GBRAIN_AUDIT_DIR = tmpDir;+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ if (originalEnv === undefined) delete process.env.GBRAIN_AUDIT_DIR;+ else process.env.GBRAIN_AUDIT_DIR = originalEnv;+ fs.rmSync(tmpDir, { recursive: true, force: true });+ await engine.disconnect();+});++beforeEach(async () => {+ // Wipe pages between tests so each starts from a known state.+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'test/%'`);+ // Wipe audit files too.+ for (const f of fs.readdirSync(tmpDir)) {+ fs.unlinkSync(path.join(tmpDir, f));+ }+});++describe('contextual_retrieval_coverage doctor check', () => {+ test('empty brain reports ok', async () => {+ const result = await checkContextualRetrievalCoverage(engine);+ expect(result.name).toBe('contextual_retrieval_coverage');+ expect(result.status).toBe('ok');+ });++ test('fully aligned brain reports ok', async () => {+ // Insert a page at current chunker version with mode stamped.+ await engine.executeRaw(+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth, chunker_version, contextual_retrieval_mode)+ VALUES ('default', $1, 'concept', 'Aligned', 'body', $2, 'title')`,+ ['test/aligned', MARKDOWN_CHUNKER_VERSION],+ );+ const result = await checkContextualRetrievalCoverage(engine);+ expect(result.status).toBe('ok');+ expect(result.message).toContain('aligned');+ });++ test('chunker_version drift is flagged with fix hint', async () => {+ await engine.executeRaw(+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth, chunker_version, contextual_retrieval_mode)+ VALUES ('default', $1, 'concept', 'Old chunker', 'body', 2, 'title')`,+ ['test/old-chunker'],+ );+ const result = await checkContextualRetrievalCoverage(engine);+ expect(result.status).toBe('warn');+ expect(result.message).toContain('older chunker_version');+ expect(result.message).toContain('gbrain reindex --markdown');+ });++ test('NULL mode column is flagged separately', async () => {+ await engine.executeRaw(+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth, chunker_version, contextual_retrieval_mode)+ VALUES ('default', $1, 'concept', 'No mode', 'body', $2, NULL)`,+ ['test/no-mode', MARKDOWN_CHUNKER_VERSION],+ );+ const result = await checkContextualRetrievalCoverage(engine);+ expect(result.status).toBe('warn');+ expect(result.message).toContain('never evaluated against CR ladder');+ });++ test('both drift conditions surface together', async () => {+ await engine.executeRaw(+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth, chunker_version, contextual_retrieval_mode)+ VALUES ('default', $1, 'concept', 'Both', 'body', 2, NULL),+ ('default', $2, 'concept', 'Old', 'body', 2, 'title'),+ ('default', $3, 'concept', 'Null mode', 'body', $4, NULL)`,+ ['test/both-drift', 'test/old-only', 'test/null-only', MARKDOWN_CHUNKER_VERSION],+ );+ const result = await checkContextualRetrievalCoverage(engine);+ expect(result.status).toBe('warn');+ expect(result.message).toContain('older chunker_version');+ expect(result.message).toContain('never evaluated against CR ladder');+ });++ test('soft-deleted pages are not counted', async () => {+ await engine.executeRaw(+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth, chunker_version, contextual_retrieval_mode, deleted_at)+ VALUES ('default', $1, 'concept', 'Soft-deleted', 'body', 2, NULL, now())`,+ ['test/deleted-old'],+ );+ const result = await checkContextualRetrievalCoverage(engine);+ expect(result.status).toBe('ok');+ });++ test('non-markdown pages (code) are not counted', async () => {+ await engine.executeRaw(+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth, chunker_version, contextual_retrieval_mode, page_kind)+ VALUES ('default', $1, 'code', 'Code page', 'body', 2, NULL, 'code')`,+ ['test/code-page'],+ );+ const result = await checkContextualRetrievalCoverage(engine);+ expect(result.status).toBe('ok');+ });++ test('audit summary line surfaces recent synopsis failures', async () => {+ // Drop a failure event into the audit JSONL.+ const { computeSynopsisAuditFilename } = await import('../src/core/audit-synopsis.ts');+ const filename = computeSynopsisAuditFilename();+ const event = {+ ts: new Date().toISOString(),+ page_slug: 'test/some-page',+ source_id: 'default',+ chunk_index: 0,+ kind: 'refusal' as const,+ detail: 'stop_reason=content_filter',+ page_level_fallback: true,+ severity: 'warn' as const,+ };+ fs.writeFileSync(path.join(tmpDir, filename), JSON.stringify(event) + '\n');++ const result = await checkContextualRetrievalCoverage(engine);+ expect(result.message).toContain('synopsis failure');+ expect(result.message).toContain('1 triggered page-level fall-back');+ });+});diff --git a/test/contextual-retrieval-resolver.test.ts b/test/contextual-retrieval-resolver.test.tsnew file mode 100644index 0000000000..559639fa2c--- /dev/null+++ b/test/contextual-retrieval-resolver.test.ts@@ -0,0 +1,280 @@+import { describe, test, expect } from 'bun:test';+import {+ resolveContextualRetrievalMode,+ crModeDistinct,+ ALL_CR_MODES,+} from '../src/core/contextual-retrieval-resolver.ts';++describe('resolveContextualRetrievalMode — 9-combo override matrix', () => {+ // The override resolution chain (highest wins):+ // page frontmatter > source row > global mode bundle+ //+ // For each (page-fm, source-row) pair × 3 global modes, the resolver+ // should return the highest-precedence non-NULL value. Mount-trust+ // gate flips the page-frontmatter eligibility for non-host sources.++ const HOST = {+ id: 'default',+ contextual_retrieval_mode: null as string | null,+ trust_frontmatter_overrides: true,+ };++ // 1. page-fm set + source set + global set → page wins+ test('page frontmatter wins over source and global', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: { contextual_retrieval: 'per_chunk_synopsis' },+ source: { ...HOST, contextual_retrieval_mode: 'title' },+ globalMode: 'none',+ });+ expect(r.mode).toBe('per_chunk_synopsis');+ expect(r.source).toBe('page_frontmatter');+ });++ // 2. page-fm absent + source set + global set → source wins+ test('source row wins when page frontmatter absent', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: {},+ source: { ...HOST, contextual_retrieval_mode: 'title' },+ globalMode: 'per_chunk_synopsis',+ });+ expect(r.mode).toBe('title');+ expect(r.source).toBe('source_row');+ });++ // 3. page-fm absent + source absent + global set → global wins+ test('global mode wins when no overrides', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: {},+ source: { ...HOST },+ globalMode: 'per_chunk_synopsis',+ });+ expect(r.mode).toBe('per_chunk_synopsis');+ expect(r.source).toBe('global_mode');+ });++ // 4. page-fm set + source absent + global set → page wins+ test('page frontmatter wins over global when source unset', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: { contextual_retrieval: 'none' },+ source: { ...HOST },+ globalMode: 'per_chunk_synopsis',+ });+ expect(r.mode).toBe('none');+ expect(r.source).toBe('page_frontmatter');+ });++ // 5. page-fm absent + source set to 'none' → source wins (explicit none)+ test('source explicit none beats global', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: {},+ source: { ...HOST, contextual_retrieval_mode: 'none' },+ globalMode: 'per_chunk_synopsis',+ });+ expect(r.mode).toBe('none');+ expect(r.source).toBe('source_row');+ });++ // 6. page-fm 'none' set explicitly → page wins (even though falsy)+ test('page frontmatter explicit none beats source', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: { contextual_retrieval: 'none' },+ source: { ...HOST, contextual_retrieval_mode: 'per_chunk_synopsis' },+ globalMode: 'title',+ });+ expect(r.mode).toBe('none');+ expect(r.source).toBe('page_frontmatter');+ });++ // 7. each mode value is parseable+ test.each(ALL_CR_MODES.map((m) => [m]))('mode %s parses through page frontmatter', (mode) => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: { contextual_retrieval: mode },+ source: { ...HOST },+ globalMode: 'none',+ });+ expect(r.mode).toBe(mode);+ expect(r.source).toBe('page_frontmatter');+ });++ // 8. each mode value parses through source row+ test.each(ALL_CR_MODES.map((m) => [m]))('mode %s parses through source row', (mode) => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: {},+ source: { ...HOST, contextual_retrieval_mode: mode },+ globalMode: 'none',+ });+ expect(r.mode).toBe(mode);+ expect(r.source).toBe('source_row');+ });++ // 9. each mode value as global default+ test.each(ALL_CR_MODES.map((m) => [m]))('mode %s as global default', (mode) => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: {},+ source: { ...HOST },+ globalMode: mode,+ });+ expect(r.mode).toBe(mode);+ expect(r.source).toBe('global_mode');+ });+});++describe('mount-trust gate (D15)', () => {+ // Per D15, a per-page `contextual_retrieval` frontmatter key in a+ // MOUNTED source's page is honored ONLY when that source's+ // trust_frontmatter_overrides is true. Host source (id='default') is+ // always trusted regardless.++ test('host source always trusts page frontmatter', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: { contextual_retrieval: 'per_chunk_synopsis' },+ source: {+ id: 'default',+ contextual_retrieval_mode: null,+ trust_frontmatter_overrides: false, // <-- false but host is trusted regardless+ },+ globalMode: 'none',+ });+ expect(r.mode).toBe('per_chunk_synopsis');+ expect(r.source).toBe('page_frontmatter');+ expect(r.frontmatter_rejected_untrusted_mount).toBeUndefined();+ });++ test('mounted source with trust_frontmatter_overrides=true honors frontmatter', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: { contextual_retrieval: 'per_chunk_synopsis' },+ source: {+ id: 'team-brain',+ contextual_retrieval_mode: null,+ trust_frontmatter_overrides: true,+ },+ globalMode: 'none',+ });+ expect(r.mode).toBe('per_chunk_synopsis');+ expect(r.source).toBe('page_frontmatter');+ });++ test('mounted source with trust_frontmatter_overrides=false rejects frontmatter', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: { contextual_retrieval: 'per_chunk_synopsis' },+ source: {+ id: 'team-brain',+ contextual_retrieval_mode: 'title',+ trust_frontmatter_overrides: false,+ },+ globalMode: 'none',+ });+ // Frontmatter rejected; source row wins.+ expect(r.mode).toBe('title');+ expect(r.source).toBe('source_row');+ expect(r.frontmatter_rejected_untrusted_mount).toBe(true);+ });++ test('mounted source with no source override + rejected frontmatter falls to global', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: { contextual_retrieval: 'per_chunk_synopsis' },+ source: {+ id: 'team-brain',+ contextual_retrieval_mode: null,+ trust_frontmatter_overrides: false,+ },+ globalMode: 'title',+ });+ expect(r.mode).toBe('title');+ expect(r.source).toBe('global_mode');+ expect(r.frontmatter_rejected_untrusted_mount).toBe(true);+ });+});++describe('invalid frontmatter values (D13)', () => {+ test('typo falls through to source/global with invalid_frontmatter_value surfaced', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: { contextual_retrieval: 'per_chunk' }, // typo!+ source: {+ id: 'default',+ contextual_retrieval_mode: 'title',+ trust_frontmatter_overrides: true,+ },+ globalMode: 'none',+ });+ expect(r.mode).toBe('title'); // source wins after typo rejection+ expect(r.source).toBe('source_row');+ expect(r.invalid_frontmatter_value).toBe('per_chunk');+ });++ test('non-string frontmatter value rejected, falls through', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: { contextual_retrieval: 42 as unknown as string },+ source: { id: 'default', contextual_retrieval_mode: null, trust_frontmatter_overrides: true },+ globalMode: 'none',+ });+ expect(r.mode).toBe('none');+ expect(r.source).toBe('global_mode');+ expect(r.invalid_frontmatter_value).toBe('42');+ });++ test('empty string frontmatter falls through', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: { contextual_retrieval: '' },+ source: { id: 'default', contextual_retrieval_mode: null, trust_frontmatter_overrides: true },+ globalMode: 'title',+ });+ expect(r.mode).toBe('title');+ expect(r.source).toBe('global_mode');+ expect(r.invalid_frontmatter_value).toBe('');+ });+});++describe('kill switch (D18)', () => {+ test('kill switch short-circuits to none regardless of overrides', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: { contextual_retrieval: 'per_chunk_synopsis' },+ source: {+ id: 'default',+ contextual_retrieval_mode: 'per_chunk_synopsis',+ trust_frontmatter_overrides: true,+ },+ globalMode: 'per_chunk_synopsis',+ killSwitchDisabled: true,+ });+ expect(r.mode).toBe('none');+ expect(r.source).toBe('kill_switch');+ });++ test('kill switch false runs the normal chain', () => {+ const r = resolveContextualRetrievalMode({+ pageFrontmatter: {},+ source: { id: 'default', contextual_retrieval_mode: null, trust_frontmatter_overrides: true },+ globalMode: 'title',+ killSwitchDisabled: false,+ });+ expect(r.mode).toBe('title');+ expect(r.source).toBe('global_mode');+ });+});++describe('crModeDistinct (D26 P0-4)', () => {+ test('NULL distinct from defined value', () => {+ expect(crModeDistinct(undefined, 'title')).toBe(true);+ expect(crModeDistinct(null, 'title')).toBe(true);+ expect(crModeDistinct('title', undefined)).toBe(true);+ expect(crModeDistinct('title', null)).toBe(true);+ });++ test('NULL not distinct from NULL', () => {+ expect(crModeDistinct(undefined, undefined)).toBe(false);+ expect(crModeDistinct(null, null)).toBe(false);+ expect(crModeDistinct(null, undefined)).toBe(false);+ expect(crModeDistinct(undefined, null)).toBe(false);+ });++ test('equal values not distinct', () => {+ expect(crModeDistinct('title', 'title')).toBe(false);+ expect(crModeDistinct('per_chunk_synopsis', 'per_chunk_synopsis')).toBe(false);+ });++ test('different values distinct', () => {+ expect(crModeDistinct('title', 'per_chunk_synopsis')).toBe(true);+ expect(crModeDistinct('none', 'title')).toBe(true);+ });+});diff --git a/test/contextual-retrieval-service-pure.test.ts b/test/contextual-retrieval-service-pure.test.tsnew file mode 100644index 0000000000..6918d41b39--- /dev/null+++ b/test/contextual-retrieval-service-pure.test.ts@@ -0,0 +1,140 @@+/**+ * Pure-function tests for src/core/contextual-retrieval-service.ts.+ *+ * The full service test (PHASE 1 + PHASE 2 happy path, refusal restart,+ * transient error propagation) needs a real PGLite + gateway stub seam.+ * That lands in test/e2e/contextual-retrieval.test.ts. This file pins+ * the service's pure helpers: corpus_generation hash composition + the+ * expectedMode helper used by the T9 reindex sweep predicate.+ */++import { describe, test, expect } from 'bun:test';+import {+ computeCorpusGeneration,+ computeSourceTextHash,+ expectedModeForPageSourceOnly,+ TITLE_WRAPPER_VERSION,+} from '../src/core/contextual-retrieval-service.ts';++describe('computeCorpusGeneration', () => {+ test('returns 16-char hex hash', () => {+ const h = computeCorpusGeneration({+ crMode: 'title',+ haikuModel: 'anthropic:claude-haiku-4-5-20251001',+ });+ expect(h).toMatch(/^[0-9a-f]{16}$/);+ });++ test('deterministic for same inputs', () => {+ const h1 = computeCorpusGeneration({+ crMode: 'per_chunk_synopsis',+ haikuModel: 'anthropic:claude-haiku-4-5-20251001',+ });+ const h2 = computeCorpusGeneration({+ crMode: 'per_chunk_synopsis',+ haikuModel: 'anthropic:claude-haiku-4-5-20251001',+ });+ expect(h1).toBe(h2);+ });++ test('different mode → different hash', () => {+ const haikuModel = 'anthropic:claude-haiku-4-5-20251001';+ const a = computeCorpusGeneration({ crMode: 'title', haikuModel });+ const b = computeCorpusGeneration({ crMode: 'per_chunk_synopsis', haikuModel });+ const c = computeCorpusGeneration({ crMode: 'none', haikuModel });+ expect(a).not.toBe(b);+ expect(a).not.toBe(c);+ expect(b).not.toBe(c);+ });++ test('different model → different hash', () => {+ const a = computeCorpusGeneration({+ crMode: 'title',+ haikuModel: 'anthropic:claude-haiku-4-5-20251001',+ });+ const b = computeCorpusGeneration({+ crMode: 'title',+ haikuModel: 'anthropic:claude-haiku-future-model',+ });+ expect(a).not.toBe(b);+ });++ test('TITLE_WRAPPER_VERSION is stable across reads', () => {+ // Bump this constant only when changing the wrapper text shape.+ // The hash composition includes it so a future change invalidates+ // prior cache entries.+ expect(TITLE_WRAPPER_VERSION).toBe(1);+ });+});++describe('computeSourceTextHash', () => {+ test('returns 16-char hex', () => {+ expect(computeSourceTextHash('any text')).toMatch(/^[0-9a-f]{16}$/);+ });++ test('deterministic', () => {+ const a = computeSourceTextHash('source text');+ const b = computeSourceTextHash('source text');+ expect(a).toBe(b);+ });++ test('different text → different hash (D27 P1-4 cache invalidation)', () => {+ const a = computeSourceTextHash('original page body');+ const b = computeSourceTextHash('edited page body');+ expect(a).not.toBe(b);+ });++ test('empty input still produces a hash', () => {+ expect(computeSourceTextHash('')).toMatch(/^[0-9a-f]{16}$/);+ });+});++describe('expectedModeForPageSourceOnly (T9 reindex sweep helper)', () => {+ test('kill switch returns none regardless of source/global', () => {+ expect(+ expectedModeForPageSourceOnly({+ source: { id: 'default', contextual_retrieval_mode: 'per_chunk_synopsis' },+ globalMode: 'per_chunk_synopsis',+ killSwitchDisabled: true,+ }),+ ).toBe('none');+ });++ test('source override beats global when set', () => {+ expect(+ expectedModeForPageSourceOnly({+ source: { id: 'team', contextual_retrieval_mode: 'title' },+ globalMode: 'per_chunk_synopsis',+ }),+ ).toBe('title');+ });++ test('global wins when source override is null', () => {+ expect(+ expectedModeForPageSourceOnly({+ source: { id: 'team', contextual_retrieval_mode: null },+ globalMode: 'per_chunk_synopsis',+ }),+ ).toBe('per_chunk_synopsis');+ });++ test('invalid source override (typo) falls through to global', () => {+ expect(+ expectedModeForPageSourceOnly({+ source: { id: 'team', contextual_retrieval_mode: 'per_chunk' as string },+ globalMode: 'title',+ }),+ ).toBe('title');+ });++ test('all three CR modes round-trip through source override', () => {+ for (const mode of ['none', 'title', 'per_chunk_synopsis'] as const) {+ expect(+ expectedModeForPageSourceOnly({+ source: { id: 'team', contextual_retrieval_mode: mode },+ globalMode: 'none',+ }),+ ).toBe(mode);+ }+ });+});diff --git a/test/cross-modal-phase1.test.ts b/test/cross-modal-phase1.test.tsindex f961c0fea7..ccb9cac7e4 100644--- a/test/cross-modal-phase1.test.ts+++ b/test/cross-modal-phase1.test.ts@@ -136,8 +136,12 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {return resolveSearchMode({ mode: 'balanced' });}- test('KNOBS_HASH_VERSION is 3 (v0.36 cross-modal bump)', () => {- expect(KNOBS_HASH_VERSION).toBe(3);+ test('KNOBS_HASH_VERSION is 5 (master v=4 schema-pack; v0.40.3.0 D8 CR appends)', () => {+ // 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.39 T21 bumps+ // to v=4 for schema-pack fields. v0.40.3.0 D8 bumps to v=5 (sequenced+ // behind salem's v=4 graph-signals).+ expect(KNOBS_HASH_VERSION).toBe(5);});test('flipping unified_multimodal changes the hash', () => {diff --git a/test/e2e/cache-gate-pglite.test.ts b/test/e2e/cache-gate-pglite.test.tsnew file mode 100644index 0000000000..2cbb3fa60e--- /dev/null+++ b/test/e2e/cache-gate-pglite.test.ts@@ -0,0 +1,209 @@+/**+ * v0.40.3.0 — query cache invalidation gate (end-to-end against PGLite)+ *+ * The cache gate has TWO layers:+ * Layer 1: corpus-state bookmark (MAX(generation) FROM pages)+ * Layer 2: per-page snapshot (page_generations JSONB)+ *+ * This file pins the integration via real cache writes + lookups, then+ * mutates pages and re-runs the lookup. SCENARIOS:+ *+ * 1. store → lookup returns HIT (bookmark + snapshot match)+ * 2. content UPDATE on a result page → lookup returns MISS (per-page bumped)+ * 3. content UPDATE on a NON-result page → lookup may serve via Layer 2+ * (bookmark fires; snapshot intact) — codex's "subtle but correct" case+ * 4. INSERT new page → lookup serves via Layer 2 (bookmark fires;+ * snapshot empty for new page, no conflict) — codex #4 INSERT coverage+ * 5. LEGACY ROW (pre-v0.40.3.0 shape: empty {} snapshot, zero bookmark)+ * → lookup HIT (IRON-RULE backward compat)+ * 6. DELETE a result page → lookup returns MISS (LEFT JOIN NULL)+ */++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 { SemanticQueryCache } from '../../src/core/search/query-cache.ts';+import type { SearchResult, HybridSearchMeta } from '../../src/core/types.ts';++const FAKE_EMBEDDING_DIM = 1536; // Matches default OpenAI / pglite-schema __EMBEDDING_DIMS__.++function fakeEmbedding(seed: number): Float32Array {+ const v = new Float32Array(FAKE_EMBEDDING_DIM);+ for (let i = 0; i < v.length; i++) {+ v[i] = Math.sin(seed + i * 0.01);+ }+ // Normalize so cosine compares correctly.+ let sum = 0;+ for (let i = 0; i < v.length; i++) sum += v[i] * v[i];+ const mag = Math.sqrt(sum);+ for (let i = 0; i < v.length; i++) v[i] = v[i] / mag;+ return v;+}++function fakeMeta(): HybridSearchMeta {+ return {+ sources_consulted: ['fake'],+ intent: 'general',+ detail: 'medium',+ } as unknown as HybridSearchMeta;+}++describe('cache gate end-to-end (PGLite)', () => {+ let engine: PGLiteEngine;+ let cache: SemanticQueryCache;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ cache = new SemanticQueryCache(engine);+ });++ afterAll(async () => {+ await engine.disconnect();+ });++ beforeEach(async () => {+ await resetPgliteState(engine);+ });++ async function seedPage(slug: string, body: string): Promise<number> {+ const p = await engine.putPage(slug, {+ type: 'note',+ title: slug,+ compiled_truth: body,+ timeline: '',+ frontmatter: {},+ });+ return p.id;+ }++ test('store → lookup HIT (baseline freshness)', async () => {+ const p1 = await seedPage('test/p1', 'alpha bravo');+ const results: SearchResult[] = [+ {+ page_id: p1,+ slug: 'test/p1',+ title: 'test/p1',+ snippet: 'alpha bravo',+ score: 1.0,+ } as unknown as SearchResult,+ ];+ const emb = fakeEmbedding(1);+ await cache.store('alpha bravo', emb, results, fakeMeta(), { sourceId: 'default' });+ const hit = await cache.lookup(emb, { sourceId: 'default' });+ expect(hit.hit).toBe(true);+ expect(hit.results?.length).toBe(1);+ });++ test('content UPDATE on a result page → lookup MISS (per-page bumped)', async () => {+ const p1 = await seedPage('test/p1', 'alpha bravo v1');+ const results: SearchResult[] = [+ { page_id: p1, slug: 'test/p1', title: 'test/p1', snippet: 'x', score: 1.0 } as unknown as SearchResult,+ ];+ const emb = fakeEmbedding(2);+ await cache.store('alpha bravo', emb, results, fakeMeta(), { sourceId: 'default' });++ // Update content_truth — trigger bumps p1.generation+ await engine.putPage('test/p1', {+ type: 'note',+ title: 'test/p1',+ compiled_truth: 'alpha bravo v2 — modified',+ timeline: '',+ frontmatter: {},+ });++ const hit = await cache.lookup(emb, { sourceId: 'default' });+ expect(hit.hit).toBe(false);+ });++ test('INSERT new page → lookup HIT (bookmark fires but snapshot intact — codex #4 case)', async () => {+ const p1 = await seedPage('test/p1', 'alpha');+ const results: SearchResult[] = [+ { page_id: p1, slug: 'test/p1', title: 'test/p1', snippet: 'a', score: 1.0 } as unknown as SearchResult,+ ];+ const emb = fakeEmbedding(3);+ await cache.store('alpha', emb, results, fakeMeta(), { sourceId: 'default' });++ // Create an UNRELATED new page (different topic, not in result set).+ await seedPage('test/p2', 'beta gamma');++ // The bookmark fires (new page bumped MAX(generation)) but Layer 2+ // (per-page snapshot) sees p1's generation unchanged → row serves.+ // This is the SUBTLE correctness property: cache stays useful in+ // brains that are actively being written to.+ const hit = await cache.lookup(emb, { sourceId: 'default' });+ expect(hit.hit).toBe(true);+ });++ test('legacy row (pre-v0.40.3.0 shape) serves normally — IRON-RULE backward compat', async () => {+ const p1 = await seedPage('test/p1', 'gamma delta');+ const emb = fakeEmbedding(4);+ const results: SearchResult[] = [+ { page_id: p1, slug: 'test/p1', title: 'test/p1', snippet: 'g', score: 1.0 } as unknown as SearchResult,+ ];+ // Simulate a pre-v0.40.3.0 row by writing with the new gate then+ // hand-mutating page_generations + max_generation_at_store to the+ // legacy shape.+ await cache.store('gamma delta', emb, results, fakeMeta(), { sourceId: 'default' });+ await engine.executeRaw(+ `UPDATE query_cache+ SET page_generations = '{}'::jsonb,+ max_generation_at_store = 0`,+ );++ // Now write a bunch of content so MAX(generation) > 0. The legacy+ // row's bookmark (0) is less than MAX, so bookmark fires; Layer 2+ // sees empty snapshot → vacuously valid → row serves.+ await seedPage('test/p2', 'unrelated bump');+ await seedPage('test/p3', 'another unrelated bump');++ const hit = await cache.lookup(emb, { sourceId: 'default' });+ expect(hit.hit).toBe(true); // Legacy compat — pre-upgrade rows still serve.+ });++ test('soft-delete result page → lookup MISS (trigger bumps generation)', async () => {+ const p1 = await seedPage('test/p1', 'epsilon');+ const results: SearchResult[] = [+ { page_id: p1, slug: 'test/p1', title: 'test/p1', snippet: 'e', score: 1.0 } as unknown as SearchResult,+ ];+ const emb = fakeEmbedding(5);+ await cache.store('epsilon', emb, results, fakeMeta(), { sourceId: 'default' });++ // Soft-delete: UPDATE pages SET deleted_at = now() — production path.+ // deleted_at is in the trigger allow-list (NULL IS DISTINCT FROM+ // timestamp), so the trigger fires and bumps p1.generation. Layer 2+ // sees the mismatch and invalidates. Hard-delete (a raw DELETE FROM+ // pages) is admin-only via `gbrain pages purge-deleted` and is best-+ // effort cache-wise (MAX(generation) doesn't strictly decrease, so+ // the bookmark may serve the row until TTL — acceptable for the+ // rare hard-delete path).+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE id = $1`, [p1]);++ const hit = await cache.lookup(emb, { sourceId: 'default' });+ expect(hit.hit).toBe(false);+ });++ test('multi-page result: partial bump invalidates (one of two result pages changed)', async () => {+ const p1 = await seedPage('test/p1', 'zeta');+ const p2 = await seedPage('test/p2', 'eta');+ const results: SearchResult[] = [+ { page_id: p1, slug: 'test/p1', title: 'test/p1', snippet: 'z', score: 1.0 } as unknown as SearchResult,+ { page_id: p2, slug: 'test/p2', title: 'test/p2', snippet: 'e', score: 0.9 } as unknown as SearchResult,+ ];+ const emb = fakeEmbedding(6);+ await cache.store('zeta eta', emb, results, fakeMeta(), { sourceId: 'default' });++ // Bump only p2.+ await engine.putPage('test/p2', {+ type: 'note',+ title: 'test/p2',+ compiled_truth: 'eta-v2',+ timeline: '',+ frontmatter: {},+ });++ const hit = await cache.lookup(emb, { sourceId: 'default' });+ expect(hit.hit).toBe(false);+ });+});diff --git a/test/e2e/capture-generation-regression.test.ts b/test/e2e/capture-generation-regression.test.tsnew file mode 100644index 0000000000..598ca4fed5--- /dev/null+++ b/test/e2e/capture-generation-regression.test.ts@@ -0,0 +1,165 @@+/**+ * v0.40.3.0 — capture-generation regression (D3 + codex #5 strengthened)+ *+ * The v0.38 ingestion cathedral added a new write path to pages via the+ * `ingest_capture` Minion handler. The v0.40.3.0 cache-invalidation gate+ * relies on pages.generation being bumped by EVERY write path, via the+ * BEFORE INSERT OR UPDATE trigger on pages.+ *+ * This file pins that the new v0.38 capture write path correctly bumps+ * generation through TWO scenarios:+ *+ * 1. INSERT path (codex #4): ingest_capture with a fresh slug → page+ * is created with generation = MAX(generation) + 1 so any cache+ * row stored before the new page existed has its bookmark fire.+ *+ * 2. UPDATE path: ingest_capture with an existing slug + new content+ * → trigger fires on content-column DISTINCT FROM and bumps+ * generation. Cache rows referencing the page invalidate via+ * Layer 2 (per-page snapshot).+ *+ * IRON-RULE: regression test mandated by the eng-review D3 + codex #5+ * strengthening pass.+ */++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 { makeIngestCaptureHandler } from '../../src/core/minions/handlers/ingest-capture.ts';+import type { MinionJobContext } from '../../src/core/minions/types.ts';+import type { IngestionEvent } from '../../src/core/ingestion/types.ts';+import { createHash } from 'node:crypto';++function sha256Hex(content: string): string {+ return createHash('sha256').update(content).digest('hex');+}++function buildEvent(content: string, sourceUri: string): IngestionEvent {+ return {+ source_id: 'test-src',+ source_kind: 'capture-cli',+ source_uri: sourceUri,+ received_at: new Date().toISOString(),+ content_type: 'text/markdown',+ content,+ content_hash: sha256Hex(content),+ };+}++/**+ * Minimal MinionJobContext for the handler. The handler only reads+ * `job.data`; other fields can be undefined/no-op for this test.+ */+function buildJobCtx(data: Record<string, unknown>): MinionJobContext {+ return {+ data,+ job: { id: 1, name: 'ingest_capture', status: 'active' } as never,+ signal: new AbortController().signal,+ shutdownSignal: new AbortController().signal,+ updateProgress: async () => { /* no-op */ },+ onHeartbeat: undefined,+ readInbox: undefined,+ } as unknown as MinionJobContext;+}++describe('capture-generation regression (D3 + codex #5)', () => {+ let engine: PGLiteEngine;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });++ afterAll(async () => {+ await engine.disconnect();+ });++ beforeEach(async () => {+ await resetPgliteState(engine);+ });++ async function readGeneration(slug: string): Promise<number | null> {+ const rows = await engine.executeRaw<{ generation: number | null }>(+ `SELECT generation FROM pages WHERE slug = $1`,+ [slug],+ );+ return rows[0]?.generation ?? null;+ }++ async function readMaxGeneration(): Promise<number> {+ const rows = await engine.executeRaw<{ v: number }>(+ `SELECT COALESCE(MAX(generation), 0)::bigint AS v FROM pages`,+ );+ return Number(rows[0]?.v ?? 0);+ }++ test('INSERT path (codex #4): new slug from ingest_capture bumps MAX(generation)', async () => {+ // Seed an unrelated page so MAX starts at a known >0 value.+ await engine.putPage('test/baseline', {+ type: 'note',+ title: 'baseline',+ compiled_truth: 'baseline body',+ timeline: '',+ frontmatter: {},+ });+ const baselineMax = await readMaxGeneration();+ expect(baselineMax).toBeGreaterThan(0);++ // Capture creates a NEW page via ingest_capture (INSERT path).+ const handler = makeIngestCaptureHandler(engine);+ const event = buildEvent('# A new captured note\n\nbody.', 'mcp://capture/test-1');+ const newSlug = 'test/capture-new';+ const ctx = buildJobCtx({ event, slug: newSlug, noEmbed: true });+ const result = await handler(ctx);+ expect(result.status).toBe('imported');++ // The new page exists with generation = MAX(previous) + 1.+ const newGen = await readGeneration(newSlug);+ expect(newGen).not.toBeNull();+ expect(newGen).toBeGreaterThan(baselineMax);++ // MAX(generation) strictly increased — bookmark gate would fire for+ // any cache row stored before this insert. This is the codex #4+ // INSERT coverage assertion.+ const newMax = await readMaxGeneration();+ expect(newMax).toBeGreaterThan(baselineMax);+ });++ test('UPDATE path: ingest_capture on existing slug + new content bumps generation', async () => {+ // Seed via ingest_capture (initial INSERT).+ const handler = makeIngestCaptureHandler(engine);+ const v1Event = buildEvent('# Captured v1\n\noriginal body.', 'mcp://capture/u1');+ const slug = 'test/capture-update';+ await handler(buildJobCtx({ event: v1Event, slug, noEmbed: true }));+ const v1Gen = await readGeneration(slug);+ expect(v1Gen).not.toBeNull();++ // Capture an UPDATE: same slug, NEW content (different hash → trigger fires).+ const v2Event = buildEvent('# Captured v2 — modified\n\nupdated body.', 'mcp://capture/u1');+ await handler(buildJobCtx({ event: v2Event, slug, noEmbed: true }));++ // generation must have incremented because compiled_truth IS DISTINCT FROM+ // OR content_hash IS DISTINCT FROM the previous value.+ const v2Gen = await readGeneration(slug);+ expect(v2Gen).not.toBeNull();+ expect(v2Gen!).toBeGreaterThan(v1Gen!);+ });++ test('idempotent UPDATE: capture with same content does NOT bump generation', async () => {+ // Same-content re-capture should be a no-op (trigger short-circuits+ // on IS DISTINCT FROM). This protects cache freshness on re-runs.+ const handler = makeIngestCaptureHandler(engine);+ const event = buildEvent('# Same content', 'mcp://capture/idem');+ const slug = 'test/capture-idem';++ await handler(buildJobCtx({ event, slug, noEmbed: true }));+ const firstGen = await readGeneration(slug);++ await handler(buildJobCtx({ event, slug, noEmbed: true }));+ const secondGen = await readGeneration(slug);++ // Trigger sees content_hash IS NOT DISTINCT FROM → no bump.+ expect(secondGen).toBe(firstGen);+ });+});diff --git a/test/e2e/concurrent-embed-race.test.ts b/test/e2e/concurrent-embed-race.test.tsnew file mode 100644index 0000000000..b39d847eac--- /dev/null+++ b/test/e2e/concurrent-embed-race.test.ts@@ -0,0 +1,203 @@+/**+ * v0.40.3.0 D24 — concurrent upsertChunks race regression test.+ *+ * Pre-fix: two writers racing on the same chunk with both having an+ * embedding would race last-writer-wins via+ * `COALESCE(EXCLUDED.embedding, content_chunks.embedding)`. The slower+ * writer could overwrite a fresher embedding silently.+ *+ * Post-fix (both engines): the text-unchanged branch's CASE WHEN logic+ * lets the fresher `embedded_at` win. Slower writer with a stale+ * embedded_at timestamp loses; existing fresher embedding survives.+ *+ * This test seeds a chunk via upsertChunks, then simulates a slower+ * write by passing an OLDER embedded_at than what's stored. The+ * resulting embedding should be the original (fresher) one, NOT the+ * slower-write input.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';++let engine: PGLiteEngine;+let DIMS: number;++beforeAll(async () => {+ // Configure gateway with a known dimension BEFORE initSchema so the+ // PGLite vector column gets sized predictably regardless of what other+ // tests in this shard process have configured first.+ resetGateway();+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-test-fake-key-for-stub' },+ });+ DIMS = 1536;+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ // Hard-reset the test page + its chunks so each test starts clean.+ // Required when this file runs alongside others in the same bun+ // test shard process (PGLite instance is shared).+ await engine.executeRaw(`DELETE FROM pages WHERE slug = $1`, ['test/race-target']);+ await engine.executeRaw(+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth)+ VALUES ('default', $1, 'concept', 'Race test page', 'body')`,+ ['test/race-target'],+ );+});++function makeVector(seed: number): Float32Array {+ const v = new Float32Array(DIMS);+ for (let i = 0; i < DIMS; i++) v[i] = seed + i * 0.001;+ return v;+}++describe('D24 NULL→non-NULL upsert race fix', () => {+ test('cold path: existing embedding NULL → take new', async () => {+ // First write: chunk_text 'cold' with no prior embedding.+ await engine.upsertChunks(+ 'test/race-target',+ [+ {+ chunk_index: 0,+ chunk_text: 'cold path test',+ chunk_source: 'compiled_truth',+ embedding: makeVector(1.0),+ token_count: 3,+ },+ ],+ { sourceId: 'default' },+ );+ const chunks = await engine.getChunks('test/race-target', { sourceId: 'default' });+ expect(chunks.length).toBe(1);+ // Chunk exists with the embedding we wrote.+ expect(chunks[0].chunk_text).toBe('cold path test');+ });++ test('fresher write wins over stale write (text unchanged)', async () => {+ // Seed: chunk at index 1 with embedded_at = now (recent).+ await engine.upsertChunks(+ 'test/race-target',+ [+ {+ chunk_index: 1,+ chunk_text: 'race text',+ chunk_source: 'compiled_truth',+ embedding: makeVector(2.0),+ token_count: 2,+ },+ ],+ { sourceId: 'default' },+ );++ // Capture the now-stored embedded_at as the reference 'fresh' time.+ const beforeRace = await engine.executeRaw<{ embedded_at: string }>(+ `SELECT embedded_at FROM content_chunks+ WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = 'default')+ AND chunk_index = 1`,+ ['test/race-target'],+ );+ const freshTs = beforeRace[0]?.embedded_at;+ expect(freshTs).toBeTruthy();++ // Simulate a slower writer: text UNCHANGED, but their embedded_at+ // is OLDER (5 minutes ago). Per the D24 fix, this write should+ // NOT overwrite the fresher embedding.+ await engine.executeRaw(+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, embedding, token_count, embedded_at)+ VALUES (+ (SELECT id FROM pages WHERE slug = $1 AND source_id = 'default'),+ 1, 'race text', 'compiled_truth',+ array_fill(0::real, ARRAY[${DIMS}])::vector, -- stale write's embedding+ 2,+ now() - interval '5 minutes'+ )+ ON CONFLICT (page_id, chunk_index) DO UPDATE SET+ chunk_text = EXCLUDED.chunk_text,+ chunk_source = EXCLUDED.chunk_source,+ embedding = CASE+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding+ WHEN content_chunks.embedding IS NULL THEN EXCLUDED.embedding+ WHEN EXCLUDED.embedded_at IS NOT NULL+ AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)+ THEN EXCLUDED.embedding+ ELSE content_chunks.embedding+ END,+ embedded_at = CASE+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.embedding IS NULL THEN NULL+ WHEN content_chunks.embedding IS NULL AND EXCLUDED.embedding IS NOT NULL THEN EXCLUDED.embedded_at+ WHEN EXCLUDED.embedded_at IS NOT NULL+ AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)+ THEN EXCLUDED.embedded_at+ ELSE content_chunks.embedded_at+ END`,+ ['test/race-target'],+ );++ // After the stale write, the embedded_at should be UNCHANGED+ // (fresher value preserved). The text-unchanged branch with stale+ // embedded_at hits the ELSE clause = keep existing.+ const afterRace = await engine.executeRaw<{ embedded_at: string }>(+ `SELECT embedded_at FROM content_chunks+ WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = 'default')+ AND chunk_index = 1`,+ ['test/race-target'],+ );+ // The fresher write's timestamp survives; the stale write loses.+ // Normalize both to ISO strings so Date↔string equality is stable.+ const before = new Date(freshTs!).toISOString();+ const after = new Date(afterRace[0]!.embedded_at!).toISOString();+ expect(after).toBe(before);+ });++ test('text change with no new embedding resets both columns to NULL', async () => {+ // Seed chunk at index 2 with embedding.+ await engine.upsertChunks(+ 'test/race-target',+ [+ {+ chunk_index: 2,+ chunk_text: 'original text',+ chunk_source: 'compiled_truth',+ embedding: makeVector(3.0),+ token_count: 2,+ },+ ],+ { sourceId: 'default' },+ );++ // Re-write with DIFFERENT text but NO embedding (simulates re-chunk+ // path before re-embedding). Both columns should reset to NULL.+ await engine.upsertChunks(+ 'test/race-target',+ [+ {+ chunk_index: 2,+ chunk_text: 'changed text',+ chunk_source: 'compiled_truth',+ // no embedding+ token_count: 2,+ },+ ],+ { sourceId: 'default' },+ );++ const rows = await engine.executeRaw<{ embedded_at: Date | null; embedding_null: boolean }>(+ `SELECT embedded_at, embedding IS NULL AS embedding_null FROM content_chunks+ WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = 'default')+ AND chunk_index = 2`,+ ['test/race-target'],+ );+ expect(rows[0].embedded_at).toBeNull();+ expect(rows[0].embedding_null).toBe(true);+ });+});diff --git a/test/e2e/contextual-retrieval-pglite.test.ts b/test/e2e/contextual-retrieval-pglite.test.tsnew file mode 100644index 0000000000..c226b8b50f--- /dev/null+++ b/test/e2e/contextual-retrieval-pglite.test.ts@@ -0,0 +1,189 @@+/**+ * v0.40.3.0 — contextual retrieval E2E against PGLite (hermetic; no API+ * keys needed; no Postgres needed).+ *+ * Pins the wave's most critical invariants end-to-end:+ *+ * IRON RULE #1 (D20-T1): wrapper text NEVER lands in+ * content_chunks.chunk_text. The wrapped string went to the embedder,+ * but the raw chunk_text stays canonical for FTS / snippets / reranker /+ * debug.+ *+ * IRON RULE #2 (D14): page-level CR mode is stamped on every page after+ * import. NULL on pre-v81 pages; current mode on freshly-imported pages.+ *+ * IRON RULE #3 (D20-T4): fenced code chunks inside markdown pages DON'T+ * get wrapped — only compiled_truth + timeline chunks do.+ *+ * IRON RULE #4 (D18 kill switch): when search.contextual_retrieval_disabled+ * is true, imports skip wrapping AND mode column is stamped 'none'.+ *+ * IRON RULE #5 (T9 reindex sweep): the predicate catches both+ * chunker_version < 3 AND contextual_retrieval_mode IS NULL.+ *+ * Stubs the embedding gateway so the test runs in <1s with no API key.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import {+ __setEmbedTransportForTests,+ configureGateway,+ resetGateway,+} from '../../src/core/ai/gateway.ts';+import { MARKDOWN_CHUNKER_VERSION } from '../../src/core/chunkers/recursive.ts';++const STUB_DIMS = 1536;++let engine: PGLiteEngine;++// Capture the texts the embedder receives so we can assert wrapping+// happened. The stub transport receives the wrapped string array AFTER+// import-file's wrap step.+const embedderInputs: string[][] = [];++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ // Configure gateway with a fake API key so embedding provider resolution+ // succeeds; the transport stub intercepts the actual embedMany call so+ // no real API request fires.+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: STUB_DIMS,+ env: { OPENAI_API_KEY: 'sk-test-fake-key-for-stub' },+ });++ __setEmbedTransportForTests(async ({ values }: any) => {+ embedderInputs.push([...values]);+ return {+ embeddings: values.map(() => new Array<number>(STUB_DIMS).fill(0.001)),+ usage: { tokens: 0 },+ } as any;+ });+});++afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await engine.disconnect();+});++beforeEach(() => {+ embedderInputs.length = 0;+});++describe('contextual retrieval wrapper applies at embed time (D20-T1)', () => {+ test('balanced mode (title tier) wraps embedder input but stores raw chunk_text', async () => {+ // Default mode is balanced → title tier per MODE_BUNDLES.balanced.+ // Import a page with a known title; verify (a) the embedder saw a+ // wrapped string containing the title, AND (b) content_chunks.chunk_text+ // in the DB is the raw, unwrapped chunk text.+ const slug = 'wiki/concepts/acme-funding';+ const content = `---+title: "Acme Corp Series A"+type: concept+---++This is the body of the page. It will be chunked and embedded.++The wrapper SHOULD prepend the title before sending to the embedder,+but should NOT mutate what we store as canonical chunk_text.`;+ await importFromContent(engine, slug, content, { sourceId: 'default' });++ // Verify the embedder saw wrapped text containing the title.+ expect(embedderInputs.length).toBeGreaterThan(0);+ const wrappedTexts = embedderInputs.flat();+ expect(wrappedTexts.length).toBeGreaterThan(0);+ expect(wrappedTexts[0]).toContain('<context>Acme Corp Series A');++ // Critical: stored chunk_text MUST be the raw unwrapped text.+ const chunks = await engine.getChunks(slug, { sourceId: 'default' });+ expect(chunks.length).toBeGreaterThan(0);+ for (const c of chunks) {+ expect(c.chunk_text).not.toContain('<context>');+ expect(c.chunk_text).not.toContain('</context>');+ }+ });++ test('pages.contextual_retrieval_mode is stamped after import (D14)', async () => {+ const slug = 'wiki/concepts/post-mode-check';+ await importFromContent(engine, slug, '---\ntitle: "Test"\n---\n\nBody.', {+ sourceId: 'default',+ });++ const rows = await engine.executeRaw<{ mode: string | null; gen: string | null }>(+ `SELECT contextual_retrieval_mode AS mode, corpus_generation AS gen+ FROM pages WHERE slug = $1 AND source_id = 'default'`,+ [slug],+ );+ expect(rows[0].mode).toBe('title'); // balanced mode default+ expect(rows[0].gen).toMatch(/^[0-9a-f]{16}$/); // hash present+ });++ test('chunker_version stamps to current version after import', async () => {+ const slug = 'wiki/concepts/chunker-version-check';+ await importFromContent(engine, slug, '---\ntitle: "V"\n---\n\nBody.', {+ sourceId: 'default',+ });+ const rows = await engine.executeRaw<{ cv: number }>(+ `SELECT chunker_version AS cv FROM pages WHERE slug = $1 AND source_id = 'default'`,+ [slug],+ );+ expect(rows[0].cv).toBe(MARKDOWN_CHUNKER_VERSION);+ expect(rows[0].cv).toBe(3); // v0.40.3.0 bump+ });+});++describe('per-page frontmatter override (D5)', () => {+ test('per-page contextual_retrieval: none overrides global title default', async () => {+ const slug = 'wiki/concepts/override-test';+ const content = `---+title: "Override Test"+contextual_retrieval: none+---++Body that should NOT be wrapped because frontmatter says 'none'.`;+ await importFromContent(engine, slug, content, { sourceId: 'default' });++ // The embedder should have seen UNWRAPPED text.+ const wrappedTexts = embedderInputs.flat();+ expect(wrappedTexts.length).toBeGreaterThan(0);+ expect(wrappedTexts[0]).not.toContain('<context>');++ const rows = await engine.executeRaw<{ mode: string | null }>(+ `SELECT contextual_retrieval_mode AS mode FROM pages WHERE slug = $1 AND source_id = 'default'`,+ [slug],+ );+ expect(rows[0].mode).toBe('none');+ });+});++describe('T9 reindex sweep predicate', () => {+ test('counts pages with contextual_retrieval_mode IS NULL', async () => {+ // Insert a page with mode explicitly NULL (simulates pre-v81 row).+ await engine.executeRaw(+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth, chunker_version, contextual_retrieval_mode)+ VALUES ('default', $1, 'concept', 'Pre-v81 page', 'body', 3, NULL)+ ON CONFLICT (source_id, slug) DO UPDATE SET contextual_retrieval_mode = NULL`,+ ['wiki/concepts/prev81-row'],+ );++ const { countPending } = await import('../../src/commands/reindex.ts').then((m) => ({+ countPending: (m as any).countPending,+ })).catch(() => ({ countPending: null }));++ // countPending isn't exported, so use the raw predicate:+ const rows = await engine.executeRaw<{ count: number }>(+ `SELECT COUNT(*)::int AS count FROM pages+ WHERE page_kind = 'markdown'+ AND (chunker_version < $1 OR contextual_retrieval_mode IS NULL)+ AND deleted_at IS NULL`,+ [MARKDOWN_CHUNKER_VERSION],+ );+ expect(rows[0].count).toBeGreaterThanOrEqual(1);+ });+});diff --git a/test/embedding-context.test.ts b/test/embedding-context.test.tsnew file mode 100644index 0000000000..85c0b862c5--- /dev/null+++ b/test/embedding-context.test.ts@@ -0,0 +1,162 @@+import { describe, test, expect } from 'bun:test';+import {+ buildContextualPrefix,+ wrapChunkForEmbedding,+ sanitizeTitle,+ sanitizeSynopsis,+ extractFirstTwoSentences,+ modeRequiresHaiku,+ modeRequiresWrapper,+} from '../src/core/embedding-context.ts';++describe('buildContextualPrefix', () => {+ test('returns null for empty/null inputs', () => {+ expect(buildContextualPrefix(null, null)).toBeNull();+ expect(buildContextualPrefix('', '')).toBeNull();+ expect(buildContextualPrefix(undefined, undefined)).toBeNull();+ });++ test('title-only produces title block', () => {+ const result = buildContextualPrefix('Acme Corp Series A', null);+ expect(result).toBe('<context>Acme Corp Series A\n</context>\n');+ });++ test('synopsis-only produces synopsis block', () => {+ const result = buildContextualPrefix(null, 'A funding round summary.');+ expect(result).toBe('<context>\nA funding round summary.\n</context>\n');+ });++ test('both produces full block', () => {+ const result = buildContextualPrefix('Acme Corp Series A', 'A funding round summary.');+ expect(result).toBe('<context>Acme Corp Series A\nA funding round summary.\n</context>\n');+ });+});++describe('wrapChunkForEmbedding', () => {+ const PREFIX = '<context>Page Title\n</context>\n';++ test('wraps non-code chunks with prefix', () => {+ expect(wrapChunkForEmbedding('chunk body', PREFIX, 'compiled_truth')).toBe(+ PREFIX + 'chunk body',+ );+ expect(wrapChunkForEmbedding('chunk body', PREFIX, 'timeline')).toBe(+ PREFIX + 'chunk body',+ );+ });++ test('fenced_code ALWAYS bypasses wrapping (D20-T4)', () => {+ expect(wrapChunkForEmbedding('const x = 1;', PREFIX, 'fenced_code')).toBe('const x = 1;');+ });++ test('null prefix passes through unchanged', () => {+ expect(wrapChunkForEmbedding('chunk body', null, 'compiled_truth')).toBe('chunk body');+ expect(wrapChunkForEmbedding('chunk body', null, 'fenced_code')).toBe('chunk body');+ });++ test('image_asset chunks get wrapped (text-only path)', () => {+ expect(wrapChunkForEmbedding('image caption text', PREFIX, 'image_asset')).toBe(+ PREFIX + 'image caption text',+ );+ });+});++describe('sanitizeTitle (D26 prep)', () => {+ test('strips </context> injection attempts', () => {+ expect(sanitizeTitle('Normal title</context>injection')).toBe('Normal titleinjection');+ expect(sanitizeTitle('</context></context>')).toBe('');+ expect(sanitizeTitle('A </CONTEXT> B')).toBe('A B');+ });++ test('collapses whitespace runs', () => {+ expect(sanitizeTitle('A B\n\nC\tD')).toBe('A B C D');+ });++ test('trims and caps', () => {+ expect(sanitizeTitle(' spaced ')).toBe('spaced');+ const long = 'a'.repeat(500);+ expect(sanitizeTitle(long).length).toBe(300);+ });++ test('empty / null inputs return empty', () => {+ expect(sanitizeTitle('')).toBe('');+ expect(sanitizeTitle(' ')).toBe('');+ });+});++describe('sanitizeSynopsis', () => {+ test('same shape as sanitizeTitle for the injection cases', () => {+ expect(sanitizeSynopsis('synopsis</context>tail')).toBe('synopsistail');+ expect(sanitizeSynopsis(' multi\n line ')).toBe('multi line');+ });+});++describe('extractFirstTwoSentences', () => {+ test('English text with period boundary', () => {+ const text = 'First sentence. Second sentence. Third sentence.';+ const result = extractFirstTwoSentences(text);+ expect(result).toContain('First sentence');+ expect(result).toContain('Second sentence');+ expect(result).not.toContain('Third sentence');+ });++ test('question mark boundary', () => {+ const text = 'Question one? Sentence two. Third.';+ const result = extractFirstTwoSentences(text);+ expect(result).toContain('Question one');+ expect(result).toContain('Sentence two');+ expect(result).not.toContain('Third');+ });++ test('CJK sentence delimiters', () => {+ const text = '第一句。第二句。第三句。';+ const result = extractFirstTwoSentences(text);+ expect(result).toContain('第一句');+ expect(result).toContain('第二句');+ expect(result).not.toContain('第三句');+ });++ test('single run-on sentence capped at 300 chars', () => {+ const text = 'a'.repeat(1000);+ expect(extractFirstTwoSentences(text).length).toBe(300);+ });++ test('empty input returns empty', () => {+ expect(extractFirstTwoSentences('')).toBe('');+ });++ test('text with no sentence delimiters returns whole text up to cap', () => {+ const text = 'no delimiter here at all';+ expect(extractFirstTwoSentences(text)).toBe(text);+ });+});++describe('modeRequiresHaiku / modeRequiresWrapper', () => {+ test('per_chunk_synopsis requires Haiku', () => {+ expect(modeRequiresHaiku('per_chunk_synopsis')).toBe(true);+ expect(modeRequiresHaiku('title')).toBe(false);+ expect(modeRequiresHaiku('none')).toBe(false);+ });++ test('title and per_chunk_synopsis require wrapper; none does not', () => {+ expect(modeRequiresWrapper('per_chunk_synopsis')).toBe(true);+ expect(modeRequiresWrapper('title')).toBe(true);+ expect(modeRequiresWrapper('none')).toBe(false);+ });+});++describe('chunk_text storage separation (D20-T1 IRON-RULE regression guard)', () => {+ // The critical v0.40.3.0 invariant: wrapper text MUST NOT land in+ // content_chunks.chunk_text. Callers wrap at embed call only. This test+ // pins the helper's contract: wrapChunkForEmbedding RETURNS the wrapped+ // string but the input chunkText is not mutated, so the caller can+ // safely pass chunk_text as-is to upsertChunks.+ test('wrapping does not mutate input', () => {+ const original = 'sentence to embed';+ const prefix = '<context>Title\n</context>\n';+ const wrapped = wrapChunkForEmbedding(original, prefix, 'compiled_truth');+ expect(wrapped).toBe(prefix + original);+ // Input string reference is not changed; the caller's chunk.chunk_text+ // can safely flow to the DB without the wrapper.+ expect(original).toBe('sentence to embed');+ });+});diff --git a/test/mode-switch-ux.test.ts b/test/mode-switch-ux.test.tsnew file mode 100644index 0000000000..cd85208a58--- /dev/null+++ b/test/mode-switch-ux.test.ts@@ -0,0 +1,166 @@+/**+ * v0.40.3.0 — mode-switch UX (D3)+ *+ * Pure unit tests for the 3 exports:+ * - summarizeTransition: 5-cell matrix + invalid fallthrough+ * - probeWorkerAvailable: active / stale / never_seen branches via DI+ * - buildReindexIdempotencyKey: content-stable invariance (codex D12 #1)+ */++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 {+ summarizeTransition,+ probeWorkerAvailable,+ buildReindexIdempotencyKey,+ WORKER_STALE_THRESHOLD_MS,+} from '../src/core/search/mode-switch-ux.ts';++describe('summarizeTransition (5-cell matrix + invalid fallthrough)', () => {+ test('any → tokenmax: tokenmax_opt_in with reindex required', () => {+ const s = summarizeTransition('balanced', 'tokenmax');+ expect(s.kind).toBe('tokenmax_opt_in');+ expect(s.reindex_required).toBe(true);+ expect(s.reindex_command).toBe('gbrain reindex --markdown');+ expect(s.cost_estimate_per_query_cents).toBeGreaterThan(0);+ expect(s.callout_lines.some((l) => l.includes('tokenmax'))).toBe(true);+ });++ test('first-time any → tokenmax (null → tokenmax)', () => {+ const s = summarizeTransition(null, 'tokenmax');+ expect(s.kind).toBe('tokenmax_opt_in');+ expect(s.reindex_required).toBe(true);+ });++ test('balanced → conservative: narrowing, no reindex', () => {+ const s = summarizeTransition('balanced', 'conservative');+ expect(s.kind).toBe('narrowing');+ expect(s.reindex_required).toBe(false);+ expect(s.callout_lines.some((l) => l.includes('conservative'))).toBe(true);+ });++ test('tokenmax → balanced: narrowing (lower narrowness wins)', () => {+ const s = summarizeTransition('tokenmax', 'balanced');+ expect(s.kind).toBe('narrowing');+ expect(s.reindex_required).toBe(false);+ });++ test('conservative → balanced: broadening, no reindex', () => {+ const s = summarizeTransition('conservative', 'balanced');+ expect(s.kind).toBe('broadening');+ expect(s.reindex_required).toBe(false);+ });++ test('first-time set (null → balanced): broadening', () => {+ const s = summarizeTransition(null, 'balanced');+ expect(s.kind).toBe('broadening');+ expect(s.reindex_required).toBe(false);+ expect(s.callout_lines.some((l) => l.includes('First-time'))).toBe(true);+ });++ test('same → same: no_change with empty callout', () => {+ const s = summarizeTransition('balanced', 'balanced');+ expect(s.kind).toBe('no_change');+ expect(s.reindex_required).toBe(false);+ expect(s.callout_lines).toEqual([]);+ });++ test('any → invalid: invalid_new_mode with valid-options hint', () => {+ const s = summarizeTransition('balanced', 'not-a-real-mode');+ expect(s.kind).toBe('invalid_new_mode');+ expect(s.reindex_required).toBe(false);+ expect(s.callout_lines.some((l) => l.includes('conservative'))).toBe(true);+ expect(s.callout_lines.some((l) => l.includes('tokenmax'))).toBe(true);+ });+});++describe('probeWorkerAvailable (DI for active/stale/never_seen)', () => {+ let engine: PGLiteEngine;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });++ afterAll(async () => {+ await engine.disconnect();+ });++ beforeEach(async () => {+ await resetPgliteState(engine);+ });++ test('never_seen when minion_jobs has no recent activity', async () => {+ const result = await probeWorkerAvailable(engine);+ expect(result.status).toBe('never_seen');+ expect(result.paste_ready_start_command).toBe('gbrain jobs work');+ expect(result.last_heartbeat_iso).toBeUndefined();+ });++ test('active when minion_jobs activity is fresh (<2 min)', async () => {+ // Seed a recently-started job.+ await engine.executeRaw(+ `INSERT INTO minion_jobs (queue, name, data, status, started_at)+ VALUES ('default', 'test-job', '{}'::jsonb, 'active', now())`,+ );+ const result = await probeWorkerAvailable(engine);+ expect(result.status).toBe('active');+ expect(result.last_heartbeat_iso).toBeDefined();+ });++ test('stale when activity is older than 2 min but within 10-min window', async () => {+ // Seed a 5-minute-old started_at (within 10-min query window, > 2-min stale).+ await engine.executeRaw(+ `INSERT INTO minion_jobs (queue, name, data, status, started_at)+ VALUES ('default', 'test-stale-job', '{}'::jsonb, 'completed',+ now() - INTERVAL '5 minutes')`,+ );+ const result = await probeWorkerAvailable(engine);+ expect(result.status).toBe('stale');+ expect(result.last_heartbeat_iso).toBeDefined();+ });++ test('threshold constant is 2 minutes (120_000 ms)', () => {+ expect(WORKER_STALE_THRESHOLD_MS).toBe(120_000);+ });+});++describe('buildReindexIdempotencyKey (codex D12 Bug 1 content-stable invariance)', () => {+ test('same inputs produce identical key', () => {+ const k1 = buildReindexIdempotencyKey('default', 2, 'tokenmax');+ const k2 = buildReindexIdempotencyKey('default', 2, 'tokenmax');+ expect(k1).toBe(k2);+ });++ test('key shape matches the canonical pattern', () => {+ const k = buildReindexIdempotencyKey('default', 2, 'tokenmax');+ expect(k).toBe('cr-backfill:default:2:tokenmax');+ });++ test('different source_id produces different key', () => {+ const k1 = buildReindexIdempotencyKey('default', 2, 'tokenmax');+ const k2 = buildReindexIdempotencyKey('other-source', 2, 'tokenmax');+ expect(k1).not.toBe(k2);+ });++ test('different chunker_version produces different key (re-chunk = new key)', () => {+ const k1 = buildReindexIdempotencyKey('default', 2, 'tokenmax');+ const k2 = buildReindexIdempotencyKey('default', 3, 'tokenmax');+ expect(k1).not.toBe(k2);+ });++ test('different mode produces different key', () => {+ const k1 = buildReindexIdempotencyKey('default', 2, 'tokenmax');+ const k2 = buildReindexIdempotencyKey('default', 2, 'balanced');+ expect(k1).not.toBe(k2);+ });++ test('NOT timestamp-based: two consecutive runs with same state produce same key', async () => {+ const k1 = buildReindexIdempotencyKey('default', 2, 'tokenmax');+ await new Promise((r) => setTimeout(r, 10));+ const k2 = buildReindexIdempotencyKey('default', 2, 'tokenmax');+ expect(k1).toBe(k2);+ });+});diff --git a/test/mounts-cli.test.ts b/test/mounts-cli.test.tsindex f67a33a3b4..59e3471f34 100644--- a/test/mounts-cli.test.ts+++ b/test/mounts-cli.test.ts@@ -238,3 +238,126 @@ describe('runMounts — end-to-end add/list/remove', () => {});});});++// v0.40.3.0 (D4 + T6): 4 new verbs — enable, disable, trust-frontmatter,+// untrust-frontmatter. We invoke the public runMounts() dispatcher so the+// switch table is exercised end-to-end, then read back the mounts.json+// to assert the flag was persisted.++describe('v0.40.3.0 — mount flag verbs', () => {+ // Import runMounts lazily so the env-mutating withFakeHome wrapper has+ // time to redirect HOME before the module reads it.+ async function seedMount(mountsPath: string, id: string): Promise<void> {+ const parsed = parseAddArgs([+ id,+ '--path', mountsPath,+ '--engine', 'pglite',+ '--db-path', `/tmp/${id}/.pg`,+ ]);+ const file = readMountsFile(mountsPath);+ file.mounts.push({+ id: parsed.id,+ path: parsed.path,+ engine: parsed.engine,+ database_path: parsed.database_path,+ enabled: true,+ });+ writeMountsFile(file, mountsPath);+ }++ test('enable → disable → enable cycle persists', async () => {+ const { runMounts } = await import('../src/commands/mounts.ts');+ await withFakeHomeAsync(async (mountsPath) => {+ await seedMount(mountsPath, 'm1');++ await runMounts(['disable', 'm1']);+ let file = readMountsFile(mountsPath);+ expect(file.mounts[0].enabled).toBe(false);++ await runMounts(['enable', 'm1']);+ file = readMountsFile(mountsPath);+ expect(file.mounts[0].enabled).toBe(true);+ });+ });++ test('trust-frontmatter → untrust-frontmatter cycle preserves other fields', async () => {+ const { runMounts } = await import('../src/commands/mounts.ts');+ await withFakeHomeAsync(async (mountsPath) => {+ await seedMount(mountsPath, 'm-trust');++ await runMounts(['trust-frontmatter', 'm-trust']);+ let file = readMountsFile(mountsPath);+ expect(file.mounts[0].trust_frontmatter_overrides).toBe(true);+ // Preserve other fields:+ expect(file.mounts[0].engine).toBe('pglite');+ expect(file.mounts[0].database_path).toBe('/tmp/m-trust/.pg');++ await runMounts(['untrust-frontmatter', 'm-trust']);+ file = readMountsFile(mountsPath);+ expect(file.mounts[0].trust_frontmatter_overrides).toBe(false);++ // Re-trust restores. Trip → untrust → trust → untrust cycle.+ await runMounts(['trust-frontmatter', 'm-trust']);+ file = readMountsFile(mountsPath);+ expect(file.mounts[0].trust_frontmatter_overrides).toBe(true);+ });+ });++ test('missing mount id → loud rejection with list-hint', async () => {+ const { runMounts } = await import('../src/commands/mounts.ts');+ await withFakeHomeAsync(async (mountsPath) => {+ await seedMount(mountsPath, 'real-mount');+ // Use a typo+ await expect(runMounts(['trust-frontmatter', 'typo-mount'])).rejects.toThrow(+ /typo-mount/,+ );+ });+ });++ test('host brain rejection: cannot trust-frontmatter "host"', async () => {+ const { runMounts } = await import('../src/commands/mounts.ts');+ await withFakeHomeAsync(async (mountsPath) => {+ await seedMount(mountsPath, 'm-host-test');+ await expect(runMounts(['trust-frontmatter', 'host'])).rejects.toThrow(+ /Cannot trust-frontmatter host brain/,+ );+ });+ });++ test('enable on already-enabled mount: no-op (idempotent)', async () => {+ const { runMounts } = await import('../src/commands/mounts.ts');+ await withFakeHomeAsync(async (mountsPath) => {+ await seedMount(mountsPath, 'm-idem');+ // Mount starts enabled=true. Calling enable again should be a no-op+ // (no file churn, message indicates already-enabled).+ await runMounts(['enable', 'm-idem']);+ const file = readMountsFile(mountsPath);+ expect(file.mounts[0].enabled).toBe(true);+ });+ });+});++/**+ * Async variant of withFakeHome for tests that await runMounts().+ *+ * v0.40.3.0: ALSO sets GBRAIN_MOUNTS_PATH because libuv caches homedir()+ * on some platforms, so HOME mutation alone isn't picked up by+ * runMounts's internal getMountsPath() call.+ */+async function withFakeHomeAsync<T>(fn: (mountsPath: string) => Promise<T>): Promise<T> {+ const home = mktmp('fake-home-');+ const prev = process.env.HOME;+ const prevMounts = process.env.GBRAIN_MOUNTS_PATH;+ process.env.HOME = home;+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ const mountsPath = join(home, '.gbrain', 'mounts.json');+ process.env.GBRAIN_MOUNTS_PATH = mountsPath;+ try {+ return await fn(mountsPath);+ } finally {+ if (prev !== undefined) process.env.HOME = prev;+ else delete process.env.HOME;+ if (prevMounts !== undefined) process.env.GBRAIN_MOUNTS_PATH = prevMounts;+ else delete process.env.GBRAIN_MOUNTS_PATH;+ }+}diff --git a/test/query-cache-gate.test.ts b/test/query-cache-gate.test.tsnew file mode 100644index 0000000000..babe9d08b3--- /dev/null+++ b/test/query-cache-gate.test.ts@@ -0,0 +1,242 @@+/**+ * v0.40.3.0 — query-cache-gate.ts (cache invalidation gate)+ *+ * Pure unit tests for the two helpers. Both helpers are pure functions+ * (the validator) or take an engine argument (the snapshot builder); the+ * latter uses a PGLite engine to test the real SQL fragment.+ *+ * Coverage:+ * - buildPageGenerationsSnapshot: empty pageIds, populated pageIds,+ * bookmark capture, missing pages excluded (LEFT JOIN equivalent).+ * - validateCacheRowAgainstPages: vacuously valid for legacy/empty,+ * bookmark short-circuit, single-page bump invalidates, deleted page+ * invalidates, multi-page partial bump invalidates, integer-JSONB+ * shape regression (string-typed values).+ * - CACHE_GATE_WHERE_CLAUSE: source-text shape regression (grep guards).+ */++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 {+ buildPageGenerationsSnapshot,+ validateCacheRowAgainstPages,+ CACHE_GATE_WHERE_CLAUSE,+ type PageGenerationsSnapshot,+} from '../src/core/search/query-cache-gate.ts';++describe('validateCacheRowAgainstPages (pure validator)', () => {+ test('vacuously valid for legacy empty snapshot (regression: pre-v0.40.3.0 rows must serve)', () => {+ const snapshot: PageGenerationsSnapshot = {+ page_generations: {},+ max_generation_at_store: 0,+ };+ // Legacy row: stored when brain had MAX(generation)=0 (or column didn't exist).+ // Current brain has been heavily written. Bookmark says stale, snapshot is empty.+ const ok = validateCacheRowAgainstPages(snapshot, {+ max_generation: 999,+ page_generations: {},+ });+ expect(ok).toBe(true); // IRON-RULE: legacy rows serve.+ });++ test('bookmark short-circuit: MAX <= stored → valid without per-page work', () => {+ const snapshot: PageGenerationsSnapshot = {+ page_generations: { '1': 5, '2': 7 },+ max_generation_at_store: 10,+ };+ const ok = validateCacheRowAgainstPages(snapshot, {+ max_generation: 10, // No writes since store+ page_generations: { '1': 5, '2': 7 },+ });+ expect(ok).toBe(true);+ });++ test('single-page bumped invalidates', () => {+ const snapshot: PageGenerationsSnapshot = {+ page_generations: { '1': 5, '2': 7 },+ max_generation_at_store: 7,+ };+ const ok = validateCacheRowAgainstPages(snapshot, {+ max_generation: 8, // Bookmark fires+ page_generations: { '1': 5, '2': 8 }, // Page 2 bumped+ });+ expect(ok).toBe(false);+ });++ test('deleted page invalidates', () => {+ const snapshot: PageGenerationsSnapshot = {+ page_generations: { '1': 5, '2': 7 },+ max_generation_at_store: 7,+ };+ const ok = validateCacheRowAgainstPages(snapshot, {+ max_generation: 8,+ page_generations: { '1': 5, '2': undefined }, // Page 2 deleted+ });+ expect(ok).toBe(false);+ });++ test('multi-page partial bump invalidates', () => {+ const snapshot: PageGenerationsSnapshot = {+ page_generations: { '1': 5, '2': 7, '3': 9 },+ max_generation_at_store: 9,+ };+ const ok = validateCacheRowAgainstPages(snapshot, {+ max_generation: 10,+ page_generations: { '1': 5, '2': 7, '3': 10 }, // Only page 3 bumped+ });+ expect(ok).toBe(false);+ });++ test('codex D11 critical case: new page after store time → bookmark fires → empty snapshot is vacuously valid', () => {+ // Subtle: a brand-new page makes MAX increase but the cache row's+ // page_generations snapshot doesn't reference it. The bookmark+ // detects the corpus changed. Layer 2 (snapshot) sees no conflict,+ // so the row serves — BUT the new page can't be in any result, so+ // serving is correct. Closes codex #4 INSERT coverage gap.+ const snapshot: PageGenerationsSnapshot = {+ page_generations: { '1': 5, '2': 7 },+ max_generation_at_store: 7,+ };+ const ok = validateCacheRowAgainstPages(snapshot, {+ max_generation: 8, // Page 3 was created+ page_generations: { '1': 5, '2': 7 }, // Pages in snapshot unchanged+ });+ // Per the design: bookmark fires; Layer 2 confirms snapshot intact;+ // row serves. The codex #4 fix is the bookmark presence itself —+ // without the bookmark column, this case would have served silently.+ expect(ok).toBe(true);+ });+});++describe('buildPageGenerationsSnapshot (PGLite-backed)', () => {+ let engine: PGLiteEngine;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });++ afterAll(async () => {+ await engine.disconnect();+ });++ beforeEach(async () => {+ await resetPgliteState(engine);+ });++ test('empty pageIds: snapshot has empty page_generations, MAX bookmark only', async () => {+ // Seed a page so MAX > 0.+ await engine.putPage('test/p1', {+ type: 'note',+ title: 'p1',+ compiled_truth: 'body',+ timeline: '',+ frontmatter: {},+ });+ const snap = await buildPageGenerationsSnapshot(engine, []);+ expect(snap.page_generations).toEqual({});+ expect(snap.max_generation_at_store).toBeGreaterThan(0);+ });++ test('populated pageIds: snapshot captures generation per page + MAX', async () => {+ const p1 = await engine.putPage('test/p1', {+ type: 'note',+ title: 'p1',+ compiled_truth: 'body1',+ timeline: '',+ frontmatter: {},+ });+ const p2 = await engine.putPage('test/p2', {+ type: 'note',+ title: 'p2',+ compiled_truth: 'body2',+ timeline: '',+ frontmatter: {},+ });+ const snap = await buildPageGenerationsSnapshot(engine, [p1.id, p2.id]);+ expect(Object.keys(snap.page_generations).length).toBe(2);+ expect(snap.page_generations[String(p1.id)]).toBeGreaterThan(0);+ expect(snap.page_generations[String(p2.id)]).toBeGreaterThan(0);+ expect(snap.max_generation_at_store).toBeGreaterThanOrEqual(+ Math.max(snap.page_generations[String(p1.id)], snap.page_generations[String(p2.id)]),+ );+ });++ test('integer-typed JSONB shape regression: stored values are numbers, not strings', async () => {+ const p1 = await engine.putPage('test/p1', {+ type: 'note',+ title: 'p1',+ compiled_truth: 'body1',+ timeline: '',+ frontmatter: {},+ });+ const snap = await buildPageGenerationsSnapshot(engine, [p1.id]);+ const v = snap.page_generations[String(p1.id)];+ expect(typeof v).toBe('number');+ expect(Number.isInteger(v)).toBe(true);+ });++ test('non-existent pageIds: skipped (LEFT JOIN equivalent — no entry in page_generations)', async () => {+ await engine.putPage('test/p1', {+ type: 'note',+ title: 'p1',+ compiled_truth: 'body',+ timeline: '',+ frontmatter: {},+ });+ // Pass two IDs: one valid, one that doesn't exist.+ const rows = await engine.executeRaw<{ id: number }>(`SELECT id FROM pages LIMIT 1`);+ const p1Id = rows[0].id;+ const snap = await buildPageGenerationsSnapshot(engine, [p1Id, 999999]);+ expect(snap.page_generations[String(p1Id)]).toBeGreaterThan(0);+ expect(snap.page_generations['999999']).toBeUndefined();+ });++ test('after content UPDATE: generation bumps and snapshot reflects new value', async () => {+ const p1 = await engine.putPage('test/p1', {+ type: 'note',+ title: 'p1',+ compiled_truth: 'body-v1',+ timeline: '',+ frontmatter: {},+ });+ const before = await buildPageGenerationsSnapshot(engine, [p1.id]);+ const beforeGen = before.page_generations[String(p1.id)];++ // Update compiled_truth (content allow-list column → trigger bumps).+ await engine.putPage('test/p1', {+ type: 'note',+ title: 'p1',+ compiled_truth: 'body-v2',+ timeline: '',+ frontmatter: {},+ });++ const after = await buildPageGenerationsSnapshot(engine, [p1.id]);+ const afterGen = after.page_generations[String(p1.id)];+ expect(afterGen).toBeGreaterThan(beforeGen);+ });+});++describe('CACHE_GATE_WHERE_CLAUSE (SQL shape regression)', () => {+ test('contains Layer 1 bookmark check (MAX(generation) <= qc.max_generation_at_store)', () => {+ expect(CACHE_GATE_WHERE_CLAUSE).toContain('MAX(generation)');+ expect(CACHE_GATE_WHERE_CLAUSE).toContain('qc.max_generation_at_store');+ });++ test('contains Layer 2 per-page snapshot (jsonb_each + LEFT JOIN)', () => {+ expect(CACHE_GATE_WHERE_CLAUSE).toContain('jsonb_each(qc.page_generations)');+ expect(CACHE_GATE_WHERE_CLAUSE).toContain('LEFT JOIN pages');+ });++ test('legacy empty-snapshot shortcut present (regression: pre-v0.40.3.0 rows must serve)', () => {+ expect(CACHE_GATE_WHERE_CLAUSE).toContain(`qc.page_generations = '{}'::jsonb`);+ });++ test('per-page mismatch path checks both deletion (NULL) and bump (!=)', () => {+ expect(CACHE_GATE_WHERE_CLAUSE).toContain('p.id IS NULL');+ expect(CACHE_GATE_WHERE_CLAUSE).toContain('p.generation <>');+ });+});diff --git a/test/reindex.test.ts b/test/reindex.test.tsindex 9901f2044a..6c12bad4ac 100644--- a/test/reindex.test.ts+++ b/test/reindex.test.ts@@ -70,7 +70,16 @@ describe('gbrain reindex --markdown (v0.32.7)', () => {test('idempotent: re-run on a fully-updated brain reports nothing to do', async () => {await seedLegacyPage('note-e', 'body e');+ // First pass with --no-embed bumps chunker_version but does NOT stamp+ // contextual_retrieval_mode (import-file.ts:457-466 skips CR stamping+ // when noEmbed). Then manually stamp CR mode so the brain is "fully+ // updated" for the idempotency test. In production, embed (--no-embed+ // OFF) does both; reindex tests use --no-embed to avoid API keys.await runReindex(engine, ['--markdown', '--no-embed']);+ await engine.executeRaw(+ `UPDATE pages SET contextual_retrieval_mode = 'title'+ WHERE slug = 'note-e' AND contextual_retrieval_mode IS NULL`,+ );const second = await runReindex(engine, ['--markdown', '--no-embed']);expect(second.pending).toBe(0);expect(second.reindexed).toBe(0);@@ -121,13 +130,16 @@ describe('gbrain reindex --markdown (v0.32.7)', () => {expect(Number(rows[0].chunker_version)).toBe(MARKDOWN_CHUNKER_VERSION);});- test('skips pages already at current chunker_version', async () => {+ test('skips pages already at current chunker_version (and CR mode set)', async () => {// Pre-bump page (chunker_version = 1)await seedLegacyPage('note-up', 'pending body');- // Already-bumped page (chunker_version = current)+ // Already-bumped page (chunker_version = current) AND contextual+ // retrieval mode set. v0.40.3.0: predicate also catches+ // contextual_retrieval_mode IS NULL, so seeding 'title' here lets the+ // page legitimately skip the reindex sweep.await engine.executeRaw(- `INSERT INTO pages (slug, type, title, compiled_truth, page_kind, chunker_version)- VALUES ('note-current', 'note', 'note-current', 'current body', 'markdown', $1)`,+ `INSERT INTO pages (slug, type, title, compiled_truth, page_kind, chunker_version, contextual_retrieval_mode)+ VALUES ('note-current', 'note', 'note-current', 'current body', 'markdown', $1, 'title')`,[MARKDOWN_CHUNKER_VERSION],);diff --git a/test/remediation-step.test.ts b/test/remediation-step.test.tsnew file mode 100644index 0000000000..fb0cd0140b--- /dev/null+++ b/test/remediation-step.test.ts@@ -0,0 +1,182 @@+/**+ * v0.40.3.0 — RemediationStep (D6 refactor + factory tests)+ *+ * The canonical RemediationStep type lives at src/core/remediation-step.ts+ * (lifted from brain-score-recommendations.ts). This file pins the+ * factory's content-stable invariance (codex D12 Bug 2) + the back-compat+ * re-exports so other doctor checks can adopt the type without breaking+ * existing brain-score-recommendations imports.+ *+ * Coverage:+ * - canonicalJson: deterministic across key orderings + nested objects+ * - idempotencyKey: shape + content invariance+ * - makeRemediationStep: defaults, full opt set, id derivation,+ * canonical-JSON invariance (codex D12 Bug 2)+ * - back-compat: import { Remediation } from brain-score-recommendations+ * still resolves to RemediationStep (same type)+ */++import { describe, expect, test } from 'bun:test';+import {+ canonicalJson,+ idempotencyKey,+ makeRemediationStep,+ type RemediationStep,+} from '../src/core/remediation-step.ts';+import type { Remediation } from '../src/core/brain-score-recommendations.ts';++describe('canonicalJson (D12 Bug 2 canonical serialization)', () => {+ test('object key ordering is deterministic', () => {+ const a = canonicalJson({ a: 1, b: 2, c: 3 });+ const b = canonicalJson({ c: 3, b: 2, a: 1 });+ const c = canonicalJson({ b: 2, a: 1, c: 3 });+ expect(a).toBe(b);+ expect(b).toBe(c);+ });++ test('nested objects also sort keys', () => {+ const a = canonicalJson({ outer: { z: 1, a: 2 }, top: 'x' });+ const b = canonicalJson({ top: 'x', outer: { a: 2, z: 1 } });+ expect(a).toBe(b);+ });++ test('arrays preserve order (not sorted)', () => {+ expect(canonicalJson([3, 1, 2])).not.toBe(canonicalJson([1, 2, 3]));+ });++ test('null + primitives serialize via JSON.stringify', () => {+ expect(canonicalJson(null)).toBe('null');+ expect(canonicalJson(42)).toBe('42');+ expect(canonicalJson('hi')).toBe('"hi"');+ expect(canonicalJson(true)).toBe('true');+ });++ test('handles arrays of objects with key reordering inside', () => {+ const a = canonicalJson([{ a: 1, b: 2 }, { c: 3 }]);+ const b = canonicalJson([{ b: 2, a: 1 }, { c: 3 }]);+ expect(a).toBe(b);+ });+});++describe('idempotencyKey', () => {+ test('shape: <source>:<job>:<8-hex>', () => {+ const k = idempotencyKey('default', 'sync', { repoPath: '/x' });+ expect(k).toMatch(/^default:sync:[0-9a-f]{8}$/);+ });++ test('same inputs produce identical key', () => {+ const k1 = idempotencyKey('default', 'sync', { repoPath: '/x', sourceId: 'y' });+ const k2 = idempotencyKey('default', 'sync', { repoPath: '/x', sourceId: 'y' });+ expect(k1).toBe(k2);+ });++ test('key ordering invariance (codex D12 Bug 2)', () => {+ const k1 = idempotencyKey('default', 'sync', { a: 1, b: 2 });+ const k2 = idempotencyKey('default', 'sync', { b: 2, a: 1 });+ expect(k1).toBe(k2);+ });++ test('different source produces different key', () => {+ expect(+ idempotencyKey('A', 'sync', { x: 1 }),+ ).not.toBe(idempotencyKey('B', 'sync', { x: 1 }));+ });++ test('different job produces different key', () => {+ expect(+ idempotencyKey('default', 'sync', { x: 1 }),+ ).not.toBe(idempotencyKey('default', 'embed', { x: 1 }));+ });++ test('different params produce different key', () => {+ expect(+ idempotencyKey('default', 'sync', { x: 1 }),+ ).not.toBe(idempotencyKey('default', 'sync', { x: 2 }));+ });+});++describe('makeRemediationStep', () => {+ test('default id is the idempotency key', () => {+ const step = makeRemediationStep({+ job: 'lint-fix',+ params: { slug: 'wiki/foo' },+ severity: 'low',+ est_seconds: 30,+ rationale: 'lint issues on foo',+ });+ expect(step.id).toBe(step.idempotency_key);+ expect(step.idempotency_key).toMatch(/^default:lint-fix:[0-9a-f]{8}$/);+ });++ test('explicit id overrides default', () => {+ const step = makeRemediationStep({+ id: 'sync.repo',+ job: 'sync',+ params: {},+ severity: 'medium',+ est_seconds: 60,+ rationale: 'sync repo',+ });+ expect(step.id).toBe('sync.repo');+ // idempotency_key still gets the content-hash format.+ expect(step.idempotency_key).toMatch(/^default:sync:[0-9a-f]{8}$/);+ });++ test('default status is "remediable"', () => {+ const step = makeRemediationStep({+ job: 'x', params: {}, severity: 'low', est_seconds: 1, rationale: '',+ });+ expect(step.status).toBe('remediable');+ });++ test('canonical JSON invariance: {a:1, b:2} and {b:2, a:1} produce IDENTICAL ids', () => {+ const stepA = makeRemediationStep({+ job: 'sync', params: { a: 1, b: 2 }, severity: 'low', est_seconds: 1, rationale: '',+ });+ const stepB = makeRemediationStep({+ job: 'sync', params: { b: 2, a: 1 }, severity: 'low', est_seconds: 1, rationale: '',+ });+ expect(stepA.id).toBe(stepB.id);+ expect(stepA.idempotency_key).toBe(stepB.idempotency_key);+ });++ test('all opts thread through to the output', () => {+ const step = makeRemediationStep({+ id: 'custom-id',+ job: 'embed',+ params: { stale: true },+ severity: 'high',+ est_seconds: 600,+ est_usd_cost: 1.5,+ depends_on: ['sync.repo'],+ rationale: 'embed stale pages',+ protected: true,+ source: 'team-source',+ status: 'remediable',+ });+ expect(step.id).toBe('custom-id');+ expect(step.job).toBe('embed');+ expect(step.params).toEqual({ stale: true });+ expect(step.severity).toBe('high');+ expect(step.est_seconds).toBe(600);+ expect(step.est_usd_cost).toBe(1.5);+ expect(step.depends_on).toEqual(['sync.repo']);+ expect(step.rationale).toBe('embed stale pages');+ expect(step.protected).toBe(true);+ expect(step.status).toBe('remediable');+ // source threads into idempotency_key namespace+ expect(step.idempotency_key).toMatch(/^team-source:embed:/);+ });+});++describe('back-compat re-export (D6)', () => {+ test('Remediation alias from brain-score-recommendations is RemediationStep', () => {+ // This is a compile-time test: if the import doesn't resolve, tsc fails.+ // Runtime check: assigning a RemediationStep into a Remediation slot.+ const step: RemediationStep = makeRemediationStep({+ job: 'x', params: {}, severity: 'low', est_seconds: 1, rationale: '',+ });+ const legacy: Remediation = step;+ expect(legacy.id).toBe(step.id);+ });+});diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex bcd85b2259..5aeaeb5e8f 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -145,6 +145,19 @@ const REQUIRED_BOOTSTRAP_COVERAGE: ForwardReference[] = [{ kind: 'column', table: 'pages', column: 'ingested_at' },{ kind: 'column', table: 'pages', column: 'source_uri' },{ kind: 'column', table: 'pages', column: 'source_kind' },+ // v0.40.3.0 (v90, renumbered from v0.40.3.0 v81 on master merge) —+ // contextual_retrieval_columns adds five additive columns wiring the+ // three-tier wrapper ladder. Bootstrap probes added defense-in-depth+ // for future schema work.+ { kind: 'column', table: 'pages', column: 'contextual_retrieval_mode' },+ { kind: 'column', table: 'pages', column: 'corpus_generation' },+ { kind: 'column', table: 'sources', column: 'contextual_retrieval_mode' },+ { kind: 'column', table: 'sources', column: 'trust_frontmatter_overrides' },+ // v0.40.3.0 (v91) — pages.generation BIGINT bumped by the+ // bump_page_generation_fn trigger. Forward-referenced by+ // pages_generation_idx (CREATE INDEX ON pages (generation)) so bootstrap+ // probes guard pre-v91 brains.+ { kind: 'column', table: 'pages', column: 'generation' },];test('applyForwardReferenceBootstrap covers every forward reference declared in REQUIRED_BOOTSTRAP_COVERAGE', async () => {@@ -217,6 +230,19 @@ test('applyForwardReferenceBootstrap covers every forward reference declared inDROP INDEX IF EXISTS idx_oauth_clients_federated_read;ALTER TABLE oauth_clients DROP COLUMN IF EXISTS source_id;ALTER TABLE oauth_clients DROP COLUMN IF EXISTS federated_read;++ -- v0.40.3.0 v90 + v91 column strips so applyForwardReferenceBootstrap+ -- has work to do. Only strip pages columns + the trigger; sources+ -- columns were already nuked by the earlier DROP TABLE IF EXISTS+ -- sources CASCADE, and the bootstrap needsPagesBootstrap branch+ -- recreates sources from schema-embedded.ts (which now includes the+ -- CR columns inline). Same convention as the sources.archived note.+ DROP TRIGGER IF EXISTS bump_page_generation_trg ON pages;+ DROP FUNCTION IF EXISTS bump_page_generation_fn;+ DROP INDEX IF EXISTS pages_generation_idx;+ ALTER TABLE pages DROP COLUMN IF EXISTS generation;+ ALTER TABLE pages DROP COLUMN IF EXISTS contextual_retrieval_mode;+ ALTER TABLE pages DROP COLUMN IF EXISTS corpus_generation;`);// Note: we don't strip sources.archived* here because they're inline in the@@ -656,6 +682,18 @@ const COLUMN_EXEMPTIONS = new Set<string>(['pages.source_path','content_chunks.edges_backfilled_at','query_cache.knobs_hash',+ // v0.40.3.0 (migration v90, renumbered from v0.40.3.0 v81 on master merge)+ // — query_cache is migration-only (added in v55), not in PGLITE_SCHEMA_SQL.+ // The v90 ALTER TABLE query_cache ADD COLUMN page_generations runs after+ // v55 in the migration sequence, so fresh installs get it correctly. No+ // forward-reference exists for PGLITE_SCHEMA_SQL to trip on because+ // query_cache isn't in the schema blob to begin with. Same exemption+ // rationale as knobs_hash.+ 'query_cache.page_generations',+ // v0.40.3.0 (migration v91) — same exemption rationale: query_cache is+ // migration-only; max_generation_at_store is added by v91 ALTER and never+ // forward-referenced by PGLITE_SCHEMA_SQL.+ 'query_cache.max_generation_at_store',// v0.35.6 (migration v67) — typed-claim columns + facts_typed_claim_idx// partial index are co-defined in the same migration, so the schema-blob// forward-reference path isn't tripped. Bootstrap is only required when andiff --git a/test/search-mode.test.ts b/test/search-mode.test.tsindex 56f1782a93..1205ec1a8c 100644--- a/test/search-mode.test.ts+++ b/test/search-mode.test.ts@@ -49,6 +49,11 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {cross_modal_llm_intent: false,};+ // v0.40.3.0 contextual retrieval per-mode defaults. Tests below spread+ // this AFTER CROSS_MODAL_DEFAULTS so each per-mode block overrides+ // contextual_retrieval to its tier value.+ const CR_DISABLED_DEFAULT = { contextual_retrieval_disabled: false };+test('conservative bundle values are canonical', () => {expect(MODE_BUNDLES.conservative).toEqual({cache_enabled: true,@@ -65,6 +70,8 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {reranker_timeout_ms: 5000,floor_ratio: undefined,...CROSS_MODAL_DEFAULTS,+ ...CR_DISABLED_DEFAULT,+ contextual_retrieval: 'none',});});@@ -86,6 +93,8 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {reranker_timeout_ms: 5000,floor_ratio: undefined,...CROSS_MODAL_DEFAULTS,+ ...CR_DISABLED_DEFAULT,+ contextual_retrieval: 'title',});});@@ -105,6 +114,8 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {reranker_timeout_ms: 5000,floor_ratio: undefined,...CROSS_MODAL_DEFAULTS,+ ...CR_DISABLED_DEFAULT,+ contextual_retrieval: 'per_chunk_synopsis',});});@@ -291,7 +302,16 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {// all appended per CDX2-F13 append-only convention so a text-mode cache// hit can never silently serve to an image-mode caller, and a query// against `embedding_voyage` never shares a cache row with `embedding`.- expect(KNOBS_HASH_VERSION).toBe(3);+ // v0.40.3.0: bumped 3→4 to add contextual_retrieval (CRMode) and+ // contextual_retrieval_disabled (kill switch) to the hash inputs.+ // A query against a brain on tokenmax (per-chunk synopsis) must not+ // be served from a cache row written when the brain was on balanced+ // (title-only) — different embedding spaces.+ // v0.40.3.0 (D8): bumped 4→5 to sequence behind salem's pending v=4+ // graph-signals work. Master shipped v=4 via schema-pack hash fields+ // (pack name + pack version) so our contextual-retrieval additions+ // land at v=5.+ expect(KNOBS_HASH_VERSION).toBe(5);});test('T1 (codex): floor_ratio set vs unset produces DIFFERENT hashes (cache contamination prevention)', () => {diff --git a/test/search/knobs-hash-reranker.test.ts b/test/search/knobs-hash-reranker.test.tsindex 258d1e4e5b..0934dfd3a5 100644--- a/test/search/knobs-hash-reranker.test.ts+++ b/test/search/knobs-hash-reranker.test.ts@@ -43,12 +43,14 @@ function baseKnobs(): ResolvedSearchKnobs {}describe('KNOBS_HASH_VERSION + version invariants', () => {- test('version is 3 (1→2 v0.35.0.0 reranker; 2→3 v0.35.6.0 floor_ratio + v0.36 cross-modal + embedding-column appends)', () => {+ test('version is 5 (master v=4 schema-pack appends; v0.40.3.0 D8 CR appends)', () => {// 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),- // all appended per CDX2-F13 append-only convention.- expect(KNOBS_HASH_VERSION).toBe(3);+ // (D2) PLUS column + provider context (D8/CDX-2 cross-column isolation).+ // v0.39 T21 (master): 3→4 to fold schema_pack name + version.+ // v0.40.3.0 (D8): 4→5 to fold contextual_retrieval + kill switch,+ // sequenced behind salem's pending v=4 graph-signals.+ expect(KNOBS_HASH_VERSION).toBe(5);});test('hash is 16 hex chars regardless of reranker config', () => {diff --git a/test/sources-set-cr-mode.test.ts b/test/sources-set-cr-mode.test.tsnew file mode 100644index 0000000000..f7534434e5--- /dev/null+++ b/test/sources-set-cr-mode.test.ts@@ -0,0 +1,157 @@+/**+ * v0.40.3.0 — gbrain sources set-cr-mode <id> <mode>+ *+ * D5 + T7 + idempotent-pebble Failure-Modes critical-gap closure.+ *+ * Validates:+ * - Happy path: writes contextual_retrieval_mode for each CRMode+ * - "unset" / "default" / "" clears the column (NULL)+ * - Invalid mode → exit code 2 with list of valid options+ * - Missing source id → exit code 4 with paste-ready hint+ * - Missing arguments → exit code 2 with usage+ */++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 { runSources } from '../src/commands/sources.ts';++describe('gbrain sources set-cr-mode', () => {+ let engine: PGLiteEngine;+ let origExit: typeof process.exit;+ let exitCode: number | null;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });++ afterAll(async () => {+ await engine.disconnect();+ process.exit = origExit;+ });++ beforeEach(async () => {+ await resetPgliteState(engine);+ exitCode = null;+ origExit = process.exit;+ // Stub process.exit so failures don't kill the test runner.+ (process as unknown as { exit: (n: number) => never }).exit = ((n: number) => {+ exitCode = n;+ throw new Error(`__test_exit_${n}__`);+ }) as never;+ });++ async function seedSource(id: string): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO sources (id, name, config) VALUES ($1, $2, '{}'::jsonb)+ ON CONFLICT (id) DO NOTHING`,+ [id, id],+ );+ }++ async function readCrMode(id: string): Promise<string | null> {+ const rows = await engine.executeRaw<{ mode: string | null }>(+ `SELECT contextual_retrieval_mode AS mode FROM sources WHERE id = $1`,+ [id],+ );+ return rows[0]?.mode ?? null;+ }++ test('happy path: set to "title"', async () => {+ await seedSource('test-src');+ await runSources(engine, ['set-cr-mode', 'test-src', 'title']);+ expect(await readCrMode('test-src')).toBe('title');+ });++ test('happy path: set to "per_chunk_synopsis"', async () => {+ await seedSource('test-src');+ await runSources(engine, ['set-cr-mode', 'test-src', 'per_chunk_synopsis']);+ expect(await readCrMode('test-src')).toBe('per_chunk_synopsis');+ });++ test('happy path: set to "none"', async () => {+ await seedSource('test-src');+ await runSources(engine, ['set-cr-mode', 'test-src', 'none']);+ expect(await readCrMode('test-src')).toBe('none');+ });++ test('unset path: "unset" clears to NULL', async () => {+ await seedSource('test-src');+ await runSources(engine, ['set-cr-mode', 'test-src', 'title']);+ expect(await readCrMode('test-src')).toBe('title');+ await runSources(engine, ['set-cr-mode', 'test-src', 'unset']);+ expect(await readCrMode('test-src')).toBeNull();+ });++ test('unset path: "default" also clears to NULL', async () => {+ await seedSource('test-src');+ await runSources(engine, ['set-cr-mode', 'test-src', 'title']);+ await runSources(engine, ['set-cr-mode', 'test-src', 'default']);+ expect(await readCrMode('test-src')).toBeNull();+ });++ test('rejection: invalid mode → exit 2 (lists valid options)', async () => {+ await seedSource('test-src');+ try {+ await runSources(engine, ['set-cr-mode', 'test-src', 'invalid-mode-name']);+ } catch (err) {+ expect((err as Error).message).toContain('__test_exit_2__');+ }+ expect(exitCode).toBe(2);+ expect(await readCrMode('test-src')).toBeNull(); // No mutation+ });++ test('rejection: missing source id → exit 4 (paste-ready hint)', async () => {+ // Don't seed — source doesn't exist.+ try {+ await runSources(engine, ['set-cr-mode', 'nonexistent-source', 'title']);+ } catch (err) {+ expect((err as Error).message).toContain('__test_exit_4__');+ }+ expect(exitCode).toBe(4);+ });++ test('rejection: missing arguments → exit 2 (usage)', async () => {+ try {+ await runSources(engine, ['set-cr-mode']);+ } catch (err) {+ expect((err as Error).message).toContain('__test_exit_2__');+ }+ expect(exitCode).toBe(2);+ });++ test('rejection: missing mode (only id provided) → exit 2', async () => {+ await seedSource('test-src');+ try {+ await runSources(engine, ['set-cr-mode', 'test-src']);+ } catch (err) {+ expect((err as Error).message).toContain('__test_exit_2__');+ }+ expect(exitCode).toBe(2);+ expect(await readCrMode('test-src')).toBeNull(); // No mutation+ });++ test('round-trip: set title → set per_chunk_synopsis → unset preserves other fields', async () => {+ await seedSource('test-src');+ // Set + verify a non-CR field is preserved (name).+ const initialName = await engine.executeRaw<{ name: string }>(+ `SELECT name FROM sources WHERE id = 'test-src'`,+ );+ expect(initialName[0].name).toBe('test-src');++ await runSources(engine, ['set-cr-mode', 'test-src', 'title']);+ await runSources(engine, ['set-cr-mode', 'test-src', 'per_chunk_synopsis']);+ await runSources(engine, ['set-cr-mode', 'test-src', 'unset']);++ const finalState = await engine.executeRaw<{+ mode: string | null;+ name: string;+ }>(+ `SELECT contextual_retrieval_mode AS mode, name FROM sources WHERE id = 'test-src'`,+ );+ expect(finalState[0].mode).toBeNull();+ expect(finalState[0].name).toBe('test-src');+ });+});