Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): stale reserved frontmatter keys are not file/database drift (#6454)

garrytan93b41f152d71
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 487466c031..8ac1747eb3 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -125,6 +125,7 @@ should also check `results[].complete`.
| `connector-checkpoints` | `connector_checkpoints` | Deletes managed connector checkpoint rows and retry pointers that no registered connector source can load and that are older than 7 days. They accumulate after a content setting such as `g_history_days` changes, or when a connector host older than v0.60.11.0 runs during an upgrade. Cleanup only: it never copies or re-keys a checkpoint, takes no journal admission and runs brain-wide (`--source` does not narrow it). | Rows a queued or running connector write, or a connector's recorded pending set, still references. |
| `orphan-bindings` | `orphan_persistence_bindings` | Deletes persistence source bindings whose source was removed, or that belong to an earlier incarnation of a source re-added under the same id. `gbrain sources remove` and `gbrain sources purge` delete the binding; one an older gbrain left behind makes the re-added source read as claimed, so every `gbrain sync --source <id>` fails with `writer_coordinator_required`. Bookkeeping only: no journal admission, no page or file changes, and it runs brain-wide (`--source` does not narrow it). See [orphan bindings](#orphan-bindings). | A binding that a queued, running or recovering write request of the same source incarnation still references. |
| `managed-sync-orphans` | `sync_failures` | Explicit-only, preview-bound. Retires managed sync bookkeeping nothing current can resume or clear: a `managed-sync-failure` row whose cursor key has no cursor, and an unfinished `managed-sync` cursor recorded by a principal that is no longer an active local writer (or a pre-options cursor a later run superseded) whose pending request is terminal. `op_checkpoints` rows only; no journal admission, no page or file changes. The preview prints a hash; `--apply --expect <hash>` retires exactly that set. See [managed sync orphans](#managed-sync-orphans). | An unfinished cursor whose pending request is still queued, running or recovering, or one the live writer can resume with its recorded options (doctor prints that sync command). |
+| `frontmatter-keys` | `stale_frontmatter_keys` | Explicit-only, preview-bound. Strips the parser's reserved top-level keys (`type`, `title`, `tags`, `slug`) that an older import stored inside `pages.frontmatter`. Since v0.60.176.0 those keys are not file/database drift and never render (#6454), so this is hygiene: database rows only, in source-scoped coordinated batches of up to 1,000 pages, no file, body or embedding change. Each swept page advances its `knowledge_revision` once, so a client holding an older revision of a swept page gets one `revision_conflict` and re-reads. See [frontmatter keys](#frontmatter-keys). | A page whose keys were cleared by a write between preview and apply (`already_clean`). |
| `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). |
| `attribution-backfill` | none | Fills write attribution (who wrote it) on pages, page versions and facts written before attribution was recorded, only where exactly one committed request in the write journal proves the writer: the page write whose recorded result is the row's revision, or the `remember` that inserted the fact. Fills NULLs only, in committed batches of 1,000 that resume after an interruption; no content, revision, page file or request ID changes. See [write attribution](../mcp/ADMIN.md#write-attribution). | `unrecorded_pages`, `unrecorded_page_versions`, `unrecorded_facts`: rows the journal cannot prove. They stay `unrecorded`; nothing is inferred. |
| `safe-chunks` | `safe_index_pending` (also `contextual_retrieval_coverage`, `details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. |
@@ -399,6 +400,45 @@ failure row and its manifest (when no other cursor shares the run) in one
transaction, so a cursor the writer picked up meanwhile is left alone. Do not
delete `op_checkpoints` rows by hand.
+### Frontmatter keys
+
+<a id="frontmatter-keys"></a>
+
+**Say to your agent:** *"doctor reports `stale_frontmatter_keys` on tens of
+thousands of pages. Is anything broken, and what does the sweep change?"*
+
+Imports before mid-2026 could store the parser's four reserved keys (`type`,
+`title`, `tags`, `slug`) inside `pages.frontmatter`. A file never carries them
+there (the parser lifts them into page columns), so for those rows the
+canonical file and the database copy never compared equal, and every
+coordinated write was refused `source_changed` (#6454). Since v0.60.176.0 the
+comparison and the render skip those four top-level keys on both sides, so
+the refusals stop on their own and the stored keys are inert: nothing is
+broken. Refused writes whose receipt is retained replay with
+[`gbrain repair failed-writes`](#failed-writes).
+
+`gbrain repair frontmatter-keys` removes the inert keys from the rows. It is
+explicit-only and preview-bound; the preview says how many pages carry which
+keys and prints a hash, and the apply sweeps exactly that set in source-scoped
+batches of up to 1,000 pages, each a coordinated maintenance write under the
+pages' key locks (a bare `UPDATE pages` is refused by the managed writer
+guard). Database rows only: no file, body, tag or embedding change, no journal
+admission. The one visible effect is the revision: the database advances
+`knowledge_revision` on any frontmatter change, so every swept page gets a
+new revision once and a client that saved an older `expected_revision` gets
+one `revision_conflict` on its next write and re-reads.
+
+```bash
+gbrain doctor --only stale_frontmatter_keys # count per source
+gbrain repair frontmatter-keys --source default # preview: pages and keys, prints the hash
+gbrain repair frontmatter-keys --source default --apply --expect <hash>
+gbrain doctor --only stale_frontmatter_keys # ok
+```
+
+A page whose keys a write cleared between preview and apply is counted
+`already_clean`. Nested user keys with the same names (`metadata.title`) are
+never touched; only the four top-level keys are.
+
### Orphan children
**Say to your agent:** *"gbrain fails with `unexpected chunk number` or
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 93157d474b..fb582f4a51 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,12 +16,12 @@ src/commands/sync.ts 517 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3303 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts)
src/core/cycle/synthesize.ts 3228 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); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)
src/core/cycle/extract-atoms.ts 1654 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); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +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); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count
-src/core/engine.ts 2781 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; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts)
+src/core/engine.ts 2787 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; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts)
src/core/import-file.ts 2025 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); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 240 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); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)
-src/core/pglite-engine.ts 3023 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); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured)
-src/core/postgres-engine.ts 3027 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); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured)
+src/core/pglite-engine.ts 3026 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); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts)
+src/core/postgres-engine.ts 3030 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); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts)
src/core/search/hybrid.ts 1632 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; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)
src/core/types.ts 2280 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +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); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
diff --git a/src/commands/doctor/checks/frontmatter-keys.ts b/src/commands/doctor/checks/frontmatter-keys.ts
new file mode 100644
index 0000000000..7ef487a12b
--- /dev/null
+++ b/src/commands/doctor/checks/frontmatter-keys.ts
@@ -0,0 +1,32 @@
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+import { agentFix, checkError } from '../check-fix.ts';
+
+/**
+ * #6454: live pages whose stored frontmatter still carries one of the
+ * parser's reserved top-level keys (`type`, `title`, `tags`, `slug`), which an
+ * older import kept. Since `comparableFrontmatter` they are not file/database
+ * drift and never render, so this is hygiene: names the explicit-only,
+ * preview-bound `gbrain repair frontmatter-keys` sweep per source and says
+ * that each swept row advances its knowledge_revision once. Read-only.
+ */
+export async function staleFrontmatterKeysCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
+ const docs = 'docs/guides/repair.md#frontmatter-keys';
+ try {
+ const sources = sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);
+ const counts = await engine.countStaleFrontmatterKeyPages({ sourceIds: sources });
+ const count = counts.reduce((sum, row) => sum + row.n, 0);
+ const details = { count, sources: counts, source_ids: counts.map(row => row.source_id), repair: 'frontmatter-keys', docs };
+ if (!count) return { name: 'stale_frontmatter_keys', status: 'ok', details, message: 'No stored frontmatter carries a parser-reserved key (type, title, tags, slug).' };
+ const first = counts[0].source_id;
+ return { name: 'stale_frontmatter_keys', status: 'warn', details,
+ message: `${count} page(s) store a parser-reserved key (type, title, tags, slug) inside their frontmatter, left by an older import: `
+ + `${counts.map(row => `${row.source_id}: ${row.n}`).join(', ')}. Writes compare and render around these keys since v0.60.176.0, so this is hygiene, not a wedge. `
+ + `Preview the sweep on the brain host: gbrain repair frontmatter-keys --source ${first} — it lists the pages and prints the apply command; each swept page `
+ + `advances its knowledge_revision once (a client holding an older revision gets one revision_conflict).`,
+ fix: agentFix(['gbrain', 'repair', 'frontmatter-keys', '--source', first],
+ 'Read-only preview: lists the pages carrying reserved keys, saves the set under a hash and prints the apply command.', 'stale_frontmatter_keys', { docs }) };
+ } catch (error) {
+ return checkError('stale_frontmatter_keys', 'count stored frontmatter reserved keys', error, { details: { count: 'unknown', docs } });
+ }
+}
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index f76b5c668f..41503d7dfc 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -326,6 +326,7 @@ export const timelineHistoryEntry: DoctorEntry = {
'captured_facts_active',
'loop_facts_drift',
'ontology_facts_fenced',
+ 'stale_frontmatter_keys',
],
run: runTimelineHistory,
};
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index e0dda56911..3adeefa6c2 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -298,6 +298,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
impact: 'Some ontology observations were moved onto an entity page\'s Facts table, and ontology_get no longer returns the ones a later page write retired',
run: async (engine, scope) => (await import('./checks/ontology-facts.ts')).ontologyFactsCheck(engine, scope.sourceIds),
},
+ {
+ id: 'stale_frontmatter_keys', resolution: 'repair', registration: 'wave',
+ hostOnly: 'Sweeping stored frontmatter keys is a host-side, explicit-only repair.',
+ count: d => Number(d.count ?? 0),
+ impact: 'Some pages store a parser-reserved frontmatter key (type, title, tags, slug) left by an older import; writes compare around it, the sweep is hygiene',
+ run: async (engine, scope) => (await import('./checks/frontmatter-keys.ts')).staleFrontmatterKeysCheck(engine, scope.sourceIds),
+ },
];
/** A check that could not run reports unknown, never ok. */
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 04f73052dd..089e7a919a 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -437,6 +437,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.165.0', text: '`gbrain extract --stale` and `extract links|all --source db` skip and count a page another writer changed mid-run (`skipped_concurrent_write`) instead of aborting the run; the page stays stale for the next run. `extract all --source db` marks a page extracted only when both its links and its timeline finished at the same revision. On a managed brain, `extract timeline --from-meetings` (and its job) now writes through the coordinator as one `managed_maintenance_meeting_timeline` request per entity page, gated at the meeting\'s trust tier; a refused or pending write fails the job and the command exits 1. An owner on an older build refuses that request kind until it upgrades. On a managed brain, `extract_entities` now writes stubs, timeline rows and backlinks through the coordinator (creating a stub needs permission to write pages); a refusal or pending write returns its error envelope and names the entities already written, instead of a raw `writer_coordinator_required` error or a silently missing timeline row.' },
// Memory proof wave 2 W1 (question-ranked recall).
{ since: '0.60.169.0', text: '`recall` takes an optional `question` and returns saved facts ranked by relevance to it (facts below the match threshold are left out); calls without it still return the newest facts, every response now says `facts_order`, and a call that passes only `query` carries a `recall_hint` notice. `gbrain recall --question` passes the question instead of reading its value as an entity name. In `query`, the facts of an entity the question names come only from that entity page\'s own source, and the temporal fact reserve (`search.temporal_fact_reserve`, off by default) scores with the same question scorer: whole-word matches, and a long fact\'s word matches count for less.' },
+ // Fix wave 15 G2 (GBRA-79, #6454); `since` is a placeholder equal to the branch's VERSION until the integrator sets the merge-slot stamp.
+ { since: '0.60.175.0', text: 'A coordinated write to a page whose stored frontmatter carries one of the parser\'s reserved top-level keys (`type`, `title`, `tags`, `slug`, kept by imports before mid-2026) is no longer refused `source_changed` when the file matches the database in every other way: the file/database comparison (publication, `sources reconcile`, file repairs) strips those four keys on both sides, as the parser does (#6454). A real body, title or tag drift still refuses. Writes refused this way whose receipt is retained replay with `gbrain repair failed-writes --source <id>`; doctor `stale_frontmatter_keys` counts the rows and names the explicit-only `gbrain repair frontmatter-keys` sweep, which removes the inert keys in coordinated batches and advances each swept page\'s `knowledge_revision` once (a client holding an older revision gets one `revision_conflict`).' },
+ { since: '0.60.175.0', text: 'A published page file now always carries the page\'s own `type`, `title` and tags from the database columns. A legacy row whose stored frontmatter also held a `type` or `title` that disagreed with the columns used to render the stored value (and stored `tags` rendered when the page had none); the next write of such a page now renders the columns and drops the stale keys, so the file\'s header can change once. Nested keys of the same names (`metadata.title`) and the `slug:` stamp for slugs the path cannot derive are unchanged.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 37e1a2f013..ce464d4e8d 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -260,6 +260,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'persistence_request_indexes',
'persistence_write_stall',
'lost_caller_writes',
+ 'stale_frontmatter_keys',
'managed_sync_not_moving',
'persistence_session_timeouts',
// #6317: consumer heartbeat rows and host identity (doctor/checks/persistence-consumers.ts).
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 67601faa41..5a957b5ef9 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -785,6 +785,44 @@ export async function markPagesAttendanceBlocked(
return result.affectedRows;
}
+/**
+ * #6454: live pages whose stored frontmatter still carries one of the parser's
+ * reserved top-level keys (`type`, `title`, `tags`, `slug`; older imports kept
+ * them). Not drift since `comparableFrontmatter` (markdown.ts), but hygiene
+ * `gbrain repair frontmatter-keys` sweeps on consent. Counts per source for
+ * the doctor check; the listing pages by id for the preview-bound sweep.
+ */
+export const RESERVED_FRONTMATTER_KEYS_SQL = ['type', 'title', 'tags', 'slug'];
+const normalizeStaleKeyCount = compileRowNormalizer<{ source_id: string; n: number }>({ n: 'bigint' });
+export async function countStaleFrontmatterKeyPages(exec: ScopedRead, opts: { sourceIds: string[] }): Promise<Array<{ source_id: string; n: number }>> {
+ if (opts.sourceIds.length === 0) return [];
+ const { rows } = await exec.run<{ source_id: string; n: number | string }>(sqlFragment`
+ SELECT source_id, count(*)::bigint AS n FROM pages
+ WHERE source_id = ANY(${opts.sourceIds}::text[]) AND deleted_at IS NULL AND frontmatter ?| ${RESERVED_FRONTMATTER_KEYS_SQL}::text[]
+ GROUP BY source_id ORDER BY source_id
+ `);
+ return rows.map(row => normalizeStaleKeyCount(row));
+ }
+export async function listStaleFrontmatterKeyPages(exec: ScopedRead, opts: { sourceId: string; afterId: number; limit: number }):
+ Promise<Array<{ id: number; slug: string; keys: string[] }>> {
+ const { rows } = await exec.run<{ id: number | string; slug: string; keys: string[] }>(sqlFragment`
+ SELECT id, slug, ARRAY(SELECT k FROM unnest(${RESERVED_FRONTMATTER_KEYS_SQL}::text[]) AS k WHERE frontmatter ? k ORDER BY k) AS keys
+ FROM pages
+ WHERE source_id = ${opts.sourceId} AND deleted_at IS NULL AND frontmatter ?| ${RESERVED_FRONTMATTER_KEYS_SQL}::text[] AND id > ${opts.afterId}
+ ORDER BY id LIMIT ${opts.limit}
+ `);
+ return rows.map(row => ({ id: Number(row.id), slug: row.slug, keys: row.keys }));
+ }
+/** Strips the reserved keys from the named live pages of one source; the revision trigger advances each changed row. */
+export async function stripStaleFrontmatterKeys(exec: SqlExecutor, opts: { sourceId: string; ids: number[] }): Promise<number> {
+ if (opts.ids.length === 0) return 0;
+ const result = await exec.run(sqlFragment`
+ UPDATE pages SET frontmatter = frontmatter - ${RESERVED_FRONTMATTER_KEYS_SQL}::text[]
+ WHERE source_id = ${opts.sourceId} AND id = ANY(${opts.ids}::int[]) AND deleted_at IS NULL AND frontmatter ?| ${RESERVED_FRONTMATTER_KEYS_SQL}::text[]
+ `);
+ return result.affectedRows;
+ }
+
export async function findByTitleFuzzy(
exec: LegacyUnscopedRead,
name: string,
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 8be71c7672..4842e20c3b 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -1416,6 +1416,12 @@ export interface BrainEngine {
markPagesExtractedBatch(refs: Array<{ slug: string; source_id: string; extractedAt?: string }>, defaultExtractedAt: string): Promise<number>;
/** #5761: mark pages attendance-blocked at `revision`; skips refs whose page moved past it. Returns rows marked. */
markPagesAttendanceBlocked(refs: Array<{ slug: string; source_id: string; revision: string }>): Promise<number>;
+ /** #6454: live pages per source whose stored frontmatter still carries a parser-reserved key (type/title/tags/slug). */
+ countStaleFrontmatterKeyPages(opts: { sourceIds: string[] }): Promise<Array<{ source_id: string; n: number }>>;
+ /** #6454: those pages of one source in id order after `afterId`, with the stale keys each carries. */
+ listStaleFrontmatterKeyPages(opts: { sourceId: string; afterId: number; limit: number }): Promise<Array<{ id: number; slug: string; keys: string[] }>>;
+ /** #6454: strips the reserved keys from the named live pages of one source (coordinated maintenance write); rows changed. */
+ stripStaleFrontmatterKeys(opts: { sourceId: string; ids: number[] }): Promise<number>;
// Links
/**
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index 62222957df..c63cd16ae2 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -418,11 +418,7 @@ export function parseMarkdown(
const tags = extractTags(frontmatter);
const slug = coerceFrontmatterString(frontmatter.slug) || inferSlug(filePath);
- const cleanFrontmatter = { ...frontmatter };
- delete cleanFrontmatter.type;
- delete cleanFrontmatter.title;
- delete cleanFrontmatter.tags;
- delete cleanFrontmatter.slug;
+ const cleanFrontmatter = comparableFrontmatter(frontmatter);
const result: ParsedMarkdown = {
frontmatter: cleanFrontmatter,
@@ -1212,6 +1208,21 @@ import { existsSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, resolve, sep as pathSep } from 'node:path';
/** Options for serializePageToMarkdown. */
+/**
+ * #6454: the four top-level frontmatter keys the parser lifts into page
+ * columns (`type`, `title`, `tags`, `slug`) and drops from
+ * `ParsedMarkdown.frontmatter`. A file can never carry them into the stored
+ * frontmatter, so a stored copy of one of them (older imports kept them) is
+ * not drift: every file-versus-database comparison and every render strips
+ * them first, top-level only; nested user keys are left alone.
+ */
+export const RESERVED_FRONTMATTER_KEYS = ['type', 'title', 'tags', 'slug'] as const;
+export function comparableFrontmatter(frontmatter: Record<string, unknown> | null | undefined): Record<string, unknown> {
+ const clean: Record<string, unknown> = { ...(frontmatter ?? {}) };
+ for (const key of RESERVED_FRONTMATTER_KEYS) delete clean[key];
+ return clean;
+}
+
export interface SerializePageOpts {
/** Frontmatter fields merged on top of page.frontmatter at render time.
* Use this to stamp provenance (`ingested_via: 'webhook'`), identity
@@ -1240,8 +1251,10 @@ export function serializePageToMarkdown(
tags: string[],
opts: SerializePageOpts = {},
): string {
+ // #6454: the columns are the page's type, title and tags; a stored reserved key (older imports kept
+ // them) never overrides them in the rendered file. Stripped before the slug stamp so the #5966 rule still runs.
const frontmatter: Record<string, unknown> = {
- ...slugStampedFrontmatter(page.slug, (page.frontmatter ?? {}) as Record<string, unknown>),
+ ...slugStampedFrontmatter(page.slug, comparableFrontmatter(page.frontmatter)),
...(opts.frontmatterOverrides ?? {}),
};
return serializeMarkdown(
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index a3ab5ddf0e..e101d02168 100644
--- a/src/core/persistence/file-repair.ts
+++ b/src/core/persistence/file-repair.ts
@@ -48,7 +48,7 @@ import { ownerImportTrust, ownerSourceGateInput } from '../trust/channel.ts';
import { ContentSanityBlockError } from '../content-sanity.ts';
import { loadImportSanityConfig, type ContentRefusal, type ImportSanityConfig } from '../import-screen.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
-import { parseMarkdown, resolveParsedSubtype, type ParseOpts } from '../markdown.ts';
+import { comparableFrontmatter, parseMarkdown, resolveParsedSubtype, type ParseOpts } from '../markdown.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { opError, type OperationContext } from '../ops/contract.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
@@ -179,7 +179,7 @@ export function fileSha256(path: string): string {
/** The canonical page fields a publication stores; what the preview hash binds besides the bytes. */
export function canonicalRepairFields(page: Pick<ParsedPage, 'type' | 'title' | 'compiled_truth' | 'timeline' | 'frontmatter'>, tags: string[]) {
- return { type: page.type, title: page.title, body: page.compiled_truth, timeline: page.timeline ?? '', frontmatter: page.frontmatter, tags: [...new Set(tags)].sort() };
+ return { type: page.type, title: page.title, body: page.compiled_truth, timeline: page.timeline ?? '', frontmatter: comparableFrontmatter(page.frontmatter), tags: [...new Set(tags)].sort() };
}
export interface RepairPublicationInput {
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 823f60fc8e..add3398501 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -10,7 +10,7 @@ import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page, PageVersion } from '../types.ts';
import { importFromContent, verifyPageReadable, type ParsedPage } from '../import-file.ts';
-import { frontmatterHoldMessageWithoutKeys, parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParseOpts } from '../markdown.ts';
+import { comparableFrontmatter, frontmatterHoldMessageWithoutKeys, parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParseOpts } from '../markdown.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { isOpPageSlug } from '../ops/context.ts';
@@ -82,10 +82,14 @@ function pageRefusal(code: RegistryCode, message: string, row: WriteRequest, cau
: ownerStatusFix(row.source_id)) });
}
-/** The parser trims titles, so a stored title differing only in surrounding whitespace is not drift (#5635). */
+/**
+ * The parser trims titles, so a stored title differing only in surrounding whitespace is not drift (#5635), and it
+ * never carries `type`/`title`/`tags`/`slug` into the frontmatter object, so a stored copy of one (#6454: older
+ * imports kept them) is compared through `comparableFrontmatter` on both sides, never as drift.
+ */
function canonical(page: Pick<Page, 'type' | 'title' | 'compiled_truth' | 'timeline' | 'frontmatter'>, tags: string[]) {
return { type: page.type, title: page.title.trim(), compiled_truth: page.compiled_truth, timeline: page.timeline ?? '',
- frontmatter: page.frontmatter, tags: [...new Set(tags)].sort() };
+ frontmatter: comparableFrontmatter(page.frontmatter), tags: [...new Set(tags)].sort() };
}
interface CanonicalProvenance { source_kind: string; ingested_via: string; ingested_at: string; }
/** Canonical stamps belong to the first write, never to a later preparation attempt. */
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index a0523352c2..b2d64a16a3 100644
--- a/src/core/persistence/preview-approval.ts
+++ b/src/core/persistence/preview-approval.ts
@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';
/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */
export const APPROVAL_MAX_AGE_DAYS = 7;
-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/persistence/reconcile-merge.ts b/src/core/persistence/reconcile-merge.ts
index f89f31a6fb..a47a3febac 100644
--- a/src/core/persistence/reconcile-merge.ts
+++ b/src/core/persistence/reconcile-merge.ts
@@ -1,5 +1,6 @@
import type { ParsedPage } from '../import-file.ts';
import type { Page } from '../types.ts';
+import { comparableFrontmatter } from '../markdown.ts';
import { opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { digest, stableJson } from './digest.ts';
@@ -15,7 +16,7 @@ const protectedKeys = new Set([...RECONCILE_SCAN_KEYS, ...RECONCILE_SAFETY_KEYS,
export function reconcileCanonical(page: Pick<Page, 'type' | 'title' | 'compiled_truth' | 'timeline' | 'frontmatter'>, tags: string[]): ParsedPage {
const value = { type: page.type, title: page.title, compiled_truth: page.compiled_truth, timeline: page.timeline ?? '',
- frontmatter: page.frontmatter, tags: [...new Set(tags)].sort() };
+ frontmatter: comparableFrontmatter(page.frontmatter), tags: [...new Set(tags)].sort() };
validateReconcileJson(value, true);
return JSON.parse(stableJson(value)) as ParsedPage;
}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 682b857fa9..cedd19678f 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1880,6 +1880,9 @@ export class PGLiteEngine implements BrainEngine {
async markPagesAttendanceBlocked(refs: Array<{ slug: string; source_id: string; revision: string }>): Promise<number> {
return pagesImpl.markPagesAttendanceBlocked(this.engineSql, refs);
}
+ async countStaleFrontmatterKeyPages(opts: { sourceIds: string[] }) { return pagesImpl.countStaleFrontmatterKeyPages(scopedRead(this.engineSql), opts); }
+ async listStaleFrontmatterKeyPages(opts: { sourceId: string; afterId: number; limit: number }) { return pagesImpl.listStaleFrontmatterKeyPages(scopedRead(this.engineSql), opts); }
+ async stripStaleFrontmatterKeys(opts: { sourceId: string; ids: number[] }) { return pagesImpl.stripStaleFrontmatterKeys(this.engineSql, opts); }
// Links
async addLink(
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 33f756b4b8..93c545a294 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -1618,6 +1618,9 @@ export class PostgresEngine implements BrainEngine {
async markPagesAttendanceBlocked(refs: Array<{ slug: string; source_id: string; revision: string }>): Promise<number> {
return pagesImpl.markPagesAttendanceBlocked(this.engineSql, refs);
}
+ async countStaleFrontmatterKeyPages(opts: { sourceIds: string[] }) { return this.withScopedReadTransaction(opts.sourceIds, undefined, tx => pagesImpl.countStaleFrontmatterKeyPages(scopedRead(this.engineSqlOn(tx)), opts)); }
+ async listStaleFrontmatterKeyPages(opts: { sourceId: string; afterId: number; limit: number }) { return this.withScopedReadTransaction(undefined, opts.sourceId, tx => pagesImpl.listStaleFrontmatterKeyPages(scopedRead(this.engineSqlOn(tx)), opts)); }
+ async stripStaleFrontmatterKeys(opts: { sourceId: string; ids: number[] }) { return pagesImpl.stripStaleFrontmatterKeys(this.engineSql, opts); }
// Links
async addLink(
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 4926fe9c9e..65d2aade17 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -25,7 +25,7 @@ import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricin
import { shellQuote, type Action } from '../agent-output.ts';
import type { RepairKindSpec } from './registry.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/frontmatter-keys.ts b/src/core/repair/frontmatter-keys.ts
new file mode 100644
index 0000000000..14f64e9b42
--- /dev/null
+++ b/src/core/repair/frontmatter-keys.ts
@@ -0,0 +1,118 @@
+/**
+ * `gbrain repair frontmatter-keys [--source <id>]` (#6454): strip the
+ * parser's reserved top-level keys (`type`, `title`, `tags`, `slug`) that
+ * older imports stored inside `pages.frontmatter`. Since `comparableFrontmatter`
+ * (markdown.ts) those keys are not drift and never render, so this sweep is
+ * hygiene, not the fix. Explicit-only and preview-bound: the preview lists the
+ * rows under a hash and `--apply --expect <hash>` sweeps exactly that set, in
+ * source-scoped batches of up to 1,000 pages, each a coordinated maintenance
+ * write (`withCoordinatedWrite`: a bare UPDATE is refused by the managed
+ * writer guard) under the page key locks of the pages it touches. The
+ * database's revision trigger advances `knowledge_revision` once per swept
+ * row, so a client holding an older revision of a swept page gets one
+ * `revision_conflict`; the preview says so. No journal admission, no file or
+ * body change, no embedding.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+import { maintenanceAttribution } from '../persistence/attribution.ts';
+import { withCoordinatedWrite } from '../persistence/context.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
+
+const BATCH = 1000;
+const PAGE = 1000;
+const SAMPLE = 20;
+
+interface StaleRow { id: number; slug: string; keys: string[] }
+interface Batch { source_id: string; selection: string[]; rows: StaleRow[] }
+type BatchItem = RepairItem & { batch: Batch; hash: string; last: boolean };
+
+export const REVISION_ADVANCE_WARNING = 'Each swept page advances its knowledge_revision once (the database revision trigger), so a client holding an '
+ + 'older revision of a swept page gets one revision_conflict and re-reads; nothing else about the page changes.';
+
+const previewCommand = (scope: RepairScope) => `gbrain repair frontmatter-keys${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;
+
+async function staleRows(engine: BrainEngine, sourceId: string): Promise<StaleRow[]> {
+ const rows: StaleRow[] = [];
+ for (let afterId = 0; ;) {
+ const page = await engine.listStaleFrontmatterKeyPages({ sourceId, afterId, limit: PAGE });
+ rows.push(...page);
+ if (page.length < PAGE) return rows;
+ afterId = page[page.length - 1].id;
+ }
+}
+
+function item(batch: Batch, index: number, hash: string, last: boolean): BatchItem {
+ const first = batch.rows[0], end = batch.rows[batch.rows.length - 1];
+ return { cursor: { phase: 0, id: index + 1 }, source_id: batch.source_id, slug: `pages#${first.id}-${end.id}`, chars: 0, action: 'strip_reserved_frontmatter_keys',
+ change: { from: `${batch.rows.length} page(s) carrying ${[...new Set(batch.rows.flatMap(row => row.keys))].sort().join(', ')}`, to: 'reserved keys removed' },
+ batch, hash, last };
+}
+
+/** Rows grouped per source into batches of at most BATCH, in id order. */
+function batches(scope: RepairScope, rowsBySource: Map<string, StaleRow[]>): Batch[] {
+ const out: Batch[] = [];
+ for (const [source_id, rows] of rowsBySource) {
+ for (let start = 0; start < rows.length; start += BATCH) out.push({ source_id, selection: scope.source_ids, rows: rows.slice(start, start + BATCH) });
+ }
+ return out;
+}
+
+export const frontmatterKeysRepair: RepairHandler = {
+ kind: 'frontmatter-keys',
+ publication: 'projection',
+ embeds: false,
+ outcomeItemsLimit: 1000,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const command = previewCommand(scope);
+ if (!opts?.apply) {
+ const rowsBySource = new Map<string, StaleRow[]>();
+ for (const sourceId of scope.source_ids) {
+ const rows = await staleRows(engine, sourceId);
+ if (rows.length) rowsBySource.set(sourceId, rows);
+ }
+ const planned = batches(scope, rowsBySource);
+ const hash = previewHash({ kind: 'frontmatter-keys-v1', brain_id: scope.brain_id, selection: scope.source_ids,
+ rows: planned.flatMap(batch => batch.rows.map(row => [batch.source_id, row.id, row.keys])) });
+ if (planned.length) await saveApprovedSet<Batch>(engine, { command: 'frontmatter-keys', hash }, planned);
+ const total = planned.reduce((sum, batch) => sum + batch.rows.length, 0);
+ const byKey: Record<string, number> = {};
+ for (const batch of planned) for (const row of batch.rows) for (const key of row.keys) byKey[key] = (byKey[key] ?? 0) + 1;
+ return { items: planned.map((batch, index) => item(batch, index, hash, index === planned.length - 1)), preview_hash: hash, residuals: {},
+ ...(total ? { warnings: [`${total} page(s) will have ${Object.entries(byKey).map(([key, n]) => `${key} (${n})`).join(', ')} removed from their stored frontmatter. ${REVISION_ADVANCE_WARNING}`] } : {}),
+ listing: planned.map(batch => ({ item: `${batch.source_id}:pages#${batch.rows[0].id}-${batch.rows[batch.rows.length - 1].id}`, class: 'strip',
+ detail: `${batch.rows.length} page(s); e.g. ${batch.rows.slice(0, 3).map(row => row.slug).join(', ')}` })),
+ details: { total, by_key: byKey, sample: planned.flatMap(batch => batch.rows.map(row => ({ source_id: batch.source_id, slug: row.slug, keys: row.keys }))).slice(0, SAMPLE) } };
+ }
+ if (!opts.expect) {
+ throw new OperationError('invalid_params', 'gbrain repair frontmatter-keys --apply sweeps only the set a preview printed.',
+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`, 'docs/guides/repair.md#frontmatter-keys');
+ }
+ const approved = await loadApprovedSet<Batch>(engine, { command: 'frontmatter-keys', hash: opts.expect, previewCommand: command });
+ if (approved.items.some(batch => JSON.stringify(batch.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);
+ const items = approved.items.map((batch, index) => item(batch, index, opts.expect!, index === approved.items.length - 1));
+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { batch, hash, last } = entry as BatchItem;
+ const stripped = await ctx.engine.transaction(async tx => {
+ const [brain] = await tx.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
+ const strip = async () => {
+ await tx.lockPageKeys(batch.rows.map(row => ({ sourceId: batch.source_id, slug: row.slug })));
+ return tx.stripStaleFrontmatterKeys({ sourceId: batch.source_id, ids: batch.rows.map(row => row.id) });
+ };
+ return brain?.enabled ? withCoordinatedWrite(tx, [batch.source_id], strip, await maintenanceAttribution(tx)) : strip();
+ });
+ if (last) await clearApprovedSet(ctx.engine, { command: 'frontmatter-keys', hash });
+ return stripped > 0 ? { applied: true, outcome: 'stripped', reason: `${stripped} of ${batch.rows.length} page(s)`, detail: { pages: stripped } }
+ : { applied: false, outcome: 'already_clean', detail: { pages: 0 } };
+ },
+ render(details) {
+ const sample = (details.sample ?? []) as Array<{ source_id: string; slug: string; keys: string[] }>;
+ const total = Number(details.total ?? 0);
+ const lines = sample.map(row => ` ${row.source_id}:${row.slug} carries ${row.keys.join(', ')}`);
+ if (total > sample.length) lines.push(` ... ${total - sample.length} more page(s) in the previewed set`);
+ return lines;
+ },
+};
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 1546882e57..3b4b0bcb84 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -60,6 +60,7 @@ import { attributionBackfillRepair } from './attribution-backfill.ts';
import { plannerStatsRepair } from './planner-stats.ts';
import { fencesRepair } from './fences.ts';
import { slugConflictsRepair } from './slug-conflicts.ts';
+import { frontmatterKeysRepair } from './frontmatter-keys.ts';
import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
import type { OperationError } from '../ops/contract.ts';
@@ -259,6 +260,13 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'Bookkeeping only (op_checkpoints); no journal admission. The preview prints a hash; --apply --expect <hash> retires exactly that set. '
+ 'A cursor with a live pending request, or one the live writer can still resume, is kept and counted.',
},
+ 'frontmatter-keys': {
+ handler: frontmatterKeysRepair, embeds: 'none', checks: ['stale_frontmatter_keys'], explicit_only: true, preview_bound: true,
+ summary: 'Strip the parser\'s reserved keys (type, title, tags, slug) that older imports stored inside pages.frontmatter (#6454). Since this release '
+ + 'those keys are not file/database drift and never render, so the sweep is hygiene: database rows only, in source-scoped coordinated batches of up '
+ + 'to 1,000 pages, no file, body or embedding change. Each swept page advances its knowledge_revision once (a client holding an older revision '
+ + 'gets one revision_conflict). Preview-bound: --apply --expect <hash> sweeps exactly the previewed set; runs only when named.',
+ },
};
export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));
diff --git a/test/engine-surface-coverage.test.ts b/test/engine-surface-coverage.test.ts
index b40b7a4293..f432f33afe 100644
--- a/test/engine-surface-coverage.test.ts
+++ b/test/engine-surface-coverage.test.ts
@@ -61,6 +61,8 @@ const INTERFACE_METHODS: readonly string[] = [
'countChunklessPagesWithContent', 'listChunklessPagesWithContent', 'deleteChunks',
// Extraction watermark
'countStalePagesForExtraction', 'listStalePagesForExtraction', 'markPagesExtractedBatch', 'markPagesAttendanceBlocked',
+ // #6454 stale reserved frontmatter keys
+ 'countStaleFrontmatterKeyPages', 'listStaleFrontmatterKeyPages', 'stripStaleFrontmatterKeys',
// Links + graph
'addLink', 'addLinksBatch', 'replaceDerivedLinks', 'replaceDerivedLinksBatch', 'removeLink', 'getLinks', 'getBacklinks', 'listLinkSources',
'findByTitleFuzzy', 'traverseGraph', 'traversePaths', 'traversePathsDetailed', 'relationalFanout', 'relationalChainHop', 'getBacklinkCounts',
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index 4c5023db2d..c21d99a241 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -195,7 +195,7 @@ for (const backend of testBackends()) {
const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };
const previews = { 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts',
'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes',
- frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans' };
+ frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys' };
// The post-upgrade banner names both findings with the kind's read-only preview.
const banner = await postUpgradeRecoveryBanner(engine, 'host');
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index d80e4ddce2..02d8a90bf1 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -1089,6 +1089,19 @@
"name": "ontology_facts_fenced",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "count": 0,
+ "docs": "docs/guides/repair.md#frontmatter-keys",
+ "repair": "frontmatter-keys",
+ "source_ids": [],
+ "sources": []
+ },
+ "message": "No stored frontmatter carries a parser-reserved key (type, title, tags, slug).",
+ "name": "stale_frontmatter_keys",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 38f6e58224..668ae9e6d4 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -1108,6 +1108,19 @@
"name": "ontology_facts_fenced",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "count": 0,
+ "docs": "docs/guides/repair.md#frontmatter-keys",
+ "repair": "frontmatter-keys",
+ "source_ids": [],
+ "sources": []
+ },
+ "message": "No stored frontmatter carries a parser-reserved key (type, title, tags, slug).",
+ "name": "stale_frontmatter_keys",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).",
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 5198d047bd..c3527b980b 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -473,6 +473,10 @@
"category": "brain",
"name": "ontology_facts_fenced"
},
+ {
+ "category": "ops",
+ "name": "stale_frontmatter_keys"
+ },
{
"category": "brain",
"name": "extraction_date_grounding"
diff --git a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json
index 9cae80d835..99db5b51d9 100644
--- a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json
+++ b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json
@@ -35,6 +35,7 @@
"countStaleChunks#signature+sourceId": {
"raw": 1
},
+ "countStaleFrontmatterKeyPages#default": {},
"countStalePagesForExtraction#attendance-blocked+sourceId": {},
"countStalePagesForExtraction#attendance-exclude": {},
"countStalePagesForExtraction#default": {},
@@ -239,6 +240,7 @@
"listStaleChunks#updated_desc+sourceId+cursor": {
"raw": 1
},
+ "listStaleFrontmatterKeyPages#default": {},
"listStalePagesForExtraction#afterPageId+versionTs+sourceId": {},
"listStalePagesForExtraction#default": {},
"listStaleTakes#default": {},
@@ -344,6 +346,7 @@
"softDeletePage#default": {},
"softDeletePage#sourceId": {},
"softDeletePages#default": {},
+ "stripStaleFrontmatterKeys#default": {},
"sumStaleChunkChars#default": {
"raw": 1
},
diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.json
index a43d472317..fbfd265c5b 100644
--- a/test/fixtures/goldens/rls-scope-inventory.json
+++ b/test/fixtures/goldens/rls-scope-inventory.json
@@ -201,6 +201,19 @@
"src-a"
]
},
+ "countStaleFrontmatterKeyPages#default": {
+ "flagOffLanes": [
+ "pool"
+ ],
+ "flagOffOpensTransaction": false,
+ "flagOn": "scoped",
+ "flagOnLanes": [
+ "tx"
+ ],
+ "flagOnScopes": [
+ "src-a"
+ ]
+ },
"countStalePagesForExtraction#attendance-blocked+sourceId": {
"flagOffLanes": [
"pool"
@@ -2198,6 +2211,19 @@
"src-a"
]
},
+ "listStaleFrontmatterKeyPages#default": {
+ "flagOffLanes": [
+ "pool"
+ ],
+ "flagOffOpensTransaction": false,
+ "flagOn": "scoped",
+ "flagOnLanes": [
+ "tx"
+ ],
+ "flagOnScopes": [
+ "src-a"
+ ]
+ },
"listStalePagesForExtraction#afterPageId+versionTs+sourceId": {
"flagOffLanes": [
"pool"
@@ -3043,6 +3069,17 @@
],
"flagOnScopes": []
},
+ "stripStaleFrontmatterKeys#default": {
+ "flagOffLanes": [
+ "pool"
+ ],
+ "flagOffOpensTransaction": false,
+ "flagOn": "unscoped",
+ "flagOnLanes": [
+ "pool"
+ ],
+ "flagOnScopes": []
+ },
"sumStaleChunkChars#default": {
"flagOffLanes": [
"pool"
@@ -3380,12 +3417,13 @@
}
},
"static": {
- "callSites": 27,
+ "callSites": 29,
"directMethods": {
"_searchKeywordCJK": 1,
"countChunklessPagesWithContent": 1,
"countKeywordPages": 1,
"countStaleChunks": 1,
+ "countStaleFrontmatterKeyPages": 1,
"countStalePagesForExtraction": 1,
"findDuplicatePage": 1,
"findDuplicatePages": 1,
@@ -3400,6 +3438,7 @@
"listPages": 1,
"listPrefixSampledPages": 1,
"listStaleChunks": 1,
+ "listStaleFrontmatterKeyPages": 1,
"listStalePagesForExtraction": 1,
"readPageSnapshot": 1,
"readPageSnapshotsBatch": 1,
@@ -3432,6 +3471,7 @@
"countChunklessPagesWithContent": "direct",
"countKeywordPages": "direct",
"countStaleChunks": "direct",
+ "countStaleFrontmatterKeyPages": "direct",
"countStalePagesForExtraction": "direct",
"countStaleTakes": "none",
"countUnconsolidatedFacts": "none",
@@ -3525,6 +3565,7 @@
"listPages": "direct",
"listPrefixSampledPages": "direct",
"listStaleChunks": "direct",
+ "listStaleFrontmatterKeyPages": "direct",
"listStalePagesForExtraction": "direct",
"listStaleTakes": "none",
"listSupersessions": "none",
@@ -3584,6 +3625,7 @@
"softDeletePage": "none",
"softDeletePages": "none",
"sql": "none",
+ "stripStaleFrontmatterKeys": "none",
"sumStaleChunkChars": "none",
"supersedeTake": "none",
"sweepContradictionCache": "none",
diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.json
index b57bbd201e..86d9f9adbd 100644
--- a/test/fixtures/goldens/sql-text/_classification.json
+++ b/test/fixtures/goldens/sql-text/_classification.json
@@ -18,7 +18,7 @@
"out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)": 5,
"out-of-scope:shared-read-enrichment (already one SQL copy in search/read-enrichment.ts)": 9,
"out-of-scope:stats-health (brain-wide aggregates)": 2,
- "pages": 35,
+ "pages": 38,
"salience": 5,
"sources": 2,
"tags": 3,
@@ -47,6 +47,7 @@
"countChunklessPagesWithContent": "chunks",
"countKeywordPages": "out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)",
"countStaleChunks": "chunks",
+ "countStaleFrontmatterKeyPages": "pages",
"countStalePagesForExtraction": "pages",
"countStaleTakes": "takes",
"countUnconsolidatedFacts": "facts",
@@ -140,6 +141,7 @@
"listPages": "pages",
"listPrefixSampledPages": "pages",
"listStaleChunks": "chunks",
+ "listStaleFrontmatterKeyPages": "pages",
"listStalePagesForExtraction": "pages",
"listStaleTakes": "takes",
"listSupersessions": "facts",
@@ -199,6 +201,7 @@
"softDeletePage": "pages",
"softDeletePages": "pages",
"sql": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)",
+ "stripStaleFrontmatterKeys": "pages",
"sumStaleChunkChars": "chunks",
"supersedeTake": "takes",
"sweepContradictionCache": "takes",
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 7cc56b8727..05c6e74984 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -2489,6 +2489,19 @@
}
},
"pages": {
+ "countStaleFrontmatterKeyPages": {
+ "default": [
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ]
+ },
"countStalePagesForExtraction": {
"attendance-blocked+sourceId": [
{
@@ -3037,6 +3050,19 @@
}
]
},
+ "listStaleFrontmatterKeyPages": {
+ "default": [
+ {
+ "paramCount": 5,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ]
+ },
"listStalePagesForExtraction": {
"afterPageId+versionTs+sourceId": [
{
@@ -3689,6 +3715,19 @@
}
]
},
+ "stripStaleFrontmatterKeys": {
+ "default": [
+ {
+ "paramCount": 4,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ]
+ },
"updatePageContextualRetrievalState": {
"default": [
{
diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json
index 2152ac5a0f..7a925afd75 100644
--- a/test/fixtures/goldens/sql-text/pages.json
+++ b/test/fixtures/goldens/sql-text/pages.json
@@ -2,6 +2,19 @@
"golden": {
"domain": "pages",
"methods": {
+ "countStaleFrontmatterKeyPages": {
+ "default": [
+ {
+ "lane": "pool",
+ "params": [
+ "array<string>",
+ "array<string>"
+ ],
+ "sql": "SELECT source_id, count(*)::bigint AS n FROM pages WHERE source_id = ANY($1::text[]) AND deleted_at IS NULL AND frontmatter ?| $2::text[] GROUP BY source_id ORDER BY source_id",
+ "textSha256": "a6aa5270504c70e330a9c23731f7f2c7f2efbf90b16c48a83e43195e537930bd"
+ }
+ ]
+ },
"countStalePagesForExtraction": {
"attendance-blocked+sourceId": [
{
@@ -641,6 +654,22 @@
}
]
},
+ "listStaleFrontmatterKeyPages": {
+ "default": [
+ {
+ "lane": "pool",
+ "params": [
+ "array<string>",
+ "string",
+ "array<string>",
+ "number",
+ "number"
+ ],
+ "sql": "SELECT id, slug, ARRAY(SELECT k FROM unnest($1::text[]) AS k WHERE frontmatter ? k ORDER BY k) AS keys FROM pages WHERE source_id = $2 AND deleted_at IS NULL AND frontmatter ?| $3::text[] AND id > $4 ORDER BY id LIMIT $5",
+ "textSha256": "3595340f4f1ae3e42ab96ec07baff1c86fa2e78cb3a5bcbf09d2e1a4dee884a8"
+ }
+ ]
+ },
"listStalePagesForExtraction": {
"afterPageId+versionTs+sourceId": [
{
@@ -1410,6 +1439,21 @@
}
]
},
+ "stripStaleFrontmatterKeys": {
+ "default": [
+ {
+ "lane": "pool",
+ "params": [
+ "array<string>",
+ "string",
+ "array<number>",
+ "array<string>"
+ ],
+ "sql": "UPDATE pages SET frontmatter = frontmatter - $1::text[] WHERE source_id = $2 AND id = ANY($3::int[]) AND deleted_at IS NULL AND frontmatter ?| $4::text[]",
+ "textSha256": "12fe54535ce3d72bb4f980079919a8550d73cb9ba93fe539176bf6dc1cd08fbd"
+ }
+ ]
+ },
"updatePageContextualRetrievalState": {
"default": [
{
diff --git a/test/frontmatter-reserved-keys-6454.test.ts b/test/frontmatter-reserved-keys-6454.test.ts
new file mode 100644
index 0000000000..fcbf53aa0e
--- /dev/null
+++ b/test/frontmatter-reserved-keys-6454.test.ts
@@ -0,0 +1,186 @@
+/**
+ * #6454: older imports stored the parser's four reserved keys (`type`,
+ * `title`, `tags`, `slug`) inside `pages.frontmatter`. A file can never carry
+ * them into the parsed frontmatter object, so for those rows the canonical
+ * file and the database copy never digest-matched and every coordinated
+ * write was refused `source_changed` (~80k pages on the reported brain).
+ *
+ * Fix: `comparableFrontmatter` strips the four top-level keys on both sides
+ * of the drift comparison (publication, reconcile, repair), and the render
+ * strips them before the slug stamp so a stale stored `type`/`title` never
+ * overrides the page columns in the published file ([R40]: that half is a
+ * rendering change for legacy rows, pinned here on its own).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import type { Page } from '../src/core/types.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { comparableFrontmatter, parseMarkdown, serializeMarkdown, serializePageToMarkdown } from '../src/core/markdown.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const logger = { info() {}, warn() {}, error() {} };
+
+const page = (overrides: Partial<Page>): Page => ({
+ id: 1, slug: 'people/alice-example', type: 'person', title: 'Alice Example', compiled_truth: '# Alice Example\n\nBody.', timeline: '',
+ frontmatter: {}, source_id: 'default', created_at: new Date(0), updated_at: new Date(0), ...overrides,
+} as Page);
+
+describe('comparableFrontmatter (#6454)', () => {
+ test('strips only the four top-level reserved keys and leaves nested user keys alone', () => {
+ const stored = { type: 'person', title: 'Old Title', tags: ['stale'], slug: 'people/other', yc_user_id: 1,
+ nested: { type: 'kept', title: 'kept', tags: ['kept'], slug: 'kept' }, trust_tier: 'agent_written' };
+ expect(comparableFrontmatter(stored)).toEqual({ yc_user_id: 1, nested: { type: 'kept', title: 'kept', tags: ['kept'], slug: 'kept' }, trust_tier: 'agent_written' });
+ expect(stored.type).toBe('person');
+ expect(comparableFrontmatter(null)).toEqual({});
+ expect(comparableFrontmatter(undefined)).toEqual({});
+ });
+
+ test('the parser never produces a reserved key, so a clean frontmatter compares equal to itself', () => {
+ const parsed = parseMarkdown('---\ntype: person\ntitle: Alice\ntags: [a]\nslug: people/alice\nyc_user_id: 1\n---\n# Alice\n', 'people/alice.md');
+ expect(parsed.frontmatter).toEqual({ yc_user_id: 1 });
+ expect(comparableFrontmatter(parsed.frontmatter)).toEqual(parsed.frontmatter);
+ });
+});
+
+describe('serializePageToMarkdown renders the columns, never a stale stored reserved key ([R40])', () => {
+ test('a legacy row whose stored type/title disagree with the columns renders the columns', () => {
+ const rendered = serializePageToMarkdown(page({ type: 'note', title: 'Column Title', frontmatter: { type: 'person', title: 'Stored Title', yc_user_id: 1 } }), []);
+ const parsed = parseMarkdown(rendered, 'people/alice-example.md');
+ expect(parsed.type).toBe('note');
+ expect(parsed.title).toBe('Column Title');
+ expect(parsed.frontmatter).toEqual({ yc_user_id: 1 });
+ expect(rendered).not.toContain('Stored Title');
+ expect(rendered).not.toContain('type: person');
+ });
+
+ test('stored tags with an empty tag list no longer render; a non-empty tag list renders only the column tags', () => {
+ const empty = serializePageToMarkdown(page({ frontmatter: { tags: ['stale'] } }), []);
+ expect(parseMarkdown(empty, 'people/alice-example.md').tags).toEqual([]);
+ expect(empty).not.toContain('stale');
+ const tagged = serializePageToMarkdown(page({ frontmatter: { tags: ['stale'] } }), ['live']);
+ expect(parseMarkdown(tagged, 'people/alice-example.md').tags).toEqual(['live']);
+ expect(tagged).not.toContain('stale');
+ });
+
+ test('a clean page renders byte-identically to the primitive serializer (digest-neutral), nested keys included', () => {
+ const frontmatter = { yc_user_id: 1, nested: { type: 'kept', title: 'kept' }, validate: false };
+ const clean = page({ frontmatter });
+ expect(serializePageToMarkdown(clean, ['x'])).toBe(serializeMarkdown(frontmatter, clean.compiled_truth, '', { type: 'person', title: 'Alice Example', tags: ['x'] }));
+ });
+
+ test('the doubled-hyphen slug stamp (#5966) survives the strip, and a stored slug naming another page is dropped', () => {
+ const doubled = serializePageToMarkdown(page({ slug: 'people/a--b', frontmatter: { slug: 'people/elsewhere' } }), []);
+ expect(doubled).toMatch(/^slug: people\/a--b$/m);
+ const plain = serializePageToMarkdown(page({ frontmatter: { slug: 'people/elsewhere' } }), []);
+ expect(plain).not.toMatch(/^slug:/m);
+ expect(parseMarkdown(plain, 'people/alice-example.md').slug).toBe('people/alice-example');
+ });
+});
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-6454-db-'));
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });
+});
+
+/** The reporter's rows: the parser-stripped keys stored in `pages.frontmatter` by an older import (guard lifted for the seed). */
+export async function seedStaleReservedKeys(engine: BrainEngine, sourceId: string, slug: string, keys: Record<string, unknown>): Promise<void> {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try {
+ await engine.executeRaw('UPDATE pages SET frontmatter = frontmatter || $3::text::jsonb WHERE source_id=$1 AND slug=$2', [sourceId, slug, JSON.stringify(keys)]);
+ } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+}
+
+test('a page whose stored frontmatter carries stale type/title commits an unchanged-body write; real drift still refuses', async () => {
+ for (const engine of engines) await staleKeysCase(engine);
+}, 240_000);
+
+async function staleKeysCase(engine: BrainEngine): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-6454-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const sourceId = `s6454-${randomUUID().slice(0, 8)}`;
+ const slug = 'people/example-person';
+ const content = '---\ntype: person\ntitle: Example Person\ntags: [founder]\n---\n# Example Person\n\nAn observation.\n';
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;
+ const put = (params: Record<string, unknown>) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), ...params } })
+ .then(receipt => receipt as { state: string }, (error: { code?: string }) => ({ state: 'refused', code: error.code }));
+ expect((await put({ content })).state).toBe('committed');
+ const file = join(root, 'people', 'example-person.md');
+ const published = readFileSync(file, 'utf8');
+ const revision = async () => (await engine.readPageSnapshot(slug, { sourceId }))!.revision;
+
+ // The reporter's rows: stored `type`/`title` the file can never carry (and that disagree with nothing yet).
+ await seedStaleReservedKeys(engine, sourceId, slug, { type: 'person', title: 'Example Person' });
+ // Before the fix: source_changed / file_database_drift although the file is exactly the last publication.
+ expect(await put({ content, expected_revision: await revision() })).toMatchObject({ state: 'committed' });
+ const [row] = await engine.executeRaw<{ frontmatter: Record<string, unknown> }>('SELECT frontmatter FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ expect(Object.keys(row.frontmatter)).not.toContain('type');
+ expect(Object.keys(row.frontmatter)).not.toContain('title');
+
+ // Stale keys that disagree with the columns: still not drift, and the published file renders the columns ([R40]).
+ await seedStaleReservedKeys(engine, sourceId, slug, { type: 'note', title: 'A Title The Columns Never Had', tags: ['stale-tag'], slug: 'people/elsewhere' });
+ const edited = content.replace('An observation.', 'An observation, edited through put_page.');
+ expect(await put({ content: edited, expected_revision: await revision() })).toMatchObject({ state: 'committed' });
+ const rendered = readFileSync(file, 'utf8');
+ expect(rendered).toContain('type: person');
+ expect(rendered).toContain('title: Example Person');
+ expect(rendered).not.toContain('A Title The Columns Never Had');
+ expect(rendered).not.toContain('stale-tag');
+ expect(rendered).not.toMatch(/^slug:/m);
+ expect(parseMarkdown(rendered, 'people/example-person.md').tags).toEqual(['founder']);
+
+ // Real drift must still refuse, with the file and the row left as they are (the fix widens nothing).
+ const [before] = await engine.executeRaw<{ frontmatter: Record<string, unknown>; compiled_truth: string; title: string }>(
+ 'SELECT frontmatter, compiled_truth, title FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ for (const drift of [
+ rendered.replace('An observation, edited through put_page.', 'An observation edited by hand in the file.'),
+ rendered.replace('title: Example Person', 'title: Renamed In The File'),
+ rendered.replace('tags:\n - founder', 'tags:\n - founder\n - hand-added'),
+ ]) {
+ expect(drift).not.toBe(rendered);
+ writeFileSync(file, drift);
+ expect(await put({ content: edited, expected_revision: await revision() })).toMatchObject({ state: 'refused', code: 'source_changed' });
+ expect(readFileSync(file, 'utf8')).toBe(drift);
+ const [after] = await engine.executeRaw<typeof before>('SELECT frontmatter, compiled_truth, title FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ expect(after).toEqual(before);
+ }
+ writeFileSync(file, rendered);
+ expect(await put({ content: edited, expected_revision: await revision() })).toMatchObject({ state: 'committed' });
+ expect(published).not.toBe(rendered);
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
diff --git a/test/helpers/engine-sql-rollback-cases.ts b/test/helpers/engine-sql-rollback-cases.ts
index ee19924be6..a7ab6c186d 100644
--- a/test/helpers/engine-sql-rollback-cases.ts
+++ b/test/helpers/engine-sql-rollback-cases.ts
@@ -274,6 +274,25 @@ export const ROLLBACK_CASES: RollbackCase[] = [
return rows[0] ? { body: rows[0].body, deleted: rows[0].deleted } : null;
},
},
+ {
+ domain: 'pages (stale reserved frontmatter keys, #6454)',
+ async seed(engine) {
+ await seedPage(engine);
+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter || '{"type":"legacy","title":"Stored Title"}'::jsonb WHERE slug = $1 AND source_id = 'default'`, [SLUG]);
+ },
+ async write(tx) {
+ const [row] = await tx.listStaleFrontmatterKeyPages({ sourceId: 'default', afterId: 0, limit: 10 });
+ expect(row).toMatchObject({ slug: SLUG, keys: ['title', 'type'] });
+ expect(await tx.countStaleFrontmatterKeyPages({ sourceIds: ['default'] })).toEqual([{ source_id: 'default', n: 1 }]);
+ expect(await tx.stripStaleFrontmatterKeys({ sourceId: 'default', ids: [row.id] })).toBe(1);
+ expect(await tx.countStaleFrontmatterKeyPages({ sourceIds: ['default'] })).toEqual([]);
+ },
+ async observe(engine) {
+ const rows = await engine.executeRaw<{ stale: boolean }>(
+ `SELECT frontmatter ?| ARRAY['type','title','tags','slug'] AS stale FROM pages WHERE slug = $1 AND source_id = 'default'`, [SLUG]);
+ return rows[0]?.stale ?? null;
+ },
+ },
{
domain: 'pages (attendance marker)',
async seed(engine) {
diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.ts
index e399342b03..86426aa06c 100644
--- a/test/helpers/postgres-engine-sql-cases.ts
+++ b/test/helpers/postgres-engine-sql-cases.ts
@@ -90,6 +90,7 @@ export const DOMAIN_OF: Record<string, string> = {
'resolveSlugWithAlias': 'pages', 'resolveSlugWithAliasDetailed': 'pages', 'setPageAliases': 'pages',
'countStalePagesForExtraction': 'pages', 'listStalePagesForExtraction': 'pages', 'markPagesExtractedBatch': 'pages',
'markPagesAttendanceBlocked': 'pages',
+ 'countStaleFrontmatterKeyPages': 'pages', 'listStaleFrontmatterKeyPages': 'pages', 'stripStaleFrontmatterKeys': 'pages',
// links
'addLink': 'links', 'addLinksBatch': 'links', 'replaceDerivedLinks': 'links', 'replaceDerivedLinksBatch': 'links', 'removeLinksByPagesAndSource': 'links',
'removeLink': 'links', 'getLinks': 'links', 'getBacklinks': 'links', 'listLinkSources': 'links',
@@ -392,6 +393,9 @@ export const SQL_CASES: SqlCase[] = [
]),
...variants('markPagesExtractedBatch', [['default', (e) => e.markPagesExtractedBatch([{ slug: SLUG, source_id: SRC }], '2026-01-01T00:00:00Z')]]),
...variants('markPagesAttendanceBlocked', [['default', (e) => e.markPagesAttendanceBlocked([{ slug: SLUG, source_id: SRC, revision: '00000000-0000-4000-8000-000000000001' }])]]),
+ ...variants('countStaleFrontmatterKeyPages', [['default', (e) => e.countStaleFrontmatterKeyPages({ sourceIds: [SRC] })]]),
+ ...variants('listStaleFrontmatterKeyPages', [['default', (e) => e.listStaleFrontmatterKeyPages({ sourceId: SRC, afterId: 0, limit: 10 })]]),
+ ...variants('stripStaleFrontmatterKeys', [['default', (e) => e.stripStaleFrontmatterKeys({ sourceId: SRC, ids: [1] })]]),
// ── links ──
...variants('addLink', [
diff --git a/test/postgres-rls-scope-inventory.test.ts b/test/postgres-rls-scope-inventory.test.ts
index 63a25f78fb..583f17ed56 100644
--- a/test/postgres-rls-scope-inventory.test.ts
+++ b/test/postgres-rls-scope-inventory.test.ts
@@ -154,8 +154,8 @@ describe('EO4 RLS scope inventory (master)', () => {
const scoping = astScoping(capture.ast);
const callSites = Object.values(capture.ast).reduce((a, m) => a + m.directCallSites, 0);
- expect(callSites).toBe(27);
- expect(Object.values(capture.ast).filter((m) => m.directCallSites > 0).length).toBe(27);
+ expect(callSites).toBe(29);
+ expect(Object.values(capture.ast).filter((m) => m.directCallSites > 0).length).toBe(29);
const byMethod = new Map<string, RuntimeObservation[]>();
for (const [key, obs] of Object.entries(capture.runtime)) {
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 909aa7570f..e9ec45dda4 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -32,6 +32,7 @@ test/extract-endpoint-revision.serial.test.ts
test/extract-entities-managed.test.ts
test/extract-timeline-from-meetings-managed.test.ts
test/fence-repair-receipts.test.ts
+test/frontmatter-reserved-keys-6454.test.ts
test/graduation-copy.test.ts
test/graduation-digest.test.ts
test/graduation-drain.test.ts
@@ -111,6 +112,7 @@ test/repair-embedding-effects.test.ts
test/repair-failed-writes-conflict-6429.test.ts
test/repair-failed-writes-drift-w411.test.ts
test/repair-fences.test.ts
+test/repair-frontmatter-keys-sweep-6454.test.ts
test/repair-frontmatter.test.ts
test/scripts/test-stress-postgres.test.ts
test/shared-content-freshness.test.ts
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 4bb7fce3c2..fc9e344573 100644
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { withEnv } from './helpers/with-env.ts';
-const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans'];
+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));
diff --git a/test/repair-frontmatter-keys-sweep-6454.test.ts b/test/repair-frontmatter-keys-sweep-6454.test.ts
new file mode 100644
index 0000000000..1dced2912e
--- /dev/null
+++ b/test/repair-frontmatter-keys-sweep-6454.test.ts
@@ -0,0 +1,155 @@
+/**
+ * #6454 [R16]: the consented, source-scoped, preview-bound
+ * `gbrain repair frontmatter-keys` sweep and its doctor check
+ * `stale_frontmatter_keys`. The sweep is hygiene (the compare-side fix makes
+ * the stored keys inert); it runs as a coordinated maintenance write under
+ * the pages' key locks because the managed writer guard refuses a bare
+ * `UPDATE pages`, and its preview states that every swept row advances its
+ * knowledge_revision once.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { repairRunner, repairSpec } from '../src/core/repair/registry.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { REVISION_ADVANCE_WARNING } from '../src/core/repair/frontmatter-keys.ts';
+import { staleFrontmatterKeysCheck } from '../src/commands/doctor/checks/frontmatter-keys.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-sweep-6454-db-'));
+const logger = { info() {}, warn() {}, error() {} };
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });
+});
+
+test('frontmatter-keys is explicit-only and preview-bound, clears stale_frontmatter_keys', () => {
+ expect(repairSpec('frontmatter-keys')).toMatchObject({ explicit_only: true, preview_bound: true, checks: ['stale_frontmatter_keys'], embeds: 'none' });
+});
+
+test('the sweep previews, applies under the coordinator per source, advances one revision per swept page and leaves the other source alone', async () => {
+ for (const engine of engines) await sweepCase(engine);
+}, 240_000);
+
+const STALE = { type: 'person', title: 'Stored Title', tags: ['stale'] };
+
+async function sweepCase(engine: BrainEngine): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-sweep-6454-'));
+ const roots = { a: join(dir, 'a'), b: join(dir, 'b') }; mkdirSync(roots.a); mkdirSync(roots.b);
+ const sources = { a: `sweep-a-${randomUUID().slice(0, 8)}`, b: `sweep-b-${randomUUID().slice(0, 8)}` };
+ const slugs = ['people/one-example', 'people/two-example', 'people/three-example'];
+ const frontmatterOf = async (sourceId: string, slug: string) => (await engine.executeRaw<{ frontmatter: Record<string, unknown> }>(
+ 'SELECT frontmatter FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0].frontmatter;
+ const revisionOf = async (sourceId: string, slug: string) => (await engine.readPageSnapshot(slug, { sourceId }))!.revision;
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ for (const key of ['a', 'b'] as const) await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sources[key], roots[key]]);
+ await engine.setConfig('sync.write_through', 'true');
+ for (const key of ['a', 'b'] as const) await claimWorktree(engine, sources[key], roots[key]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const ctxFor = (sourceId: string) => ({ engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext);
+ for (const key of ['a', 'b'] as const) for (const slug of slugs) {
+ await submitPageMutation(ctxFor(sources[key]), { operation: 'put_page', params: { slug, request_id: randomUUID(),
+ content: `---\ntype: person\ntitle: ${slug}\n---\n# ${slug}\n\nBody.\n` } });
+ }
+ // The reporter's rows in both sources (guard lifted for the seed, as an older import wrote them); one page in A is clean.
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter || $2::text::jsonb WHERE source_id = ANY($1::text[]) AND slug <> 'people/three-example'`,
+ [[sources.a, sources.b], JSON.stringify(STALE)]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const filesBefore = Object.fromEntries(slugs.map(slug => [slug, readFileSync(join(roots.a, `${slug}.md`), 'utf8')]));
+
+ // Forced negative: the bare UPDATE the sweep must not be is refused by the managed writer guard, row unchanged.
+ await expect(engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter - 'type' WHERE source_id=$1 AND slug=$2`, [sources.a, slugs[0]]))
+ .rejects.toThrow(/writer_coordinator_required/);
+ expect(await frontmatterOf(sources.a, slugs[0])).toMatchObject(STALE);
+
+ // Doctor counts per source and names the preview.
+ const warn = await staleFrontmatterKeysCheck(engine, [sources.a, sources.b]);
+ expect(warn.status).toBe('warn');
+ expect(warn.details).toMatchObject({ count: 4, sources: [{ source_id: sources.a, n: 2 }, { source_id: sources.b, n: 2 }], repair: 'frontmatter-keys' });
+ expect(warn.message).toContain(`gbrain repair frontmatter-keys --source ${sources.a}`);
+ expect(warn.message).toContain('knowledge_revision');
+
+ // Preview: writes nothing, reports the rows and the revision advance, prints the hash.
+ const revisionsBefore = Object.fromEntries(slugs.map(slug => [slug, null as string | null]));
+ for (const slug of slugs) revisionsBefore[slug] = await revisionOf(sources.a, slug);
+ const scope = await resolveRepairScope(engine, sources.a);
+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('frontmatter-keys', scope, { explicit: true, sourceFlag: sources.a });
+ expect(preview.affected).toBe(1);
+ expect(preview.warnings?.[0]).toContain('2 page(s) will have tags (2), title (2), type (2) removed');
+ expect(preview.warnings?.[0]).toContain(REVISION_ADVANCE_WARNING);
+ expect(preview.listing).toEqual([{ item: expect.stringMatching(new RegExp(`^${sources.a}:pages#\\d+-\\d+$`)), class: 'strip', detail: expect.stringContaining('2 page(s)') }]);
+ expect(preview.details).toMatchObject({ total: 2, by_key: { type: 2, title: 2, tags: 2 } });
+ expect(preview.cost).toMatchObject({ lifetime_ids: 0, receipt_bytes: 0, embedding_pages: 0 });
+ expect(preview.apply_command).toBe(`gbrain repair frontmatter-keys --source ${sources.a} --apply --expect ${preview.preview_hash}`);
+ for (const slug of slugs) expect(await revisionOf(sources.a, slug)).toBe(revisionsBefore[slug]!);
+ expect(await frontmatterOf(sources.a, slugs[0])).toMatchObject(STALE);
+
+ // --apply without --expect is refused; a hash for another selection is preview_changed.
+ await expect((await repairRunner(engine, { apply: true, logger })).run('frontmatter-keys', scope, { explicit: true, sourceFlag: sources.a }))
+ .rejects.toMatchObject({ code: 'invalid_params' });
+ const scopeB = await resolveRepairScope(engine, sources.b);
+ await expect((await repairRunner(engine, { apply: true, logger })).run('frontmatter-keys', scopeB, { explicit: true, sourceFlag: sources.b, expect: preview.preview_hash }))
+ .rejects.toMatchObject({ code: 'preview_changed' });
+
+ // A client read the page before the sweep and holds its revision.
+ const heldRevision = revisionsBefore[slugs[0]]!;
+ const applied = await (await repairRunner(engine, { apply: true, logger })).run('frontmatter-keys', scope, { explicit: true, sourceFlag: sources.a, expect: preview.preview_hash });
+ expect(applied).toMatchObject({ applied: 1, skipped: 0, complete: true, outcomes: { stripped: 1 } });
+ for (const slug of slugs.slice(0, 2)) {
+ const frontmatter = await frontmatterOf(sources.a, slug);
+ for (const key of ['type', 'title', 'tags', 'slug']) expect(Object.hasOwn(frontmatter, key)).toBe(false);
+ expect(frontmatter).toMatchObject({ source_kind: 'put_page' });
+ expect(await revisionOf(sources.a, slug)).not.toBe(revisionsBefore[slug]!);
+ }
+ // The clean page in A kept its revision; the files are untouched (database rows only); source B is untouched.
+ expect(await revisionOf(sources.a, slugs[2])).toBe(revisionsBefore[slugs[2]]!);
+ for (const slug of slugs) expect(readFileSync(join(roots.a, `${slug}.md`), 'utf8')).toBe(filesBefore[slug]);
+ for (const slug of slugs.slice(0, 2)) expect(await frontmatterOf(sources.b, slug)).toMatchObject(STALE);
+ expect(await engine.countStaleFrontmatterKeyPages({ sourceIds: [sources.a, sources.b] })).toEqual([{ source_id: sources.b, n: 2 }]);
+ expect((await staleFrontmatterKeysCheck(engine, [sources.a])).status).toBe('ok');
+
+ // Exactly one revision_conflict for the held revision; the re-read revision commits.
+ const put = (expected: string) => submitPageMutation(ctxFor(sources.a), { operation: 'put_page', params: { slug: slugs[0], request_id: randomUUID(), expected_revision: expected,
+ content: `---\ntype: person\ntitle: ${slugs[0]}\n---\n# ${slugs[0]}\n\nBody, edited after the sweep.\n` } })
+ .then(receipt => (receipt as { state: string }).state, (error: { code?: string }) => error.code);
+ expect(await put(heldRevision)).toBe('revision_conflict');
+ expect(await put(await revisionOf(sources.a, slugs[0]))).toBe('committed');
+
+ // A second preview finds nothing in A; applying the stale hash again is preview_changed (the set was cleared).
+ const again = await (await repairRunner(engine, { apply: false, logger })).run('frontmatter-keys', scope, { explicit: true, sourceFlag: sources.a });
+ expect(again.affected).toBe(0);
+ await expect((await repairRunner(engine, { apply: true, logger })).run('frontmatter-keys', scope, { explicit: true, sourceFlag: sources.a, expect: preview.preview_hash }))
+ .rejects.toMatchObject({ code: 'preview_changed' });
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(dir, { recursive: true, force: true });
+ }
+}