Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(fact-keys): CLI, doctor check, pipeline eval arm, tests, docs
garrytanc1bbbbb386b8
diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.ymlindex 635a101749..2da350ac40 100644--- a/.github/workflows/persistence-validation.yml+++ b/.github/workflows/persistence-validation.yml@@ -211,6 +211,7 @@ 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 69558540ec..94e942c892 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` — 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/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/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 9cbbb00e0e..e181e42967 100644--- a/docs/designs/FACT_KEYS.md+++ b/docs/designs/FACT_KEYS.md@@ -1,13 +1,53 @@# Fact keys in chunk embeddings — design note-Status: **proposed, revision 4. The third engineering review round approved it with changes, and those changes are folded in here.** There is-no product code for it yet. This note covers obligations 1–9 from the-preregistered plan-([`docs/eval/TIME_AWARE_RETRIEVAL_PREREG.md`](../eval/TIME_AWARE_RETRIEVAL_PREREG.md));-where it departs from one, it says so and why. Development results are in+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+([`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++- **Only `title`-mode pages are keyed.** Keys exist only in the title-tier+ embedding input (the `balanced` default). Pages in `none` or+ `per_chunk_synopsis` mode get no keys, so per-chunk tier detection on+ synopsis pages isn't needed: a synopsis page never carries keys, and its+ title-tier vectors from a partial re-embed carry none either.+- **`content_chunks.fact_keys`** holds each chunk's derived key text, next to+ the `page_fact_keys` provenance rows. Chunk rows carry their keys through+ `getChunks`, so `wrapChunkTextsForStoredMode`, `embeddingInputHash` and+ every plain re-embed path build the same keyed input with no extra lookup.+- **Exact-input install check.** `installPageEmbeddings` refuses a title-tier+ vector whose key text differs from the stored row. Callers pass the key text+ they embedded, or the prepared row the input was built from. This is the+ captured-input comparison of obligation 6, done on the input itself rather+ than on a separate hash parameter, so every existing caller is covered.+- **One SQL rule in `upsertChunks`:** when a row's key text changes and the+ incoming row brings no new vector, the stored vector and its provenance are+ dropped in the same statement. Re-chunking a page (the replacement chunks+ carry no keys) therefore never leaves a keyed vector behind, and+ `retireStaleFactKeys` deletes the rows of older revisions on every path that+ seals a new chunk set.+- **Withdrawal** finds keyed pages through `page_fact_keys` (key subject `'*'`+ matches any subject-scoped withdrawal) and sends them down the existing+ delete-and-rebuild path. The rebuild runs under a new revision, so the+ page's other keys are retired too until its next extraction.+- **Disable and recovery are commands.** `gbrain fact-keys clear` strips keys+ page by page with the same prepare-then-swap (re-embed without keys, then+ swap), whatever the setting says. `gbrain fact-keys refresh` re-runs facts+ extraction for eligible pages without current keys. `gbrain fact-keys status`+ and doctor's `retrieval_enrichment` report coverage and leftovers.+- **Extraction lanes.** Keys come from the extractor's output for that lane.+ `put_page` and capture lanes extract every notability tier. Git sync asks+ the extractor for high-notability facts only, so synced pages carry fewer+ keys.+- **Other vector columns** of a re-keyed chunk are nulled in the swap+ transaction. Only the active column gets the new vector.+## What it doesgbrain already extracts facts when an eligible page is written@@ -389,21 +429,15 @@ there.promotion and demotion with partial re-embeds; a graduation round trip thatkeeps the invariant.-## Open questions for review--1. **The `tokenmax` gate.** The preregistered gate also requires beating- `tokenmax` synopses, which the LongMemEval harness can't generate. One- option is to add synopsis generation (paid, about the cost of one embedding- run). The other is to amend the preregistration to compare against the- `balanced` default only and record the reason. Code waits on this choice.-2. **Extractor model.** The dev gate pinned Haiku 4.5, and production defaults- to the reasoning tier. The sealed run uses the shipping default.-3. **Embedding multiplier.** The cohort multiplier is expected to exceed- 1.3×. The proposal is to report it rather than gate on it, because the- re-embed is intended work. The alternative is to delay the first embed of- eligible pages until extraction lands or a deadline passes, trading- write-time searchability for cost.-4. **Visibility policy.** This note uses the fail-closed intersection. The- alternative treats keys as page-visible: keys are paraphrases of text the- page already exposes and only change ranking. That needs an explicit- policy decision, and it widens what private facts influence.+## Decisions (2026-10-05)++1. **The `tokenmax` gate** stays in the gate. It runs on LoCoMo (development+ conversations, then a third arm on the sealed run), because on+ LongMemEval-M production synopses would cost about $4,280. M stays as+ confirmation against `balanced` only (preregistration amendment 2).+2. **Extractor model:** sealed cells use the shipping default. Haiku 4.5 is+ disclosed as the development stand-in.+3. **Embedding cost** is reported, not gated (amendment 1). The verdict+ reports the embedding-spend ratio on the fact-bearing cohort and sync time.+4. **Visibility** fails closed. Coverage is reported with+ `facts.default_visibility` unset and set to `world`.diff --git a/docs/guides/time-aware-recall.md b/docs/guides/time-aware-recall.mdindex a61566cb9b..7cf97384b7 100644--- a/docs/guides/time-aware-recall.md+++ b/docs/guides/time-aware-recall.md@@ -38,11 +38,49 @@ 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 carries eval-only arms for the next steps of-time-aware retrieval — fact keys merged into chunk embeddings and a soft time-scope driven by the question's explicit time words. They run only inside-`gbrain eval longmemeval` (`--fact-keys`, `--time-scope`); see+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[`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 c7deb086a4..8b1547dd20 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 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/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 pathssrc/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 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/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_keyssrc/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 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/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 keysrc/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 a8396d1fae..06718009d0 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, backfill: true, 'book-mirror': true, 'edges-backfill': true, embed: true, features: true,+ advisor: true, anomalies: true, feedback: true, 'fact-keys': 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,6 +3036,7 @@ 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 13acfd1620..154eefe143 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -316,6 +316,7 @@ 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.tsnew file mode 100644index 0000000000..a1828989ef--- /dev/null+++ b/src/cli/commands/fact-keys.ts@@ -0,0 +1,10 @@+/**+ * `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.tsnew file mode 100644index 0000000000..f5fed9ef18--- /dev/null+++ b/src/commands/doctor/checks/retrieval-enrichment.ts@@ -0,0 +1,39 @@+/**+ * 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 1e54ec8fef..47779627ed 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -83,6 +83,7 @@ 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';@@ -165,6 +166,7 @@ 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.tsnew file mode 100644index 0000000000..c0ed72ec08--- /dev/null+++ b/src/commands/fact-keys.ts@@ -0,0 +1,126 @@+/**+ * 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 22a3e7e54a..a065002b34 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -59,6 +59,7 @@ 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'],@@ -172,6 +173,7 @@ 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 098aff1f81..7a8d4f3316 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1372,6 +1372,8 @@ 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/doctor-categories.ts b/src/core/doctor-categories.tsindex 47bd973088..dcfb8ffc65 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -295,6 +295,7 @@ 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/facts/backstop.ts b/src/core/facts/backstop.tsindex 046147348b..235a90054f 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -660,10 +660,7 @@ 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 && input.pageSlug === ctx.factKeys.slug && input.turnText === ctx.factKeys.text) {- const { publishExtractedFactKeys } = await import('./fact-keys-publish.ts');- await publishExtractedFactKeys(ctx.engine, ctx.factKeys, outcome.facts, visibility, resolveEntitySlugWithSource, abortSignal);- }+ 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 721bb9f769..0c0d61f4e0 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.*/-const RESCUE_SLUG_PREFIXES = ['meetings/', 'personal/', 'daily/'] as const;+export 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 @@ const RESCUE_SLUG_PREFIXES = ['meetings/', 'personal/', 'daily/'] as const;// 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).-const ELIGIBLE_TYPES: PageType[] = [+export 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 @@ const ELIGIBLE_TYPES: PageType[] = ['media', 'tweet', 'analysis',];-const MIN_BODY_CHARS = 80;+export const MIN_BODY_CHARS = 80;export function isFactsBackstopEligible(slug: string,@@ -100,3 +100,11 @@ 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.tsindex d63444206d..8e80689858 100644--- a/src/core/facts/fact-keys-publish.ts+++ b/src/core/facts/fact-keys-publish.ts@@ -128,9 +128,9 @@ export async function publishPageFactKeys(engine: BrainEngine, binding: FactKeysconst 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 signature = currentEmbeddingSignature();+ const canEmbed = !!opts.embed || !!currentEmbeddingSignature();let vectors: Float32Array[] = [];- if (changed.length && signature) {+ if (changed.length && canEmbed) {try {vectors = await (opts.embed ?? embedBatch)(wrapChunkTextsForStoredMode(page, changed.map(({ chunk, keys: next }) => ({ ...chunk, fact_keys: next }))),@@ -206,9 +206,11 @@ export async function clearPageFactKeys(engine: BrainEngine, sourceId: string, s* 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) {diff --git a/src/core/facts/fact-keys-status.ts b/src/core/facts/fact-keys-status.tsnew file mode 100644index 0000000000..4bc3dc5de2--- /dev/null+++ b/src/core/facts/fact-keys-status.ts@@ -0,0 +1,34 @@+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/utils.ts b/src/core/utils.tsindex 0a70ac96e5..179d9fb7c2 100644--- a/src/core/utils.ts+++ b/src/core/utils.ts@@ -444,6 +444,7 @@ 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 551e0618f4..dc515bba89 100644--- a/src/eval/longmemeval/retrieval-arms.ts+++ b/src/eval/longmemeval/retrieval-arms.ts@@ -8,7 +8,10 @@* 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. `chunk_text` is untouched, so retrieval+ * 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* still returns the raw session. Extractions are cached on disk by* content hash so arms and reruns never pay twice.*@@ -38,7 +41,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';+export type FactExtractor = 'paper' | 'production' | 'pipeline';const FACT_EXTRACT_CONCURRENCY = 8;@@ -169,6 +172,7 @@ 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);@@ -261,10 +265,11 @@ 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', help: [+ { name: '--fact-extractor', arg: 'paper|production|pipeline', help: ['Fact source for --fact-keys: paper = the benchmark\'s published user-turn',- '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; } },+ '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; } },{ 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.'],@@ -289,12 +294,40 @@ 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;- const model = o.factExtractor === 'production' && !o.factKeysModel+ 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? 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/test/cli-dispatch-phase.test.ts b/test/cli-dispatch-phase.test.tsindex 82febfb007..2415f2ca3c 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(65);+ expect(shape.switchCases.length).toBe(66);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.tsnew file mode 100644index 0000000000..be61b013f6--- /dev/null+++ b/test/fact-keys-backstop.test.ts@@ -0,0 +1,86 @@+/**+ * 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.tsnew file mode 100644index 0000000000..eda6ae3d10--- /dev/null+++ b/test/fact-keys-publish.test.ts@@ -0,0 +1,187 @@+/**+ * 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 7d807b48ac..84f0c493ad 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -180,6 +180,9 @@"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",@@ -570,6 +573,9 @@"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"],@@ -973,6 +979,8 @@"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)",@@ -1331,20 +1339,21 @@"9 embedded_at timestamp with time zone/timestamptz NULL","10 embedded_text_hash text/text NULL","11 embedding_input_hash text/text 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"+ "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"],"flags": "relkind=r rls=false force_rls=false"},@@ -2216,6 +2225,20 @@],"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 cdc1320166..5db06a732e 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -180,6 +180,9 @@"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",@@ -570,6 +573,9 @@"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"],@@ -973,6 +979,8 @@"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)",@@ -1331,20 +1339,21 @@"9 embedded_at timestamp with time zone/timestamptz NULL","10 embedded_text_hash text/text NULL","11 embedding_input_hash text/text 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"+ "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"],"flags": "relkind=r rls=false force_rls=false"},@@ -2216,6 +2225,20 @@],"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 4f88afa57e..23c6cb1086 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -180,6 +180,9 @@"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",@@ -570,6 +573,9 @@"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"],@@ -969,6 +975,8 @@"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)",@@ -1327,20 +1335,21 @@"9 embedded_at timestamp with time zone/timestamptz NULL","10 embedded_text_hash text/text NULL","11 embedding_input_hash text/text 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"+ "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"],"flags": "relkind=r rls=false force_rls=false"},@@ -2212,6 +2221,20 @@],"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 24b6e2ee56..df22c0d851 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -128,6 +128,9 @@"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)",@@ -426,6 +429,9 @@"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"],@@ -713,6 +719,8 @@"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)",@@ -964,15 +972,16 @@"9 embedded_at timestamp with time zone/timestamptz NULL","10 embedded_text_hash text/text NULL","11 embedding_input_hash text/text 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"+ "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"],"flags": "relkind=r rls=false force_rls=false"},@@ -1620,6 +1629,20 @@],"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 3d080b787c..c5e34b0eb2 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -128,6 +128,9 @@"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)",@@ -426,6 +429,9 @@"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"],@@ -713,6 +719,8 @@"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)",@@ -964,15 +972,16 @@"9 embedded_at timestamp with time zone/timestamptz NULL","10 embedded_text_hash text/text NULL","11 embedding_input_hash text/text 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"+ "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"],"flags": "relkind=r rls=false force_rls=false"},@@ -1620,6 +1629,20 @@],"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 2ba4bdbf4f..aa23741956 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -128,6 +128,9 @@"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)",@@ -426,6 +429,9 @@"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"],@@ -712,6 +718,8 @@"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)",@@ -963,15 +971,16 @@"9 embedded_at timestamp with time zone/timestamptz NULL","10 embedded_text_hash text/text NULL","11 embedding_input_hash text/text 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"+ "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"],"flags": "relkind=r rls=false force_rls=false"},@@ -1619,6 +1628,20 @@],"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 5854eec413..e1f07dcc48 100644--- a/test/fixtures/goldens/cli/dispatch-phase.json+++ b/test/fixtures/goldens/cli/dispatch-phase.json@@ -793,6 +793,13 @@"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 05da7cc873..646b1fcb9d 100644--- a/test/fixtures/goldens/cli/help-and-errors.json+++ b/test/fixtures/goldens/cli/help-and-errors.json@@ -104,6 +104,7 @@" 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).",@@ -315,6 +316,7 @@" 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).",@@ -526,6 +528,7 @@" 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 19da3153ae..2baa94e7b8 100644--- a/test/fixtures/goldens/cli/literal-imports.json+++ b/test/fixtures/goldens/cli/literal-imports.json@@ -71,6 +71,9 @@"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 81d48dcdb1..db3ac4ca5f 100644--- a/test/fixtures/goldens/cli/membership-sets.json+++ b/test/fixtures/goldens/cli/membership-sets.json@@ -69,6 +69,7 @@"refusedNotInCliOnly": [],"refusedWithoutHint": ["edge-proposals",+ "fact-keys","feedback","watch"],@@ -131,6 +132,7 @@"export","extract","extract-conversation-facts",+ "fact-keys","facts","features","feedback",@@ -241,6 +243,7 @@"export","extract","extract-conversation-facts",+ "fact-keys","facts","features","feedback",@@ -311,6 +314,7 @@"embed","export","extract-conversation-facts",+ "fact-keys","features","feedback","founder",@@ -362,6 +366,7 @@"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 86194ddbaa..40e91a77f5 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 208 (latest: 208)",+ "message": "Version 209 (latest: 209)","name": "schema_version","status": "ok"},{"category": "meta",- "message": "935 column(s) verified against live schema",+ "message": "931 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -1610,6 +1610,21 @@"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 618bf92713..931a66b48f 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 208 (latest: 208)",+ "message": "Version 209 (latest: 209)","name": "schema_version","status": "ok"},{"category": "meta",- "message": "935 column(s) verified against live schema",+ "message": "931 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -1687,6 +1687,21 @@"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 c17732c488..c65d7b99db 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -661,6 +661,10 @@"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 cfe9cbf0b3..3eeb167c4f 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 203,+ "count": 204,"gaps": [17,18,@@ -29,7 +29,7 @@"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 208,+ "latest": 209,"records": [{"handler": {@@ -3081,6 +3081,19 @@"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": [@@ -3286,7 +3299,8 @@205,206,207,- 208+ 208,+ 209]},"normalizer": "migrations-record-v1"diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.tsindex f487839ed4..3e22d3a397 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: 105, rebind: 2, rebuild: 2, discard: 6, schema_owned: 3 });+ expect(counts).toEqual({ carry: 106, 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 });