Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
belief ledger: unmanaged projection points and derived link writers, backfill probe, docs (SoR, ENGINES, memory boundaries, KEY_FILES, canonical writers)
garrytane638d8a73222
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 823fff6205..b402fa6145 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -344,11 +344,13 @@ and the fix is the read-only `gbrain migrate --to postgres --plan --json`.| Concurrency | Single process | Connection pooling || Backups | Manual (file copy) | Managed by Supabase |+**The belief ledger lives only in the database.** `belief_events` and its side tables record what the brain had recorded, and when (`gbrain beliefs status`). Markdown carries only current state, so a rebuild from Markdown, `gbrain reinit-pglite` or a dropped database starts an empty history; back up the database itself. After restoring a Postgres (or PGLite) backup, replay the purges made after the backup was taken: until then content purged later is readable again, and `gbrain doctor --only belief_ledger_coverage` reports a restore whose purge replay was partial, unavailable or unverified. Graduation copies the ledger verbatim (equal event keys and digests); the legacy copier refuses a brain that has one.+**Migration:** on a PGLite brain, `gbrain migrate --to postgres` (alias `--to supabase`) graduates the brain to Postgres. Without `--yes` it prints the plan and exits 3; `--yes --expect <plan_hash>` runs it. Graduation drains pending writes, copies every table verbatim with its primary keys (pages, facts, takes, versions, links, timeline, embeddings, transcripts and paid caches, request history and withdrawals, token and OAuth rows) into a fenced target, verifies row counts and digests, runs `gbrain doctor` on the target, and only then flips routing. It works for brains with write history and for managed brains. The PGLite data dir is retained as `<path>.graduated-<run_id>` and a tombstone file takes its place. Walkthrough, recovery by error code, rollback and what stays on this computer: [Move a PGLite brain to Postgres](guides/move-to-postgres.md).**Say to your agent:** *"Upgrade my brain to Postgres. Show me the plan first."*-The legacy copier handles every other direction: `gbrain migrate --to pglite`, PGLite to Postgres when `gbrain config set migrate.graduation false` opts out of graduation, and history-free brains on Windows. It re-creates pages through `putPage` (chunks, embeddings, links, tags, timeline, facts) and copies config rows minus the engine-local denylist (`MIGRATE_CONFIG_ENGINE_LOCAL_KEYS`: the target-owned `engine`/`version` connection + schema ledger and the physical embedding-column registry keys); skipped keys are printed, never silent, and the run ends with a per-table copied-count summary. It forwards the full page row (origin path, kind, provenance, `ingested_at`, aliases, chunk code metadata). Pages the source had sealed are rebuilt on the target before the config flip, without an embedding key, keeping chunk ids and vectors whose input matches. A failed rebuild blocks the flip: the run exits 1 with no error code, prints `The active engine was NOT switched` and the failing pages, and leaves the source engine active; fix them (`gbrain projections drain` on the target) and re-run `gbrain migrate` to resume. Pages the source had not sealed arrive queued, with their verbatim chunks. It does not carry request IDs, withdrawals, attribution or ownership, so it refuses a managed brain and any brain with durable write history, fact withdrawals or canonical worktree ownership (rows in `persistence_requests`, `fact_withdrawals` or `persistence_worktrees`).+The legacy copier handles every other direction: `gbrain migrate --to pglite`, PGLite to Postgres when `gbrain config set migrate.graduation false` opts out of graduation, and history-free brains on Windows. It re-creates pages through `putPage` (chunks, embeddings, links, tags, timeline, facts) and copies config rows minus the engine-local denylist (`MIGRATE_CONFIG_ENGINE_LOCAL_KEYS`: the target-owned `engine`/`version` connection + schema ledger and the physical embedding-column registry keys); skipped keys are printed, never silent, and the run ends with a per-table copied-count summary. It forwards the full page row (origin path, kind, provenance, `ingested_at`, aliases, chunk code metadata). Pages the source had sealed are rebuilt on the target before the config flip, without an embedding key, keeping chunk ids and vectors whose input matches. A failed rebuild blocks the flip: the run exits 1 with no error code, prints `The active engine was NOT switched` and the failing pages, and leaves the source engine active; fix them (`gbrain projections drain` on the target) and re-run `gbrain migrate` to resume. Pages the source had not sealed arrive queued, with their verbatim chunks. It does not carry request IDs, withdrawals, attribution or ownership, so it refuses a managed brain and any brain with durable write history, fact withdrawals or canonical worktree ownership (rows in `persistence_requests`, `fact_withdrawals` or `persistence_worktrees`), and a brain with a belief ledger (rows in `belief_events`), which it names.<a id="engine-migration-refused"></a>**Engine migration refused (`writer_coordinator_required`).** The legacy copier's refusal is an agent-contract envelope whose `fix` names the refusing side; every branch verifies with the read-only `gbrain doctor --no-migrate --json`, and nothing has changed in either datastore:diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 92ca18fc62..18eab00568 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -54,12 +54,12 @@ link it here rather than raising the cap.| [Managed sync bookkeeping](key-files/managed-sync-bookkeeping.md) | `sync-failures.ts`, `managed-sync-orphans.ts`, `sync-checkpoint-replaced.ts` || [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/read-policy-sql.ts` || [Core Search (2/2)](key-files/core-search-2.md) | `search/rerank.ts` through `search/vector-pool.ts`, the relational arm and multi-hop chain modules, `hub-dampening.ts`, `crag.ts` |-| [Core Services (1/3)](key-files/core-services-1.md) | `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` through `src/core/connectors/` |+| [Core Services (1/3)](key-files/core-services-1.md) | `src/core/advisor/*.ts` through `src/core/connectors/` || [Core Services (1/3, continued)](key-files/core-services-1-continued.md) | `src/core/context/` through `src/core/context/ipc-path.ts` || [Core Services (2/3)](key-files/core-services-2.md) | `src/core/conversation-parser/` through `src/core/ops/sources.ts`, except `src/core/persistence/` || [Core Services (2/3, continued)](key-files/core-services-2-continued.md) | `page-state/`, `page-body/page-shape.ts`, `progressive-batch/` || [Core Services (3/3)](key-files/core-services-3.md) | `src/core/think/index.ts` through `src/core/verbs/usage-log.ts` |-| [Core Utilities (1/2)](key-files/core-utilities-1.md) | `src/core/archive-crawler-config.ts` through `src/core/remediation-checkpoint.ts`; [`cycle.ts`](key-files/core-cycle-primitive.md) |+| [Core Utilities (1/2)](key-files/core-utilities-1.md) | `archive-crawler-config.ts` through `remediation-checkpoint.ts`; [`cycle.ts`](key-files/core-cycle-primitive.md) || [Core Utilities (2/2)](key-files/core-utilities-2.md) | `src/core/repair/` through `src/core/verbs.ts` || [Engines (1/2)](key-files/engines-1.md) | `src/core/connection-manager.ts` through `src/core/pglite-repair.ts` || [Engines (2/2)](key-files/engines-2.md) | `src/core/pglite-resetwal.ts` through `src/core/worker-pool.ts` |@@ -76,7 +76,7 @@ link it here rather than raising the cap.| [Shared brain skills](key-files/shared-skills.md) | Canonical catalog, enrollment, migration, publication and harness integration || [Skills](key-files/skills.md) | `src/core/audit-skill-brain-first.ts` through `src/core/skills-integrity.ts` || [Tooling And Tests](key-files/tooling-and-tests.md) | `.github/workflows/test.yml` through `test/remote-privacy-sweep.test.ts` |-| [CI Health And Test Guards](key-files/ci-health-and-test-guards.md) | `.github/workflows/nightly-watch.yml` through `scripts/check-image-decoders-embedded.sh`, plus contributor audit, fix-wave gate |+| [CI Health And Test Guards](key-files/ci-health-and-test-guards.md) | `nightly-watch.yml` through `check-image-decoders-embedded.sh`, contributor audit, fix-wave gate || [BrainBench — in a sibling repo](key-files/brainbench.md) | Cross-file subsystem contract || [Hindsight calibration](key-files/hindsight.md) | Cross-file subsystem contract || [Schema packs: mutation surface](key-files/schema-mutation.md) | Cross-file subsystem contract |@@ -89,4 +89,5 @@ link it here rather than raising the cap.| [Workspace push and backup coverage](key-files/workspace-push-and-backup.md) | Workspace push, hook push backstops, backup verdicts || [Secret and sensitivity scanning](key-files/secret-scan.md) | `secret-scan*.ts`: detection, allowlist, scan counters || [Ambient capture consent gate](key-files/ambient-capture.md) | `memory.auto_writeback` capture lanes |+| [Belief ledger](key-files/belief-ledger.md) | `src/core/belief/`, `gbrain beliefs`, doctor coverage || [Quarantine](key-files/quarantine.md) | Gate-marker strip; quarantined pages in facts, reads, writes |diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 28f54a24a1..8d9089fe20 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -245,3 +245,4 @@ src/core/trust/supersede-handlers.ts 3 filesystem_guard Trust-guard supersessionsrc/core/trust/timeline-projection.ts 2 engine_guard gbrain extract's timeline projection inserts gate-allowed rows stamped with the page tier inside an attributed maintenanceTransaction; on a managed brain the canonical table trigger refuses it outside the coordinator.src/eval/brainbench/trust-scenario.ts 2 isolated_eval BrainBench trust suites register their fixture sources in the scenario's own isolated benchmark brain (persistence disabled for the registration, re-enabled after); never opened against the active managed brain.src/core/oversized-backfill.ts 1 coordinator The oversized-page backfill (gbrain reindex --oversized, the post-upgrade pass) rewrites a size-skipped page without its gate markers through importFromContent on unmanaged brains (assertUnmanagedCanonicalWriter applies) and through submitPageMutation put_page (managed_quarantine_clear, expected_revision) on managed brains; its only direct write is the page_embedding_budget hold row, which is derived spend state, not canonical content.+src/core/belief/ledger.ts 0 contract The belief ledger finalization contract writes no canonical table: withBeliefBatch reads the held page keys before and after the caller's projections and appends belief_events in the same transaction (publications, coordinated database writes, and the unmanaged projection points in belief/projection-point.ts).diff --git a/docs/architecture/key-files/belief-ledger.md b/docs/architecture/key-files/belief-ledger.mdnew file mode 100644index 0000000000..919cbeb973--- /dev/null+++ b/docs/architecture/key-files/belief-ledger.md@@ -0,0 +1,19 @@+# Key files: belief ledger++[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+Design: [BELIEF_LEDGER.md](../../designs/BELIEF_LEDGER.md). Operator surface: `gbrain beliefs`, doctor `belief_ledger_coverage`.++- `src/core/belief/schema.ts` — the ledger DDL (`belief_events`, `belief_page_lifetimes`, `belief_commit_marks`, `belief_redactions`, `belief_retier_manifest`) shared by migration v249 and both schema blobs; `sources.purge_epoch` is migration-only. Edit here, then `bun run build:schema`.+- `src/core/belief/keys.ts` — subject keys and hashes. A key never holds a row id: page slugs serialize as the lifetime (`L:<uuid>`), a slug with no page as `S:<incarnation>:<slug>`. Append, replay, lookup and `state_hash` share this one serialization.+- `src/core/belief/lifetimes.ts` — page lifetimes, the ledger's page identity: minted at first need, kept across a rename, ended by a hard delete or a recreate; `page_id` is a hint only.+- `src/core/belief/state.ts` / `subjects.ts` — raw stream state (a page, its fence and DB-only facts, takes, and links whose origin, else from, page it is) and its keyed subjects; row ids are payload, never keys.+- `src/core/belief/ledger.ts` — the finalization contract. `withBeliefBatch` reads the state of the held page keys before and after the transaction's projections and appends the canonical diff (origin `live` on a managed brain, `unmanaged` otherwise, or the caller's override). `beliefBatchCovers` and `insideBeliefBatch` let a nested writer skip its own batch. Managed mode comes from `readManagedMode`, never a direct `persistence_brain` read.+- `src/core/belief/append.ts` — the one insert (`appendBeliefEvents`): tombstones and the redaction register first, then deterministic `event_key`s. `markBeliefCommits` writes the post-commit observation (`observed_at >= recorded_at`); `__setBeliefEmitterFaultForTests` is the forced-probe seam.+- `src/core/belief/coverage.ts` — `enableBeliefLedger` (`coverage.started`, a resumable per-page baseline, `coverage.complete` whose recorded_at is the watermark; certified only on a managed brain) and `disableBeliefLedger` (`coverage.stopped`).+- `src/core/belief/coverage-report.ts` — readers: `coverageIntervals`, `coverageAt` (refuses `coverage_from` before the watermark, `coverage_gap` in a stopped span), `beliefEventVisibility` (an unmarked publication is `unproven` until a commit mark or a later event of the page proves it). Drift: `scanBeliefDrift` (sampled, or deep) compares each slug's current `state_hash` with its newest event; `reconcileBeliefDrift` appends `reconcile` events (the slug interval stays uncertified). `orphanLifetimes`, `unmarkedPublications`/`fillCommitMarks`, and `cycleBeliefReconcile` for the extract phase.+- `src/core/belief/projection-point.ts` — `unmanagedBeliefPoint`: the legacy import, `extract_facts` fence reconcile, takes reextract and the derived link writers (`derived-links.ts`, the remote auto-links effect, attendance repair) lock their sorted page keys and run in an `unmanaged` batch, then mark the commit. Every other unmanaged writer is found by drift.+- `src/core/belief/backfill.ts` — `backfillBeliefHistory`: marked history from `page_versions` only (git is not read), origin `backfill`, historical time in `source_time`, recorded_at the run time; a purge during the run retries (`belief_preparation_stale`), and the summary event says whether pruned versions left it incomplete.+- `src/core/belief/history.ts` — the one history reader (`readBeliefHistory`); remote callers see only events that were world-visible when recorded on a page visible now, failing closed.+- `src/commands/beliefs.ts` — `gbrain beliefs enable|disable|status|reconcile|backfill` (local only; `--json`); an unknown source is `invalid_params`.+- `src/commands/doctor/checks/belief-ledger.ts` — doctor `belief_ledger_coverage`: intervals and certification, baseline progress, drift (sampled; complete under `--tier deep`), orphan lifetimes, unmarked publications, and a restore whose purge replay was partial, unavailable or unverified (`ask_user`). `--fix` reconciles and fills marks; a brain without coverage is information with an `ask_user` enable.diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 44de701c25..856076ef95 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -96,6 +96,7 @@ also contain knowledge absent from canonical files and must be backed up.| `config` (some keys) | Site-local routing config (e.g. `sync.repo_path`). || Withdrawal ledger and page overlays | Authoritative withdrawal decisions must survive stale imports and owner downtime. Markdown mirrors can lag. || Mutation journal, receipts, outbox, ownership and local registrations | Durable replay identity, publication recovery and authorization cannot be rebuilt from Markdown. |+| Belief ledger (`belief_events`, `belief_page_lifetimes`, `belief_commit_marks`, `belief_redactions`, `belief_retier_manifest`) | What the brain had recorded, and when. Markdown holds only the current state, so the history cannot be rebuilt from it; a rebuild from Markdown starts a new, empty history. See [BELIEF_LEDGER.md](../designs/BELIEF_LEDGER.md). |A new derived table that holds user-knowledge MUST land FS-first.If you're tempted to add one as "DB-only for now," the structural@@ -197,6 +198,15 @@ start `unrecorded`; version history is not copied).(`local_cli`), else this host's identity (`application`, `host:<id>`), else`host:unregistered`: attribution never creates an identity file. No directwriter is left unattributed.+- **Belief ledger on unmanaged brains:** three of these writers record their+ belief changes as `unmanaged` events when their source has the ledger on+ (`src/core/belief/projection-point.ts`): the legacy import, the cycle's+ `extract_facts` fence reconcile and the takes reextract, plus the derived+ link writers (extract, the remote auto-links effect and attendance repair)+ on any brain. Every other writer above changes beliefs unrecorded, so an+ unmanaged source's history is never certified; the drift check in+ `gbrain doctor` and the cycle's extract phase find those changes and append+ `reconcile` events.Agents: treat `NULL` attribution on an unmanaged brain as "written beforeattribution existed, or before `gbrain extract`, meeting timeline extraction@@ -356,6 +366,14 @@ does not erase the withdrawal ledger or promise physical erasure.## Disaster recovery+The belief ledger is DB-only (see the exceptions above). The rebuild below+keeps it, but every fact, take and link it deletes and re-derives is recorded+as a change by the next `gbrain doctor --fix` or cycle (`reconcile` events,+and the slugs stay uncertified for that interval), and dropping the database+loses the history for good. After a database backup restore, replay the+purges made after the backup (`gbrain doctor --only belief_ledger_coverage`+names any restore whose replay was partial, unavailable or unverified).+This example is only for a database whose affected facts, takes, links andtimeline entries have been verified to exist in canonical files. Before runningthe destructive commands, stop writers and verify a restorable database backupdiff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex 37d1095b40..51ee18b0cf 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -245,8 +245,9 @@ mention after the real fence. Pinned by `test/fence-marker-code-context.test.ts`("remote privacy boundary" and "remote page replacement").Markdown export is a portable view of pages, **not a full database backup**.-DB-only facts and pages, revision history, withdrawal state, jobs, settings, and-authentication records may not be recoverable from Markdown. Use the engine's+DB-only facts and pages, revision history, the belief ledger (what the brain+had recorded, and when; `gbrain beliefs`), withdrawal state, jobs, settings,+and authentication records may not be recoverable from Markdown. Use the engine'sfull backup/restore path and verify a restore into a separate location. Treatdatabase backups as sensitive. See the [system-of-record contract](../architecture/system-of-record.md)and [isolated local backup guide](in-agent-setup.md#6-back-up-the-complete-local-database).@@ -319,7 +320,9 @@ the same request id).it is not physical erasure. Out of its reach, and named in every receipt: thebrain repository's git history (the commits that carry the row are listed,never rewritten) and every other clone or remote, backups taken before the-purge (a restore brings back the content and an older purge ledger), provider+purge (a restore brings back the content and an older purge ledger; with the+belief ledger on, `gbrain doctor --only belief_ledger_coverage` asks you to+replay those purges when the restore could not), providercopies (embedding and decision providers), Markdown exports and compiledcontext files, and deleted rows in database pages and the write-ahead log untilvacuum. On PGLite, `--vacuum` compacts the touched tables; on Postgres thediff --git a/llms-full.txt b/llms-full.txtindex 766153c72f..aee1f37712 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5583,11 +5583,13 @@ and the fix is the read-only `gbrain migrate --to postgres --plan --json`.| Concurrency | Single process | Connection pooling || Backups | Manual (file copy) | Managed by Supabase |+**The belief ledger lives only in the database.** `belief_events` and its side tables record what the brain had recorded, and when (`gbrain beliefs status`). Markdown carries only current state, so a rebuild from Markdown, `gbrain reinit-pglite` or a dropped database starts an empty history; back up the database itself. After restoring a Postgres (or PGLite) backup, replay the purges made after the backup was taken: until then content purged later is readable again, and `gbrain doctor --only belief_ledger_coverage` reports a restore whose purge replay was partial, unavailable or unverified. Graduation copies the ledger verbatim (equal event keys and digests); the legacy copier refuses a brain that has one.+**Migration:** on a PGLite brain, `gbrain migrate --to postgres` (alias `--to supabase`) graduates the brain to Postgres. Without `--yes` it prints the plan and exits 3; `--yes --expect <plan_hash>` runs it. Graduation drains pending writes, copies every table verbatim with its primary keys (pages, facts, takes, versions, links, timeline, embeddings, transcripts and paid caches, request history and withdrawals, token and OAuth rows) into a fenced target, verifies row counts and digests, runs `gbrain doctor` on the target, and only then flips routing. It works for brains with write history and for managed brains. The PGLite data dir is retained as `<path>.graduated-<run_id>` and a tombstone file takes its place. Walkthrough, recovery by error code, rollback and what stays on this computer: [Move a PGLite brain to Postgres](guides/move-to-postgres.md).**Say to your agent:** *"Upgrade my brain to Postgres. Show me the plan first."*-The legacy copier handles every other direction: `gbrain migrate --to pglite`, PGLite to Postgres when `gbrain config set migrate.graduation false` opts out of graduation, and history-free brains on Windows. It re-creates pages through `putPage` (chunks, embeddings, links, tags, timeline, facts) and copies config rows minus the engine-local denylist (`MIGRATE_CONFIG_ENGINE_LOCAL_KEYS`: the target-owned `engine`/`version` connection + schema ledger and the physical embedding-column registry keys); skipped keys are printed, never silent, and the run ends with a per-table copied-count summary. It forwards the full page row (origin path, kind, provenance, `ingested_at`, aliases, chunk code metadata). Pages the source had sealed are rebuilt on the target before the config flip, without an embedding key, keeping chunk ids and vectors whose input matches. A failed rebuild blocks the flip: the run exits 1 with no error code, prints `The active engine was NOT switched` and the failing pages, and leaves the source engine active; fix them (`gbrain projections drain` on the target) and re-run `gbrain migrate` to resume. Pages the source had not sealed arrive queued, with their verbatim chunks. It does not carry request IDs, withdrawals, attribution or ownership, so it refuses a managed brain and any brain with durable write history, fact withdrawals or canonical worktree ownership (rows in `persistence_requests`, `fact_withdrawals` or `persistence_worktrees`).+The legacy copier handles every other direction: `gbrain migrate --to pglite`, PGLite to Postgres when `gbrain config set migrate.graduation false` opts out of graduation, and history-free brains on Windows. It re-creates pages through `putPage` (chunks, embeddings, links, tags, timeline, facts) and copies config rows minus the engine-local denylist (`MIGRATE_CONFIG_ENGINE_LOCAL_KEYS`: the target-owned `engine`/`version` connection + schema ledger and the physical embedding-column registry keys); skipped keys are printed, never silent, and the run ends with a per-table copied-count summary. It forwards the full page row (origin path, kind, provenance, `ingested_at`, aliases, chunk code metadata). Pages the source had sealed are rebuilt on the target before the config flip, without an embedding key, keeping chunk ids and vectors whose input matches. A failed rebuild blocks the flip: the run exits 1 with no error code, prints `The active engine was NOT switched` and the failing pages, and leaves the source engine active; fix them (`gbrain projections drain` on the target) and re-run `gbrain migrate` to resume. Pages the source had not sealed arrive queued, with their verbatim chunks. It does not carry request IDs, withdrawals, attribution or ownership, so it refuses a managed brain and any brain with durable write history, fact withdrawals or canonical worktree ownership (rows in `persistence_requests`, `fact_withdrawals` or `persistence_worktrees`), and a brain with a belief ledger (rows in `belief_events`), which it names.<a id="engine-migration-refused"></a>**Engine migration refused (`writer_coordinator_required`).** The legacy copier's refusal is an agent-contract envelope whose `fix` names the refusing side; every branch verifies with the read-only `gbrain doctor --no-migrate --json`, and nothing has changed in either datastore:diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex e6fd635be7..59c3bb1e66 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -17,7 +17,7 @@ src/core/cycle.ts 3315 ratchet +1 W1 belief ledger: the extract phase runs the ssrc/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.tssrc/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 countsrc/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 2065 ratchet +3 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +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 2062src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 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 importsdiff --git a/src/core/attendance-repair.ts b/src/core/attendance-repair.tsindex 24f020b831..59accb3968 100644--- a/src/core/attendance-repair.ts+++ b/src/core/attendance-repair.ts@@ -10,6 +10,7 @@ import { invalidatePackCache } from './schema-pack/registry.ts';import { ownsAttendanceInference } from './schema-pack/link-inference.ts';import { executeRawJsonb } from './sql-query.ts';import { applyAttendanceDelta } from './derived-links.ts';+import { unmanagedBeliefPoint } from './belief/projection-point.ts';export const ATTENDANCE_REPAIR_PARSER = `attendance-repair-v2:${LINK_EXTRACTOR_VERSION_TS}`;export const ATTENDANCE_REPAIR_LIMIT = 250;@@ -320,6 +321,7 @@ export async function applyAttendanceRepair(engine: BrainEngine, preview: Attendfor (const approved of pending) {const end = approved ? preview.window.findIndex(page => page.id === approved.page.id) + 1 : preview.window.length;const segment = preview.window.slice(pagesProcessed, end);+ const beliefs = approved ? unmanagedBeliefPoint(preview.sourceId, [approved.page.slug], 'attendance_repair') : null;const result = await engine.transaction(async tx => {await tx.executeRaw("SET LOCAL lock_timeout='5s'");await tx.executeRaw("SET LOCAL statement_timeout='10s'");@@ -360,7 +362,7 @@ export async function applyAttendanceRepair(engine: BrainEngine, preview: Attendreturn { created: 0, removed: 0, replayed: 1 };}if (attendanceRepairHash(prepared.result) !== attendanceRepairHash(approved)) throw new Error('Attendance edges or resolution changed; preview again');- const delta = await applyAttendanceDelta(tx, approved.page, approved.remove, prepared.additions);+ const delta = await beliefs!.run(tx, () => applyAttendanceDelta(tx, approved.page, approved.remove, prepared.additions));if ((await ontology(tx, preview.sourceId)).hash !== preview.ontology) throw new Error('Attendance ontology changed during repair');const after = await readEdges(tx, approved.page.id);if (!approved.reason && after.count > MAX_EDGES) throw new Error('Attendance delta exceeded its edge bound');@@ -368,6 +370,7 @@ export async function applyAttendanceRepair(engine: BrainEngine, preview: AttendVALUES ($1,$2,($3::jsonb)->'keys')`, [CHECKPOINT_OP, key], [{ keys: [attendanceRepairHash([after.edges, after.count])] }]);return { ...delta, replayed: 0 };});+ await beliefs?.commit(engine);pagesProcessed = end;if (approved) { committed++; originId = approved.page.id; }created += result.created; removed += result.removed; replayed += result.replayed;diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.tsindex 47c519f298..23807b126b 100644--- a/src/core/belief/ledger.ts+++ b/src/core/belief/ledger.ts@@ -68,6 +68,9 @@ export function beliefBatchCovers(sourceId: string, slugs: readonly string[]): breturn !!outer && outer.opts.sourceId === sourceId && slugs.every(slug => outer.opts.slugs.includes(slug));}+/** True inside any belief batch: a nested writer's own publication commits with the enclosing transaction, not before it. */+export const insideBeliefBatch = (): boolean => !!store.getStore();+/** Coverage and purge probes for one source, in one read. */export async function readLedgerSource(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<{ incarnation: string; purgeEpoch: number; coverage: string | null; purgesPossible: boolean } | null> {const [row] = await tx.executeRaw<Record<string, unknown>>(`SELECT s.incarnation::text AS incarnation, s.purge_epoch,diff --git a/src/core/belief/projection-point.ts b/src/core/belief/projection-point.tsnew file mode 100644index 0000000000..ebd0be2b1a--- /dev/null+++ b/src/core/belief/projection-point.ts@@ -0,0 +1,40 @@+/**+ * The unmanaged projection points (docs/designs/BELIEF_LEDGER.md section 4):+ * legacy import, the cycle's `writeFenceReconcile` and takes reextract write+ * outside the shared publication path, so each runs its transaction's+ * projections in an `unmanaged` belief batch over the page keys it holds+ * (sorted, locked before the batch reads its pre-state). A writer nested in+ * an enclosing batch that already records those slugs appends nothing of its+ * own. `commit` marks the publication after the transaction commits; a mark+ * left unwritten (a crash, or a point nested in another batch whose+ * transaction commits later) is filled by doctor or the cycle.+ */+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { markBeliefCommits } from './append.ts';+import { beliefBatchCovers, coverageActive, insideBeliefBatch, readLedgerSource, withBeliefBatch } from './ledger.ts';++export function unmanagedBeliefPoint(sourceId: string, slugs: readonly string[], op: string) {+ const sorted = [...new Set(slugs)].sort();+ const publicationId = randomUUID();+ const report = { appended: 0 };+ let nested = false;+ return {+ async run<T>(tx: BrainEngine, fn: () => Promise<T>): Promise<T> {+ if (beliefBatchCovers(sourceId, sorted)) return fn();+ nested = insideBeliefBatch();+ await tx.lockPageKeys(sorted.map(slug => ({ sourceId, slug })));+ return withBeliefBatch(tx, { sourceId, slugs: sorted, op, origin: 'unmanaged', publicationId, report }, fn);+ },+ async commit(engine: Pick<BrainEngine, 'executeRaw'>): Promise<void> {+ if (report.appended && !nested) await markBeliefCommits(engine, [publicationId]);+ },+ };+}++/** The given sources whose ledger records now: a bulk writer wraps only their items. */+export async function beliefCoveredSources(tx: Pick<BrainEngine, 'executeRaw'>, sourceIds: readonly string[]): Promise<Set<string>> {+ const covered = new Set<string>();+ for (const sourceId of new Set(sourceIds)) if (coverageActive((await readLedgerSource(tx, sourceId))?.coverage ?? null)) covered.add(sourceId);+ return covered;+}diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 78bb483106..4a43df48c0 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -48,6 +48,7 @@* structurally unfenceable and never gate.*/+import { unmanagedBeliefPoint } from '../belief/projection-point.ts';import { isQuarantined } from '../quarantine.ts';import { existsSync, readFileSync } from 'node:fs';@@ -1076,7 +1077,8 @@ export async function runExtractFacts(const authority = await managedAuthority();if (authority) return publishFenceReconcile(engine, authority, page, slug, toInsert);try {- return await maintenanceTransaction(engine, async tx => {+ const beliefs = unmanagedBeliefPoint(sourceId, [slug], 'extract_facts');+ const written = await maintenanceTransaction(engine, tx => beliefs.run(tx, async () => {opts.signal?.throwIfAborted();if (watermark && !await lockReconcileRevision(tx, sourceId, slug, page.knowledge_revision ?? null)) return null;const current = await tx.getPage(slug, { sourceId });@@ -1084,7 +1086,9 @@ export async function runExtractFacts(const written = await writeFenceReconcile(tx, sourceId, slug, plan, writes, opts.signal);if (watermark && !deferInserts) await settleFactsReconcile(tx, sourceId, slug, 'complete', page.knowledge_revision ?? null);return written;- });+ }));+ await beliefs.commit(engine);+ return written;} catch (error) {if (!isAborted(opts.signal)) throw error;result.warnings.push(`${slug}: fact reconciliation cancelled; transaction rolled back`);diff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.tsindex 063de2bdad..bf804f5242 100644--- a/src/core/cycle/extract-takes.ts+++ b/src/core/cycle/extract-takes.ts@@ -25,6 +25,8 @@* v0.22.12 classifier path (extension follow-up — not blocking v0.28).*/+import { unmanagedBeliefPoint } from '../belief/projection-point.ts';+import { coveredSources } from '../belief/coverage-report.ts';import { isQuarantined, QUARANTINE_KEY } from '../quarantine.ts';import { readFileSync } from 'node:fs';import { join, relative, sep } from 'node:path';@@ -326,6 +328,7 @@ export async function extractTakesFromDb(const refs = (await engine.listAllPageRefs()).filter(ref => (!slugFilter || slugFilter.has(ref.slug)) && (!opts.sourceId || ref.source_id === opts.sourceId));const buffer: TakeBatchInput[] = [];const coordinated = !dryRun && await managedPersistenceEnabled(engine);+ const covered = dryRun || coordinated ? new Set<string>() : new Set(await coveredSources(engine));const authorities = new Map<string, Promise<MaintenanceAuthority>>();const authorityFor = (sourceId: string) => {if (!authorities.has(sourceId)) authorities.set(sourceId, maintenancePreflight(engine, sourceId).then(a => a!));@@ -346,6 +349,15 @@ export async function extractTakesFromDb(}continue;}+ if (covered.has(source_id)) {+ const beliefs = unmanagedBeliefPoint(source_id, [slug], 'takes_reextract');+ await maintenanceTransaction(engine, tx => beliefs.run(tx, async () => {+ const takes = await reconcilePageTakes(tx, page, slug, rebuild, false, result);+ result.takesUpserted += await upsertProjectedTakes(engine, takes.map(t => parsedTakeToBatchInput(page.id, t)), result, tx);+ }));+ await beliefs.commit(engine);+ continue;+ }const takes = await reconcilePageTakes(engine, page, slug, rebuild, dryRun, result);for (const t of takes) {buffer.push(parsedTakeToBatchInput(page.id, t));diff --git a/src/core/derived-links.ts b/src/core/derived-links.tsindex bf1107ff27..a11487e115 100644--- a/src/core/derived-links.ts+++ b/src/core/derived-links.ts@@ -1,6 +1,7 @@import type { BrainEngine, LinkBatchInput } from './engine.ts';import { assertPageRevision, PageRevisionConflictError, RevisionBackfillPendingError, type PageSnapshot } from './page-state/types.ts';import { pipelined } from './page-state/transactions.ts';+import { beliefCoveredSources, unmanagedBeliefPoint } from './belief/projection-point.ts';import { executeRawJsonb } from './sql-query.ts';import { pageSnapshotKey } from './page-snapshot-batch.ts';import { sanitizeForJsonb } from './batch-rows.ts';@@ -145,21 +146,24 @@ const lockedExtractionGeneration = async (tx: BrainEngine) => (await tx.executeR'SELECT value FROM config WHERE key = $1 FOR SHARE', [LINK_EXTRACTION_GENERATION_KEY]))[0]?.value ?? null;export async function replaceDerivedLinks(- engine: Pick<BrainEngine, 'transaction'>,+ engine: Pick<BrainEngine, 'transaction' | 'executeRaw'>,origin: DerivedLinkOrigin,links: LinkBatchInput[],opts: DerivedLinkReplacementOptions = {},): Promise<{ created: number; removed: number }> {const { producers, rows } = derivedLinkRows(origin, links, opts);- return engine.transaction(async tx => {+ const beliefs = unmanagedBeliefPoint(origin.sourceId, [origin.slug], 'derived_links');+ const result = await engine.transaction(async tx => {await pipelined(tx, [async () => { if (!opts.semanticsPrimed) await primeRelationSemantics(tx); },() => tx.lockPageKeys(derivedLinkLockKeys(origin, rows)),]);if (opts.lineGrammar && await lockedExtractionGeneration(tx) !== opts.lineGrammar.generation) throw new DerivedLinkSettingsChangedError();const snapshot = origin.snapshot !== undefined ? origin.snapshot : await tx.readPageSnapshot(origin.slug, { sourceId: origin.sourceId });- return publishDerivedLinks(tx, origin, producers, rows, opts, snapshot);+ return beliefs.run(tx, () => publishDerivedLinks(tx, origin, producers, rows, opts, snapshot));});+ await beliefs.commit(engine);+ return result;}export interface DerivedLinkBatchItem { origin: DerivedLinkOrigin; links: LinkBatchInput[]; opts?: DerivedLinkReplacementOptions }@@ -174,12 +178,13 @@ export interface DerivedLinkBatchItem { origin: DerivedLinkOrigin; links: LinkBa* one by one through replaceDerivedLinks.*/export async function replaceDerivedLinksBatch(- engine: Pick<BrainEngine, 'transaction'>,+ engine: Pick<BrainEngine, 'transaction' | 'executeRaw'>,items: readonly DerivedLinkBatchItem[],): Promise<Array<{ created: number; removed: number }>> {const prepared = items.map(item => ({ origin: item.origin, opts: item.opts ?? {}, ...derivedLinkRows(item.origin, item.links, item.opts ?? {}) }));if (!prepared.length) return [];- return engine.transaction(async tx => {+ const beliefs = prepared.map(item => unmanagedBeliefPoint(item.origin.sourceId, [item.origin.slug], 'derived_links'));+ const results = await engine.transaction(async tx => {await pipelined(tx, [async () => { if (prepared.some(item => !item.opts.semanticsPrimed)) await primeRelationSemantics(tx); },() => tx.lockPageKeys(prepared.flatMap(item => derivedLinkLockKeys(item.origin, item.rows))),@@ -190,13 +195,17 @@ export async function replaceDerivedLinksBatch(}const { snapshots } = await tx.readPageSnapshotsBatch(prepared.filter(item => item.origin.snapshot === undefined).map(item => ({ slug: item.origin.slug, sourceId: item.origin.sourceId })), { maxBytes: Number.MAX_SAFE_INTEGER });+ const covered = await beliefCoveredSources(tx, prepared.map(item => item.origin.sourceId));const results: Array<{ created: number; removed: number }> = [];- for (const { origin, producers, rows, opts } of prepared) {+ for (const [i, { origin, producers, rows, opts }] of prepared.entries()) {const snapshot = origin.snapshot !== undefined ? origin.snapshot : snapshots.get(pageSnapshotKey(origin.sourceId, origin.slug)) ?? null;- results.push(await publishDerivedLinks(tx, origin, producers, rows, opts, snapshot));+ const publish = () => publishDerivedLinks(tx, origin, producers, rows, opts, snapshot);+ results.push(await (covered.has(origin.sourceId) ? beliefs[i]!.run(tx, publish) : publish()));}return results;});+ for (const point of beliefs) await point.commit(engine);+ return results;}/**diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 79511499d3..25cfbe1d75 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 { unmanagedBeliefPoint } from './belief/projection-point.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';@@ -881,7 +882,8 @@ export async function importFromContent(validate: tx => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),apply: applyPrepared, ...(segmented ? { afterCommit: segmented.afterCommit, segmented } : {}),});- await maintenanceTransaction(engine, applyPrepared, writeTrustOfGate(opts.writeGate)).catch(async (err: unknown) => {+ const beliefs = unmanagedBeliefPoint(txOpts.sourceId, [slug], 'import');+ await maintenanceTransaction(engine, tx => beliefs.run(tx, () => applyPrepared(tx)), writeTrustOfGate(opts.writeGate)).catch(async (err: unknown) => {await abortSegmentedStaging(engine, segmented?.prepared);// #4287: name the dimension-mismatch rollback instead of letting the bare// pgvector message ("expected N dimensions, not M") surface with no code,@@ -898,6 +900,7 @@ export async function importFromContent(}throw decorateEmbeddingDimError(err, slug, activeColName);});+ await beliefs.commit(engine);await segmented?.afterCommit(engine);diff --git a/src/core/persistence/effect-links.ts b/src/core/persistence/effect-links.tsindex d5584b0c7e..6a6d808258 100644--- a/src/core/persistence/effect-links.ts+++ b/src/core/persistence/effect-links.ts@@ -1,4 +1,5 @@import type { BrainEngine, LinkBatchInput } from '../engine.ts';+import { unmanagedBeliefPoint } from '../belief/projection-point.ts';import type { PageSnapshot } from '../page-state/types.ts';import { OperationError } from '../ops/contract.ts';import { matchesSlugAllowList, slugUnderBoundPrefixes } from '../ops/context.ts';@@ -84,6 +85,7 @@ export async function runLinksEffect(engine: BrainEngine, effect: PersistenceEffif (!await isAutoLinkEnabled(engine) || !await isRemoteAutoLinksEnabled(engine)) return skip(engine, 'disabled');if (isSegmentedPage(snapshot.page)) return skip(engine, 'page_body_segmented');const { targets, skipped } = await mentionTargets(engine, snapshot, sourceId);+ const beliefs = unmanagedBeliefPoint(sourceId, [snapshot.page.slug], 'remote_auto_links');await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");await guardEffectSource(tx, effect, hostId);@@ -115,8 +117,10 @@ export async function runLinksEffect(engine: BrainEngine, effect: PersistenceEffconst additions: LinkBatchInput[] = [...wanted].filter(([slug]) => !kept.has(slug)).map(([slug, context]) => ({from_slug: live.page.slug, to_slug: slug, from_source_id: sourceId, to_source_id: sourceId, link_type: 'mentions', context,link_source: REMOTE_MENTION_LINK_SOURCE, link_kind: 'plain', origin_slug: live.page.slug, origin_source_id: sourceId }));- if (obsolete.length) await tx.executeRaw('DELETE FROM links WHERE id=ANY($1::bigint[])', [obsolete]);- const added = additions.length ? await tx.addLinksBatch(additions, { auditSite: 'addLinksBatch' }) : 0;+ const added = await beliefs.run(tx, async () => {+ if (obsolete.length) await tx.executeRaw('DELETE FROM links WHERE id=ANY($1::bigint[])', [obsolete]);+ return additions.length ? await tx.addLinksBatch(additions, { auditSite: 'addLinksBatch' }) : 0;+ });// Wanted pages: a missing mention target is recorded so the edge appears once that page is written (core/wanted-links.ts).if (await isRemoteWantedPagesEnabled(tx)) {await replaceWantedLinks(tx, { pageId: Number(live.page.id), sourceId }, { producers: ['body'], rows: skipped@@ -127,4 +131,5 @@ export async function runLinksEffect(engine: BrainEngine, effect: PersistenceEffawait completeEffect(tx, effect, { links: 'committed', added, removed: obsolete.length, skipped_targets: skipped.slice(0, SKIPPED_TARGET_LIMIT),...(skipped.length > SKIPPED_TARGET_LIMIT ? { skipped_target_count: skipped.length } : {}) });});+ await beliefs.commit(engine);}diff --git a/test/belief-ledger-coverage.test.ts b/test/belief-ledger-coverage.test.tsindex 4d3df3129b..0e27b385e8 100644--- a/test/belief-ledger-coverage.test.ts+++ b/test/belief-ledger-coverage.test.ts@@ -27,6 +27,11 @@ import { assertLegacyEngineMigration } from '../src/core/persistence/maintenanceimport { copiedEntries, copyAll, digestMismatches } from './helpers/graduation-copy-harness.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { testBackends } from './helpers/test-backends.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { extractTakes } from '../src/core/cycle/extract-takes.ts';+import { extractStaleFromDB } from '../src/commands/extract.ts';+import { backfillBeliefHistory } from '../src/core/belief/backfill.ts';import { beliefLedgerEntry } from '../src/commands/doctor/checks/belief-ledger.ts';import type { DoctorContext } from '../src/commands/doctor/context.ts';import type { Check } from '../src/commands/doctor.ts';@@ -392,6 +397,78 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {}, { enable: false });}, 180_000);+ test('unmanaged projection points: legacy import, extract_facts, takes reextract and derived links each append one marked unmanaged publication; a dropped point shows as drift', async () => {+ await brain(async b => {+ const marked = async (publicationId: string) => (await b.engine.executeRaw('SELECT 1 FROM belief_commit_marks WHERE publication_id = $1::uuid', [publicationId])).length === 1;+ const projectedDrift = async () => (await scanBeliefDrift(b.engine, b.sourceId, { deep: true })).drifted.map(d => d.slug).filter(slug => !slug.startsWith('extracts/'));+ const step = async (run: () => Promise<unknown>) => {+ const before = await b.lastId();+ await run();+ const events = await b.events(before);+ expect(new Set(events.map(e => e.publication_id)).size).toBe(1);+ expect(await marked(events[0]!.publication_id)).toBe(true);+ return events.map(e => [e.slug, `${e.subject_kind}:${e.event_type}`, e.origin, e.cause.op]);+ };+ const importPage = (slug: string, body: string) => importFromContent(b.engine, slug, body, { sourceId: b.sourceId, noEmbed: true });+ await importPage('people/alice-example', beliefPage({ type: 'person', title: 'Alice Example' }));+ const acme = beliefPage({ facts: ['Acme raised a seed round'], takes: ['Acme will win its market'], links: ['people/alice-example'] });+ expect(await step(() => importPage('companies/acme-example', acme))).toEqual([['companies/acme-example', 'page:page.published', 'unmanaged', 'import']]);+ expect(await step(() => runExtractFacts(b.engine, { sourceId: b.sourceId, slugs: ['companies/acme-example'] })))+ .toEqual([['companies/acme-example', 'fact:fact.asserted', 'unmanaged', 'extract_facts']]);+ expect(await step(() => extractTakes(b.engine, { source: 'db', sourceId: b.sourceId, slugs: ['companies/acme-example'] })))+ .toEqual([['companies/acme-example', 'take:take.asserted', 'unmanaged', 'takes_reextract']]);+ expect(await step(() => extractStaleFromDB(b.engine, { dryRun: false, jsonMode: false, quiet: true, sourceIdFilter: b.sourceId, catchUp: false })))+ .toEqual([['companies/acme-example', 'link:link.asserted', 'unmanaged', 'derived_links']]);+ expect(await projectedDrift()).toEqual([]);+ // Forced probe: a takes reextract whose events are dropped leaves its slug drifted.+ await importPage('companies/beta-example', beliefPage({ title: 'Beta Example', takes: ['Beta will ship late'] }));+ fault(drafts => drafts.filter(d => d.cause.op !== 'takes_reextract'));+ await extractTakes(b.engine, { source: 'db', sourceId: b.sourceId, slugs: ['companies/beta-example'] });+ __setBeliefEmitterFaultForTests(null);+ expect(await projectedDrift()).toEqual(['companies/beta-example']);+ }, { managed: false });+ }, 180_000);++ test('backfill from page_versions: one marked backfill publication per version, historical time in source_time only, idempotent, and a purge mid-run re-prepares', async () => {+ await brain(async b => {+ await b.put('companies/acme-example', beliefPage({ facts: ['Acme raised a seed round'], takes: ['Acme will win its market'] }));+ await b.put('companies/acme-example', beliefPage({ facts: ['Acme raised a seed round', 'Acme has ten staff'], takes: ['Acme will win its market'] }));+ await b.put('companies/acme-example', beliefPage({ facts: ['Acme has ten staff'], takes: [{ claim: 'Acme will win its market', weight: '0.4' }] }));+ await expect(backfillBeliefHistory(b.engine, b.sourceId)).rejects.toMatchObject({ code: 'belief_coverage_required' });+ await b.enable();+ const since = (await coverageIntervals(b.engine, b.sourceId))[0]!.started_at;+ const before = await b.lastId();+ let bumped = 0;+ const report = await backfillBeliefHistory(b.engine, b.sourceId, { prepareHook: async (_slug, attempt) => {+ if (attempt === 0) { bumped++; await b.engine.executeRaw('UPDATE sources SET purge_epoch = purge_epoch + 1 WHERE id = $1', [b.sourceId]); }+ } });+ expect(bumped).toBe(1);+ expect(report).toMatchObject({ since, events: 9, retried: 1, pages: [{ slug: 'companies/acme-example', versions: 3, events: 9, complete: true, reasons: [] }] });+ const events = await b.events(before);+ expect(events.map(e => [`${e.subject_kind}:${e.event_type}`, e.cause.version === null ? 'start' : 'version', e.value?.fact ?? e.value?.weight ?? null])).toEqual([+ ['page:page.published', 'version', null], ['fact:fact.asserted', 'version', 'Acme raised a seed round'], ['take:take.asserted', 'version', 0.5],+ ['page:page.published', 'version', null], ['fact:fact.asserted', 'version', 'Acme has ten staff'],+ ['page:page.published', 'start', null], ['fact:fact.retracted', 'start', null], ['take:take.revised', 'start', 0.4],+ ['page:backfill', 'version', null]]);+ expect(events.every(e => e.origin === 'backfill')).toBe(true);+ expect(events.at(-1)!.value).toEqual({ backfill_complete: true, versions: 2, reasons: [], coverage_start: since });+ expect(events.at(-1)!.cause).toEqual({ op: 'backfill', purge_epoch: 1 });+ const times = await b.engine.executeRaw<{ source_time: string | null; recorded_at: string; marked: boolean }>(`SELECT e.source_time, e.recorded_at,+ EXISTS (SELECT 1 FROM belief_commit_marks m WHERE m.publication_id = e.publication_id) AS marked FROM belief_events e WHERE e.source_id = $1 AND e.id > $2 ORDER BY e.id`, [b.sourceId, before]);+ const ms = (v: unknown) => new Date(v as string).getTime();+ expect(times.every(t => t.marked && t.source_time !== null && ms(t.source_time) <= ms(since) && ms(t.recorded_at) >= ms(since))).toBe(true);+ expect(new Set(events.map(e => e.publication_id)).size).toBe(4);+ expect((await backfillBeliefHistory(b.engine, b.sourceId)).events).toBe(0);+ expect(await b.lastId()).toBe(events.at(-1)!.id);+ // Forced probe: a purge on every attempt exhausts the retries and refuses with belief_preparation_stale.+ await b.put('companies/beta-example', beliefPage({ title: 'Beta Example', facts: ['Beta ships late'] }));+ await b.engine.executeRaw(`UPDATE pages SET created_at = $2::timestamptz - interval '1 hour' WHERE source_id = $1 AND slug = 'companies/beta-example'`, [b.sourceId, since]);+ await expect(backfillBeliefHistory(b.engine, b.sourceId, { slugs: ['companies/beta-example'], prepareHook: async () => {+ await b.engine.executeRaw('UPDATE sources SET purge_epoch = purge_epoch + 1 WHERE id = $1', [b.sourceId]);+ } })).rejects.toMatchObject({ code: 'belief_preparation_stale' });+ }, { enable: false });+ }, 180_000);+test('probe 9: graduation PGLite -> ' + engineCase.name + ' carries an identical ledger: equal event_key sets, digests and replay', async () => {await beliefBrain(async b => {await seeded(b);