Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fact keys: killed by the preregistered tokenmax gate on LoCoMo dev — remove product code, publish negative result
garrytan2815a8368cb3
diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.ymlindex 2da350ac40..635a101749 100644--- a/.github/workflows/persistence-validation.yml+++ b/.github/workflows/persistence-validation.yml@@ -211,7 +211,6 @@ jobs:test/decide/conflict-proposals-managed.test.tstest/declared-lineage-visibility.test.tstest/extract-endpoint-revision.serial.test.ts- test/fact-keys-publish.test.tstest/graduation-digest.test.tstest/graduation-drain.test.tstest/graduation-inventory.test.tsdiff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 94e942c892..69558540ec 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/temporal-grammar.ts` + `src/core/search/time-range.ts` + `src/core/event-dates.ts` + `src/core/search/hybrid/time-scope.ts` — deterministic time expressions (no LLM). `findTimeMentions(text, refDay, direction)` resolves explicit cues only (ISO and written dates, `in/during <Month>`, capitalized bare months, `Qn YYYY`, `in YYYY`, yesterday/today/tomorrow, last/this/next week|weekend|month|year, rolling "past month", seasons, last/this <weekday>, `N units ago`, `in N units`) to inclusive day ranges; quoted spans, plural weekdays and modal "may" never resolve; overlapping matches keep the longest. `parseQueryTimeRange(query, refDay)` returns one range or abstains with `no_cue`, `duration_question` ("how long", "how many days ago/passed/before…") or `multi_role` (two times not joined by and/or/to/through). `extractEventDates(text, observationDay)` returns the observation day plus mentioned dates, resolving relative phrases only against a known observation day and skipping code fences, inline code and URLs. `applyTimeScope(results, range, datesOf, {mode, k, slackDays=2})` is a permutation: `reserved` keeps the top ⌈k/2⌉ in place and fills the rest of k with in-range results; `partition` moves every in-range result first. These are used by the eval-only `--time-scope` arm; no production search path calls them yet. Tests: `test/time-range-parse.test.ts` (published LongMemEval time-range examples as goldens), `test/time-scope-stage.test.ts`.-- `src/core/fact-keys.ts` + `src/core/facts/fact-keys-publish.ts` + `src/core/facts/fact-keys-retire.ts` + `src/core/facts/fact-keys-status.ts` — fact keys merged into a chunk's title-tier embedding input (docs/designs/FACT_KEYS.md; setting `search.fact_keys`, default off). `assignFactKeys(items, chunks, 'chunk'|'page')` (chunk = each fact on the chunk sharing the most content words; code/image chunks never keyed; 800-char cap; `<context>` tags stripped); the input is `buildContextualPrefix(title, null, factKeys)` (`<context>{title}\nFacts: {keys}\n</context>\n`). Production: `runFactsBackstop` binds the extracted text to the page revision (`bindFactKeysSnapshot`), and after extraction `publishPageFactKeys` swaps `page_fact_keys` occurrence rows, `content_chunks.fact_keys` and the re-embedded vectors in one guarded transaction (protocol declare → source `FOR SHARE` → page lock; revision, text and chunk inventory rechecked; withdrawn items and private-on-world items dropped). Only `title`-mode pages without protected fences or `embed_skip` are keyed. `installPageEmbeddings` refuses a title-tier vector built from other key text; `upsertChunks` drops a vector whose key text changed; `retireStaleFactKeys` runs on every chunk-sealing path; withdrawal discovery joins `page_fact_keys`. CLI `gbrain fact-keys status|refresh|clear`; doctor `retrieval_enrichment`. The eval arm `--fact-extractor pipeline` runs this path. Tests: `test/fact-keys.test.ts`, `test/fact-keys-publish.test.ts`.+- `src/core/fact-keys.ts` — fact keys merged into a chunk's embedding input. `assignFactKeys(items, chunks, 'chunk'|'page')` (chunk = each fact on the chunk sharing the most content words, page = all facts on every chunk; code/image chunks never keyed; 800-char cap; `<context>` tags stripped) and `factKeyedEmbeddingInput(chunkText, title, keys)` (`<context>{title}\nFacts: {keys}\n</context>\n{chunk}`; null keys reproduce today's title-wrapped or raw input byte-for-byte). `chunk_text` is never changed. Used by the eval-only `--fact-keys` arm. Test: `test/fact-keys.test.ts`.- `src/core/search/feedback-boost.ts` — the use-attributed feedback ranking stage. `applyFeedbackStage(engine, results, { reranked })` reads each result page's learned weight (`retrieval_weights`, half its learned deviation when the page changed since) and current `content_hash` in one query by page id, stamps `content_hash` (answer recording uses it) and, when `feedback.influence` λ > 0, multiplies the ordering score by `1 + λ·2·(w − 0.5)` (bounded `[1 − λ, 1 + λ]`, stamped `feedback_boost`). The ordering score is `rerank_score` when the reranker reordered the list (unscored tail rows stay after the head) and the fused `score` otherwise; raw `score`/`rerank_score` are never modified, so autocut and evidence read the same values. Neutral weights return the list untouched. Called once from `hybrid/rank.ts` `rerankAndPin` (between the reranker and the relational re-pin) and at the end of both keyword-only paths in `hybrid/keyword-only.ts`; paths that bypass `hybridSearch` get no feedback. Fail-open (errors counted, shown by `gbrain feedback status`). Pinned by `test/feedback-boost.test.ts` and `test/e2e/feedback-parity.test.ts`.diff --git a/docs/designs/FACT_KEYS.md b/docs/designs/FACT_KEYS.mdindex e181e42967..4121c64b92 100644--- a/docs/designs/FACT_KEYS.md+++ b/docs/designs/FACT_KEYS.md@@ -1,16 +1,19 @@# Fact keys in chunk embeddings — design note-Status: **built behind `search.fact_keys` (default off until the held-out-verdict).** Revision 4 of this note passed three engineering review rounds-(approve with changes, folded in). The "As built" section records where the-code is simpler than the reviewed text; where they differ, it wins. This note-covers obligations 1–9 from the preregistered plan+Status: **killed by the preregistered gate (2026-10-05); no product code+ships.** Fact keys under `balanced` did not beat `tokenmax` synopses on the+LoCoMo development conversations, which the gate requires, and did not beat+`balanced` there either. The full build described below (migration v209+`page_fact_keys` + `content_chunks.fact_keys`, publication, retirement,+withdrawal discovery, `gbrain fact-keys`, doctor `retrieval_enrichment`) is+preserved in branch history at `5024ec99f4f591227d12b39b38e304d3255de2c5`.+Results and the decision record:+[`docs/eval/TIME_AWARE_RETRIEVAL_RESULTS.md`](../eval/TIME_AWARE_RETRIEVAL_RESULTS.md),+[`docs/eval/decisions/p6-fact-keys/`](../eval/decisions/p6-fact-keys/).+This note covers obligations 1–9 from the preregistered plan([`docs/eval/TIME_AWARE_RETRIEVAL_PREREG.md`](../eval/TIME_AWARE_RETRIEVAL_PREREG.md)).-Development results are in-[`docs/eval/TIME_AWARE_RETRIEVAL_RESULTS.md`](../eval/TIME_AWARE_RETRIEVAL_RESULTS.md).-File references are relative to `src/core/` on master.-## As built+## As built (at `5024ec99f`, not shipped)- **Only `title`-mode pages are keyed.** Keys exist only in the title-tierembedding input (the `balanced` default). Pages in `none` ordiff --git a/docs/eval/TIME_AWARE_RETRIEVAL_RESULTS.md b/docs/eval/TIME_AWARE_RETRIEVAL_RESULTS.mdindex 74f0574c08..eb9a70d8f2 100644--- a/docs/eval/TIME_AWARE_RETRIEVAL_RESULTS.md+++ b/docs/eval/TIME_AWARE_RETRIEVAL_RESULTS.md@@ -49,7 +49,14 @@ inside the parsed range, and 39 of 135 gold sessions fall outside it (forexample "last Saturday" questions whose evidence spans several Saturdays, orpreference questions about "this weekend" whose evidence predates it).-### Fact keys+### Fact keys — killed by the `tokenmax` gate++Fact keys win on LongMemEval-M but lose the preregistered gate on LoCoMo:+under `balanced` they do not beat `tokenmax` synopses, and on LoCoMo they do+not beat `balanced` either. No product code ships+([decision record](decisions/p6-fact-keys/); the full build stays in branch+history at `5024ec99f`).+| Arm | Benchmark | Strict R@5 | NDCG@5 Δ (95% CI) | Wins / losses (NDCG) ||---|---|---:|---:|---:|@@ -81,6 +88,32 @@ session's chunks look alike and pushes gold sessions down. The publishedprompt extracts 404 facts per question against 174 for gbrain's extractor,which reads the first 8,000 characters of a page and keeps notable facts.+**The gate, on LoCoMo development conversations** (conv-44, conv-47, conv-48;+464 questions without the adversarial category; strict recall_all@5 over+sessions, `--reranker on --autocut off`, paired bootstrap over questions, 10,000+draws). A = `balanced`; B = `balanced` + chunk keys from gbrain's extractor+(Haiku 4.5); C = `tokenmax` with production per-chunk synopses (Haiku 4.5):++| Comparison | Strict R@5 | Δ (95% CI) | Wins / losses | NDCG@5 Δ (95% CI) |+|---|---:|---:|---:|---:|+| B vs C (the gate) | 86.4% vs 87.5% | −1.1 pts [−2.4, 0.0] | 1 / 6 | −0.009 [−0.020, +0.001] |+| B vs A | 86.4% vs 86.0% | +0.4 pts [−0.7, +1.7] | 5 / 3 | +0.001 [−0.005, +0.007] |+| C vs A | 87.5% vs 86.0% | +1.5 pts [+0.2, +2.8] | 8 / 1 | +0.010 [+0.001, +0.020] |++By category (strict R@5, A / B / C): single-hop 256 / 255 / 259 of 263,+multi-hop 31 / 36 / 35 of 71, temporal 92 / 92 / 92 of 100, open-domain+20 / 18 / 20 of 30. Keys help only multi-hop questions, where synopses gain+the same. The bootstrap resamples questions and ignores clustering within+three conversations, so the intervals are optimistic. Development spend:+$45 of synopses plus about $6 of extraction, embedding and reranking.++Side by side: fact keys add +3.2 points over `balanced` on LongMemEval-M+(500-session haystacks) and nothing on LoCoMo (one conversation per+haystack), where `tokenmax` adds +1.5. The M comparison against `tokenmax`+was not run because of cost (preregistration amendment 2).++Follow-up, untested: fact keys stacked on `tokenmax`, against `tokenmax` alone.+### Notes-first reading — no gain, removedSame build with the date frame on, notes on vs off@@ -99,9 +132,10 @@ structured answer with citations and gaps.## Deviations-- The preregistered comparison against the `tokenmax` contextual-synopsis- bundle was not run: the benchmark harness does not generate per-chunk- synopses at import, so `--mode tokenmax` measured the same embeddings as- `balanced`.+- The `tokenmax` comparison moved from LongMemEval-M to LoCoMo+ (preregistration amendment 2): production per-chunk synopses for M project+ to about $4,280. The harness now builds production synopses for+ `--mode tokenmax`; LoCoMo converts to the LongMemEval format with+ `scripts/locomo-to-longmemeval.ts`.- The reading-arm think lane passed each question's date as the referencedate through a local harness change pending in gbrain-evals.diff --git a/docs/eval/decisions/p6-fact-keys/README.md b/docs/eval/decisions/p6-fact-keys/README.mdnew file mode 100644index 0000000000..4f4716518f--- /dev/null+++ b/docs/eval/decisions/p6-fact-keys/README.md@@ -0,0 +1,29 @@+# Decision: fact keys in chunk embeddings — killed++- **Plan:** P6, mechanism F2 (fact keys from gbrain's facts extractor merged+ into the chunk embedding input).+- **Decided:** 2026-10-05, on development data, under the preregistered kill+ gate ([`TIME_AWARE_RETRIEVAL_PREREG.md`](../../TIME_AWARE_RETRIEVAL_PREREG.md),+ "Kill gates", amendments 1 and 2).+- **Gate:** F2 must beat `balanced` on its target metric with a paired 95% CI+ excluding zero, **and** beat the `tokenmax` contextual-synopsis bundle.+- **Verdict:** **fail.** On the LoCoMo development conversations fact keys+ under `balanced` score −1.1 points strict recall_all@5 against `tokenmax`+ (95% CI [−2.4, 0.0], 1 win / 6 losses) and +0.4 against `balanced`+ (CI [−0.7, +1.7]). `tokenmax` beats `balanced` by +1.5 (CI [+0.2, +2.8]).+- **Context:** on LongMemEval-M development questions fact keys beat+ `balanced` by +3.2 points (CI [+1.3, +5.1], 18 wins / 3 losses); M did not+ run the `tokenmax` comparison because of cost.+- **Consequence:** no product code, schema, config key or backfill ships. The+ eval arms stay (`--fact-keys`, `--fact-extractor paper|production`), as do+ the harness's production synopses for `--mode tokenmax` and the LoCoMo+ converter.+- **Full build, not shipped:** branch `capy/p6-time-aware-reading` at+ `5024ec99f4f591227d12b39b38e304d3255de2c5` (migration v209, publication with+ prepare-then-swap, retirement hook, withdrawal discovery, `gbrain fact-keys`,+ doctor `retrieval_enrichment`, and a `--fact-extractor pipeline` arm that+ runs that shipping path). Design: [`docs/designs/FACT_KEYS.md`](../../../designs/FACT_KEYS.md).+- **Untested follow-up:** fact keys stacked on `tokenmax`, against `tokenmax`+ alone.++Numbers: [`TIME_AWARE_RETRIEVAL_RESULTS.md`](../../TIME_AWARE_RETRIEVAL_RESULTS.md), "Fact keys".diff --git a/docs/guides/time-aware-recall.md b/docs/guides/time-aware-recall.mdindex 7cf97384b7..63fb5924e0 100644--- a/docs/guides/time-aware-recall.md+++ b/docs/guides/time-aware-recall.md@@ -38,49 +38,13 @@ correctly with the date frame against 80.7% without it (+9.3 points, 95% CIRetrieval is unchanged. Results:[`docs/eval/TIME_AWARE_RETRIEVAL_RESULTS.md`](../eval/TIME_AWARE_RETRIEVAL_RESULTS.md).-## Fact keys--Fact keys help search find a page when a question is phrased like a fact-the page states but not like its wording. They're off by default until the-held-out verdict is in. When `search.fact_keys` is on, every eligible page-write that runs facts extraction also places the extracted facts into the-embedding input of the page's own chunks:--```-<context>{title}-Facts: {fact}; {fact}-</context>-{chunk text}-```--The stored chunk text, keyword search, the reranker and the returned page-are unchanged. A key never appears as text in any result.--- **Turn on:** `gbrain config set search.fact_keys on`. New writes key- themselves. Keyed chunks are embedded a second time once extraction lands,- so ask the user before turning this on for a large brain.-- **Coverage:** `gbrain fact-keys status`, or doctor's `retrieval_enrichment`- check. Only pages in the `title` embedding tier are keyed, which is the- `balanced` default. Pages with protected facts or takes fences, or with- `embed_skip`, are not keyed. Private facts never key a world-visible page.- Facts default to private unless `facts.default_visibility` is `world`,- which bootstrap sets for single-user brains.-- **Backfill:** `gbrain fact-keys refresh --dry-run` lists eligible pages- without keys. `gbrain fact-keys refresh` re-runs facts extraction for them,- at one paid model call per page (default limit 50).-- **Turn off:** `gbrain config set search.fact_keys off`, then run- `gbrain fact-keys clear` until it reports no pages left. Clearing re-embeds- each keyed chunk without keys before swapping the vector in.-- **Forget:** forgetting a fact also finds the pages its key was merged into,- and rebuilds them without it.--Design: [`docs/designs/FACT_KEYS.md`](../designs/FACT_KEYS.md).-## Measuring it-The LongMemEval harness measures fact keys (`--fact-keys chunk---fact-extractor pipeline` runs the shipping path; `paper` and `production`-are the development arms) and the rejected soft time scope (`--time-scope`).-`--mode tokenmax` builds production per-chunk synopses for comparison. See+The LongMemEval harness carries eval-only arms for two retrieval mechanisms+that were measured and not shipped: fact keys merged into chunk embeddings+(`--fact-keys`) and a soft time scope driven by the question's explicit time+words (`--time-scope`). `--mode tokenmax` builds production per-chunk+synopses, and `scripts/locomo-to-longmemeval.ts` converts LoCoMo+conversations to the same format. See[`docs/eval-bench.md`](../eval-bench.md) and the[evaluation key files](../architecture/key-files/evaluation.md).diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 9bea697168..b712b775b1 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -17,13 +17,13 @@ src/core/cycle.ts 3253 ratchet +2 System One v1 S9: extract_facts phase tail runsrc/core/cycle/synthesize.ts 3312 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict)src/core/cycle/extract-atoms.ts 1809 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement)src/core/engine.ts 2707 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso-src/core/import-file.ts 2182 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +3 P6 fact keys: retireStaleFactKeys on the chunk-replacing import paths+src/core/import-file.ts 2179 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied)src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 339 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line)src/core/pglite-engine.ts 2995 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts)src/core/postgres-engine.ts 2932 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts)src/core/search/hybrid.ts 1586 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key-src/core/types.ts 2214 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +4 P6 fact keys: Chunk/ChunkInput fact_keys+src/core/types.ts 2210 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop)src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)src/commands/init.ts 1876 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail readsrc/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)-src/core/config.ts 1866 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 P6 fact keys: search.fact_keys key+src/core/config.ts 1864 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts)src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook envsrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 663 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts)diff --git a/src/cli.ts b/src/cli.tsindex 06718009d0..a8396d1fae 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -152,7 +152,7 @@ const SELF_HELP_WITHOUT_ENGINE: Record<string, true | (() => Promise<(engine: ne// answered before any engine or job-queue work (cathedral-6).agent: async () => (await import('./commands/agent.ts')).runAgent as never,// D3: post-connect records whose handler answers --help before the engine; run through the table.- advisor: true, anomalies: true, feedback: true, 'fact-keys': true, backfill: true, 'book-mirror': true, 'edges-backfill': true, embed: true, features: true,+ advisor: true, anomalies: true, feedback: true, backfill: true, 'book-mirror': true, 'edges-backfill': true, embed: true, features: true,founder: true, 'graph-query': true, orphans: true, salience: true, think: true,brainstorm: true, lsd: true, migrate: true, pages: true, pricing: true, 'retrieval-upgrade': true, whoknows: true,};@@ -3036,7 +3036,6 @@ TOOLSsalience [--days N] [--kind P] v0.29: pages ranked by emotional + activity salienceanomalies [--since D] [--sigma N] v0.29: cohort-based statistical anomalies (tag, type)feedback <status|reset> retrieval feedback: learned page weights; rate answers with gbrain rate- fact-keys <status|refresh|clear> facts merged into chunk embeddings (search.fact_keys)transcripts <ingest|status|recent> v0.46: import agent session logs + chat exports (local-only)dream [--dry-run] [--json] Run the overnight maintenance cycle once (cron-friendly).See also: autopilot --install (continuous daemon).diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 154eefe143..13acfd1620 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -316,7 +316,6 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp{ name: 'salience', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/salience.ts') },{ name: 'anomalies', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/anomalies.ts') },{ name: 'feedback', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/feedback.ts') },- { name: 'fact-keys', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/fact-keys.ts') },{ name: 'status', phase: 'post-connect', thinClient: 'none', help: () => import('./help/status.ts'), load: () => import('./commands/status.ts') },{ name: 'advisor', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/advisor.ts') },{ name: 'conversation-parser', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/conversation-parser.ts') },diff --git a/src/cli/commands/fact-keys.ts b/src/cli/commands/fact-keys.tsdeleted file mode 100644index a1828989ef..0000000000--- a/src/cli/commands/fact-keys.ts+++ /dev/null@@ -1,10 +0,0 @@-/**- * `gbrain fact-keys`: post-connect dispatch; the record lives in- * src/cli/command-table.ts.- */-import type { BrainEngine } from '../../core/engine.ts';--export async function run(engine: BrainEngine, args: string[]): Promise<void> {- const { runFactKeys } = await import('../../commands/fact-keys.ts');- await runFactKeys(engine, args);-}diff --git a/src/commands/doctor/checks/retrieval-enrichment.ts b/src/commands/doctor/checks/retrieval-enrichment.tsdeleted file mode 100644index f5fed9ef18..0000000000--- a/src/commands/doctor/checks/retrieval-enrichment.ts+++ /dev/null@@ -1,39 +0,0 @@-/**- * Fact keys (docs/designs/FACT_KEYS.md): keyed coverage, eligible pages- * without keys, and keys left behind while the setting is off. Read-only.- */-import type { Check } from '../../doctor.ts';-import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';-import { factKeysStatus } from '../../../core/facts/fact-keys-status.ts';--async function runRetrievalEnrichment(ctx: DoctorContext): Promise<Check[]> {- const engine = connectedEngine(ctx);- const checks: Check[] = [];- if (engine === null) return checks;- ctx.progress.heartbeat('retrieval_enrichment');- try {- const status = await factKeysStatus(engine);- const details = { ...status, docs: 'docs/guides/time-aware-recall.md' };- if (!status.enabled && (status.keyed_chunks > 0 || status.key_rows > 0)) {- checks.push({ name: 'retrieval_enrichment', status: 'warn', details,- message: `Fact keys are off but ${status.keyed_pages} page(s) still carry keys. Run \`gbrain fact-keys clear\` (re-embeds the keyed chunks; repeat until it reports none left).` });- } else if (!status.enabled) {- checks.push({ name: 'retrieval_enrichment', status: 'ok', details, message: 'Fact keys are off (search.fact_keys).' });- } else {- checks.push({ name: 'retrieval_enrichment', status: 'ok', details,- message: `Fact keys on: ${status.keyed_pages} page(s) keyed, ${status.eligible_unkeyed_pages} eligible page(s) without keys${status.eligible_unkeyed_pages ? ' (new writes key themselves; `gbrain fact-keys refresh --dry-run` lists the rest — refresh re-runs paid extraction, so ask the user first)' : ''}.` });- }- } catch (err) {- const code = (err as { code?: string } | null)?.code;- checks.push(code === '42P01' || code === '42703'- ? { name: 'retrieval_enrichment', status: 'ok', message: 'Skipped (fact-key schema unavailable; apply migrations with gbrain apply-migrations --yes).' }- : { name: 'retrieval_enrichment', status: 'warn', message: `Fact keys could not be inspected: ${err instanceof Error ? err.message : String(err)}. Health is unknown.` });- }- return checks;-}--export const retrievalEnrichmentEntry: DoctorEntry = {- name: 'retrieval_enrichment',- emits: ['retrieval_enrichment'],- run: runRetrievalEnrichment,-};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 47779627ed..1e54ec8fef 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -83,7 +83,6 @@ import { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';import { legacyTokenGrantsEntry } from './checks/legacy-token-grants.ts';import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';import { retrievalFeedbackEntry } from './checks/retrieval-feedback.ts';-import { retrievalEnrichmentEntry } from './checks/retrieval-enrichment.ts';import { autoChronicleEntry } from './checks/auto-chronicle.ts';import { factsDrainEntry } from './checks/facts-drain.ts';import { factTakeVectorsEntry } from './checks/vector-coverage.ts';@@ -166,7 +165,6 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [factTakeVectorsEntry,plannerStatsEntry,retrievalFeedbackEntry,- retrievalEnrichmentEntry,revisionBackfillEntry,searchModeEntry,];diff --git a/src/commands/fact-keys.ts b/src/commands/fact-keys.tsdeleted file mode 100644index c0ed72ec08..0000000000--- a/src/commands/fact-keys.ts+++ /dev/null@@ -1,126 +0,0 @@-/**- * gbrain fact-keys — status, refresh and clear for fact keys in chunk- * embeddings (docs/designs/FACT_KEYS.md, docs/guides/time-aware-recall.md).- *- * gbrain fact-keys status [--json]- * gbrain fact-keys refresh [--page SLUG] [--source ID] [--limit N] [--dry-run] [--json]- * gbrain fact-keys clear [--page SLUG] [--source ID] [--limit N] [--json]- *- * refresh re-runs facts extraction (a paid model call per page) for eligible- * pages without keys for their current revision; extraction publishes the- * keys. clear strips keys whatever `search.fact_keys` says, re-embedding the- * keyed chunks first, so no vector is ever left without its keys' provenance.- */-import type { BrainEngine } from '../core/engine.ts';-import { setCliExitVerdict } from '../core/cli-force-exit.ts';-import { factKeysStatus, FACT_KEYS_ELIGIBLE_SQL as ELIGIBLE_SQL } from '../core/facts/fact-keys-status.ts';-import { clearPageFactKeys, factKeysEnabled, FACT_KEYS_CONFIG_KEY } from '../core/facts/fact-keys-publish.ts';--const HELP = `Usage: gbrain fact-keys <status|refresh|clear> [options]--Fact keys merge facts extracted from a page into the embedding input of the-page's own chunks, so a question phrased like a fact finds the page. Stored-chunk text and search results are unchanged. Setting: ${FACT_KEYS_CONFIG_KEY} (on|off).-- status [--json] keyed pages and chunks, eligible pages without keys, leftovers while off- refresh [--page SLUG] [--source ID] [--limit N] [--dry-run] [--json]- re-run facts extraction for eligible pages without current keys- (one paid model call per page; default limit 50; --dry-run lists them)- clear [--page SLUG] [--source ID] [--limit N] [--json]- strip keys (re-embeds keyed chunks first); run after turning the setting off--Guide: docs/guides/time-aware-recall.md-`;--function flag(args: string[], name: string): string | undefined {- const i = args.indexOf(name);- return i >= 0 ? args[i + 1] : undefined;-}--async function refreshCandidates(engine: BrainEngine, opts: { slug?: string; sourceId?: string; limit: number }) {- return engine.executeRaw<{ source_id: string; slug: string }>(`SELECT p.source_id,p.slug FROM pages p- WHERE ${ELIGIBLE_SQL} AND ($1::text IS NULL OR p.slug=$1) AND ($2::text IS NULL OR p.source_id=$2)- AND NOT EXISTS (SELECT 1 FROM page_fact_keys k WHERE k.page_id=p.id AND k.page_revision=p.knowledge_revision::text)- ORDER BY p.updated_at DESC, p.id LIMIT $3`, [opts.slug ?? null, opts.sourceId ?? null, opts.limit]);-}--async function clearCandidates(engine: BrainEngine, opts: { slug?: string; sourceId?: string; limit: number }) {- return engine.executeRaw<{ source_id: string; slug: string }>(`SELECT p.source_id,p.slug FROM pages p- WHERE ($1::text IS NULL OR p.slug=$1) AND ($2::text IS NULL OR p.source_id=$2)- AND (EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.fact_keys IS NOT NULL)- OR EXISTS (SELECT 1 FROM page_fact_keys k WHERE k.page_id=p.id))- ORDER BY p.id LIMIT $3`, [opts.slug ?? null, opts.sourceId ?? null, opts.limit]);-}--export async function runFactKeys(engine: BrainEngine, args: string[]): Promise<void> {- const sub = args[0];- if (!sub || sub === '--help' || sub === '-h' || args.includes('--help')) { process.stdout.write(HELP); return; }- const json = args.includes('--json');- const scope = { slug: flag(args, '--page'), sourceId: flag(args, '--source'), limit: Number(flag(args, '--limit') ?? 50) };- if (!Number.isInteger(scope.limit) || scope.limit <= 0) {- process.stderr.write(`--limit must be a positive integer (got: ${flag(args, '--limit')})\n`);- setCliExitVerdict(2);- return;- }- if (sub === 'status') {- const status = await factKeysStatus(engine);- if (json) { process.stdout.write(JSON.stringify(status, null, 2) + '\n'); return; }- const lines = [- `Fact keys: ${status.enabled ? 'on' : 'off'} (${FACT_KEYS_CONFIG_KEY})`,- `Keyed: ${status.keyed_pages} page(s), ${status.keyed_chunks} chunk(s), ${status.key_rows} key row(s)`,- `Eligible pages without keys: ${status.eligible_unkeyed_pages}`,- ];- if (status.enabled && status.eligible_unkeyed_pages > 0) lines.push('Next: `gbrain fact-keys refresh --dry-run` lists them; refresh re-runs paid extraction, so ask the user before a large run.');- if (!status.enabled && (status.keyed_chunks > 0 || status.key_rows > 0)) lines.push('Keys remain while the setting is off. Next: `gbrain fact-keys clear` strips them (re-embeds the keyed chunks).');- process.stdout.write(lines.join('\n') + '\n');- return;- }- if (sub === 'refresh') {- if (!await factKeysEnabled(engine)) {- process.stderr.write(`Fact keys are off. Turn them on with \`gbrain config set ${FACT_KEYS_CONFIG_KEY} on\` (ask the user first: keys re-embed keyed chunks), then rerun.\n`);- setCliExitVerdict(2);- return;- }- const pages = await refreshCandidates(engine, scope);- if (args.includes('--dry-run')) {- if (json) process.stdout.write(JSON.stringify({ dry_run: true, pages }, null, 2) + '\n');- else process.stdout.write(`${pages.length} page(s) would be re-extracted (one paid model call each):\n${pages.map(p => ` ${p.source_id}:${p.slug}`).join('\n')}\n`);- return;- }- const { runFactsBackstop } = await import('../core/facts/backstop.ts');- const results: Array<{ source_id: string; slug: string; outcome: string }> = [];- for (const { source_id, slug } of pages) {- const page = await engine.getPage(slug, { sourceId: source_id });- if (!page) { results.push({ source_id, slug, outcome: 'missing' }); continue; }- try {- const r = await runFactsBackstop({ slug, type: page.type, compiled_truth: page.compiled_truth, frontmatter: (page.frontmatter ?? {}) as Record<string, unknown> },- { engine, sourceId: source_id, sessionId: null, source: 'mcp:put_page', mode: 'inline', notabilityFilter: 'all' });- const keyed = await engine.executeRaw('SELECT 1 FROM page_fact_keys k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1 AND p.slug=$2 AND k.page_revision=p.knowledge_revision::text LIMIT 1', [source_id, slug]);- results.push({ source_id, slug, outcome: keyed.length ? 'keyed' : ('skipped' in r && r.skipped) ? String(r.skipped) : 'no_keys' });- } catch (error) {- results.push({ source_id, slug, outcome: `error: ${error instanceof Error ? error.message : String(error)}` });- }- }- if (json) process.stdout.write(JSON.stringify({ pages: results }, null, 2) + '\n');- else process.stdout.write(`Refreshed ${results.filter(r => r.outcome === 'keyed').length}/${results.length} page(s).\n${results.filter(r => r.outcome !== 'keyed').map(r => ` ${r.source_id}:${r.slug} ${r.outcome}`).join('\n')}${results.some(r => r.outcome !== 'keyed') ? '\n' : ''}`);- if (results.some(r => r.outcome.startsWith('error'))) setCliExitVerdict(1);- return;- }- if (sub === 'clear') {- const pages = await clearCandidates(engine, scope);- const results: Array<{ source_id: string; slug: string; outcome: string }> = [];- for (const { source_id, slug } of pages) {- const r = await clearPageFactKeys(engine, source_id, slug);- if (!r.published && r.reason === 'superseded') {- await engine.executeRaw('DELETE FROM page_fact_keys k USING pages p WHERE p.id=k.page_id AND p.source_id=$1 AND p.slug=$2 AND NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.fact_keys IS NOT NULL)', [source_id, slug]);- }- results.push({ source_id, slug, outcome: r.published ? 'cleared' : r.reason });- }- if (json) process.stdout.write(JSON.stringify({ pages: results }, null, 2) + '\n');- else process.stdout.write(`Cleared ${results.filter(r => r.outcome === 'cleared').length}/${results.length} page(s).${results.length === scope.limit ? ' More may remain; rerun.' : ''}\n`);- if (results.some(r => r.outcome !== 'cleared')) setCliExitVerdict(1);- return;- }- process.stderr.write(`Unknown subcommand: ${sub}\n\n${HELP}`);- setCliExitVerdict(2);-}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex cc35873b31..3feaeb24c3 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -59,7 +59,6 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],- 'fact-keys': ['--brain', '--dry-run', '--help', '--json', '--limit', '--page', '--path', '--source', '--version'],'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--source'],'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--expect', '--explain', '--facts', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],'feedback': ['--brain', '--help', '--json', '--page', '--source'],@@ -173,7 +172,6 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {'export': ['--brain', '--source'],'extract': ['--brain', '--source'],'extract-conversation-facts': ['--brain'],- 'fact-keys': ['--brain'],'facts': ['--brain', '--source'],'features': ['--brain'],'feedback': ['--brain'],diff --git a/src/core/config.ts b/src/core/config.tsindex 7a8d4f3316..098aff1f81 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1372,8 +1372,6 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.metadata_boost_gate','search.crag_escalation','search.crag_think',- // Fact keys (docs/designs/FACT_KEYS.md): facts merged into title-tier chunk embeddings (facts/fact-keys-publish.ts reads; on|off).- 'search.fact_keys',// Evidence delivery (search/evidence-delivery.ts): default unit (auto),// window radius, default/auto/remote-max token budgets; think reads its own unit.'search.return_unit',diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsindex fb48e054cf..000cd39626 100644--- a/src/core/contextual-retrieval-service.ts+++ b/src/core/contextual-retrieval-service.ts@@ -502,9 +502,10 @@ async function tryBuildPhase1(opts: {// 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(title, null);const wrappedTexts = chunks.map((c) =>modeRequiresWrapper(attemptMode)- ? wrapChunkForEmbedding(c.chunk_text, buildContextualPrefix(title, null, c.fact_keys), c.chunk_source)+ ? wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source): c.chunk_text,);diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex dcfb8ffc65..47bd973088 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -295,7 +295,6 @@ export const META_CHECK_NAMES: ReadonlySet<string> = new Set(['default_source_local_path','eval_capture','retrieval_feedback_health',- 'retrieval_enrichment',// #4613 — links_link_source_check CHECK shape: schema coherence healed by// `gbrain apply-migrations` (sibling of pages_upsert_arbiter).'links_link_source_check',diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.tsindex e46d9857e9..02b2b1ee87 100644--- a/src/core/embed-stale.ts+++ b/src/core/embed-stale.ts@@ -49,7 +49,7 @@ import { AbortError } from './abort-check.ts';export function carryChunkMetadata(loaded: Pick<Partial<Chunk>,'modality' | 'language' | 'symbol_name' | 'symbol_type' | 'start_line'- | 'end_line' | 'parent_symbol_path' | 'doc_comment' | 'symbol_name_qualified' | 'fact_keys'>,+ | 'end_line' | 'parent_symbol_path' | 'doc_comment' | 'symbol_name_qualified'>,base: ChunkInput,): ChunkInput {return {@@ -63,7 +63,6 @@ export function carryChunkMetadata(parent_symbol_path: loaded.parent_symbol_path ?? undefined,doc_comment: loaded.doc_comment ?? undefined,symbol_name_qualified: loaded.symbol_name_qualified ?? undefined,- fact_keys: loaded.fact_keys,};}diff --git a/src/core/embedding-context.ts b/src/core/embedding-context.tsindex 7c2d84fdde..c8b14c94b3 100644--- a/src/core/embedding-context.ts+++ b/src/core/embedding-context.ts@@ -42,11 +42,9 @@ const SUMMARY_HARD_CAP_CHARS = 300;export function buildContextualPrefix(title: string | null | undefined,synopsis: string | null | undefined,- factKeys?: string | null,): string | null {const safeTitle = sanitizeTitle(title ?? '');const safeSynopsis = sanitizeSynopsis(synopsis ?? '');- if (factKeys && !safeSynopsis) return `<context>${safeTitle}\nFacts: ${factKeys}\n</context>\n`;if (!safeTitle && !safeSynopsis) {return null;@@ -210,11 +208,12 @@ export function wrapChunkTextsForStoredMode(| { title?: string | null; contextual_retrieval_mode?: CRMode | null }| null| undefined,- chunks: ReadonlyArray<{ chunk_text: string; chunk_source?: string | null; fact_keys?: string | null }>,+ chunks: ReadonlyArray<{ chunk_text: string; chunk_source?: string | null }>,): string[] {const mode = page?.contextual_retrieval_mode;if (mode == null || !modeRequiresWrapper(mode)) {return chunks.map((c) => c.chunk_text);}- return chunks.map((c) => wrapChunkForEmbedding(c.chunk_text, buildContextualPrefix(page?.title ?? '', null, c.fact_keys), c.chunk_source));+ const prefix = buildContextualPrefix(page?.title ?? '', null);+ return chunks.map((c) => wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source));}diff --git a/src/core/embedding-input-hash.ts b/src/core/embedding-input-hash.tsindex 337f89e88a..6b8e5ed54e 100644--- a/src/core/embedding-input-hash.ts+++ b/src/core/embedding-input-hash.ts@@ -4,7 +4,7 @@* `content_chunks.embedding_input_hash` is written in the same statement as the* vector. It digests the vector column, model and dimensions, the wrapping tier* the vector was built under, and the exact embedding input: the chunk text for- * `none` and fenced code, the title prefix (with the chunk's fact keys, v209) plus the chunk text for `title`, and+ * `none` and fenced code, the title prefix plus the chunk text for `title`, and* (because a generated synopsis cannot be recomputed) the page's synopsis* corpus generation, the full title the synopsis prompt read, the document-body hash and the chunk text for* `per_chunk_synopsis`. A projection rebuild keeps a vector only when the stored@@ -28,7 +28,7 @@ export interface EmbeddingInputContext {bodyHash: string;}-type HashedChunk = { chunk_text: string; chunk_source?: string | null; fact_keys?: string | null };+type HashedChunk = { chunk_text: string; chunk_source?: string | null };/** The document a synopsis is generated from: every non-image chunk, in order. */export function synopsisBodyHash(chunks: ReadonlyArray<HashedChunk>): string {@@ -48,7 +48,7 @@ export function isContextualMode(mode: string | null | undefined): boolean {export function embeddingInputHash(ctx: EmbeddingInputContext, tier: EmbeddingTier, chunk: HashedChunk): string {const raw = tier === 'none' || chunk.chunk_source === 'fenced_code';const input = raw ? chunk.chunk_text- : tier === 'title' ? wrapChunkForEmbedding(chunk.chunk_text, buildContextualPrefix(ctx.title, null, chunk.fact_keys), chunk.chunk_source)+ : tier === 'title' ? wrapChunkForEmbedding(chunk.chunk_text, buildContextualPrefix(ctx.title, null), chunk.chunk_source): digest([ctx.title, ctx.bodyHash, chunk.chunk_text]);return digest(['embedding-input-v1', ctx.column, ctx.model, ctx.dimensions, tier,tier === 'per_chunk_synopsis' ? ctx.corpusGeneration : null, sha256(input)]);diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 97b7c3d4ce..3041d7ea8f 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -157,7 +157,7 @@ export async function upsertChunksOnce(// #4246: embedded_text_hash records md5(chunk_text) AT EMBED TIME so a// later text rewrite that keeps the vector is detectable as content// drift (invalidateContentDriftEmbeddings). NULL when no embedding lands.- const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, fact_keys, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;+ const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;let resolvedModel: string | null = null;try {// Keep the gateway lazy so module-load failure remains inside this soft@@ -193,7 +193,6 @@ export async function upsertChunksOnce(token_count: chunk.token_count || null,// #5553: embedding-input provenance travels only with the vector it describes.embedding_input_hash: embedding ? chunk.embedding_input_hash ?? null : null,- fact_keys: chunk.fact_keys ?? null,language: chunk.language || null,symbol_name: chunk.symbol_name || null,symbol_type: chunk.symbol_type || null,@@ -245,16 +244,16 @@ export async function upsertChunksOnce(SELECT ${pageId}::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding${trustedSql(writeCast)}, c.model, c.token_count,CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END,CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END,- c.embedding_input_hash, c.fact_keys, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line,+ c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line,c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vectorFROM jsonb_to_recordset(${JSON.stringify(incoming)}::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text,- embedding text, model text, token_count int, embedding_input_hash text, fact_keys text, language text, symbol_name text, symbol_type text,+ embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text,start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text)ON CONFLICT (page_id, chunk_index) DO UPDATE SETchunk_text = EXCLUDED.chunk_text,chunk_source = EXCLUDED.chunk_source,${col} = CASE- WHEN EXCLUDED.chunk_text != content_chunks.chunk_text OR EXCLUDED.fact_keys IS DISTINCT FROM content_chunks.fact_keys THEN EXCLUDED.${col}+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.${col}WHEN content_chunks.${col} IS NULL THEN EXCLUDED.${col}WHEN EXCLUDED.embedded_at IS NOT NULLAND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)@@ -262,7 +261,7 @@ export async function upsertChunksOnce(ELSE content_chunks.${col}END,model = CASE- WHEN EXCLUDED.chunk_text != content_chunks.chunk_text OR EXCLUDED.fact_keys IS DISTINCT FROM content_chunks.fact_keys THEN EXCLUDED.model+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.modelWHEN content_chunks.${col} IS NULL THEN EXCLUDED.modelWHEN EXCLUDED.embedded_at IS NOT NULLAND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)@@ -271,7 +270,7 @@ export async function upsertChunksOnce(END,token_count = EXCLUDED.token_count,embedded_at = CASE- WHEN (EXCLUDED.chunk_text != content_chunks.chunk_text OR EXCLUDED.fact_keys IS DISTINCT FROM content_chunks.fact_keys) AND EXCLUDED.${col} IS NULL THEN NULL+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.${col} IS NULL THEN NULLWHEN content_chunks.${col} IS NULL AND EXCLUDED.${col} IS NOT NULL THEN EXCLUDED.embedded_atWHEN EXCLUDED.embedded_at IS NOT NULLAND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)@@ -279,7 +278,7 @@ export async function upsertChunksOnce(ELSE content_chunks.embedded_atEND,embedded_text_hash = CASE- WHEN EXCLUDED.chunk_text != content_chunks.chunk_text OR EXCLUDED.fact_keys IS DISTINCT FROM content_chunks.fact_keys THEN EXCLUDED.embedded_text_hash+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hashWHEN content_chunks.${col} IS NULL THEN EXCLUDED.embedded_text_hashWHEN EXCLUDED.embedded_at IS NOT NULLAND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)@@ -287,7 +286,7 @@ export async function upsertChunksOnce(ELSE content_chunks.embedded_text_hashEND,embedding_input_hash = CASE- WHEN EXCLUDED.chunk_text != content_chunks.chunk_text OR EXCLUDED.fact_keys IS DISTINCT FROM content_chunks.fact_keys THEN EXCLUDED.embedding_input_hash+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hashWHEN content_chunks.${col} IS NULL THEN EXCLUDED.embedding_input_hashWHEN EXCLUDED.embedded_at IS NOT NULLAND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)@@ -302,7 +301,6 @@ export async function upsertChunksOnce(parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END,doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END,symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END,- fact_keys = EXCLUDED.fact_keys,modality = EXCLUDED.modality,embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)`);await exec.query(text, params);@@ -334,7 +332,7 @@ export async function getChunks(SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,cc.model, cc.token_count, cc.embedded_at, cc.language,cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line,- cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.fact_keys,+ cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality,(cc.${colId} IS NULL) AS embedding_is_null${embedCol}FROM content_chunks ccdiff --git a/src/core/fact-keys.ts b/src/core/fact-keys.tsindex abfdef6de7..bc728cd1ea 100644--- a/src/core/fact-keys.ts+++ b/src/core/fact-keys.ts@@ -12,8 +12,6 @@* embedding input. The stored `chunk_text` is never changed.*/-import { buildContextualPrefix, wrapChunkForEmbedding } from './embedding-context.ts';-export type FactKeyAssignment = 'chunk' | 'page';/** Maximum fact-key characters attached to one chunk. */@@ -83,5 +81,7 @@ export function assignFactKeys(* title-wrapped (or raw, without a title) input unchanged.*/export function factKeyedEmbeddingInput(chunkText: string, title: string | null, factKeys: string | null): string {- return wrapChunkForEmbedding(chunkText, buildContextualPrefix(title, null, factKeys), null);+ const safeTitle = (title ?? '').replace(/<\/?context>/gi, '').replace(/\s+/g, ' ').trim().slice(0, 300);+ if (!factKeys) return safeTitle ? `<context>${safeTitle}\n</context>\n${chunkText}` : chunkText;+ return `<context>${safeTitle}\nFacts: ${factKeys}\n</context>\n${chunkText}`;}diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 235a90054f..218d479d57 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -136,8 +136,6 @@ export interface FactsBackstopCtx {sourceSlug?: string;/** #5888: when the source turn happened, for the capture-lane dedup window (default: now). */turnAt?: Date;- /** v209 fact keys: the page revision this extraction reads (docs/designs/FACT_KEYS.md); null publishes no keys. */- factKeys?: import('./fact-keys-publish.ts').FactKeysBinding | null;}/** Discriminated return shape based on FactsBackstopCtx.mode. */@@ -301,8 +299,6 @@ export async function runFactsBackstop(? { mode: 'queue', enqueued: false, queueDepth: 0, skipped }: { mode: 'inline', inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped };}- const { bindFactKeysSnapshot } = await import('./fact-keys-publish.ts');- ctx = { ...ctx, factKeys: await bindFactKeysSnapshot(ctx.engine, ctx.sourceId, parsedPage.slug, parsedPage.compiled_truth).catch(() => null) };const { managedPersistenceEnabled } = await import('../persistence/ownership.ts');if (await managedPersistenceEnabled(ctx.engine)) {if (mode !== 'inline') {@@ -660,7 +656,6 @@ async function runPipelineBodyInner(// facts.default_visibility (fail-closed to 'private').const { resolveDefaultVisibility } = await import('./visibility.ts');const visibility = ctx.visibility ?? (await resolveDefaultVisibility(ctx.engine));- if (ctx.factKeys) await (await import('./fact-keys-publish.ts')).publishExtractedFactKeys(ctx.engine, ctx.factKeys, input, outcome.facts, visibility, resolveEntitySlugWithSource, abortSignal);// #5888: one exact-duplicate check for the capture lanes, before either writer.const { facts, dropped } = await dedupCapturedFacts(ctx, await inferMissingSubjects(ctx, outcome.facts, visibility, input.pageSlug, managed), visibility, resolveEntitySlugWithSource);if (managed) return withCaptureDrops(dropped, facts.length || !dropped.length ? await publishManagedFacts(ctx.engine, managed, ctx, facts, visibility, input.pageSlug) : null);diff --git a/src/core/facts/eligibility.ts b/src/core/facts/eligibility.tsindex 0c0d61f4e0..721bb9f769 100644--- a/src/core/facts/eligibility.ts+++ b/src/core/facts/eligibility.ts@@ -44,7 +44,7 @@ export type EligibilityResult = { ok: true } | { ok: false; reason: string };* legacy default) still extracts because the directory tells us it's* conversation-shape.*/-export const RESCUE_SLUG_PREFIXES = ['meetings/', 'personal/', 'daily/'] as const;+const RESCUE_SLUG_PREFIXES = ['meetings/', 'personal/', 'daily/'] as const;// v0.41.22 (T21, codex F-ELIGIBLE finding): UNION of gbrain-base's hardcoded// types AND gbrain-base-v2's canonical extractable types. Pre-rebase plan@@ -71,7 +71,7 @@ export const RESCUE_SLUG_PREFIXES = ['meetings/', 'personal/', 'daily/'] as cons// Pack-aware async lookup via extractableTypesFromPack(pack) deferred to// v0.43+ once an async eligibility-check signature is feasible across all// call sites (operations.ts + import-file.ts + others).-export const ELIGIBLE_TYPES: PageType[] = [+const ELIGIBLE_TYPES: PageType[] = [// gbrain-base (legacy) types'note', 'meeting', 'slack', 'email', 'calendar-event', 'source', 'writing',// gbrain-base-v2 canonical types declared extractable in the pack@@ -79,7 +79,7 @@ export const ELIGIBLE_TYPES: PageType[] = ['media', 'tweet', 'analysis',];-export const MIN_BODY_CHARS = 80;+const MIN_BODY_CHARS = 80;export function isFactsBackstopEligible(slug: string,@@ -100,11 +100,3 @@ export function isFactsBackstopEligible(return { ok: true };}--/** The same predicate over a `pages` row alias, for counting eligible pages in SQL. */-export function factsBackstopEligibleSql(p: string): string {- const quote = (v: string) => `'${v.replace(/'/g, "''")}'`;- return `(${p}.slug NOT LIKE 'wiki/agents/%' AND COALESCE(${p}.frontmatter->>'dream_generated','') <> 'true'- AND length(btrim(${p}.compiled_truth)) >= ${MIN_BODY_CHARS}- AND (${p}.type IN (${ELIGIBLE_TYPES.map(quote).join(',')}) OR ${RESCUE_SLUG_PREFIXES.map(prefix => `${p}.slug LIKE ${quote(prefix + '%')}`).join(' OR ')}))`;-}diff --git a/src/core/facts/fact-keys-publish.ts b/src/core/facts/fact-keys-publish.tsdeleted file mode 100644index 8e80689858..0000000000--- a/src/core/facts/fact-keys-publish.ts+++ /dev/null@@ -1,225 +0,0 @@-/**- * Fact keys in chunk embeddings — publication (docs/designs/FACT_KEYS.md).- *- * Invariant: every searchable vector was built from the page's current key- * rows. Keys are added or replaced only by prepare-then-swap: the changed- * chunks are embedded with their new keys first, then the occurrence rows,- * the chunk key text and the vectors change together in one guarded- * transaction. Any failed check writes nothing, so the page keeps its previous- * keys and vectors.- *- * Scope: pages embedded under the `title` tier (the `balanced` default).- * Pages with protected fences, `embed_skip`, or another tier get no keys.- * Visibility fails closed: a private fact never keys a world-visible page.- */-import type { BrainEngine } from '../engine.ts';-import type { ChunkInput } from '../types.ts';-import { assignFactKeys } from '../fact-keys.ts';-import { wrapChunkTextsForStoredMode } from '../embedding-context.ts';-import { currentEmbeddingSignature, embedBatch } from '../embedding.ts';-import { installPageEmbeddings, readProjectionSnapshot, type ProjectionSnapshot } from '../page-state/projections.ts';-import { declarePersistenceProtocol } from '../persistence/protocol.ts';-import { privatePagesFilterFragment } from '../search/private-visibility.ts';-import { quoteIdentifier } from '../search/embedding-column.ts';-import { FACTS_FENCE_BEGIN } from '../facts-fence.ts';-import { TAKES_FENCE_BEGIN } from '../takes-fence.ts';--export const FACT_KEYS_CONFIG_KEY = 'search.fact_keys';-export const FACT_KEYS_EXTRACTOR_VERSION = 'facts-extractor-v1';--export interface FactKeysBinding {- sourceId: string;- slug: string;- pageId: number;- revision: string;- sourceIncarnation: string;- text: string;-}--export interface FactKeyItem {- text: string;- /** Resolved entity slug the fact is about, or '*' when unresolved. */- subject: string;- visibility: 'private' | 'world';-}--export type FactKeysSkipReason = 'disabled' | 'superseded' | 'protected' | 'not_title_mode' | 'embed_skip'- | 'embedding_unconfigured' | 'embed_failed' | 'withdrawal_changed';--export type FactKeysPublishResult =- | { published: true; items: number; chunks_rekeyed: number }- | { published: false; reason: FactKeysSkipReason; detail?: string };--type EmbedFn = (texts: string[], opts?: { abortSignal?: AbortSignal }) => Promise<Float32Array[]>;--export async function factKeysEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {- const value = (await engine.getConfig(FACT_KEYS_CONFIG_KEY))?.trim().toLowerCase();- return value === 'on' || value === 'true' || value === '1';-}--/**- * Binds key publication to the exact text the extractor reads. Null when the- * feature is off or the stored page no longer holds `text`; extraction then- * proceeds as before and publishes no keys.- */-export async function bindFactKeysSnapshot(engine: BrainEngine, sourceId: string, slug: string | undefined, text: string): Promise<FactKeysBinding | null> {- if (!slug || !await factKeysEnabled(engine)) return null;- const snapshot = await engine.readPageSnapshot(slug, { sourceId });- if (!snapshot || snapshot.page.deleted_at || snapshot.page.compiled_truth !== text) return null;- return { sourceId, slug, pageId: snapshot.page.id, revision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation, text };-}--function hasProtectedFence(body: string): boolean {- return body.includes(FACTS_FENCE_BEGIN) || body.includes(TAKES_FENCE_BEGIN);-}--async function pageIsWorldVisible(engine: BrainEngine, pageId: number): Promise<boolean> {- const [row] = await engine.executeRaw<{ world: boolean }>(`SELECT (${privatePagesFilterFragment('p')}) AS world FROM pages p WHERE p.id=$1`, [pageId]);- return row?.world === true;-}--/** Items that may key this page: not withdrawn, and never a private fact on a world page. */-async function admissibleItems(engine: BrainEngine, sourceId: string, pageId: number, items: readonly FactKeyItem[]): Promise<FactKeyItem[]> {- if (!items.length) return [];- const world = await pageIsWorldVisible(engine, pageId);- const visible = items.filter(item => !world || item.visibility === 'world');- if (!visible.length) return [];- const withdrawn = await engine.executeRaw<{ i: number }>(`SELECT DISTINCT k.i FROM jsonb_to_recordset($2::text::jsonb) k(i int,text text,subject text,visibility text)- JOIN fact_withdrawals w ON w.source_id=$1 AND w.visibility=k.visibility- AND w.fact_hash IN (gbrain_fact_fingerprint(k.text),gbrain_fact_fingerprint_v1(k.text))- AND (w.subject='*' OR k.subject='*' OR w.subject=k.subject)`,- [sourceId, JSON.stringify(visible.map((item, i) => ({ i, ...item })))]);- const drop = new Set(withdrawn.map(row => Number(row.i)));- return visible.filter((_, i) => !drop.has(i));-}--async function vectorColumns(engine: BrainEngine): Promise<string[]> {- const rows = await engine.executeRaw<{ column_name: string }>(`SELECT column_name FROM information_schema.columns- WHERE table_name='content_chunks' AND udt_name IN ('vector','halfvec') AND column_name<>'embedding_image'`);- return rows.map(row => row.column_name);-}--function sameInventory(a: ProjectionSnapshot['chunks'], b: ProjectionSnapshot['chunks']): boolean {- return a.length === b.length && a.every((chunk, i) => chunk.id === b[i].id && chunk.chunk_index === b[i].chunk_index- && chunk.chunk_text === b[i].chunk_text && (chunk.fact_keys ?? null) === (b[i].fact_keys ?? null));-}--/**- * Publish occurrence keys for one bound page revision (`items` empty clears- * them). `force` publishes even when the feature is off; the disable sweep- * uses it with no items to strip keys.- */-export async function publishPageFactKeys(engine: BrainEngine, binding: FactKeysBinding, rawItems: readonly FactKeyItem[],- opts: { embed?: EmbedFn; force?: boolean; abortSignal?: AbortSignal } = {}): Promise<FactKeysPublishResult> {- const clearing = rawItems.length === 0;- if (!opts.force && !await factKeysEnabled(engine)) return { published: false, reason: 'disabled' };- const prepared = await readProjectionSnapshot(engine, binding.slug, binding.sourceId, { requireLiveSource: true });- const page = prepared?.snapshot.page;- if (!prepared || !page || prepared.snapshot.revision !== binding.revision || page.id !== binding.pageId- || prepared.snapshot.sourceIncarnation !== binding.sourceIncarnation || page.compiled_truth !== binding.text) {- return { published: false, reason: 'superseded' };- }- if (!clearing) {- if (Object.hasOwn(page.frontmatter ?? {}, 'embed_skip')) return { published: false, reason: 'embed_skip' };- if (page.contextual_retrieval_mode !== 'title') return { published: false, reason: 'not_title_mode' };- if (hasProtectedFence(page.compiled_truth) || hasProtectedFence(page.timeline ?? '')) return { published: false, reason: 'protected' };- }- const items = await admissibleItems(engine, binding.sourceId, page.id, rawItems);- const keys = items.length ? assignFactKeys(items.map(item => item.text), prepared.chunks, 'chunk') : prepared.chunks.map(() => null);- const changed = prepared.chunks.map((chunk, i) => ({ chunk, keys: keys[i] })).filter(({ chunk, keys: next }) => next !== (chunk.fact_keys ?? null));-- const canEmbed = !!opts.embed || !!currentEmbeddingSignature();- let vectors: Float32Array[] = [];- if (changed.length && canEmbed) {- try {- vectors = await (opts.embed ?? embedBatch)(- wrapChunkTextsForStoredMode(page, changed.map(({ chunk, keys: next }) => ({ ...chunk, fact_keys: next }))),- opts.abortSignal ? { abortSignal: opts.abortSignal } : {});- } catch (error) {- return { published: false, reason: 'embed_failed', detail: error instanceof Error ? error.message : String(error) };- }- if (vectors.length !== changed.length || vectors.some(v => !v?.length)) return { published: false, reason: 'embed_failed', detail: 'incomplete embedding batch' };- } else if (changed.length && !clearing) {- return { published: false, reason: 'embedding_unconfigured' };- }-- class Abort extends Error { constructor(readonly reason: FactKeysSkipReason) { super(reason); } }- try {- await engine.transaction(async tx => {- await declarePersistenceProtocol(tx as never);- await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR SHARE', [binding.sourceId]);- await tx.lockPageKeys([{ sourceId: binding.sourceId, slug: binding.slug }]);- const current = await tx.readPageSnapshot(binding.slug, { sourceId: binding.sourceId });- if (!current || current.page.deleted_at || current.revision !== binding.revision || current.page.id !== binding.pageId- || current.sourceIncarnation !== binding.sourceIncarnation || current.page.compiled_truth !== binding.text- || current.page.text_projection_revision !== current.revision) throw new Abort('superseded');- if (!sameInventory(await tx.getChunks(binding.slug, { sourceId: binding.sourceId, includeUnsealed: true }), prepared.chunks)) throw new Abort('superseded');- if (!opts.force && !await factKeysEnabled(tx)) throw new Abort('disabled');- const recheck = await admissibleItems(tx, binding.sourceId, page.id, rawItems);- if (recheck.length !== items.length || recheck.some((item, i) => item !== items[i])) throw new Abort('withdrawal_changed');- await tx.executeRaw('DELETE FROM page_fact_keys WHERE page_id=$1', [page.id]);- if (items.length) {- await tx.executeRaw(`INSERT INTO page_fact_keys (page_id,source_id,page_revision,ordinal,item_text,item_fingerprint,subject,visibility,extractor_version)- SELECT $1,$2,$3,k.ordinal,k.text,gbrain_fact_fingerprint(k.text),k.subject,k.visibility,$4- FROM jsonb_to_recordset($5::text::jsonb) k(ordinal int,text text,subject text,visibility text)`,- [page.id, binding.sourceId, binding.revision, FACT_KEYS_EXTRACTOR_VERSION,- JSON.stringify(items.map((item, ordinal) => ({ ordinal, text: item.text, subject: item.subject, visibility: item.visibility })))]);- }- if (!changed.length) return;- const ids = changed.map(({ chunk }) => chunk.id);- await tx.executeRaw(`UPDATE content_chunks c SET fact_keys=k.keys FROM jsonb_to_recordset($2::text::jsonb) k(id int,keys text)- WHERE c.page_id=$1 AND c.id=k.id`, [page.id, JSON.stringify(changed.map(({ chunk, keys: next }) => ({ id: chunk.id, keys: next })))]);- const others = (await vectorColumns(tx)).filter(name => name !== prepared.embeddingColumn.name);- if (others.length) {- await tx.executeRaw(`UPDATE content_chunks SET ${others.map(name => `${quoteIdentifier(name)}=NULL`).join(',')} WHERE page_id=$1 AND id=ANY($2::int[])`, [page.id, ids]);- }- if (!vectors.length) {- await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(prepared.embeddingColumn.name)}=NULL,embedded_at=NULL,- embedded_text_hash=NULL,embedding_input_hash=NULL WHERE page_id=$1 AND id=ANY($2::int[])`, [page.id, ids]);- return;- }- const rekeyed: ProjectionSnapshot = { ...prepared, chunks: prepared.chunks.map((chunk, i) => ({ ...chunk, fact_keys: keys[i] })) };- const installed = await installPageEmbeddings(tx, rekeyed, changed.map(({ chunk, keys: next }, i): ChunkInput => ({- chunk_index: chunk.chunk_index, chunk_text: chunk.chunk_text, chunk_source: chunk.chunk_source,- embedding: vectors[i], model: prepared.embeddingModel ?? undefined, fact_keys: next,- })));- if (!installed) throw new Abort('superseded');- });- } catch (error) {- if (error instanceof Abort) return { published: false, reason: error.reason };- throw error;- }- return { published: true, items: items.length, chunks_rekeyed: changed.length };-}--/** Remove a page's keys (prepare-then-swap with no items), whatever the setting. */-export async function clearPageFactKeys(engine: BrainEngine, sourceId: string, slug: string, opts: { embed?: EmbedFn } = {}): Promise<FactKeysPublishResult> {- const snapshot = await engine.readPageSnapshot(slug, { sourceId });- if (!snapshot || snapshot.page.deleted_at) return { published: false, reason: 'superseded' };- return publishPageFactKeys(engine, { sourceId, slug, pageId: snapshot.page.id, revision: snapshot.revision,- sourceIncarnation: snapshot.sourceIncarnation, text: snapshot.page.compiled_truth }, [], { ...opts, force: true });-}--/**- * The facts backstop's hook: occurrence keys from the extractor's own output- * for the bound revision, captured before notability filtering and dedup.- * Never throws; a failed publication leaves the previous keys and vectors.- */-export async function publishExtractedFactKeys(engine: BrainEngine, binding: FactKeysBinding,- input: { pageSlug?: string; turnText: string },- facts: ReadonlyArray<{ fact?: unknown; entity_slug?: string | null }>, visibility: 'private' | 'world',- resolve: (engine: BrainEngine, sourceId: string, ref: string) => Promise<{ slug: string; source: string } | null>,- abortSignal?: AbortSignal): Promise<FactKeysPublishResult> {- if (input.pageSlug !== binding.slug || input.turnText !== binding.text) return { published: false, reason: 'superseded' };- try {- const items: FactKeyItem[] = [];- for (const f of facts) {- if (typeof f.fact !== 'string' || !f.fact.trim()) continue;- const resolved = f.entity_slug ? await resolve(engine, binding.sourceId, f.entity_slug) : null;- items.push({ text: f.fact, subject: resolved && resolved.source !== 'fallback_slugify' ? resolved.slug : '*', visibility });- }- return await publishPageFactKeys(engine, binding, items, { abortSignal });- } catch (error) {- return { published: false, reason: 'superseded', detail: error instanceof Error ? error.message : String(error) };- }-}diff --git a/src/core/facts/fact-keys-retire.ts b/src/core/facts/fact-keys-retire.tsdeleted file mode 100644index 5e7800af94..0000000000--- a/src/core/facts/fact-keys-retire.ts+++ /dev/null@@ -1,12 +0,0 @@-import type { BrainEngine } from '../engine.ts';--/**- * Rows for any revision other than the page's current one are never used- * again. Every path that seals a new chunk set calls this in its transaction;- * the replacement chunks carry no keys, and upsertChunks drops any vector whose- * key text changed.- */-export async function retireStaleFactKeys(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string): Promise<void> {- await tx.executeRaw(`DELETE FROM page_fact_keys k USING pages p WHERE p.id=k.page_id AND p.source_id=$1 AND p.slug=$2- AND k.page_revision IS DISTINCT FROM p.knowledge_revision::text`, [sourceId, slug]);-}diff --git a/src/core/facts/fact-keys-status.ts b/src/core/facts/fact-keys-status.tsdeleted file mode 100644index 4bc3dc5de2..0000000000--- a/src/core/facts/fact-keys-status.ts+++ /dev/null@@ -1,34 +0,0 @@-import type { BrainEngine } from '../engine.ts';-import { factsBackstopEligibleSql } from './eligibility.ts';-import { factKeysEnabled } from './fact-keys-publish.ts';--export interface FactKeysStatus {- enabled: boolean;- keyed_pages: number;- keyed_chunks: number;- key_rows: number;- eligible_unkeyed_pages: number;- stale_rows_pages: number;-}--/** Title-mode, sealed pages without protected fences that the facts backstop would extract. */-export const FACT_KEYS_ELIGIBLE_SQL = `p.deleted_at IS NULL AND p.contextual_retrieval_mode='title' AND p.text_projection_revision=p.knowledge_revision- AND NOT (p.frontmatter ? 'embed_skip') AND strpos(p.compiled_truth,'gbrain:facts:')=0 AND strpos(p.compiled_truth,'gbrain:takes:')=0- AND ${factsBackstopEligibleSql('p')}`;--export async function factKeysStatus(engine: BrainEngine): Promise<FactKeysStatus> {- const [row] = await engine.executeRaw<Record<string, number>>(`SELECT- (SELECT count(DISTINCT page_id) FROM content_chunks WHERE fact_keys IS NOT NULL)::int AS keyed_pages,- (SELECT count(*) FROM content_chunks WHERE fact_keys IS NOT NULL)::int AS keyed_chunks,- (SELECT count(*) FROM page_fact_keys)::int AS key_rows,- (SELECT count(*) FROM pages p WHERE ${FACT_KEYS_ELIGIBLE_SQL}- AND NOT EXISTS (SELECT 1 FROM page_fact_keys k WHERE k.page_id=p.id AND k.page_revision=p.knowledge_revision::text))::int AS eligible_unkeyed_pages,- (SELECT count(DISTINCT k.page_id) FROM page_fact_keys k JOIN pages p ON p.id=k.page_id- WHERE k.page_revision=p.knowledge_revision::text- AND NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.fact_keys IS NOT NULL))::int AS stale_rows_pages`);- return {- enabled: await factKeysEnabled(engine),- keyed_pages: Number(row.keyed_pages), keyed_chunks: Number(row.keyed_chunks), key_rows: Number(row.key_rows),- eligible_unkeyed_pages: Number(row.eligible_unkeyed_pages), stale_rows_pages: Number(row.stale_rows_pages),- };-}diff --git a/src/core/facts/withdrawal-discovery.ts b/src/core/facts/withdrawal-discovery.tsindex 60014c62d2..3be3d74686 100644--- a/src/core/facts/withdrawal-discovery.ts+++ b/src/core/facts/withdrawal-discovery.ts@@ -65,15 +65,6 @@ export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: sAND (k.subject='*' OR f.entity_slug=k.subject)JOIN pages p ON p.source_id=f.source_id AND p.slug=COALESCE(f.source_markdown_slug,f.entity_slug)`, [sourceId, keys]);for (const row of provenance) affected.add(row.id);- // v209 fact keys: pages whose chunk embeddings carry the claim as a key. An- // unresolved key subject ('*') matches every subject-scoped withdrawal.- const keyedPages = await engine.executeRaw<{ id: number }>(`SELECT DISTINCT fk.page_id AS id- FROM jsonb_to_recordset($2::text::jsonb) k(visibility text,fact_hash text,subject text,norm text)- JOIN page_fact_keys fk ON fk.source_id=$1 AND fk.visibility=k.visibility- AND (fk.item_fingerprint=COALESCE(encode(sha256(convert_to(k.norm,'UTF8')),'hex'),k.fact_hash)- OR gbrain_fact_fingerprint_v1(fk.item_text)=k.fact_hash)- AND (k.subject='*' OR fk.subject='*' OR fk.subject=k.subject)`, [sourceId, keys]);- for (const row of keyedPages) affected.add(Number(row.id));if (affected.size > WITHDRAWAL_LIMITS.targets) await refuseAffected(engine, sourceId, affected);const match = async (incoming: Array<{ id: number; slug: string; claim: string; visibility: string | null; ambiguous: boolean }>) => {if (!incoming.length) return;diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex ce79fad873..0ecee0cbbc 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -58,7 +58,6 @@ import { decorateEmbeddingDimError } from './embedding-dim-check.ts';import { resolveImportContextualMode } from './import-contextual-mode.ts';import { runGuardrails } from './guardrails.ts';import { parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning, replaceOrInsertFactsFence } from './facts-fence.ts';-import { retireStaleFactKeys } from './facts/fact-keys-retire.ts';/*** #2044 / #4548: row-level, visibility-aware fence merge for one page@@ -906,7 +905,6 @@ export async function importFromContent(// above admitted carry over; a new seal otherwise inherits nothing from an// older index, whose contextual vector may have included a private sibling.await tx.deleteChunks(slug, txOpts);- await retireStaleFactKeys(tx, txOpts.sourceId, slug);if (chunks.length > 0) {const embeddingColumn = await stampEmbeddingInputs(tx, chunks, null,{ title: parsed.title, tier: effectiveCRMode === 'title' ? 'title' : 'none', corpusGeneration });@@ -1668,7 +1666,6 @@ async function applyImportTransaction(tx: BrainEngine, spec: ImportTransactionSp}if (spec.chunks !== undefined) {await tx.deleteChunks(spec.slug, txOpts);- await retireStaleFactKeys(tx, spec.sourceId ?? 'default', spec.slug);if (spec.chunks.length > 0) {await tx.upsertChunks(spec.slug, spec.chunks, txOpts);} else {diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex 2a80f05033..8a9dc9d0db 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -13,7 +13,6 @@ import { getFtsLanguage } from '../fts-language.ts';import { getEmbeddingModel } from '../ai/gateway.ts';import { refreshProjectionStatistics } from '../search/projection-statistics.ts';import { belowSafeChunkFence } from '../search/safe-chunks.ts';-import { retireStaleFactKeys } from '../facts/fact-keys-retire.ts';import { acceptedEmbeddingInputHashes, embeddingInputHash, isContextualMode, plainEmbeddingTier, synopsisBodyHash,type EmbeddingInputContext, type EmbeddingTier } from '../embedding-input-hash.ts';@@ -175,7 +174,6 @@ export async function installPageProjection(engine: BrainEngine, prepared: Projeawait tx.upsertChunks(slug, chunks, { sourceId, expectedRevision: snapshot.revision, embeddingColumn: context.column });if (opts.code) await installCodeChunkEdges(tx, slug, sourceId, opts.code);if (opts.seal) {- await retireStaleFactKeys(tx, sourceId, slug);await tx.executeRaw(`UPDATE pages SET chunker_version=$3WHERE source_id=$1 AND slug=$2`, [sourceId, slug, MARKDOWN_CHUNKER_VERSION]);await sealPageTextProjection(tx, slug, sourceId, current!);@@ -215,12 +213,6 @@ export async function installPageEmbeddings(engine: BrainEngine, prepared: Proje// so resolving again could send these vectors to a different model's column.const column = context.column;const tier = built?.tier ?? plainEmbeddingTier(current.page.contextual_retrieval_mode);- // v209: a title-tier vector is current only when it was built from the- // stored fact keys (the chunk's own when the caller carried them, else the- // prepared row the caller embedded from).- const preparedKeys = new Map(prepared.chunks.map(chunk => [chunk.chunk_index, chunk.fact_keys ?? null]));- if (tier === 'title' && chunks.some(chunk => (chunk.embedding || chunk.embedding_image)- && (chunk.fact_keys !== undefined ? chunk.fact_keys ?? null : preparedKeys.get(chunk.chunk_index) ?? null) !== (byIndex.get(chunk.chunk_index)!.fact_keys ?? null))) return false;const provenance = embeddingInputContext(context, current.page.title,built?.corpusGeneration !== undefined ? built.corpusGeneration : context.corpusGeneration, stored);// This is deliberately UPDATE-only: a late embed can never replace text,diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex 7f0a8650e5..dcc321b983 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -97,7 +97,6 @@ export const GRADUATION_INVENTORY: Inventory = {carry('op_checkpoints', 'operational', 'Resumable operation checkpoints.'),carry('open_loops', 'user_data', 'Open loops and their status.'),carry('page_aliases', 'user_data', 'Page aliases.'),- carry('page_fact_keys', 'user_data', 'Fact-key occurrence rows: paid extraction output per page revision; the carried vectors were built from them, so withdrawal must still find them.'),carry('page_generation_clock', 'operational', 'Page generation clock (derived side table, verified equal).'),carry('page_mention_state', 'operational', 'Entity mention index: per-page mention watermark; without it every page is due for a rescan.'),carry('page_projection_jobs', 'operational', 'Pending page projection work (derived side table, verified equal).'),diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex e9423d5c0e..8ccddd487c 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -151,7 +151,6 @@ CREATE TABLE IF NOT EXISTS content_chunks (embedded_at TIMESTAMPTZ,embedded_text_hash TEXT,embedding_input_hash TEXT,- fact_keys TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),language TEXT,symbol_name TEXT,@@ -476,21 +475,6 @@ CREATE TABLE IF NOT EXISTS retrieval_weights (PRIMARY KEY (source_id, element_kind, element_key));-CREATE TABLE IF NOT EXISTS page_fact_keys (- page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,- source_id TEXT NOT NULL,- page_revision TEXT NOT NULL,- ordinal INTEGER NOT NULL,- item_text TEXT NOT NULL,- item_fingerprint TEXT NOT NULL,- subject TEXT NOT NULL,- visibility TEXT NOT NULL CHECK (visibility IN ('private','world')),- extractor_version TEXT NOT NULL,- PRIMARY KEY (page_id, page_revision, ordinal)-);-CREATE INDEX IF NOT EXISTS page_fact_keys_withdrawal_idx- ON page_fact_keys (source_id, item_fingerprint, visibility, subject);-CREATE TABLE IF NOT EXISTS session_context_state (source_id TEXT NOT NULL,client_id TEXT NOT NULL DEFAULT 'local',diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 7d5a67c93d..14c5f98a63 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -321,9 +321,6 @@ CREATE TABLE IF NOT EXISTS content_chunks (embedded_text_hash TEXT,-- #5553 (v171): embedding-input provenance written with the vector.embedding_input_hash TEXT,- -- v209: fact-key text carried by this chunk's title-tier embedding input- -- (docs/designs/FACT_KEYS.md); changes only together with the vector.- fact_keys TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),-- v0.19.0: code chunk metadata. Nullable — markdown chunks leave these NULL.-- Powers \`query --lang\`, \`code-def <symbol>\`, and \`code-refs <symbol>\`.@@ -889,24 +886,6 @@ CREATE TABLE IF NOT EXISTS retrieval_weights (PRIMARY KEY (source_id, element_kind, element_key));--- page_fact_keys (migration v209): occurrence keys, the facts extractor's own--- output for one page revision before dedup (docs/designs/FACT_KEYS.md).--- Withdrawal discovery joins on (source, fingerprint, visibility, subject).-CREATE TABLE IF NOT EXISTS page_fact_keys (- page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,- source_id TEXT NOT NULL,- page_revision TEXT NOT NULL,- ordinal INTEGER NOT NULL,- item_text TEXT NOT NULL,- item_fingerprint TEXT NOT NULL,- subject TEXT NOT NULL,- visibility TEXT NOT NULL CHECK (visibility IN ('private','world')),- extractor_version TEXT NOT NULL,- PRIMARY KEY (page_id, page_revision, ordinal)-);-CREATE INDEX IF NOT EXISTS page_fact_keys_withdrawal_idx- ON page_fact_keys (source_id, item_fingerprint, visibility, subject);--- session_context_state (v0.45.7 / migration v126 — ambient recall issue #1):-- per-session cursor + boundary-tie dedup for the \`delta\` verb + heartbeat-- runtime. Key (source_id, client_id, session_id); client_id 'local' sentineldiff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 32f9849e03..aadccdd67a 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -209,7 +209,6 @@ import { v205 } from './v205-minion-spend-authorization.ts';import { v206 } from './v206-entity-mention-index.ts';import { v207 } from './v207-retrieval-feedback.ts';import { v208 } from './v208-delta-per-arm-cursor.ts';-import { v209 } from './v209-fact-keys.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -417,5 +416,4 @@ export const MIGRATIONS: Migration[] = [v206,v207,v208,- v209,];diff --git a/src/core/schema-migrations/v209-fact-keys.ts b/src/core/schema-migrations/v209-fact-keys.tsdeleted file mode 100644index d6fd6d701c..0000000000--- a/src/core/schema-migrations/v209-fact-keys.ts+++ /dev/null@@ -1,36 +0,0 @@-import type { Migration } from './types.ts';--// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md-// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.-//-// Fact keys (docs/designs/FACT_KEYS.md). page_fact_keys holds the facts-// extractor's own output for one page revision (occurrence keys, captured-// before dedup), the provenance withdrawal discovery joins on.-// content_chunks.fact_keys is the derived key text a chunk's title-tier-// embedding input carries; it changes only together with that chunk's vector.-// Created empty; nullable column with no backfill (keys arrive with the next-// extraction). Keep in sync with src/schema.sql.-export const FACT_KEYS_SQL = `- CREATE TABLE IF NOT EXISTS page_fact_keys (- page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,- source_id TEXT NOT NULL,- page_revision TEXT NOT NULL,- ordinal INTEGER NOT NULL,- item_text TEXT NOT NULL,- item_fingerprint TEXT NOT NULL,- subject TEXT NOT NULL,- visibility TEXT NOT NULL CHECK (visibility IN ('private','world')),- extractor_version TEXT NOT NULL,- PRIMARY KEY (page_id, page_revision, ordinal)- );- CREATE INDEX IF NOT EXISTS page_fact_keys_withdrawal_idx- ON page_fact_keys (source_id, item_fingerprint, visibility, subject);- ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS fact_keys TEXT;-`;--export const v209: Migration = {- version: 209,- name: 'fact_keys',- idempotent: true,- sql: FACT_KEYS_SQL,-};diff --git a/src/core/types.ts b/src/core/types.tsindex d7505cd82b..0c73f75d02 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -684,8 +684,6 @@ export interface Chunk {* (getChunks).*/embedding_is_null?: boolean;- /** v209 fact keys: the key text this chunk's title-tier embedding input carries (docs/designs/FACT_KEYS.md). */- fact_keys?: string | null;}/**@@ -771,8 +769,6 @@ export interface ChunkInput {embedding?: Float32Array;/** #5553: embedding-input provenance (see embedding-input-hash.ts); written only with `embedding`. */embedding_input_hash?: string;- /** v209: fact-key text in the title-tier embedding input; the stored value changes only with the vector. */- fact_keys?: string | null;model?: string;token_count?: number;/**diff --git a/src/core/utils.ts b/src/core/utils.tsindex 179d9fb7c2..0a70ac96e5 100644--- a/src/core/utils.ts+++ b/src/core/utils.ts@@ -444,7 +444,6 @@ export function rowToChunk(row: Record<string, unknown>, includeEmbedding = fals// Only present when the SELECT included it (getChunks); undefined elsewhere// so callers can tell "not selected" from "vector present"....(row.embedding_is_null !== undefined && { embedding_is_null: Boolean(row.embedding_is_null) }),- ...(row.fact_keys !== undefined && { fact_keys: (row.fact_keys as string | null) ?? null }),};}diff --git a/src/eval/longmemeval/retrieval-arms.ts b/src/eval/longmemeval/retrieval-arms.tsindex dc515bba89..551e0618f4 100644--- a/src/eval/longmemeval/retrieval-arms.ts+++ b/src/eval/longmemeval/retrieval-arms.ts@@ -8,10 +8,7 @@* the benchmark's published user-turn fact prompt; `production` — gbrain's* own facts extractor, 8,000-char input as shipped), merged into the* embedding input of that session's chunks (src/core/fact-keys.ts), and the- * chunks are re-embedded in place. `pipeline` runs the shipping path instead:- * `search.fact_keys on`, then the facts backstop on each imported page, which- * extracts and publishes keys exactly as a page write does- * (src/core/facts/fact-keys-publish.ts); its extractions are not cached. `chunk_text` is untouched, so retrieval+ * chunks are re-embedded in place. `chunk_text` is untouched, so retrieval* still returns the raw session. Extractions are cached on disk by* content hash so arms and reruns never pay twice.*@@ -41,7 +38,7 @@ import type { DayRange } from '../../core/temporal-grammar.ts';import { resolveModel } from '../../core/model-config.ts';import { rawSessionId, scoreRecall, type SlugToRawMap } from './metrics.ts';-export type FactExtractor = 'paper' | 'production' | 'pipeline';+export type FactExtractor = 'paper' | 'production';const FACT_EXTRACT_CONCURRENCY = 8;@@ -172,7 +169,6 @@ export async function applyFactKeyArm(arm: FactKeyArm,spend: FactKeySpend,): Promise<FactKeyArmResult> {- if (arm.extractor === 'pipeline') return applyPipelineFactKeys(engine, pages, arm, spend);const col = await resolveActiveEmbeddingColumnFromEngine(engine);const column = quoteIdentifier(col.name);const cast = vectorCastSuffix(col);@@ -265,11 +261,10 @@ export const LME_RETRIEVAL_ARM_FLAGS: Array<{ name: string; arg?: string; help:'input of its chunks (chunk = each fact on its best-matching chunk; page =','all facts on every chunk) and re-embed. Retrieval still returns raw sessions.'],apply: (o, v) => { if (v !== 'chunk' && v !== 'page') throw new Error(`--fact-keys must be chunk|page (got: ${v})`); o.arms.factKeys = v; } },- { name: '--fact-extractor', arg: 'paper|production|pipeline', help: [+ { name: '--fact-extractor', arg: 'paper|production', help: ['Fact source for --fact-keys: paper = the benchmark\'s published user-turn',- 'fact prompt; production = gbrain\'s facts extractor as shipped (default: paper);',- 'pipeline = the shipping path (search.fact_keys on, facts backstop per page; chunk only).'],- apply: (o, v) => { if (v !== 'paper' && v !== 'production' && v !== 'pipeline') throw new Error(`--fact-extractor must be paper|production|pipeline (got: ${v})`); o.arms.factExtractor = v; } },+ 'fact prompt; production = gbrain\'s facts extractor as shipped (default: paper).'],+ apply: (o, v) => { if (v !== 'paper' && v !== 'production') throw new Error(`--fact-extractor must be paper|production (got: ${v})`); o.arms.factExtractor = v; } },{ name: '--fact-keys-model', arg: 'MODEL', help: ['Extraction model for --fact-keys (default: the utility tier, haiku).'],apply: (o, v) => { o.arms.factKeysModel = v; } },{ name: '--fact-keys-max-usd', arg: 'N', help: ['Spend cap for uncached fact extraction (default 20). Cached extractions are free.'],@@ -294,40 +289,12 @@ export function armPins(o: RetrievalArmOptions): { retrieval_arms?: Record<strinexport async function resolveFactKeyArm(o: RetrievalArmOptions, client: ThinkLLMClient): Promise<{ arm: FactKeyArm; spend: FactKeySpend } | null> {if (!o.factKeys) return null;- if (o.factExtractor === 'pipeline' && o.factKeys !== 'chunk') throw new Error('--fact-extractor pipeline ships chunk assignment only; use --fact-keys chunk');- const model = o.factExtractor !== 'paper' && !o.factKeysModel+ const model = o.factExtractor === 'production' && !o.factKeysModel? await resolveModel(null, { configKey: 'facts.extraction_model', tier: 'reasoning', fallback: 'anthropic:claude-sonnet-4-6' }): await resolveModel(null, { cliFlag: o.factKeysModel, tier: 'utility', fallback: 'haiku' });return { arm: { assignment: o.factKeys, extractor: o.factExtractor, model, client, maxUsd: o.factKeysMaxUsd }, spend: new FactKeySpend(o.factKeysMaxUsd) };}-/**- * The shipping configuration: facts extraction on page write publishes the- * keys. Facts default to world visibility here, the single-principal posture- * a bootstrapped brain uses, so a user's own conversations can key their pages.- */-async function applyPipelineFactKeys(engine: BrainEngine, pages: ReadonlyArray<{ slug: string }>, arm: FactKeyArm,- spend: FactKeySpend): Promise<FactKeyArmResult> {- const { runFactsBackstop } = await import('../../core/facts/backstop.ts');- await engine.setConfig('search.fact_keys', 'on');- await engine.setConfig('facts.default_visibility', 'world');- const queue = [...pages];- await Promise.all(Array.from({ length: Math.min(FACT_EXTRACT_CONCURRENCY, queue.length) }, async () => {- for (let next = queue.shift(); next; next = queue.shift()) {- const page = await engine.getPage(next.slug);- if (!page) continue;- spend.calls++;- await runFactsBackstop({ slug: page.slug, type: page.type, compiled_truth: page.compiled_truth, frontmatter: (page.frontmatter ?? {}) as Record<string, unknown> },- { engine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'inline', notabilityFilter: 'all', model: arm.model });- }- }));- const [row] = await engine.executeRaw<{ pages: number; chunks: number; items: number }>(`SELECT- (SELECT count(DISTINCT page_id) FROM content_chunks WHERE fact_keys IS NOT NULL)::int AS pages,- (SELECT count(*) FROM content_chunks WHERE fact_keys IS NOT NULL)::int AS chunks,- (SELECT count(*) FROM page_fact_keys)::int AS items`);- return { pages_keyed: Number(row.pages), chunks_keyed: Number(row.chunks), items: Number(row.items) };-}-/** Row fields for a time-scope run: the decision, plus the unscoped top-k's recall from the same pool. */export function timeScopeRowExtras(row: TimeScopeArmRow, slugToRaw: SlugToRawMap, gold: readonly string[], k: number): Record<string, unknown> {const unscopedRaw = row.unscoped_slugs.map(s => rawSessionId(s, slugToRaw));diff --git a/src/schema.sql b/src/schema.sqlindex bfb119701b..7a0919b3a9 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -317,9 +317,6 @@ CREATE TABLE IF NOT EXISTS content_chunks (embedded_text_hash TEXT,-- #5553 (v171): embedding-input provenance written with the vector.embedding_input_hash TEXT,- -- v209: fact-key text carried by this chunk's title-tier embedding input- -- (docs/designs/FACT_KEYS.md); changes only together with the vector.- fact_keys TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),-- v0.19.0: code chunk metadata. Nullable — markdown chunks leave these NULL.-- Powers `query --lang`, `code-def <symbol>`, and `code-refs <symbol>`.@@ -885,24 +882,6 @@ CREATE TABLE IF NOT EXISTS retrieval_weights (PRIMARY KEY (source_id, element_kind, element_key));--- page_fact_keys (migration v209): occurrence keys, the facts extractor's own--- output for one page revision before dedup (docs/designs/FACT_KEYS.md).--- Withdrawal discovery joins on (source, fingerprint, visibility, subject).-CREATE TABLE IF NOT EXISTS page_fact_keys (- page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,- source_id TEXT NOT NULL,- page_revision TEXT NOT NULL,- ordinal INTEGER NOT NULL,- item_text TEXT NOT NULL,- item_fingerprint TEXT NOT NULL,- subject TEXT NOT NULL,- visibility TEXT NOT NULL CHECK (visibility IN ('private','world')),- extractor_version TEXT NOT NULL,- PRIMARY KEY (page_id, page_revision, ordinal)-);-CREATE INDEX IF NOT EXISTS page_fact_keys_withdrawal_idx- ON page_fact_keys (source_id, item_fingerprint, visibility, subject);--- session_context_state (v0.45.7 / migration v126 — ambient recall issue #1):-- per-session cursor + boundary-tie dedup for the `delta` verb + heartbeat-- runtime. Key (source_id, client_id, session_id); client_id 'local' sentineldiff --git a/test/cli-dispatch-phase.test.ts b/test/cli-dispatch-phase.test.tsindex 2415f2ca3c..82febfb007 100644--- a/test/cli-dispatch-phase.test.ts+++ b/test/cli-dispatch-phase.test.ts@@ -89,7 +89,7 @@ describe('CLI dispatch shape (master AST)', () => {const shape = await expectNormalizerStable(extractCliDispatch, astNormalizer);expect(shape.sets.CLI_ONLY).toEqual([...CLI_ONLY].sort());expect(shape.sets.THIN_CLIENT_REFUSED_COMMANDS).toEqual([...THIN_CLIENT_REFUSED_COMMANDS].sort());- expect(shape.switchCases.length).toBe(66);+ expect(shape.switchCases.length).toBe(65);expect(Object.keys(shape.commands).length).toBeGreaterThanOrEqual(shape.sets.CLI_ONLY.length);});diff --git a/test/fact-keys-backstop.test.ts b/test/fact-keys-backstop.test.tsdeleted file mode 100644index be61b013f6..0000000000--- a/test/fact-keys-backstop.test.ts+++ /dev/null@@ -1,86 +0,0 @@-/**- * Fact keys through the facts backstop (docs/designs/FACT_KEYS.md): a page- * write's extraction publishes keys from the extractor's own output when- * `search.fact_keys` is on, keeps the page untouched when it is off, and- * publishes nothing when the stored page no longer holds the extracted text.- * PGLite + chat/embed transport stubs; no network.- */-import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { runFactsBackstop } from '../src/core/facts/backstop.ts';-import { __setChatTransportForTests, __setEmbedTransportForTests, configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';-import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';-import { installPageProjection, preparePageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';--let engine: PGLiteEngine;-const slug = 'meetings/synthetic-keys';-const body = 'Alice-example confirmed the offsite moves to the lake cabin in June. The cedar deck repair is on the list before then.';-const embedded: string[] = [];--beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({});- await engine.initSchema();-});-afterAll(async () => { await engine.disconnect(); });-beforeEach(async () => {- embedded.length = 0;- configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'test' } });- __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {- embedded.push(...values);- return { embeddings: values.map((_, i) => Array.from({ length: 1536 }, (_, j) => (j === i % 1536 ? 1 : 0.01))) };- }) as never);- __setChatTransportForTests(async (): Promise<ChatResult> => ({- text: JSON.stringify({ facts: [- { fact: 'The offsite moves to the lake cabin in June', kind: 'event', entity: null, confidence: 1, notability: 'high' },- { fact: 'The cedar deck needs repair', kind: 'fact', entity: null, confidence: 1, notability: 'low' },- ] }),- blocks: [], stopReason: 'end', model: 'test:stub', providerId: 'test',- usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },- }));- await engine.executeRaw('DELETE FROM pages');- await engine.putPage(slug, { type: 'meeting', title: 'Synthetic keys', compiled_truth: body, timeline: '' });- const prepared = (await readProjectionSnapshot(engine, slug, 'default', { allowUnsealed: true }))!;- await installPageProjection(engine, prepared, (await preparePageProjection(prepared)).chunks, { seal: true });- await engine.executeRaw("UPDATE pages SET contextual_retrieval_mode='title' WHERE slug=$1", [slug]);- await engine.setConfig('facts.default_visibility', 'world');-});-afterEach(async () => {- __setChatTransportForTests(null);- __setEmbedTransportForTests(null);- resetGateway();- __resetFactsQueueForTests();- await engine.setConfig('search.fact_keys', 'off');-});--const keyed = () => engine.executeRaw<{ fact_keys: string | null; embedded: boolean }>(- 'SELECT fact_keys, embedding IS NOT NULL AS embedded FROM content_chunks ORDER BY chunk_index');-const page = (text = body) => ({ slug, type: 'meeting' as const, compiled_truth: text, frontmatter: {} as Record<string, unknown> });-const ctx = () => ({ engine, sourceId: 'default', sessionId: null, source: 'mcp:put_page' as const, mode: 'inline' as const, notabilityFilter: 'all' as const });--test('extraction publishes every extracted fact as a key when fact keys are on', async () => {- await engine.setConfig('search.fact_keys', 'on');- const result = await runFactsBackstop(page(), ctx());- expect(result).toMatchObject({ mode: 'inline', inserted: 2 });- expect(await keyed()).toEqual([{ fact_keys: 'The offsite moves to the lake cabin in June; The cedar deck needs repair', embedded: true }]);- expect(embedded).toContain(`<context>Synthetic keys\nFacts: The offsite moves to the lake cabin in June; The cedar deck needs repair\n</context>\n${body}`);- const rows = await engine.executeRaw<{ item_text: string; visibility: string }>('SELECT item_text,visibility FROM page_fact_keys ORDER BY ordinal');- expect(rows).toEqual([- { item_text: 'The offsite moves to the lake cabin in June', visibility: 'world' },- { item_text: 'The cedar deck needs repair', visibility: 'world' },- ]);-});--test('fact keys off: extraction runs and the page keeps its chunks unkeyed', async () => {- const result = await runFactsBackstop(page(), ctx());- expect(result).toMatchObject({ mode: 'inline', inserted: 2 });- expect((await keyed()).map(r => r.fact_keys)).toEqual([null]);- expect(await engine.executeRaw('SELECT 1 FROM page_fact_keys')).toEqual([]);-});--test('text that no longer matches the stored page publishes no keys', async () => {- await engine.setConfig('search.fact_keys', 'on');- await runFactsBackstop(page(`${body} An older draft.`), ctx());- expect((await keyed()).map(r => r.fact_keys)).toEqual([null]);- expect(await engine.executeRaw('SELECT 1 FROM page_fact_keys')).toEqual([]);-});diff --git a/test/fact-keys-publish.test.ts b/test/fact-keys-publish.test.tsdeleted file mode 100644index eda6ae3d10..0000000000--- a/test/fact-keys-publish.test.ts+++ /dev/null@@ -1,187 +0,0 @@-/**- * Fact keys (docs/designs/FACT_KEYS.md): prepare-then-swap publication,- * revision binding, fail-closed visibility, withdrawal filtering and- * discovery, retirement on a new revision, and the install-time key check.- * Real PGLite (and Postgres when DATABASE_URL is set); fake embeddings.- */-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';-import { createHash } from 'node:crypto';-import type { BrainEngine } from '../src/core/engine.ts';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { installPageEmbeddings, installPageProjection, preparePageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';-import { bindFactKeysSnapshot, clearPageFactKeys, publishPageFactKeys, type FactKeyItem } from '../src/core/facts/fact-keys-publish.ts';-import { embeddingInputContext, embeddingWriteTarget } from '../src/core/page-state/projections.ts';-import { embeddingInputHash } from '../src/core/embedding-input-hash.ts';-import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';-import { discoverWithdrawalTargets } from '../src/core/facts/withdrawal-discovery.ts';-import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';-import { testBackends } from './helpers/test-backends.ts';--const sourceId = 'fact-keys-test';-const slug = 'meetings/synthetic-planning';-const body = 'Alice-example said the offsite moves to the lake cabin. Budget talk followed about the cedar deck repair and paint.';-const timeline = '2026-01-02: Synthetic planning call.';--function fakeVector(text: string): Float32Array {- const v = new Float32Array(1536);- const h = createHash('sha256').update(text).digest();- for (let i = 0; i < 32; i++) v[i] = (h[i] - 127.5) / 128;- return v;-}-const embedded: string[][] = [];-const embed = async (texts: string[]) => { embedded.push(texts); return texts.map(fakeVector); };-const vectorText = (text: string) => `[${Array.from(fakeVector(text)).join(',')}]`;--for (const kind of testBackends()) {- describe(`fact keys ${kind}`, () => {- let engine: BrainEngine;- let closePostgres: (() => Promise<void>) | undefined;- beforeAll(async () => {- if (kind === 'postgres') ({ engine, close: closePostgres } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));- else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }- }, 120_000);- beforeEach(async () => {- embedded.length = 0;- await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [sourceId]);- await engine.setConfig('search.fact_keys', 'on');- });- afterEach(async () => {- await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]);- await engine.setConfig('search.fact_keys', 'off');- });- afterAll(async () => {- if (kind === 'pglite') await engine.disconnect();- await closePostgres?.();- });-- async function seed(opts: { mode?: string | null; frontmatter?: Record<string, unknown>; text?: string } = {}) {- await engine.putPage(slug, { type: 'meeting', title: 'Synthetic planning', compiled_truth: opts.text ?? body, timeline,- frontmatter: opts.frontmatter ?? {} }, { sourceId });- const prepared = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;- await installPageProjection(engine, prepared, (await preparePageProjection(prepared)).chunks, { seal: true });- await engine.executeRaw('UPDATE pages SET contextual_retrieval_mode=$3 WHERE source_id=$1 AND slug=$2',- [sourceId, slug, opts.mode === undefined ? 'title' : opts.mode]);- const snapshot = (await readProjectionSnapshot(engine, slug, sourceId))!;- const target = await embeddingWriteTarget(engine);- const provenance = embeddingInputContext(target, snapshot.snapshot.page.title, null, snapshot.chunks);- for (const chunk of snapshot.chunks) {- const input = `<context>Synthetic planning\n</context>\n${chunk.chunk_text}`;- await engine.executeRaw(`UPDATE content_chunks SET embedding=$2::vector,model=$3,embedded_at=now(),embedded_text_hash=md5(chunk_text),- embedding_input_hash=$4 WHERE id=$1`, [chunk.id, vectorText(input), snapshot.embeddingModel, embeddingInputHash(provenance, 'title', chunk)]);- }- return (await bindFactKeysSnapshot(engine, sourceId, slug, opts.text ?? body))!;- }- const chunks = () => engine.executeRaw<{ chunk_index: number; fact_keys: string | null; embedding: string | null; embedding_input_hash: string | null }>(- `SELECT cc.chunk_index,cc.fact_keys,cc.embedding::text AS embedding,cc.embedding_input_hash FROM content_chunks cc JOIN pages p ON p.id=cc.page_id- WHERE p.source_id=$1 AND p.slug=$2 ORDER BY cc.chunk_index`, [sourceId, slug]);- const rows = () => engine.executeRaw<{ item_text: string; subject: string; visibility: string }>(- 'SELECT item_text,subject,visibility FROM page_fact_keys WHERE source_id=$1 ORDER BY ordinal', [sourceId]);- const world = (text: string, subject = '*'): FactKeyItem => ({ text, subject, visibility: 'world' });-- test('publishes keys and swaps vectors built from them in one step', async () => {- const binding = await seed();- const result = await publishPageFactKeys(engine, binding, [world('The offsite is at the lake cabin'), world('The cedar deck needs repair')], { embed });- expect(result).toEqual({ published: true, items: 2, chunks_rekeyed: 1 });- const [first, second] = await chunks();- expect(first.fact_keys).toBe('The offsite is at the lake cabin; The cedar deck needs repair');- expect(second.fact_keys).toBeNull();- const input = `<context>Synthetic planning\nFacts: ${first.fact_keys}\n</context>\n${body}`;- expect(embedded).toEqual([[input]]);- expect(first.embedding).toBe(vectorText(input));- const snapshot = (await readProjectionSnapshot(engine, slug, sourceId))!;- const provenance = embeddingInputContext(await embeddingWriteTarget(engine), 'Synthetic planning', null, snapshot.chunks);- expect(first.embedding_input_hash).toBe(embeddingInputHash(provenance, 'title', snapshot.chunks[0]));- expect((await rows()).map(r => r.item_text)).toEqual(['The offsite is at the lake cabin', 'The cedar deck needs repair']);- expect(await publishPageFactKeys(engine, binding, [world('The offsite is at the lake cabin'), world('The cedar deck needs repair')], { embed }))- .toEqual({ published: true, items: 2, chunks_rekeyed: 0 });- });-- test('a superseded revision, a disabled setting or an ineligible page publishes nothing', async () => {- const binding = await seed();- await engine.setConfig('search.fact_keys', 'off');- expect(await publishPageFactKeys(engine, binding, [world('The offsite is at the lake cabin')], { embed })).toEqual({ published: false, reason: 'disabled' });- await engine.setConfig('search.fact_keys', 'on');- await engine.putPage(slug, { type: 'meeting', title: 'Synthetic planning', compiled_truth: `${body} Edited.`, timeline }, { sourceId });- expect(await publishPageFactKeys(engine, binding, [world('The offsite is at the lake cabin')], { embed })).toMatchObject({ published: false, reason: 'superseded' });- expect(await rows()).toEqual([]);- for (const [opts, reason] of [[{ mode: 'per_chunk_synopsis' }, 'not_title_mode'], [{ mode: null }, 'not_title_mode'],- [{ frontmatter: { embed_skip: true } }, 'embed_skip'], [{ text: `${body}\n<!--- gbrain:facts:begin -->\n<!--- gbrain:facts:end -->` }, 'protected']] as const) {- await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [sourceId]);- const fresh = await seed(opts);- expect(await publishPageFactKeys(engine, fresh, [world('The offsite is at the lake cabin')], { embed })).toEqual({ published: false, reason });- }- expect(embedded).toEqual([]);- });-- test('private facts never key a world page; withdrawn facts never key at all', async () => {- const binding = await seed();- const priv: FactKeyItem = { text: 'Alice-example dislikes the lake', subject: '*', visibility: 'private' };- expect(await publishPageFactKeys(engine, binding, [priv], { embed })).toEqual({ published: true, items: 0, chunks_rekeyed: 0 });- const fact = await engine.insertFact({ fact: 'The cedar deck needs repair', visibility: 'world', source: 'synthetic' }, { source_id: sourceId });- expect((await recordFactWithdrawal(engine, fact.id, sourceId)).withdrawn).toBe(true);- expect(await publishPageFactKeys(engine, binding, [world('The cedar deck needs repair.'), world('The offsite is at the lake cabin')], { embed }))- .toEqual({ published: true, items: 1, chunks_rekeyed: 1 });- expect((await rows()).map(r => r.item_text)).toEqual(['The offsite is at the lake cabin']);- await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [sourceId]);- const privatePage = await seed({ frontmatter: { visibility: 'private' } });- expect(await publishPageFactKeys(engine, privatePage, [priv], { embed })).toEqual({ published: true, items: 1, chunks_rekeyed: 1 });- });-- test('withdrawal discovery finds a page through its keys, including unresolved key subjects', async () => {- const binding = await seed();- await publishPageFactKeys(engine, binding, [world('Bob-example prefers the window seat', 'people/bob-example')], { embed });- const page = (await engine.readPageSnapshot(slug, { sourceId }))!;- const claim = (subject: string) => [{ visibility: 'world', fact_hash: '', subject, claim: 'Bob-example prefers the window seat!' }];- expect((await discoverWithdrawalTargets(engine, sourceId, claim('people/bob-example'))).map(t => t.page_id)).toEqual([page.page.id]);- expect(await discoverWithdrawalTargets(engine, sourceId, claim('people/carol-example'))).toEqual([]);- await publishPageFactKeys(engine, binding, [world('Bob-example prefers the window seat')], { embed });- expect((await discoverWithdrawalTargets(engine, sourceId, claim('people/carol-example'))).map(t => t.page_id)).toEqual([page.page.id]);- });-- test('a new revision retires the keys and drops the keyed vectors', async () => {- const binding = await seed();- await publishPageFactKeys(engine, binding, [world('The offsite is at the lake cabin')], { embed });- await engine.putPage(slug, { type: 'meeting', title: 'Synthetic planning', compiled_truth: body, timeline: `${timeline}\n2026-01-03: Follow-up.` }, { sourceId });- const prepared = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;- await installPageProjection(engine, prepared, (await preparePageProjection(prepared)).chunks, { seal: true, preserveEmbeddings: true });- expect(await rows()).toEqual([]);- const [first] = await chunks();- expect(first.fact_keys).toBeNull();- expect(first.embedding).toBeNull();- });-- test('an embedding built before a key change cannot install', async () => {- const binding = await seed();- const stale = (await readProjectionSnapshot(engine, slug, sourceId))!;- await publishPageFactKeys(engine, binding, [world('The offsite is at the lake cabin')], { embed });- const installed = await installPageEmbeddings(engine, stale, stale.chunks.map(chunk => ({- chunk_index: chunk.chunk_index, chunk_text: chunk.chunk_text, chunk_source: chunk.chunk_source, embedding: fakeVector('old input'),- })));- expect(installed).toBe(false);- expect((await chunks())[0].fact_keys).toBe('The offsite is at the lake cabin');- });-- test('clearing strips keys by re-embedding first, whatever the setting', async () => {- const binding = await seed();- await publishPageFactKeys(engine, binding, [world('The offsite is at the lake cabin')], { embed });- await engine.setConfig('search.fact_keys', 'off');- embedded.length = 0;- expect(await clearPageFactKeys(engine, sourceId, slug, { embed })).toEqual({ published: true, items: 0, chunks_rekeyed: 1 });- const input = `<context>Synthetic planning\n</context>\n${body}`;- expect(embedded).toEqual([[input]]);- const [first] = await chunks();- expect([first.fact_keys, first.embedding]).toEqual([null, vectorText(input)]);- expect(await rows()).toEqual([]);- });-- test('a failed embed leaves the previous keys and vectors in place', async () => {- const binding = await seed();- const before = await chunks();- const failing = async () => { throw new Error('provider down'); };- expect(await publishPageFactKeys(engine, binding, [world('The offsite is at the lake cabin')], { embed: failing }))- .toEqual({ published: false, reason: 'embed_failed', detail: 'provider down' });- expect(await chunks()).toEqual(before);- expect(await rows()).toEqual([]);- });- });-}diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 84f0c493ad..7d807b48ac 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -180,9 +180,6 @@"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",- "page_fact_keys.page_fact_keys_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_fact_keys.page_fact_keys_pkey": "p PRIMARY KEY (page_id, page_revision, ordinal)",- "page_fact_keys.page_fact_keys_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))","page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))","page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)","page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -573,9 +570,6 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],- "page_fact_keys": [- "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"- ],"page_generation_clock": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -979,8 +973,6 @@"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)","page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",- "page_fact_keys_pkey": "CREATE UNIQUE INDEX page_fact_keys_pkey ON public.page_fact_keys USING btree (page_id, page_revision, ordinal)",- "page_fact_keys_withdrawal_idx": "CREATE INDEX page_fact_keys_withdrawal_idx ON public.page_fact_keys USING btree (source_id, item_fingerprint, visibility, subject)","page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)","page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)","page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",@@ -1339,21 +1331,20 @@"9 embedded_at timestamp with time zone/timestamptz NULL","10 embedded_text_hash text/text NULL","11 embedding_input_hash text/text NULL",- "12 fact_keys text/text NULL",- "13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "14 language text/text NULL",- "15 symbol_name text/text NULL",- "16 symbol_type text/text NULL",- "17 start_line integer/int4 NULL",- "18 end_line integer/int4 NULL",- "19 modality text/text NOT NULL DEFAULT 'text'::text",- "20 embedding_image USER-DEFINED/vector NULL",- "21 embedding_multimodal USER-DEFINED/vector NULL",- "22 parent_symbol_path ARRAY/_text NULL",- "23 doc_comment text/text NULL",- "24 symbol_name_qualified text/text NULL",- "25 search_vector tsvector/tsvector NULL",- "26 edges_backfilled_at timestamp with time zone/timestamptz NULL"+ "12 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "13 language text/text NULL",+ "14 symbol_name text/text NULL",+ "15 symbol_type text/text NULL",+ "16 start_line integer/int4 NULL",+ "17 end_line integer/int4 NULL",+ "18 modality text/text NOT NULL DEFAULT 'text'::text",+ "19 embedding_image USER-DEFINED/vector NULL",+ "20 embedding_multimodal USER-DEFINED/vector NULL",+ "21 parent_symbol_path ARRAY/_text NULL",+ "22 doc_comment text/text NULL",+ "23 symbol_name_qualified text/text NULL",+ "24 search_vector tsvector/tsvector NULL",+ "25 edges_backfilled_at timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -2225,20 +2216,6 @@],"flags": "relkind=r rls=false force_rls=false"},- "page_fact_keys": {- "columns": [- "1 page_id integer/int4 NOT NULL",- "2 source_id text/text NOT NULL",- "3 page_revision text/text NOT NULL",- "4 ordinal integer/int4 NOT NULL",- "5 item_text text/text NOT NULL",- "6 item_fingerprint text/text NOT NULL",- "7 subject text/text NOT NULL",- "8 visibility text/text NOT NULL",- "9 extractor_version text/text NOT NULL"- ],- "flags": "relkind=r rls=false force_rls=false"- },"page_generation_clock": {"columns": ["1 id integer/int4 NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 5db06a732e..cdc1320166 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -180,9 +180,6 @@"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",- "page_fact_keys.page_fact_keys_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_fact_keys.page_fact_keys_pkey": "p PRIMARY KEY (page_id, page_revision, ordinal)",- "page_fact_keys.page_fact_keys_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))","page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))","page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)","page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -573,9 +570,6 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],- "page_fact_keys": [- "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"- ],"page_generation_clock": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -979,8 +973,6 @@"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)","page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",- "page_fact_keys_pkey": "CREATE UNIQUE INDEX page_fact_keys_pkey ON public.page_fact_keys USING btree (page_id, page_revision, ordinal)",- "page_fact_keys_withdrawal_idx": "CREATE INDEX page_fact_keys_withdrawal_idx ON public.page_fact_keys USING btree (source_id, item_fingerprint, visibility, subject)","page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)","page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)","page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",@@ -1339,21 +1331,20 @@"9 embedded_at timestamp with time zone/timestamptz NULL","10 embedded_text_hash text/text NULL","11 embedding_input_hash text/text NULL",- "12 fact_keys text/text NULL",- "13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "14 language text/text NULL",- "15 symbol_name text/text NULL",- "16 symbol_type text/text NULL",- "17 start_line integer/int4 NULL",- "18 end_line integer/int4 NULL",- "19 modality text/text NOT NULL DEFAULT 'text'::text",- "20 embedding_image USER-DEFINED/vector NULL",- "21 embedding_multimodal USER-DEFINED/vector NULL",- "22 parent_symbol_path ARRAY/_text NULL",- "23 doc_comment text/text NULL",- "24 symbol_name_qualified text/text NULL",- "25 search_vector tsvector/tsvector NULL",- "26 edges_backfilled_at timestamp with time zone/timestamptz NULL"+ "12 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "13 language text/text NULL",+ "14 symbol_name text/text NULL",+ "15 symbol_type text/text NULL",+ "16 start_line integer/int4 NULL",+ "17 end_line integer/int4 NULL",+ "18 modality text/text NOT NULL DEFAULT 'text'::text",+ "19 embedding_image USER-DEFINED/vector NULL",+ "20 embedding_multimodal USER-DEFINED/vector NULL",+ "21 parent_symbol_path ARRAY/_text NULL",+ "22 doc_comment text/text NULL",+ "23 symbol_name_qualified text/text NULL",+ "24 search_vector tsvector/tsvector NULL",+ "25 edges_backfilled_at timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -2225,20 +2216,6 @@],"flags": "relkind=r rls=false force_rls=false"},- "page_fact_keys": {- "columns": [- "1 page_id integer/int4 NOT NULL",- "2 source_id text/text NOT NULL",- "3 page_revision text/text NOT NULL",- "4 ordinal integer/int4 NOT NULL",- "5 item_text text/text NOT NULL",- "6 item_fingerprint text/text NOT NULL",- "7 subject text/text NOT NULL",- "8 visibility text/text NOT NULL",- "9 extractor_version text/text NOT NULL"- ],- "flags": "relkind=r rls=false force_rls=false"- },"page_generation_clock": {"columns": ["1 id integer/int4 NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 23c6cb1086..4f88afa57e 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -180,9 +180,6 @@"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",- "page_fact_keys.page_fact_keys_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_fact_keys.page_fact_keys_pkey": "p PRIMARY KEY (page_id, page_revision, ordinal)",- "page_fact_keys.page_fact_keys_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))","page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))","page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)","page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -573,9 +570,6 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],- "page_fact_keys": [- "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"- ],"page_generation_clock": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -975,8 +969,6 @@"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)","page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",- "page_fact_keys_pkey": "CREATE UNIQUE INDEX page_fact_keys_pkey ON public.page_fact_keys USING btree (page_id, page_revision, ordinal)",- "page_fact_keys_withdrawal_idx": "CREATE INDEX page_fact_keys_withdrawal_idx ON public.page_fact_keys USING btree (source_id, item_fingerprint, visibility, subject)","page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)","page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)","page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",@@ -1335,21 +1327,20 @@"9 embedded_at timestamp with time zone/timestamptz NULL","10 embedded_text_hash text/text NULL","11 embedding_input_hash text/text NULL",- "12 fact_keys text/text NULL",- "13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "14 language text/text NULL",- "15 symbol_name text/text NULL",- "16 symbol_type text/text NULL",- "17 start_line integer/int4 NULL",- "18 end_line integer/int4 NULL",- "19 modality text/text NOT NULL DEFAULT 'text'::text",- "20 embedding_image USER-DEFINED/vector NULL",- "21 embedding_multimodal USER-DEFINED/vector NULL",- "22 parent_symbol_path ARRAY/_text NULL",- "23 doc_comment text/text NULL",- "24 symbol_name_qualified text/text NULL",- "25 search_vector tsvector/tsvector NULL",- "26 edges_backfilled_at timestamp with time zone/timestamptz NULL"+ "12 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "13 language text/text NULL",+ "14 symbol_name text/text NULL",+ "15 symbol_type text/text NULL",+ "16 start_line integer/int4 NULL",+ "17 end_line integer/int4 NULL",+ "18 modality text/text NOT NULL DEFAULT 'text'::text",+ "19 embedding_image USER-DEFINED/vector NULL",+ "20 embedding_multimodal USER-DEFINED/vector NULL",+ "21 parent_symbol_path ARRAY/_text NULL",+ "22 doc_comment text/text NULL",+ "23 symbol_name_qualified text/text NULL",+ "24 search_vector tsvector/tsvector NULL",+ "25 edges_backfilled_at timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -2221,20 +2212,6 @@],"flags": "relkind=r rls=false force_rls=false"},- "page_fact_keys": {- "columns": [- "1 page_id integer/int4 NOT NULL",- "2 source_id text/text NOT NULL",- "3 page_revision text/text NOT NULL",- "4 ordinal integer/int4 NOT NULL",- "5 item_text text/text NOT NULL",- "6 item_fingerprint text/text NOT NULL",- "7 subject text/text NOT NULL",- "8 visibility text/text NOT NULL",- "9 extractor_version text/text NOT NULL"- ],- "flags": "relkind=r rls=false force_rls=false"- },"page_generation_clock": {"columns": ["1 id integer/int4 NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex df22c0d851..24b6e2ee56 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -128,9 +128,6 @@"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",- "page_fact_keys.page_fact_keys_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_fact_keys.page_fact_keys_pkey": "p PRIMARY KEY (page_id, page_revision, ordinal)",- "page_fact_keys.page_fact_keys_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))","page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))","page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)","page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",@@ -429,9 +426,6 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],- "page_fact_keys": [- "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"- ],"page_generation_clock": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -719,8 +713,6 @@"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)","page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",- "page_fact_keys_pkey": "CREATE UNIQUE INDEX page_fact_keys_pkey ON public.page_fact_keys USING btree (page_id, page_revision, ordinal)",- "page_fact_keys_withdrawal_idx": "CREATE INDEX page_fact_keys_withdrawal_idx ON public.page_fact_keys USING btree (source_id, item_fingerprint, visibility, subject)","page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)","page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",@@ -972,16 +964,15 @@"9 embedded_at timestamp with time zone/timestamptz NULL","10 embedded_text_hash text/text NULL","11 embedding_input_hash text/text NULL",- "12 fact_keys text/text NULL",- "13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "14 language text/text NULL",- "15 symbol_name text/text NULL",- "16 symbol_type text/text NULL",- "17 start_line integer/int4 NULL",- "18 end_line integer/int4 NULL",- "19 modality text/text NOT NULL DEFAULT 'text'::text",- "20 embedding_image USER-DEFINED/vector NULL",- "21 embedding_multimodal USER-DEFINED/vector NULL"+ "12 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "13 language text/text NULL",+ "14 symbol_name text/text NULL",+ "15 symbol_type text/text NULL",+ "16 start_line integer/int4 NULL",+ "17 end_line integer/int4 NULL",+ "18 modality text/text NOT NULL DEFAULT 'text'::text",+ "19 embedding_image USER-DEFINED/vector NULL",+ "20 embedding_multimodal USER-DEFINED/vector NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -1629,20 +1620,6 @@],"flags": "relkind=r rls=false force_rls=false"},- "page_fact_keys": {- "columns": [- "1 page_id integer/int4 NOT NULL",- "2 source_id text/text NOT NULL",- "3 page_revision text/text NOT NULL",- "4 ordinal integer/int4 NOT NULL",- "5 item_text text/text NOT NULL",- "6 item_fingerprint text/text NOT NULL",- "7 subject text/text NOT NULL",- "8 visibility text/text NOT NULL",- "9 extractor_version text/text NOT NULL"- ],- "flags": "relkind=r rls=false force_rls=false"- },"page_generation_clock": {"columns": ["1 id integer/int4 NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex c5e34b0eb2..3d080b787c 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -128,9 +128,6 @@"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",- "page_fact_keys.page_fact_keys_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_fact_keys.page_fact_keys_pkey": "p PRIMARY KEY (page_id, page_revision, ordinal)",- "page_fact_keys.page_fact_keys_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))","page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))","page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)","page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",@@ -429,9 +426,6 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],- "page_fact_keys": [- "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"- ],"page_generation_clock": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -719,8 +713,6 @@"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)","page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",- "page_fact_keys_pkey": "CREATE UNIQUE INDEX page_fact_keys_pkey ON public.page_fact_keys USING btree (page_id, page_revision, ordinal)",- "page_fact_keys_withdrawal_idx": "CREATE INDEX page_fact_keys_withdrawal_idx ON public.page_fact_keys USING btree (source_id, item_fingerprint, visibility, subject)","page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)","page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",@@ -972,16 +964,15 @@"9 embedded_at timestamp with time zone/timestamptz NULL","10 embedded_text_hash text/text NULL","11 embedding_input_hash text/text NULL",- "12 fact_keys text/text NULL",- "13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "14 language text/text NULL",- "15 symbol_name text/text NULL",- "16 symbol_type text/text NULL",- "17 start_line integer/int4 NULL",- "18 end_line integer/int4 NULL",- "19 modality text/text NOT NULL DEFAULT 'text'::text",- "20 embedding_image USER-DEFINED/vector NULL",- "21 embedding_multimodal USER-DEFINED/vector NULL"+ "12 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "13 language text/text NULL",+ "14 symbol_name text/text NULL",+ "15 symbol_type text/text NULL",+ "16 start_line integer/int4 NULL",+ "17 end_line integer/int4 NULL",+ "18 modality text/text NOT NULL DEFAULT 'text'::text",+ "19 embedding_image USER-DEFINED/vector NULL",+ "20 embedding_multimodal USER-DEFINED/vector NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -1629,20 +1620,6 @@],"flags": "relkind=r rls=false force_rls=false"},- "page_fact_keys": {- "columns": [- "1 page_id integer/int4 NOT NULL",- "2 source_id text/text NOT NULL",- "3 page_revision text/text NOT NULL",- "4 ordinal integer/int4 NOT NULL",- "5 item_text text/text NOT NULL",- "6 item_fingerprint text/text NOT NULL",- "7 subject text/text NOT NULL",- "8 visibility text/text NOT NULL",- "9 extractor_version text/text NOT NULL"- ],- "flags": "relkind=r rls=false force_rls=false"- },"page_generation_clock": {"columns": ["1 id integer/int4 NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex aa23741956..2ba4bdbf4f 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -128,9 +128,6 @@"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",- "page_fact_keys.page_fact_keys_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_fact_keys.page_fact_keys_pkey": "p PRIMARY KEY (page_id, page_revision, ordinal)",- "page_fact_keys.page_fact_keys_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))","page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))","page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)","page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",@@ -429,9 +426,6 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],- "page_fact_keys": [- "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"- ],"page_generation_clock": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -718,8 +712,6 @@"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)","page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",- "page_fact_keys_pkey": "CREATE UNIQUE INDEX page_fact_keys_pkey ON public.page_fact_keys USING btree (page_id, page_revision, ordinal)",- "page_fact_keys_withdrawal_idx": "CREATE INDEX page_fact_keys_withdrawal_idx ON public.page_fact_keys USING btree (source_id, item_fingerprint, visibility, subject)","page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)","page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",@@ -971,16 +963,15 @@"9 embedded_at timestamp with time zone/timestamptz NULL","10 embedded_text_hash text/text NULL","11 embedding_input_hash text/text NULL",- "12 fact_keys text/text NULL",- "13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "14 language text/text NULL",- "15 symbol_name text/text NULL",- "16 symbol_type text/text NULL",- "17 start_line integer/int4 NULL",- "18 end_line integer/int4 NULL",- "19 modality text/text NOT NULL DEFAULT 'text'::text",- "20 embedding_image USER-DEFINED/vector NULL",- "21 embedding_multimodal USER-DEFINED/vector NULL"+ "12 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "13 language text/text NULL",+ "14 symbol_name text/text NULL",+ "15 symbol_type text/text NULL",+ "16 start_line integer/int4 NULL",+ "17 end_line integer/int4 NULL",+ "18 modality text/text NOT NULL DEFAULT 'text'::text",+ "19 embedding_image USER-DEFINED/vector NULL",+ "20 embedding_multimodal USER-DEFINED/vector NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -1628,20 +1619,6 @@],"flags": "relkind=r rls=false force_rls=false"},- "page_fact_keys": {- "columns": [- "1 page_id integer/int4 NOT NULL",- "2 source_id text/text NOT NULL",- "3 page_revision text/text NOT NULL",- "4 ordinal integer/int4 NOT NULL",- "5 item_text text/text NOT NULL",- "6 item_fingerprint text/text NOT NULL",- "7 subject text/text NOT NULL",- "8 visibility text/text NOT NULL",- "9 extractor_version text/text NOT NULL"- ],- "flags": "relkind=r rls=false force_rls=false"- },"page_generation_clock": {"columns": ["1 id integer/int4 NOT NULL",diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.jsonindex e1f07dcc48..5854eec413 100644--- a/test/fixtures/goldens/cli/dispatch-phase.json+++ b/test/fixtures/goldens/cli/dispatch-phase.json@@ -793,13 +793,6 @@"thinClient": "refuse","thinClientRoutedSubcommands": []},- "fact-keys": {- "hasSwitchCase": true,- "phase": "post-connect",- "preConnectRules": [],- "thinClient": "refuse",- "thinClientRoutedSubcommands": []- },"facts": {"hasSwitchCase": false,"phase": "pre-connect-own-engine",diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.jsonindex 646b1fcb9d..05da7cc873 100644--- a/test/fixtures/goldens/cli/help-and-errors.json+++ b/test/fixtures/goldens/cli/help-and-errors.json@@ -104,7 +104,6 @@" salience [--days N] [--kind P] v0.29: pages ranked by emotional + activity salience"," anomalies [--since D] [--sigma N] v0.29: cohort-based statistical anomalies (tag, type)"," feedback <status|reset> retrieval feedback: learned page weights; rate answers with gbrain rate",- " fact-keys <status|refresh|clear> facts merged into chunk embeddings (search.fact_keys)"," transcripts <ingest|status|recent> v0.46: import agent session logs + chat exports (local-only)"," dream [--dry-run] [--json] Run the overnight maintenance cycle once (cron-friendly)."," See also: autopilot --install (continuous daemon).",@@ -316,7 +315,6 @@" salience [--days N] [--kind P] v0.29: pages ranked by emotional + activity salience"," anomalies [--since D] [--sigma N] v0.29: cohort-based statistical anomalies (tag, type)"," feedback <status|reset> retrieval feedback: learned page weights; rate answers with gbrain rate",- " fact-keys <status|refresh|clear> facts merged into chunk embeddings (search.fact_keys)"," transcripts <ingest|status|recent> v0.46: import agent session logs + chat exports (local-only)"," dream [--dry-run] [--json] Run the overnight maintenance cycle once (cron-friendly)."," See also: autopilot --install (continuous daemon).",@@ -528,7 +526,6 @@" salience [--days N] [--kind P] v0.29: pages ranked by emotional + activity salience"," anomalies [--since D] [--sigma N] v0.29: cohort-based statistical anomalies (tag, type)"," feedback <status|reset> retrieval feedback: learned page weights; rate answers with gbrain rate",- " fact-keys <status|refresh|clear> facts merged into chunk embeddings (search.fact_keys)"," transcripts <ingest|status|recent> v0.46: import agent session logs + chat exports (local-only)"," dream [--dry-run] [--json] Run the overnight maintenance cycle once (cron-friendly)."," See also: autopilot --install (continuous daemon).",diff --git a/test/fixtures/goldens/cli/literal-imports.json b/test/fixtures/goldens/cli/literal-imports.jsonindex 2baa94e7b8..19da3153ae 100644--- a/test/fixtures/goldens/cli/literal-imports.json+++ b/test/fixtures/goldens/cli/literal-imports.json@@ -71,9 +71,6 @@"extract-conversation-facts": ["./commands/extract-conversation-facts.ts"],- "fact-keys": [- "./commands/fact-keys.ts"- ],"features": ["./commands/features.ts"],diff --git a/test/fixtures/goldens/cli/membership-sets.json b/test/fixtures/goldens/cli/membership-sets.jsonindex db3ac4ca5f..81d48dcdb1 100644--- a/test/fixtures/goldens/cli/membership-sets.json+++ b/test/fixtures/goldens/cli/membership-sets.json@@ -69,7 +69,6 @@"refusedNotInCliOnly": [],"refusedWithoutHint": ["edge-proposals",- "fact-keys","feedback","watch"],@@ -132,7 +131,6 @@"export","extract","extract-conversation-facts",- "fact-keys","facts","features","feedback",@@ -243,7 +241,6 @@"export","extract","extract-conversation-facts",- "fact-keys","facts","features","feedback",@@ -314,7 +311,6 @@"embed","export","extract-conversation-facts",- "fact-keys","features","feedback","founder",@@ -366,7 +362,6 @@"export","extract","extract-conversation-facts",- "fact-keys","facts","feedback","files",diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 40e91a77f5..86194ddbaa 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -507,13 +507,13 @@},{"category": "meta",- "message": "Version 209 (latest: 209)",+ "message": "Version 208 (latest: 208)","name": "schema_version","status": "ok"},{"category": "meta",- "message": "931 column(s) verified against live schema",+ "message": "935 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -1610,21 +1610,6 @@"name": "retrieval_feedback_health","status": "ok"},- {- "category": "meta",- "details": {- "docs": "docs/guides/time-aware-recall.md",- "eligible_unkeyed_pages": 0,- "enabled": false,- "key_rows": 0,- "keyed_chunks": 0,- "keyed_pages": 0,- "stale_rows_pages": 0- },- "message": "Fact keys are off (search.fact_keys).",- "name": "retrieval_enrichment",- "status": "ok"- },{"category": "meta","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 931a66b48f..618bf92713 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -510,13 +510,13 @@},{"category": "meta",- "message": "Version 209 (latest: 209)",+ "message": "Version 208 (latest: 208)","name": "schema_version","status": "ok"},{"category": "meta",- "message": "931 column(s) verified against live schema",+ "message": "935 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -1687,21 +1687,6 @@"name": "retrieval_feedback_health","status": "ok"},- {- "category": "meta",- "details": {- "docs": "docs/guides/time-aware-recall.md",- "eligible_unkeyed_pages": 0,- "enabled": false,- "key_rows": 0,- "keyed_chunks": 0,- "keyed_pages": 0,- "stale_rows_pages": 0- },- "message": "Fact keys are off (search.fact_keys).",- "name": "retrieval_enrichment",- "status": "ok"- },{"category": "meta","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex c65d7b99db..c17732c488 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -661,10 +661,6 @@"category": "meta","name": "retrieval_feedback_health"},- {- "category": "meta",- "name": "retrieval_enrichment"- },{"category": "meta","name": "revision_backfill"diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 3eeb167c4f..cfe9cbf0b3 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 204,+ "count": 203,"gaps": [17,18,@@ -29,7 +29,7 @@"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 209,+ "latest": 208,"records": [{"handler": {@@ -3081,19 +3081,6 @@"transaction": "absent","verify": "absent","version": 208- },- {- "handler": "absent",- "idempotent": true,- "name": "fact_keys",- "sql": {- "length": 815,- "sha256": "b5dd65bc273ab98363e79872cae7a8a682a73f8fbc136d50439a8b8752824264"- },- "sqlFor": "absent",- "transaction": "absent",- "verify": "absent",- "version": 209}],"versions": [@@ -3299,8 +3286,7 @@205,206,207,- 208,- 209+ 208]},"normalizer": "migrations-record-v1"diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.tsindex 3e22d3a397..f487839ed4 100644--- a/test/graduation-inventory.test.ts+++ b/test/graduation-inventory.test.ts@@ -60,7 +60,7 @@ describe('graduation inventory', () => {expect(new Set(names).size).toBe(names.length);const counts: Record<string, number> = {};for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;- expect(counts).toEqual({ carry: 106, rebind: 2, rebuild: 2, discard: 6, schema_owned: 3 });+ expect(counts).toEqual({ carry: 105, rebind: 2, rebuild: 2, discard: 6, schema_owned: 3 });for (const e of GRADUATION_INVENTORY.entries) {expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres }).toEqual({ relation: e.relation, reason: true, present: true });