Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

W1 lane B: renames, phantom merge and owner decisions record belief events (probes 4, 19, 29); ontology rows are database-only subjects

garrytan531c6c42591d
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 3d9c56dc28..da6700a199 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -17,7 +17,7 @@ src/core/cycle.ts 3314 ratchet +2 System One v1 S9: extract_facts phase tail run
src/core/cycle/synthesize.ts 3224 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); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts
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 2822 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); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822
-src/core/import-file.ts 2062 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); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062
+src/core/import-file.ts 2063 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); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +1 W1 lane B: the import identity move runs in a belief batch (maintenanceBeliefTransaction in belief/writers.ts)
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 3065 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); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports
diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.ts
index a9ca0e2fb4..b0dfe5f465 100644
--- a/src/commands/sync/holds.ts
+++ b/src/commands/sync/holds.ts
@@ -22,7 +22,7 @@ import { importSizeLimit, contentRefusalFromReceipt, isContentRefusal, type Cont
import { slugConflictHoldMessage, type ImportResult } from '../../core/import-file.ts';
import { classifyImportHold, parseMarkdown } from '../../core/markdown.ts';
import { readSourceFileSync } from '../../core/minions/source-filesystem.ts';
-import { maintenanceTransaction } from '../../core/persistence/attribution.ts';
+import { maintenanceBeliefTransaction } from '../../core/belief/writers.ts';
import type { SyncRename } from '../../core/persistence/sync-discovery.ts';
import {
addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, gitHoldItem, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds,
@@ -353,8 +353,9 @@ export async function moveHeldRenames(engine: BrainEngine, holds: LegacyHolds |
continue;
}
try {
- await maintenanceTransaction(engine, async tx => {
- if (await tx.updateSlug(origin.slug, resolveSlugForPath(record.path), { sourceId: holds.sourceId }) === 0) return;
+ const slug = resolveSlugForPath(record.path);
+ await maintenanceBeliefTransaction(engine, { sourceId: holds.sourceId, slugs: [origin.slug, slug], op: 'sync_rename' }, async tx => {
+ if (await tx.updateSlug(origin.slug, slug, { sourceId: holds.sourceId }) === 0) return;
await tx.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2 AND source_id=$3', [record.path, origin.pageId, holds.sourceId]);
});
} catch { /* the walk imports the file as an ordinary add; the old page stays until a full walk proves it gone */ }
diff --git a/src/commands/sync/rename-collision.ts b/src/commands/sync/rename-collision.ts
index 170ca95994..0d4c3f251d 100644
--- a/src/commands/sync/rename-collision.ts
+++ b/src/commands/sync/rename-collision.ts
@@ -15,6 +15,9 @@
import type { BrainEngine } from '../../core/engine.ts';
import { moveSlugBindings } from '../../core/page-state/rename-alias.ts';
import { maintenanceTransaction } from '../../core/persistence/attribution.ts';
+import { randomUUID } from 'node:crypto';
+import { lockedBeliefBatch } from '../../core/belief/writers.ts';
+import { markBeliefCommits } from '../../core/belief/append.ts';
export type RenameOutcome = 'renamed' | 'noop' | 'live_destination';
@@ -31,13 +34,20 @@ export function purgedSlug(slug: string, pageId: number): string {
export async function renamePageOntoSlug(engine: BrainEngine, input: { sourceId: string; oldSlug: string; newSlug: string; to: string }): Promise<RenameOutcome> {
const { sourceId, oldSlug, newSlug, to } = input;
- const move = async (tx: BrainEngine) => {
+ const publicationId = randomUUID();
+ const report = { appended: 0 };
+ // W1 #6783 §3: the moved row keeps its id, so its batch pairs both sides into one page.renamed on the same lifetime.
+ const move = (tx: BrainEngine) => lockedBeliefBatch(tx, { sourceId, slugs: [oldSlug, newSlug], publicationId, op: 'sync_rename', remote: false, report }, async () => {
const moved = await tx.updateSlug(oldSlug, newSlug, { sourceId });
if (moved > 0) await tx.executeRaw('UPDATE pages SET source_path = $1 WHERE source_id = $2 AND slug = $3', [to, sourceId, newSlug]);
return moved;
+ });
+ const recorded = async <T>(outcome: T) => {
+ if (report.appended) await markBeliefCommits(engine, [publicationId]).catch(() => undefined);
+ return outcome;
};
try {
- return (await maintenanceTransaction(engine, move)) > 0 ? 'renamed' : 'noop';
+ return recorded((await maintenanceTransaction(engine, move)) > 0 ? 'renamed' : 'noop');
} catch (error) {
if (!isUniqueViolation(error)) throw error;
const [destination] = await engine.executeRaw<{ id: number | string; tombstone: boolean }>(
@@ -47,14 +57,15 @@ export async function renamePageOntoSlug(engine: BrainEngine, input: { sourceId:
const tombstoneId = Number(destination.id);
const nothingToMove = Symbol('nothing to move');
try {
- return await maintenanceTransaction(engine, async tx => {
+ return await recorded(await maintenanceTransaction(engine, async tx => {
+ await tx.lockPageKeys([{ sourceId, slug: oldSlug }, { sourceId, slug: newSlug }]);
const rekeyed = await tx.executeRaw<{ id: number }>(
'UPDATE pages SET slug = $1 WHERE id = $2 AND source_id = $3 AND deleted_at IS NOT NULL RETURNING id', [purgedSlug(newSlug, tombstoneId), tombstoneId, sourceId]);
if (!rekeyed.length) return 'live_destination' as const;
await moveSlugBindings(tx, sourceId, newSlug, purgedSlug(newSlug, tombstoneId));
if (await move(tx) === 0) throw nothingToMove;
return 'renamed' as const;
- });
+ }));
} catch (merge) {
if (merge === nothingToMove) return 'noop';
throw merge;
diff --git a/src/core/belief/identity.ts b/src/core/belief/identity.ts
index ae2a635ab5..073c9c49c9 100644
--- a/src/core/belief/identity.ts
+++ b/src/core/belief/identity.ts
@@ -11,6 +11,7 @@
*/
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
+import { readManagedMode } from '../persistence/managed-mode.ts';
import { assertHeldPageKeys } from '../page-state/guards.ts';
import { appendBeliefEvents } from './append.ts';
import { pageKey } from './keys.ts';
@@ -41,7 +42,7 @@ export async function recordFallbackRename(tx: BrainEngine, input: { sourceId: s
const appended = await appendBeliefEvents(tx, [{ sourceId: input.sourceId, incarnation: source.incarnation, lifetime, slug: input.newSlug, stream: input.newSlug,
subjectKind: 'page', subjectKey: pageKey(lifetime), eventType: 'page.renamed', trustTier: page?.trust_tier || 'unknown',
visibility: visible ? 'world' : 'private', value: { old_slug: input.staleSlug, new_slug: input.newSlug, ...(absorbed && absorbed !== lifetime ? { absorbed_lifetime: absorbed } : {}) },
- stateHash: hash, cause: { op: 'rename_fallback' } }], { publicationId, origin: source.managed ? 'live' : 'unmanaged', purgesPossible: source.purgesPossible });
+ stateHash: hash, cause: { op: 'rename_fallback' } }], { publicationId, origin: await readManagedMode(tx) ? 'live' : 'unmanaged', purgesPossible: source.purgesPossible });
return appended ? publicationId : null;
}
diff --git a/src/core/belief/retier.ts b/src/core/belief/retier.ts
index 5d28455ccd..557c9b7dbf 100644
--- a/src/core/belief/retier.ts
+++ b/src/core/belief/retier.ts
@@ -16,6 +16,7 @@
*/
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
+import { readManagedMode } from '../persistence/managed-mode.ts';
import { appendBeliefEvents, type BeliefEventDraft } from './append.ts';
import { eventKeyHex, pageKey, slugRef } from './keys.ts';
import { coverageActive, currentBeliefBatch, readLedgerSource, stateHashOf } from './ledger.ts';
@@ -87,7 +88,7 @@ export async function appendRetierEvents(tx: BrainEngine, rows: readonly RetierR
for (const sourceId of new Set(resolved.map(r => r.sourceId))) {
const source = (await readLedgerSource(tx, sourceId))!;
appended += await appendBeliefEvents(tx, resolved.filter(r => r.sourceId === sourceId).map(r => draftOf(r, cause)),
- { publicationId: pub, origin: source.managed ? 'live' : 'unmanaged', purgesPossible: source.purgesPossible });
+ { publicationId: pub, origin: await readManagedMode(tx) ? 'live' : 'unmanaged', purgesPossible: source.purgesPossible });
}
return appended ? pub : null;
}
@@ -117,7 +118,7 @@ export async function appendBulkRetier(tx: BrainEngine, rows: readonly RetierRow
cause: { op, manifest: true } };
return { draft, members };
});
- appended += await appendBeliefEvents(tx, summaries.map(s => s.draft), { publicationId, origin: source.managed ? 'live' : 'unmanaged', purgesPossible: source.purgesPossible });
+ appended += await appendBeliefEvents(tx, summaries.map(s => s.draft), { publicationId, origin: await readManagedMode(tx) ? 'live' : 'unmanaged', purgesPossible: source.purgesPossible });
const manifest = summaries.flatMap(({ draft, members }) => members.map(m => ({ event_key: eventKeyHex(publicationId, draft.subjectKey, draft.eventType),
subject_kind: m.kind, subject_key: m.key, from_tier: m.row.from, to_tier: m.row.to })));
await tx.executeRaw(`INSERT INTO belief_retier_manifest (summary_event, source_id, subject_kind, subject_key, from_tier, to_tier)
diff --git a/src/core/belief/writers.ts b/src/core/belief/writers.ts
index d851074baa..b56e7d7c3a 100644
--- a/src/core/belief/writers.ts
+++ b/src/core/belief/writers.ts
@@ -6,7 +6,10 @@
* (so the batch's reads and appends happen under them), runs its writes in a
* belief batch and writes the commit mark after commit.
*/
+import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
+import { maintenanceAttribution } from '../persistence/attribution.ts';
+import { withWriteAttribution } from '../persistence/context.ts';
import { validateSlug } from '../utils.ts';
import { normalizeDimension } from '../chronicle/ontology.ts';
import { markBeliefCommits } from './append.ts';
@@ -67,3 +70,10 @@ export async function beliefTransaction<T>(engine: BrainEngine, opts: Omit<Belie
if (report.appended) await markBeliefCommits(engine, [opts.publicationId]).catch(() => undefined);
return result;
}
+
+/** A maintenance transaction (sync or import housekeeping) whose page writes the ledger records, e.g. a cheap rename that keeps the row. */
+export async function maintenanceBeliefTransaction<T>(engine: BrainEngine, opts: { sourceId: string; slugs: readonly string[]; op: string },
+ fn: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ const attribution = await maintenanceAttribution(engine);
+ return beliefTransaction(engine, { ...opts, publicationId: randomUUID(), remote: false }, fn, (tx, run) => withWriteAttribution(tx, attribution, run));
+}
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 79511499d3..a56332a284 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -1,5 +1,6 @@
import { assertUnmanagedCanonicalWriter } from './persistence/maintenance.ts';
import { suffixedFrontmatterSlugHold } from './persistence/suffixed-slug.ts';
+import { maintenanceBeliefTransaction } from './belief/writers.ts';
import { maintenanceTransaction, ownerSourceGateInput, suppliedTrustMarkerView, trustMarkerChanged, writeTrustOfGate } from './persistence/attribution.ts';
import { assertImportBase, sameCanonicalImport, sameContentAnyKeyOrder } from './page-state/import-guard.ts';
import { stabilizeSafetyAssessments } from './persistence/reconcile-safety.ts';
@@ -575,7 +576,7 @@ export async function importFromContent(
body: { title: parsed.title, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline || '' },
});
if (identity.kind === 'move' && !existing && !opts.prepare
- && await maintenanceTransaction(engine, tx => tx.updateSlug(identity.dupSlug, slug, { sourceId: sourceId ?? 'default' })) > 0) {
+ && await maintenanceBeliefTransaction(engine, { sourceId: sourceId ?? 'default', slugs: [identity.dupSlug, slug], op: 'import_move' }, tx => tx.updateSlug(identity.dupSlug, slug, { sourceId: sourceId ?? 'default' })) > 0) {
process.stderr.write(
`[import] ${opts.sourcePath} carries frontmatter.id=${fmIdStr} from moved file ${identity.dupSourcePath}; ` +
`renamed ${identity.dupSlug} -> ${slug} in source ${sourceId ?? 'default'}.\n`
diff --git a/test/belief-ledger-identity.test.ts b/test/belief-ledger-identity.test.ts
new file mode 100644
index 0000000000..1c6e900813
--- /dev/null
+++ b/test/belief-ledger-identity.test.ts
@@ -0,0 +1,258 @@
+/**
+ * Belief ledger identity probes (docs/designs/BELIEF_LEDGER.md section 3 and
+ * section 11: 4, 19, 29). Renames keep the page lifetime and append one
+ * `page.renamed`; replay resolves the slug a lifetime had at a time; a
+ * phantom merge transfers assertions instead of renaming, and a crash between
+ * its two requests leaves both pages live; a renamed link endpoint changes no
+ * key, a reused slug starts a new lifetime and a database-only fact whose page
+ * appears later is adopted. Each runs on PGLite and on Postgres when
+ * DATABASE_URL is set, and each has a forced probe: a deliberately broken
+ * emitter that must make the assertion fail.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/ops/contract.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 { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { renamePageOntoSlug } from '../src/commands/sync/rename-collision.ts';
+import { carryRenameIdentity } from '../src/commands/sync/renames.ts';
+import { enableBeliefLedger } from '../src/core/belief/coverage.ts';
+import { lifetimeAtSlug, lifetimeSlugAt } from '../src/core/belief/identity.ts';
+import { currentStateHash } from '../src/core/belief/ledger.ts';
+import { lifetimeRef, pageKey } from '../src/core/belief/keys.ts';
+import { __setBeliefEmitterFaultForTests, type BeliefEventDraft } from '../src/core/belief/append.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { beliefBrain, beliefEngineCase, beliefPage, readEvents, shape, type BeliefBrain, type BeliefEvent } from './helpers/belief-ledger.ts';
+
+afterEach(() => __setBeliefEmitterFaultForTests(null));
+
+const fault = (fn: (drafts: BeliefEventDraft[]) => BeliefEventDraft[]) => __setBeliefEmitterFaultForTests(fn);
+const retype = (from: string, to: string) => (drafts: BeliefEventDraft[]) => drafts.map(d => d.eventType === from ? { ...d, eventType: to } : d);
+const dropType = (type: string) => (drafts: BeliefEventDraft[]) => drafts.filter(d => d.eventType !== type);
+/** The database's clock, so a replay instant orders against recorded_at on both engines. */
+const dbNow = async (engine: BrainEngine) => new Date(String((await engine.executeRaw<{ t: string }>(`SELECT clock_timestamp()::text AS t`))[0]!.t));
+async function since(b: { engine: BrainEngine; sourceId: string }, fn: () => Promise<unknown>): Promise<BeliefEvent[]> {
+ const mark = Number((await b.engine.executeRaw<{ id: number | null }>('SELECT max(id) AS id FROM belief_events WHERE source_id = $1', [b.sourceId]))[0]?.id ?? 0);
+ await fn();
+ return readEvents(b.engine, b.sourceId, mark);
+}
+const lifetimeOf = async (b: BeliefBrain, slug: string) => (await b.events()).filter(e => e.slug === slug && e.subject_kind === 'page').at(-1)!.page_lifetime!;
+
+const FENCE = (rows: string[]) => ['## Facts', '<!--- gbrain:facts:begin -->',
+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',
+ ...rows.map((claim, i) => `| ${i + 1} | ${claim} | fact | 1.0 | world | medium | 2017-01-01 | | chat | |`), '<!--- gbrain:facts:end -->', ''].join('\n');
+const PERSON = (title: string, body = '') => `---\ntitle: ${title}\ntype: person\n---\n# ${title}\n\n${body}`;
+
+interface Managed { engine: BrainEngine; sourceId: string; root: string; put(slug: string, content: string): Promise<void> }
+
+/** A managed brain with a fresh worktree source on `engine`: `seed` runs unmanaged (legacy writes allowed), then managed mode and coverage are enabled. */
+async function managedWorktree(engine: BrainEngine, seed: (f: Managed) => Promise<void>, run: (f: Managed) => Promise<void>): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-belief-identity-'));
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, async () => {
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const sourceId = `identity-${randomUUID().slice(0, 8)}`;
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ await claimWorktree(engine, sourceId, root);
+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true }, dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ const f: Managed = { engine, sourceId, root, put: async (slug, content) => {
+ const prior = await engine.readPageSnapshot(slug, { sourceId });
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID(), ...(prior ? { expected_revision: prior.revision } : {}) } });
+ } };
+ await seed(f);
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await enableBeliefLedger(engine, sourceId);
+ await run(f);
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+for (const engineCase of testBackends().map(beliefEngineCase)) {
+ describe(`belief ledger identity (${engineCase.name})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (engineCase.databaseUrl) ({ engine, close } = await isolatedPersistencePostgres(engineCase.databaseUrl));
+ else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; }
+ }, 120_000);
+ afterAll(async () => { await disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); });
+ const brain = (run: (b: BeliefBrain) => Promise<void>) => beliefBrain(run, { databaseUrl: engineCase.databaseUrl });
+
+ test('probe 4: a cheap rename and a fallback rename each append one page.renamed on the same lifetime; replay before the rename resolves the old slug', () => brain(async b => {
+ await b.put('notes/old-example', beliefPage({ type: 'note', title: 'Old', facts: ['Old example has a roof'] }));
+ const lifetime = await lifetimeOf(b, 'notes/old-example');
+ const before = await dbNow(b.engine);
+ const check = async (events: BeliefEvent[], oldSlug: string, newSlug: string, expectedLifetime: string, extra: Record<string, unknown> = {}) => {
+ // The moved rows may also take a new revision and the maintenance writer's tier; no key changes, never a delete or a new page.
+ expect(events.every(e => e.subject_kind === 'page' ? ['page.renamed', 'page.published', 'trust.retiered'].includes(e.event_type) : e.event_type === 'trust.retiered')).toBe(true);
+ expect(events.every(e => e.page_lifetime === expectedLifetime)).toBe(true);
+ const renames = events.filter(e => e.event_type === 'page.renamed');
+ expect(renames).toHaveLength(1);
+ expect(renames[0]!).toMatchObject({ slug: newSlug, page_lifetime: expectedLifetime, subject_key: pageKey(expectedLifetime), value: { old_slug: oldSlug, new_slug: newSlug, ...extra } });
+ };
+ const cheap = await since(b, () => renamePageOntoSlug(b.engine, { sourceId: b.sourceId, oldSlug: 'notes/old-example', newSlug: 'notes/new-example', to: 'notes/new-example.md' }));
+ await check(cheap, 'notes/old-example', 'notes/new-example', lifetime);
+ expect(cheap.find(e => e.event_type === 'page.renamed')!.cause).toMatchObject({ op: 'sync_rename' });
+ expect(await lifetimeSlugAt(b.engine, b.sourceId, lifetime, before)).toBe('notes/old-example');
+ expect(await lifetimeAtSlug(b.engine, b.sourceId, 'notes/old-example', before)).toBe(lifetime);
+ const after = await dbNow(b.engine);
+ expect(await lifetimeSlugAt(b.engine, b.sourceId, lifetime, after)).toBe('notes/new-example');
+ expect(await lifetimeAtSlug(b.engine, b.sourceId, 'notes/old-example', after)).toBeNull();
+ expect(await lifetimeAtSlug(b.engine, b.sourceId, 'notes/new-example', after)).toBe(lifetime);
+
+ // Fallback (#5431): the destination materialized as its own row; the stale row's identity, lifetime included, moves onto it.
+ await b.put('notes/stale-example', beliefPage({ type: 'note', title: 'Stale' }));
+ await b.put('notes/dest-example', beliefPage({ type: 'note', title: 'Stale' }));
+ const stale = await lifetimeOf(b, 'notes/stale-example');
+ const absorbed = await lifetimeOf(b, 'notes/dest-example');
+ const preFallback = await dbNow(b.engine);
+ const fallback = await since(b, () => carryRenameIdentity(b.engine, b.sourceId, 'notes/stale-example', 'notes/dest-example'));
+ await check(fallback, 'notes/stale-example', 'notes/dest-example', stale, { absorbed_lifetime: absorbed });
+ expect(shape(fallback)).toEqual(['page:page.renamed']);
+ expect(fallback[0]!.cause).toMatchObject({ op: 'rename_fallback' });
+ expect(await lifetimeSlugAt(b.engine, b.sourceId, stale, preFallback)).toBe('notes/stale-example');
+ expect(await lifetimeAtSlug(b.engine, b.sourceId, 'notes/dest-example', await dbNow(b.engine))).toBe(stale);
+
+ // Forced probe: an emitter that records the cheap rename as a publication is caught.
+ await b.put('notes/forced-example', beliefPage({ type: 'note', title: 'Forced' }));
+ const forcedLifetime = await lifetimeOf(b, 'notes/forced-example');
+ fault(retype('page.renamed', 'page.published'));
+ const forced = await since(b, () => renamePageOntoSlug(b.engine, { sourceId: b.sourceId, oldSlug: 'notes/forced-example', newSlug: 'notes/forced-moved-example', to: 'notes/forced-moved-example.md' }));
+ await expect(check(forced, 'notes/forced-example', 'notes/forced-moved-example', forcedLifetime)).rejects.toThrow();
+ }), 120_000);
+
+ test('probe 29: a renamed link endpoint changes no key, a reused slug starts a new lifetime, and a database-only fact is adopted by its later page', () => brain(async b => {
+ await b.put('people/bob-example', beliefPage({ type: 'person', title: 'Bob Example' }));
+ await b.put('notes/meeting-example', beliefPage({ type: 'note', title: 'Meeting', links: ['people/bob-example'] }));
+ const bob = await lifetimeOf(b, 'people/bob-example');
+ const [{ incarnation }] = await b.engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [b.sourceId]);
+ /** The meeting stream's state hash, over its subject keys: the link to Bob is keyed by Bob's lifetime. */
+ const meeting = () => b.engine.transaction(tx => currentStateHash(tx, b.sourceId, incarnation!, 'notes/meeting-example'));
+ const beforeRename = await meeting();
+ expect(beforeRename.state.links.map(l => beforeRename.lifetimes.get(l.to.id))).toEqual([bob]);
+ // Sync saw the file move; the cheap rename moves the row.
+ renameSync(join(b.root, 'people/bob-example.md'), join(b.root, 'people/robert-example.md'));
+ const renamed = await since(b, () => renamePageOntoSlug(b.engine, { sourceId: b.sourceId, oldSlug: 'people/bob-example', newSlug: 'people/robert-example', to: 'people/robert-example.md' }));
+ expect(renamed.filter(e => e.event_type === 'page.renamed').map(e => [e.page_lifetime, e.value])).toEqual([[bob, { old_slug: 'people/bob-example', new_slug: 'people/robert-example' }]]);
+ expect(renamed.filter(e => e.slug === 'notes/meeting-example' || e.subject_kind !== 'page')).toEqual([]);
+ const afterRename = await meeting();
+ expect(afterRename.state.links.map(l => l.to.slug)).toEqual(['people/robert-example']);
+ expect(afterRename.hash).toBe(beforeRename.hash);
+ // The old slug is reused by a new page: a new lifetime, and the renamed page's history stays its own.
+ const reused = await since(b, () => b.put('people/bob-example', beliefPage({ type: 'person', title: 'Another Bob' })));
+ const published = reused.find(e => e.event_type === 'page.published')!;
+ expect(published.page_lifetime).not.toBe(bob);
+ expect(reused.every(e => e.page_lifetime !== bob)).toBe(true);
+ const now = await dbNow(b.engine);
+ expect(await lifetimeAtSlug(b.engine, b.sourceId, 'people/bob-example', now)).toBe(published.page_lifetime);
+ expect(await lifetimeSlugAt(b.engine, b.sourceId, bob, now)).toBe('people/robert-example');
+
+ // A database-only fact about a page that does not exist yet, then the page.
+ await operationsByName.remember!.handler(b.ctx as OperationContext, { fact: 'Dana example runs the lab', provenance: 'notes', entity: 'people/dana-example', request_id: randomUUID() });
+ const dbOnlyEvent = async (slug: string) => (await b.events()).find(e => e.subject_kind === 'fact' && e.slug === slug)!;
+ const dbOnly = await dbOnlyEvent('people/dana-example');
+ expect(dbOnly.page_lifetime).toBeNull();
+ const check = (events: BeliefEvent[], slug: string, prior: BeliefEvent) => {
+ const page = events.find(e => e.event_type === 'page.published' && e.slug === slug)!;
+ const adopted = events.filter(e => e.event_type === 'fact.adopted');
+ expect(adopted).toHaveLength(1);
+ expect(adopted[0]!).toMatchObject({ slug, page_lifetime: page.page_lifetime, cause: { from_key: prior.subject_key } });
+ expect((JSON.parse(adopted[0]!.subject_key) as unknown[]).slice(0, 2)).toEqual(['f', lifetimeRef(page.page_lifetime!)]);
+ expect(events.filter(e => e.subject_kind === 'fact' && e.event_type !== 'fact.adopted')).toEqual([]);
+ };
+ check(await since(b, () => b.put('people/dana-example', beliefPage({ type: 'person', title: 'Dana Example' }))), 'people/dana-example', dbOnly);
+ // Forced probe: an emitter that records the adoption as a retraction plus a new assertion is caught.
+ await operationsByName.remember!.handler(b.ctx as OperationContext, { fact: 'Erin example runs the shop', provenance: 'notes', entity: 'people/erin-example', request_id: randomUUID() });
+ const erin = await dbOnlyEvent('people/erin-example');
+ fault(retype('fact.adopted', 'fact.asserted'));
+ const forced = await since(b, () => b.put('people/erin-example', beliefPage({ type: 'person', title: 'Erin Example' })));
+ expect(() => check(forced, 'people/erin-example', erin)).toThrow();
+ }), 120_000);
+
+ /** Seeds a canonical page and a legacy stub phantom holding one claim the canonical page also holds and one it does not. */
+ const phantomSeed = async ({ engine, sourceId, root, put }: Managed) => {
+ await put('people/alice-example', PERSON('Alice Example', FENCE(['Founded Acme'])));
+ await engine.putPage('alice', { type: 'person', title: 'alice', compiled_truth: `# alice\n\n${FENCE(['Founded Acme', 'Lives in Paris'])}`.trim(), timeline: '', frontmatter: {} }, { sourceId });
+ const phantom = (await engine.readPageSnapshot('alice', { sourceId }))!;
+ writeFileSync(join(root, 'alice.md'), serializePageToMarkdown(phantom.page, phantom.tags));
+ await runExtractFacts(engine, { sourceId, slugs: ['alice'] });
+ };
+ const lifetimes = async (engine: BrainEngine, sourceId: string) => {
+ const all = await readEvents(engine, sourceId);
+ const [fp] = await engine.executeRaw<{ fp: string }>(`SELECT gbrain_fact_fingerprint('Founded Acme') AS fp`);
+ return { overlapFp: fp!.fp, phantom: all.find(e => e.slug === 'alice' && e.subject_kind === 'page')!.page_lifetime!,
+ canonical: all.find(e => e.slug === 'people/alice-example' && e.subject_kind === 'page')!.page_lifetime! };
+ };
+ /** The merge request's events: the canonical page's publication. */
+ const mergeEvents = (events: BeliefEvent[]) => {
+ const page = events.find(e => e.event_type === 'page.published' && e.slug === 'people/alice-example');
+ return page ? events.filter(e => e.publication_id === page.publication_id) : [];
+ };
+ const checkMerge = (events: BeliefEvent[], l: { overlapFp: string; phantom: string; canonical: string }) => {
+ expect(events.filter(e => e.subject_kind === 'page' && e.event_type !== 'trust.retiered').map(e => [e.event_type, e.slug])).toEqual([['page.published', 'people/alice-example']]);
+ const transferred = events.filter(e => e.event_type === 'fact.transferred');
+ expect(transferred.map(e => e.value!.fact)).toContain('Lives in Paris');
+ for (const e of transferred) {
+ expect(e).toMatchObject({ slug: 'people/alice-example', page_lifetime: l.canonical, cause: { from_lifetime: l.phantom } });
+ expect((JSON.parse(e.cause.from_key as string) as unknown[]).slice(0, 2)).toEqual(['f', lifetimeRef(l.phantom)]);
+ expect((JSON.parse(e.subject_key) as unknown[]).slice(0, 2)).toEqual(['f', lifetimeRef(l.canonical)]);
+ }
+ expect(events.filter(e => e.event_type === 'fact.asserted')).toEqual([]);
+ // The claim both pages held is not moved (the canonical row keeps it): the phantom's copy ends on the phantom's own lifetime.
+ expect(events.filter(e => e.slug === 'alice').map(e => [e.event_type, e.page_lifetime, e.claim_fp])).toEqual([['fact.retracted', l.phantom, l.overlapFp]]);
+ };
+
+ test('probe 19: a phantom merge transfers each moved assertion from the phantom\'s lifetime; a crash before the delete leaves both pages live', () => managedWorktree(engine, phantomSeed, async ({ sourceId, root }) => {
+ const b = { engine, sourceId };
+ const l = await lifetimes(engine, sourceId);
+ // The crash: the process dies after the merge commits, before the delete request is submitted.
+ const read = engine.readPageSnapshot;
+ let reads = 0;
+ engine.readPageSnapshot = (async function (this: BrainEngine, slug: string, opts?: Parameters<BrainEngine['readPageSnapshot']>[1]) {
+ if (this === engine && slug === 'alice' && new Error().stack?.includes('redirectManagedPhantom') && ++reads === 2) throw new Error('crash between the merge and the delete');
+ return read.call(this, slug, opts);
+ }) as BrainEngine['readPageSnapshot'];
+ let merge: BeliefEvent[];
+ try { merge = await since(b, () => runExtractFacts(engine, { sourceId, brainDir: root }).catch(() => undefined)); }
+ finally { delete (engine as { readPageSnapshot?: unknown }).readPageSnapshot; }
+ expect(reads).toBe(2);
+ checkMerge(mergeEvents(merge), l);
+ expect(merge.filter(e => e.event_type === 'page.deleted')).toEqual([]);
+ expect((await engine.readPageSnapshot('alice', { sourceId }))?.page.deleted_at ?? null).toBeNull();
+ const open = await engine.executeRaw<{ slug: string }>('SELECT slug FROM belief_page_lifetimes WHERE source_id=$1 AND ended_at IS NULL AND page_lifetime = ANY($2::uuid[]) ORDER BY slug', [sourceId, [l.phantom, l.canonical]]);
+ expect(open.map(r => r.slug)).toEqual(['alice', 'people/alice-example']);
+ // The rerun replays the merge (keyed by its intent) and completes the delete: the phantom's own page.deleted, nothing transferred twice.
+ const finish = await since(b, () => runExtractFacts(engine, { sourceId, brainDir: root }));
+ expect(finish.filter(e => e.subject_kind === 'page').map(e => [e.event_type, e.slug, e.page_lifetime])).toEqual([['page.deleted', 'alice', l.phantom]]);
+ expect(finish.filter(e => e.event_type === 'fact.transferred')).toEqual([]);
+ }), 180_000);
+
+ test('probe 19 forced: an emitter that records a phantom transfer as a fresh assertion is caught', () => managedWorktree(engine, phantomSeed, async ({ sourceId, root }) => {
+ const l = await lifetimes(engine, sourceId);
+ fault(retype('fact.transferred', 'fact.asserted'));
+ const events = await since({ engine, sourceId }, () => runExtractFacts(engine, { sourceId, brainDir: root }));
+ expect(() => checkMerge(mergeEvents(events), l)).toThrow();
+ }), 180_000);
+ });
+}
diff --git a/test/belief-ledger-trust.test.ts b/test/belief-ledger-trust.test.ts
index 8ecace9225..e85c83df59 100644
--- a/test/belief-ledger-trust.test.ts
+++ b/test/belief-ledger-trust.test.ts
@@ -121,10 +121,10 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
const lifetime = published.page_lifetime!;
const before = String((await content(b, slug)).revision);
const staff = await factId(b, 'Acme has ten staff');
- const check = (events: BeliefEvent[]) => {
+ const check = (events: BeliefEvent[], revisionBefore: string) => {
const forget = events.filter(e => e.cause.op === 'forget');
expect(shape(forget)).toEqual(['page:page.view_changed', 'fact:fact.withdrawn']);
- expect(forget[0]!.value).toMatchObject({ revision_before: before });
+ expect(forget[0]!.value).toMatchObject({ revision_before: revisionBefore });
expect(forget[0]!.subject_key).toBe(pageKey(lifetime));
expect(parts(forget[1]!).slice(0, 3)).toEqual(['f', lifetimeRef(lifetime), 2]);
expect(forget[1]!).toMatchObject({ value: null, trust_tier: 'agent_written', page_lifetime: lifetime });
@@ -132,7 +132,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
};
const mark = await lastId(b);
await run(b.local, 'forget', { id: String(staff) });
- const forget = check(await readEvents(b.engine, b.sourceId, mark));
+ const forget = check(await readEvents(b.engine, b.sourceId, mark), before);
const after = String(forget[0]!.value!.revision_after);
expect(after).not.toBe(before);
// The effect worker materializes the body at the withdrawal's revision: one more view change, and its preimage version.
@@ -146,8 +146,9 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
// Forced probe: an emitter that records the withdrawal as a plain retraction is caught.
fault(retype('fact.withdrawn', 'fact.retracted'));
const seed = await factId(b, 'Acme raised a seed round');
+ const current = String((await content(b, slug)).revision);
const forced = await since(b, () => run(b.local, 'forget', { id: String(seed) }));
- expect(() => check(forced)).toThrow();
+ expect(() => check(forced, current)).toThrow();
}), 120_000);
test('probe 8: a lower-tier fence rewrite, remember.replaces, takes_supersede and a refused remote forget each append trust.contested with the proposal', withHome(async () => {
@@ -392,16 +393,16 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
await observe(b.local, 'founder', '2025-01-01');
await observe(b.local, 'advisor', '2023-01-01');
});
- const check = (events: BeliefEvent[]) => {
+ const check = (events: BeliefEvent[], starts: string[]) => {
const advisor = events.filter(e => e.event_type === 'fact.asserted' && e.value?.value === 'advisor');
expect(advisor).toHaveLength(2);
const [a, c] = advisor.map(parts);
expect(a!.slice(0, 5)).toEqual(c!.slice(0, 5));
expect(a![0]).toBe('o');
- expect([a![5], c![5]].sort()).toEqual(['2023-01-01T00:00:00.000Z', '2024-01-01T00:00:00.000Z']);
+ expect([a![5], c![5]].sort()).toEqual(starts);
expect(advisor[0]!.value!.fact).toBe(advisor[1]!.value!.fact);
};
- check(asserted);
+ check(asserted, ['2023-01-01T00:00:00.000Z', '2024-01-01T00:00:00.000Z']);
const founder = asserted.find(e => e.value?.value === 'founder')!;
const [stint] = await b.engine.executeRaw<{ id: number }>(`SELECT id::int AS id FROM facts WHERE source_id=$1 AND entity_slug=$2 AND value='founder'`, [b.sourceId, entity]);
await confirm(b, 'facts', stint!.id);
@@ -418,7 +419,35 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
await observe(b.local, 'advisor', '2019-01-01');
await observe(b.local, 'advisor', '2018-01-01');
});
- expect(() => check(forced)).toThrow();
+ expect(() => check(forced, ['2018-01-01T00:00:00.000Z', '2019-01-01T00:00:00.000Z'])).toThrow();
}), 180_000);
+
+ test('owner decisions: accepting a contested supersession supersedes the old belief and confirms the new one; undo reverses both', withHome(async () => {
+ const b = await brain();
+ const old = await run(b.local, 'remember', { fact: 'Bob example likes tea', provenance: 'owner', entity: 'people/bob-example' });
+ await confirm(b, 'facts', Number(old.id));
+ const agent = await run(b.remote, 'remember', { fact: 'Bob example likes coffee', provenance: 'web', entity: 'people/bob-example', replaces: String(old.id) });
+ const ref = Number(String(agent.contested.proposal_ref).slice(2));
+ const keys = (await readEvents(b.engine, b.sourceId)).filter(e => e.event_type === 'fact.asserted' && e.slug === 'people/bob-example').map(e => e.subject_key);
+ const [oldKey, newKey] = keys;
+ const checkAccept = (events: BeliefEvent[], replacement: string) => {
+ expect(events.map(e => [e.subject_key, e.event_type, e.trust_tier, e.value])).toEqual([
+ [oldKey, 'fact.superseded', 'user_confirmed', null],
+ [replacement, 'trust.retiered', 'user_confirmed', { from: 'agent_written', to: 'user_confirmed' }]]);
+ expect(events[0]!.cause).toMatchObject({ op: 'decide_proposal', replaced_by: replacement });
+ };
+ const accepted = await since(b, async () => { expect((await decideTrustProposal(b.engine, ref, 'accept', owner)).status).toBe('accepted'); });
+ checkAccept(accepted, newKey!);
+ const undone = await since(b, async () => { expect((await decideTrustProposal(b.engine, ref, 'undo', owner)).status).toBe('undone'); });
+ expect(undone.map(e => [e.subject_key, e.event_type, e.trust_tier, e.value?.fact ?? e.value])).toEqual([
+ [oldKey, 'fact.asserted', 'user_confirmed', 'Bob example likes tea'],
+ [newKey, 'trust.retiered', 'agent_written', { from: 'user_confirmed', to: 'agent_written' }]]);
+ // Forced probe: an emitter that records the accepted supersession as a plain retraction is caught.
+ const again = await run(b.remote, 'remember', { fact: 'Bob example likes cocoa', provenance: 'web', entity: 'people/bob-example', replaces: String(old.id) });
+ const cocoa = (await readEvents(b.engine, b.sourceId)).find(e => e.event_type === 'fact.asserted' && e.value?.fact === 'Bob example likes cocoa')!.subject_key;
+ fault(retype('fact.superseded', 'fact.retracted'));
+ const forced = await since(b, async () => { await decideTrustProposal(b.engine, Number(String(again.contested.proposal_ref).slice(2)), 'accept', owner); });
+ expect(() => checkAccept(forced, cocoa)).toThrow();
+ }), 120_000);
});
}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index a9073b3366..aa92fb102b 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -16,8 +16,10 @@ test/alias-source-cascade-5094.test.ts
test/attribution-backfill-history.test.ts
test/backstop-same-page-shadow-managed-6333.test.ts
test/behavior-change-notice.test.ts
+test/belief-ledger-identity.test.ts
test/belief-ledger-lifecycle.test.ts
test/belief-ledger-privacy.test.ts
+test/belief-ledger-trust.test.ts
test/capture-consent-admission.test.ts
test/capture-dispatch-provenance-6524.test.ts
test/chronicle-backfill-max-usd.test.ts