Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Stop the first managed facts fence from retiring facts nobody withdrew; add gbrain repair unwithdrawn-facts (#8819)

garrytan8d3b1ce4d12c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5017d333fe..3288192ca6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A page write or a managed `extract_facts` run no longer retires facts that the page's `## Facts` fence never held, and `gbrain repair unwithdrawn-facts` restores the ones earlier releases retired.** A fact a `put_page` writer attached to a page with a row number, but that was never in the page's fence, used to be expired by any later write that projected the fence. That included a write that changed nothing in the fence, often the page's first facts-fence generation, which `gbrain repair generations` cannot undo because it has no earlier generation. Now a row retires only when a fence held it: a facts-fence generation recorded it, the page as the writer read it carried it, or a stored version of the page did. Every other row stays active with its id. Removing a row from the fence still retires it, as before. Doctor `unwithdrawn_facts` counts the facts that were already retired and points to the new repair, which previews first and restores the original fact ids and lifecycle from the generation ledger. It works on brains with and without a repository.
+
+### Itemized changes
+
+- `src/core/generations/fence-evidence.ts` (new): `factsFenceHeld` decides whether a fence ever held a fact row, from the facts-fence ledger, the replaced body and the page's stored versions. `moveKeptRows` moves a kept row whose number an incoming fence row claims above the page's rows.
+- `src/core/generations/adapters/fact-rows.ts`, `src/core/persistence/canonical-projections.ts`, `src/core/trust/fence-guard.ts`: the page projection's fact generation retires only held rows. Conversation-extractor rows still give up a number a fence row claims. Its expire statement and the trust guard leave kept rows alone.
+- `src/core/cycle/extract-facts.ts`: on a managed brain the reconcile keeps stale rows no fence held, and moves one whose number a new fence row needs. An unmanaged brain's reconcile is unchanged.
+- `src/core/repair/unwithdrawn-facts.ts` and `src/commands/doctor/checks/unwithdrawn-facts.ts` (new): `gbrain repair unwithdrawn-facts [--include-ambiguous] [--apply --expect <hash>]`, bound to each page's revision at preview. Managed brains apply it through a database-only `managed_maintenance_restore_unwithdrawn_facts` request; unmanaged brains apply it under the page lock. A fact a fence held, a withdrawn, superseded or duplicated fact, and a page written since the preview are refused. Doctor check `unwithdrawn_facts`.
+- Tests: `test/fence-first-generation-8819.test.ts` and `test/repair-unwithdrawn-facts-8819.test.ts`, on PGLite and Postgres.
+
## [0.60.609.0] - 2026-11-07
**`POST /ingest` no longer answers 202 for a capture it drops, and an unsigned GitHub webhook can no longer tell from response time which repositories a brain syncs.** The same body sent to two slugs now queues two captures, where the second caller used to get the first job back and nothing written to its slug. A capture over the 50-capture waiting cap now gets 429 `ingest_backlog_full` with `Retry-After: 30` and nothing queued, where it used to get another capture's job id. A slug over 1024 bytes gets 400 `invalid_slug` before anything is queued, well short of the roughly 2.7 KB where no page can be stored under it. Every webhook request now computes the HMAC over its body, whether the repository is unknown, has no secret or is covered by a source, so a 401 takes the same work either way.
diff --git a/docs/architecture/generations.md b/docs/architecture/generations.md
index 059a172feb..82aaa5f542 100644
--- a/docs/architecture/generations.md
+++ b/docs/architecture/generations.md
@@ -70,6 +70,13 @@ ledger. A fence restore (`fence-restore.ts`) writes the earlier generation's fen
through a guarded `put_page` bound to its revision, leaving the body, timeline, tags and the other fence alone, and
refuses a fence edited since (`edited_since`, `section_moved`).
+#8819: a published fact generation retires only rows a fence of the page held at the same row number, claim and
+visibility (`generations/fence-evidence.ts`): a `fact_fence` generation recorded it, the body the writer replaced carried
+it, or a stored version of the page did. A row the fence never held (a fact a `put_page` writer attached to the page)
+stays active, and an incoming fence row that claims its number takes it while the row moves above the page's rows. The
+managed `extract_facts` reconcile applies the same rule; an unmanaged brain's reconcile still treats rows its fence lacks
+as drift. Rows an earlier release retired this way are restored by `gbrain repair unwithdrawn-facts`.
+
The dream consolidate phase records each cluster (`consolidation`, key `entity:<slug>:cluster:<ids>`,
`adapters/fact-rows.ts`): a strict chain records each member's `valid_until`, `consolidated_at` and
`consolidated_into` before it closes them (unmanaged and managed), a same-instant tie (#6023) is held `tie` with nothing
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 2f33645466..e558aec7fd 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -14,6 +14,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` and no recorded origin (blank `source_path` and `source_uri`) per source, via `databaseOnlyPageSql` (`persistence/unbound-pages.ts`), the SQL form of `isDatabaseOnlyPage` (#6536). A managed sync that records a page's origin, and a reconcile apply, clear the marker. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Tests: `e2e/unbound-source-postgres`, `unbound-source-6536`.
- `src/commands/doctor/checks/revision-backfill.ts` — `revision_backfill` (#5216, META, registered before `search_mode`): reads `readRevisionBackfillStatus` (column state, pages still without `knowledge_revision`, failed rows still pending with their page). ok when the column is NOT NULL; warn with the pending count and `gbrain apply-migrations --force-schema` as `fix` while any row is resumable (or only the NOT NULL step remains); failed rows are listed by page id, `source:slug`, attempt and error, and when only rows with spent attempts remain the `fix` is the read-only `gbrain repair orphan-children` preview. Tests: `test/doctor-revision-backfill.test.ts`.
- `src/commands/doctor/checks/extractor-facts.ts` — `extractor_facts_expired` (#5731): counts conversation-extractor facts the pre-v0.60.11.0 projection expired, by class (`evidenced`, `ambiguous`; `excluded` reported but never a finding) through `classifyExtractorFacts`, and names `gbrain repair extractor-facts` (explicit-only, so the remediation plan and banner list it with its preview). Read-only; health unknown when the query fails.
+- `src/commands/doctor/checks/unwithdrawn-facts.ts` — `unwithdrawn_facts` (#8819): counts facts a facts-fence generation retired although no fence of their page held them, by class (`evidenced`, `ambiguous`; `excluded` reported but never a finding) through `classifyUnwithdrawnFacts`, and names the explicit-only `gbrain repair unwithdrawn-facts` preview. Read-only.
- `src/commands/doctor/checks/atom-retirements.ts` — `atom_retirements_restorable` (#7013, BRAIN, a `WAVE_CHECKS` entry with `resolution: 'repair'`, host-only, cleared by the explicit-only `atoms-restore`, so remediation classifies it `explicit_kind_required`): counts the `restorable` rows of `atomRetirementsSql` per source; `warn` names the count, origins, oldest and newest `retired_at`, the end of the earliest purge hold (`hold_until`) and the read-only preview `gbrain repair atoms-restore --source <id> --json` as an agent `fix`; the apply is the user's call.
- `src/commands/doctor/checks/conversation-outcomes.ts` — `conversation_label_facts` (wave check, host-only, resolution `repair`): bounded count (capped at 1000, reported as at least N) of the default set `gbrain repair conversation-labels` would retire; names the preview, never the apply. `conversation_outcomes_stale` (wave check, host-only, resolution `operator`): counts active conversation extraction outcomes stamped with an older `extractor_version` than `CONVERSATION_EXTRACTOR_VERSION` (outcomes are never reopened automatically) and names the `--force --dry-run` re-extract preview; outcomes older than the stamp are counted as `unstamped` and never warn. Bounded scan of the extractor rows, capped at 5000 (reported as at least N). Read-only.
- `src/commands/doctor/checks/captured-facts.ts` — `captured_facts_active` (wave check, host-only): counts active capture-lane facts (`hook:writeback`, `hook:compact`, `sweep:corpus`) that `classifyCapturedFacts` classes as self-capture (`evidenced`) or paste candidates (`ambiguous`); `excluded` and `unclassifiable` are reported, never a finding. Names `gbrain repair captured-facts` (explicit-only) and says it counts facts while `self_capture` counts corpus files. Read-only; health unknown when the scan fails.
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 79fc5778a8..9a4bbd28d2 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -28,7 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
Both paths prevent LLM-chosen titles that drift between extractions from piling up.
Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (keyed `(source_id, file_path, content_hash)`, 16-char hash prefix, so an edit is a new row): `recordItemFailureCount` counts a transcript's malformed output or prompt-level provider block (`providerContentBlockReason`; never feeds the outage halt) toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (as pages do), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.
-- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first fences the source's unfenced rows (`row_num IS NULL`, live entity page, never ontology observations: `dimension IS NULL`, #6264) through `facts/unfenced-facts.ts` and adds those pages to the run's reconcile set (`unfencedRowsFenced`); rows it cannot fence this run (canonical file not on this host, malformed fence, held page lock, a claim the fence codec cannot render) are named as `FACTS_FENCE_FAILED: <slug> (<reason>)` and keep their own page out of the destructive reconcile (the empty-fence guard, per page since #6278: `pendingLegacyRows` lists the pages, `legacyRowsPending` and `legacyPages` report them, and every other page of the source still reconciles; the page keeps its fact index because reconciliation would classify its `row_num IS NULL` rows as stale and expire them). The phantom-redirect pass moves rows by fence position and so still waits until the source has no unfenced rows. `runPhaseExtractFacts` (`cycle.ts`) then reports the reconcile counts of the pages that did reconcile and names the skipped pages in its summary. Rows with no backing page or checkout, and ontology observations, never gate. It then expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. On an unmanaged brain each reconcile records its outcome in `page_facts_reconcile` (`src/core/facts/reconcile-watermark.ts`): a complete reconcile (including a no-op) stamps the page's `knowledge_revision` inside the write transaction, after a `FOR SHARE` lock and a revision recheck (a moved page writes nothing and stays due); `deferred` (lock, stale cache, embedding deferral, rejected write), `invalid` (malformed or misplaced fence, not retried until the page changes) and `cancelled` leave it due. The dream cycle passes `drain`, so an incremental run also reconciles up to 250 due pages within 60 s, never-attempted first then oldest attempt, after settling in bulk the due pages with no fence marker and no fence rows; a fence imported by a standalone sync or removed from a page is therefore reconciled even when the cycle's own sync changed nothing. A direct call with `slugs: []` and no `drain` still reconciles nothing. Doctor's `extract_health` names unreconciled fence pages and unreadable fences on unmanaged brains. Tests: `test/extract-facts-reconcile-drain.test.ts` (Postgres race through `test/e2e/extract-facts-reconcile-drain-postgres.test.ts`), `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-unfenced-rows.test.ts` (a mixed page, on PGLite and through the Postgres E2E), `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. Each deleted page's expiry is one item (ItemRun site `extract_facts.expire_deleted`, src/core/item-failure.ts): a refused expiry is a `FACTS_EXPIRE_FAILED: <slug>: <code>: …` warning (the phase warns) retried by the next run, a page the refusal breaker holds back is a `FACTS_EXPIRE_SKIPPED` warning, and run-scoped errors or most pages failing (`item_failures_systemic`) still fail the phase; test `test/pathological/a21-facts-expire-deleted.test.ts`. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`. Wave B PR 2 (lane 2e2): a segmented page reconciles like an inline one, its fences read from its marker segments (`segmentedFactsFenceView`), its write guarded by content hash and size, and its stale-cache check streamed against the canonical file (`segmentedBodyMatchesFile`, page-body/segment-facts.ts); test `test/large-pages/segmented-facts-reconcile.test.ts`. #6259: it and `extract-takes.ts` (both the DB walk and the file walk, which checks the stored page) skip a quarantined page, leaving rows projected before it was quarantined as they are. Test: `test/quarantine-fence-projection.test.ts`. #6946: a gbrain-owned `--url` clone on an unmanaged brain never gates the empty-fence guard (its facts are database-only by design).
+- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first fences the source's unfenced rows (`row_num IS NULL`, live entity page, never ontology observations: `dimension IS NULL`, #6264) through `facts/unfenced-facts.ts` and adds those pages to the run's reconcile set (`unfencedRowsFenced`); rows it cannot fence this run (canonical file not on this host, malformed fence, held page lock, a claim the fence codec cannot render) are named as `FACTS_FENCE_FAILED: <slug> (<reason>)` and keep their own page out of the destructive reconcile (the empty-fence guard, per page since #6278: `pendingLegacyRows` lists the pages, `legacyRowsPending` and `legacyPages` report them, and every other page of the source still reconciles; the page keeps its fact index because reconciliation would classify its `row_num IS NULL` rows as stale and expire them). The phantom-redirect pass moves rows by fence position and so still waits until the source has no unfenced rows. `runPhaseExtractFacts` (`cycle.ts`) then reports the reconcile counts of the pages that did reconcile and names the skipped pages in its summary. Rows with no backing page or checkout, and ontology observations, never gate. It then expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. On an unmanaged brain each reconcile records its outcome in `page_facts_reconcile` (`src/core/facts/reconcile-watermark.ts`): a complete reconcile (including a no-op) stamps the page's `knowledge_revision` inside the write transaction, after a `FOR SHARE` lock and a revision recheck (a moved page writes nothing and stays due); `deferred` (lock, stale cache, embedding deferral, rejected write), `invalid` (malformed or misplaced fence, not retried until the page changes) and `cancelled` leave it due. The dream cycle passes `drain`, so an incremental run also reconciles up to 250 due pages within 60 s, never-attempted first then oldest attempt, after settling in bulk the due pages with no fence marker and no fence rows; a fence imported by a standalone sync or removed from a page is therefore reconciled even when the cycle's own sync changed nothing. A direct call with `slugs: []` and no `drain` still reconciles nothing. Doctor's `extract_health` names unreconciled fence pages and unreadable fences on unmanaged brains. Tests: `test/extract-facts-reconcile-drain.test.ts` (Postgres race through `test/e2e/extract-facts-reconcile-drain-postgres.test.ts`), `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-unfenced-rows.test.ts` (a mixed page, on PGLite and through the Postgres E2E), `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. Each deleted page's expiry is one item (ItemRun site `extract_facts.expire_deleted`, src/core/item-failure.ts): a refused expiry is a `FACTS_EXPIRE_FAILED: <slug>: <code>: …` warning (the phase warns) retried by the next run, a page the refusal breaker holds back is a `FACTS_EXPIRE_SKIPPED` warning, and run-scoped errors or most pages failing (`item_failures_systemic`) still fail the phase; test `test/pathological/a21-facts-expire-deleted.test.ts`. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`. Wave B PR 2 (lane 2e2): a segmented page reconciles like an inline one, its fences read from its marker segments (`segmentedFactsFenceView`), its write guarded by content hash and size, and its stale-cache check streamed against the canonical file (`segmentedBodyMatchesFile`, page-body/segment-facts.ts); test `test/large-pages/segmented-facts-reconcile.test.ts`. #6259: it and `extract-takes.ts` (both the DB walk and the file walk, which checks the stored page) skip a quarantined page, leaving rows projected before it was quarantined as they are. Test: `test/quarantine-fence-projection.test.ts`. #6946: a gbrain-owned `--url` clone on an unmanaged brain never gates the empty-fence guard (its facts are database-only by design). #8819: on a managed brain `planFenceReconcile` keeps stale positioned rows no fence of the page held (`generations/fence-evidence.ts`) out of the retirements (`kept`), and `writeFenceReconcile` moves one whose number a new fence row needs (`moveKeptRows`); an unmanaged brain's reconcile still retires rows its fence lacks as drift.
- `src/core/cycle/inline-drain.ts` — the dream cycle's private-queue drain. `runSubagentsInline(engine, queue, queueName, yieldDuringPhase?, handler?, lockMs?, concurrency?)` runs N independent `drainLoop`s (`dream.synthesize.inline_concurrency`, clamp [1,8], PGLite forced serial at the callsite) sharing the queue via the same SKIP-LOCKED claim fencing workers use — everything job-scoped (lockToken, abort, timeout timer, keepalive, renewTimer, outcome recording) stays loop-local. Pool hygiene: global housekeeping sweeps are leader-only (loop 0) while `promoteDelayed` runs in every loop; idle claim-poll backs off 1s→5s; a NON-retryable loop-level failure aborts siblings after their current child (a failing child is a job outcome, never a drain crash). Exit only when the queue holds no active/waiting/delayed child (a lease-full bounce's delayed backoff must not strand a child). Outcome routing mirrors the worker: `UnrecoverableError` → dead immediately; `RateLeaseUnavailableError` → `releaseLeaseFullJob` requeue without burning an attempt; timeout terminal. Handler invocation is wrapped in `withChatPhase('job:<name>')` (worker.ts parity) so each drained child's gateway spend is attributed to the CHILD — a bare `await handler(context)` inherits the caller's AsyncLocalStorage phase, and a cycle phase that wraps its own work (dream synthesize wraps `phase:synthesize`) would absorb every child's spend into the phase tag. `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) and the null-safe nearest-rank `percentile()` telemetry helper are exported. Pinned by `test/cycle-synthesize-inline-concurrency.test.ts` (loop semantics) + `test/e2e/dream-synthesize-concurrency-postgres.test.ts` (real-Postgres exact-once + lease-ceiling). #7239: a child that throws a deterministic refusal (minions/refusal.ts) is dead after one attempt with the refusal on its result.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index c60e126b2e..28ec21caba 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -21,7 +21,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
Derived atom pages may regenerate or retire when their canonical file is already absent, while ordinary page writes retain missing-file refusal.
Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. `submitMaintenanceIntent` admits a maintenance request with its own intent kind keyed by the intent; `prepareMaintenanceMutation` also handles `managed_maintenance_phantom_merge` and `managed_maintenance_phantom_delete` (both delegated to `cycle/phantom-redirect-managed.ts`). `publishMaintenancePage` accepts an optional `eventProjection` (Life Chronicle): the event page and its depth-page timeline row commit in the same publication with the depth page key locked. Remote maintenance remains refused.
-- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; #6226 rows the older citation reading filed for either body are `superseded` (deleted by every writer) or, carrying their own detail, `superseded_annotated` (kept, never materialized); a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typed `invalid_fence` (`fence-repair/refusal.ts`): `compileCanonicalProjections`, the validation-only entry, refuses the first defect `scanCanonicalFences` finds (repeated marker, any strict-parser warning, a row number used twice on the page) with wire `invalid_params`; a new fence row whose number belongs to a database-only take refuses as `stored_row_collision` with wire `take_row_collision`. When the prior takes fence does not parse, the page's stored `takes.row_num` count as prior canonical rows (TE1), so a row Tier 1 normalized updates its take instead of colliding. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused as `invalid_fence` / `quoted_fence_rows` instead of deleting them. Pinned by `test/fence-marker-projection.test.ts`. #5969 (D3): an ordinary `put_page` / `put_pages` intent carries a `TimelineWritePolicy` (`timeline-omission.ts`) that changes only the rows the writer saw (`removed`, `removed_marked`): an explicitly empty section deletes them for every writer class; an omitted section keeps them for a local preserving writer (`materialize`) and deletes them with `drop_timeline`; maintenance, reconcile and file writers pass no policy. The pinned timeline `DELETE` returns what it removed, and the projection closure returns `{ timelineRowsRemoved: { count, earliest, latest } }` counting only `removed`/`removed_marked` rows it actually deleted (a row changed after preparation is neither deleted nor counted); `timelineRowsToRemove` judges the same set ahead of publication. #6259: a quarantined page (gate `quarantine` marker) projects no facts or takes (timeline rows still project); rows projected before it was quarantined stay as they are.
+- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; #6226 rows the older citation reading filed for either body are `superseded` (deleted by every writer) or, carrying their own detail, `superseded_annotated` (kept, never materialized); a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typed `invalid_fence` (`fence-repair/refusal.ts`): `compileCanonicalProjections`, the validation-only entry, refuses the first defect `scanCanonicalFences` finds (repeated marker, any strict-parser warning, a row number used twice on the page) with wire `invalid_params`; a new fence row whose number belongs to a database-only take refuses as `stored_row_collision` with wire `take_row_collision`. When the prior takes fence does not parse, the page's stored `takes.row_num` count as prior canonical rows (TE1), so a row Tier 1 normalized updates its take instead of colliding. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused as `invalid_fence` / `quoted_fence_rows` instead of deleting them. Pinned by `test/fence-marker-projection.test.ts`. #8819: the fact generation (`projectFactFenceGeneration`) retires only rows a fence of the page held (`generations/fence-evidence.ts`, with the prior snapshot's body as evidence); the expire statement is limited to its `retireIds`, the trust guard skips its `kept` rows, and a kept row whose number an incoming fence row claims moves above the page's rows first (`moveKeptRows`). #5969 (D3): an ordinary `put_page` / `put_pages` intent carries a `TimelineWritePolicy` (`timeline-omission.ts`) that changes only the rows the writer saw (`removed`, `removed_marked`): an explicitly empty section deletes them for every writer class; an omitted section keeps them for a local preserving writer (`materialize`) and deletes them with `drop_timeline`; maintenance, reconcile and file writers pass no policy. The pinned timeline `DELETE` returns what it removed, and the projection closure returns `{ timelineRowsRemoved: { count, earliest, latest } }` counting only `removed`/`removed_marked` rows it actually deleted (a row changed after preparation is neither deleted nor counted); `timelineRowsToRemove` judges the same set ahead of publication. #6259: a quarantined page (gate `quarantine` marker) projects no facts or takes (timeline rows still project); rows projected before it was quarantined stay as they are.
- `src/core/persistence/timeline-omission.ts` — #5969 (D3): `timelineSectionOf` reads a put_page body's Timeline section from the caller's raw content before normalization (`omitted`: no timeline sentinel and no `## Timeline`/`## History` heading outside code; `emptied`: a section with no entries; `present`). Admission (`page-mutations.ts`) records it on the intent as `timeline_section` (a caller-sent value is stripped; failed-writes replay passes the stored one through `submitPageMutation`'s `timelineSection`). `assertTimelineNotOmitted` refuses a remote omission that would delete rows with `timeline_rows_would_be_removed` (fix: `get_page include_content:true`, then the `drop_timeline: true` retry) before admission and again during preparation; `timelineWritePolicy` builds the projection policy. Successful deletes surface as the receipt's `timeline_rows_removed` advisory (`page-advisories.ts`, dates only), copied onto `put_pages` entries (`page-batch.ts`, which accepts `drop_timeline` per entry).
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 2e88a2a908..9c3c9241e1 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -9,6 +9,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; a `spends: 'llm'` kind's plan reports `llm` (its paid-model estimate, null for an unpriced model under a user-set cap, and what is left under its own daily cap), and its result's `cost` adds `llm_usd` (the estimate on a dry run, the actual spend summed from each item's `llm_usd` on an apply) and `llm_cap_remaining_usd` (the smaller of the daily cap and the run allowance, less the spend), keys other kinds never carry; `maxLlmUsd` is the run's paid-model allowance: each item's `apply` gets what is left as `llmAllowanceUsd`, and once it is used up, or an item's own `llm_usd` estimate exceeds what is left, the run stops `budget_exhausted` before that item, naming spent and allowance, and rerunning the apply command resumes it (a dry run sums the per-item estimates of the items it would apply, so `--limit` lowers it); the core opens no budget tracker; `deadline` (epoch ms) stops the run with `time_budget` before the next item; an item outcome's `stop` ends the run after that item with its reason, message and fix; a kind's `report` hook adds `repaired`, `remaining`, `verification` (or refines `stopped`) once the run ends, and a plan's `scan` is copied to the result; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`; other item failures go through one `ItemRun` (`repair.apply_items`): an accepted pending write is checked first, a run-scoped failure is thrown, an item-scoped one is a `failed[]` entry (`reason` its code, `retry: 'next_full_scan'`, `fix` the kind's preview) and the run goes on; the breaker stops it `item_failures_systemic`; a limited run with only item failures clears its cursor; a kind's `onItemFailures` gets the failed items unless the run stopped; `--expect` applies throw all but `REPAIR_ITEM_FAILURE_CODES`). `rotation.ts`: the bare-apply rotation fences and slug-conflicts share (keys joined with U+0001 for jsonb). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor; one stored-row read per page batch for the retraction check) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals; a page whose re-seal throws item-scoped is `held` `projection_unbuildable` (code, message, retry `fix`), stays withheld and is retried next run; the plan also selects pages the v0.60.31 re-chunk held (`CREDENTIAL_RESEAL_HELD`, segmented pages excluded). The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing online-built request index (`PERSISTENCE_REQUEST_ONLINE_INDEXES`: the managed sync checkpoint pair and the page purge's slug index) or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — `spends: 'llm'` for a kind that may call a paid chat model, and the doctor `checks` it clears), `repairMayEmbed` (embedding spend under the flags) and `repairMaySpend` (that or `spends: 'llm'`), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use (an applying runner resolves the CLI write wait once, before any kind runs, and puts it on the ctx as `writeWaitMs`, so every publication waits like other CLI writes and a malformed `GBRAIN_WRITE_WAIT_MS` refuses before a checkpoint; a preview never reads it) (its `run` takes `maxLlmUsd`; `repairRunner` and `repairSpec` take an optional `registry` of stub specs for tests, and production callers use the registered kinds); a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Explicit-only kinds and kinds with `preview_bound` (`fences`, which is not explicit-only and so also runs from `--all`, the remediation run and the maintenance cycle with a bare `--apply`) accept `--expect <hash>`; only explicit-only kinds accept `--include-ambiguous`; `--only`/`--skip`/`--slug` selections, `--no-llm` and `--max-usd` (only `spends: 'llm'` kinds; it only lowers their cap) are passed to `plan` as `RepairPlanOptions` and printed in the apply command; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page whose extraction at its current hash produced atoms (`origin_changed`; evidence is a live atom at that hash, managed also the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, so zero yield replaces nothing). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated atom-file edit; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `attribution-backfill.ts` (Foundations 1, F1b): an automatic `publication: 'projection'` bookkeeping kind (`embeds: 'none'`, no doctor check) that fills NULL write attribution only where exactly one committed request proves it: `pages.revision_*` and `page_versions.write_*` from the page mutation (or fenced `remember`) whose `outcome.revision` is the row's `knowledge_revision` (skipped, duplicate and observe-only requests prove nothing), and `facts.write_*` from the `remember` whose `outcome.id` names the fact with status `inserted` or `superseded`. The preview proofs and each batch run inside a short transaction with `enable_nestloop` off (the journal join on the outcome key has no index, and fresh attribution columns have no statistics), restoring the caller's setting before it ends. Items are batches of up to 1,000 ids per table in (table, id) cursor order; each batch re-runs the proof under `lockPageKeys` for its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are the `unrecorded_<table>` residuals. Test: `test/write-attribution-read.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.
- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected; `unreachable` means no HTTP response at all (connection refused, DNS, reset; a stale `provider_base_urls` entry fails every call this way, Cat 40 R0), while `network` stays a provider 5xx. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / unreachable (3+ rows: names the `provider_base_urls.<provider>` key) / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.
- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, replays a still-pending request with the ctx's CLI write wait, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.
+- `src/core/repair/unwithdrawn-facts.ts` — `gbrain repair unwithdrawn-facts` (#8819), explicit-only and preview-bound. `classifyUnwithdrawnFacts` (read-only; also the doctor check's count) takes each fact a `fact_fence` generation retired (a `retired` ledger item with a fact preimage that was active and positioned) whose row is still as the retirement left it (expired at the generation's instant, `row_num` NULL, same claim and visibility; conversation-extractor rows excluded), and classes it `evidenced` (no fence ever held it: `generations/fence-evidence.ts` over the ledger, the current page and its stored versions), `ambiguous` (`version_history_gap_at` set, or versions left unread) or `excluded:<reason>` (page missing, superseded, withdrawn, changed since retirement, `fence_held`, active duplicate, duplicate candidate). The preview saves one item per page with its revision through `preview-approval.ts`; the apply restores the preimage's lifecycle (`expired_at`, `valid_until`, `superseded_by`, consolidation marks) on the same id at its recorded row number when free, else above the page's rows, after reclassifying under the page key: managed, one database-only `managed_maintenance_restore_unwithdrawn_facts` request per page bound to the previewed revision (`prepareUnwithdrawnFactsRestore`, refusing `revision_conflict`); unmanaged, a page-locked `maintenanceTransaction` that refuses a changed revision. Doctor `unwithdrawn_facts` (`commands/doctor/checks/unwithdrawn-facts.ts`). Tests: `test/repair-unwithdrawn-facts-8819.test.ts` (PGLite and Postgres).
- `src/core/repair/conversation-labels.ts` — `gbrain repair conversation-labels`, explicit-only, preview-bound and destructive (consent payload from the registry's `consentText`). `classifyLabelFacts` (read-only) takes active per-segment extractor facts (`source` exactly `cli:extract-conversation-facts`) on live pages with a bold `METADATA_LABELS` line and classes each `excluded` (page outcome stamped with `extractor_version`, withdrawn, superseded, named by another fact's `superseded_by`, referenced by `open_loops.fact_id`), `evidenced` (context carries `segment 1970-01-01`) or `ambiguous`. The preview decides each page's outcome with the current parser at no cost (`non_extractable`, `awaiting_reextraction`, `cleaned`), hashes it all, saves one approved item per page and prints the capped hand-off (`extract-conversation-facts --slugs … --dry-run`, then `--max-cost-usd`). The apply expires the approved ids still as previewed (appending `retired: conversation-labels <hash>` to the context), expires the completion marker and writes the stamped not-extractable outcome for a page still at the previewed parser input; approved pages apply in batches of `LABEL_BATCH_PAGES` (25): one database-only `managed_maintenance_conversation_label_retire` request per batch on `LABELS_ANCHOR_SLUG` on a managed brain (`prepareConversationLabelRetirement`, every page key locked, each page rechecked), one transaction per batch otherwise. No model calls. Segmented pages are not classified (the label filter reads the body columns): their unstamped per-segment facts are counted as `segmented_pages` / `segmented_facts` and named in a warning. `countLabelFacts` is doctor `conversation_label_facts`' bounded count. Pinned by `test/repair-conversation-labels.test.ts` (+ Postgres arm) and `test/conversation-facts-retained-history.test.ts`.
- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).
- `src/core/repair/redacted-facts.ts` — `gbrain repair redacted-facts` (#7125), explicit-only and preview-bound. `classifyRedactedFacts` (read-only) takes active facts whose text holds a redaction marker and runs `restoreNeutralized` (`think/sanitize.ts`, with the pre-fix `LEGACY_EVAL_SHELL` shape) against the page the fact's context names and the page holding it (`pageTexts`: an inline page's body + timeline, a segmented page's body through `readBodyRange` up to 16 MiB, then up to 50 `page_versions` bodies): `evidenced` when every proving text proves the same restoration, `ambiguous` (`conflicting_sources`) when a text holds two spans around the words or texts disagree, `unproven` (`no_source_page` / `not_in_source`) otherwise. A proved fenced row on a segmented page is `segmented` (`segmented_page`): listed with its restoration, never rewritten (`restoreFencedRows` reads and publishes inline bodies only). The preview hashes every candidate with its restoration and saves one approved item per page; the apply reclassifies each fact, rewrites database-only rows through one database-only `managed_maintenance_restore_redacted_facts` request per page on a managed brain (`prepareRedactedFactsRestore`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain (exact-text compare-and-set; context gets `restored: redacted-facts repair`), and rewrites fenced rows' claims in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection replaces the row. Pinned by `test/repair-redacted-facts.test.ts` (+ Postgres arm).
diff --git a/docs/architecture/key-files/generations.md b/docs/architecture/key-files/generations.md
index 7e9cc29c84..745d5cea40 100644
--- a/docs/architecture/key-files/generations.md
+++ b/docs/architecture/key-files/generations.md
@@ -4,5 +4,6 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
- `src/core/generations/{contract,plan,publish,proofs,config,repair,ledger-scrub}.ts` + `adapters/{page,atoms,index}.ts` (GBRA-161) — the generation primitive: one ledger row per derived key generation (`derived_generations`, items and bounded preimages in `derived_generation_items`); `publishGeneration` holds a shrunk, oversize, unproven-empty, valve or segmented result and otherwise writes, completes, rechecks, retires (versioned, stamped) and activates in one transaction. `gbrain repair generations` restores or releases from previews; doctor `generation_retirements` / `generation_held`. Reference: [generations](../generations.md). Tests: `test/pathological/g1-generations.test.ts`, `test/pathological/g1-atom-generations.test.ts`.
+- `src/core/generations/fence-evidence.ts` (#8819) — `factsFenceHeld`: which positioned fact rows of a page some fence held at the same row number, claim and visibility (a non-retired item of any `fact_fence` generation of the page, the body the writer read, or a stored `page_versions` body, newest first, at most 1000; `complete` false past that). The page projection (`projectFactFenceGeneration`, which now returns `retireIds` and `kept`) retires only held rows and conversation-extractor rows a fence row displaces; the managed `extract_facts` reconcile keeps unheld stale rows out of its retirements. `moveKeptRows` moves a kept row whose number an incoming fence row claims above every row of the page. Tests: `test/fence-first-generation-8819.test.ts` (PGLite and Postgres).
- `src/core/generations/adapters/synthesis.ts`, `src/core/generations/synthesis-coverage.ts`, `src/core/generations/managed-retire.ts`, `src/core/cycle/synthesize-generations.ts` (GBRA-161 PR 4, #7065) — synthesis on the primitive: each re-synthesized transcript's outputs become its `synthesis` generation after postprocess; an earlier output retires (versioned, `synthesis-resynthesis`) only when it is an exact duplicate or the same subject with every claim, quote and citation covered (pure match in `synthesis-coverage.ts`); others stay live and `gbrain repair generations --kind synthesis --mode cleanup` lists and, on apply, retires them (`synthesis-cleanup`). A chunk failure, deferral or `generations.synthesis.retire_previous=false` makes the generation partial. Managed brains admit the activation plus one `managed_generation_retire` delete per retirement (`managed-retire.ts`). Reference: [generations](../generations.md#synthesis). Tests: `test/pathological/g4-synthesis-resynthesis-7065.test.ts`.
- `src/core/generations/adapters/single-page.ts` (GBRA-161 PR 5) — dream summary, `think` page and drift report as single-item generations: revision-bound, versioned first, restorable. Reference: [generations](../generations.md#single-page-kinds-and-fence-only-writers-pr-5). Tests: `test/pathological/g5-*` to `g7-*`.
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 2b1057abdd..83cb33ce29 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -276,6 +276,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/generations/managed-retire.ts` (1): the retirement stamp (`retired_by`, `retired_at`) of one synthesis output a managed generation retires runs inside its `managed_generation_retire` request's coordinated write, after the versioned page delete (GBRA-161 PR 4).
- `src/core/generations/adapters/extracted-facts.ts` (2): the extracted-facts generation's row inserts and retirements (`publishExtractedFacts`, GBRA-161 PR 2) run inside the generation activation's `maintenanceTransaction` (`publish.ts`); its restore runs in the restore runner's (`repair.ts`).
- `src/core/generations/adapters/fact-rows.ts` (1): putting a fact's recorded before-state back (`restoreFactRow`) runs only inside a generation restore's `maintenanceTransaction` (`repair.ts`, GBRA-161 PR 2).
+- `src/core/generations/fence-evidence.ts` (1): `moveKeptRows` renumbers a kept database-only fact whose row number a fence row now claims (#8819); it runs only inside the fence projection's request publication (`canonical-projections.ts`) and the extract_facts reconcile's write (`maintenanceTransaction` or the managed request's preparer).
- `src/core/import-file.ts` (12): direct markdown, code and image imports, the moved-file rename (`updateSlug`) and the #3694 legacy-hash re-stamp run in `maintenanceTransaction`; managed imports go through the page request preparer.
- `src/core/minions/handlers/ingest-capture.ts` (1): the capture ingest tombstone soft delete runs in `maintenanceTransaction`.
- `src/core/output/writer.ts` (4): `BrainWriter.transaction` is a `maintenanceTransaction`, so its pages and timeline rows carry the maintenance principal.
@@ -325,6 +326,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/repair/take-supersession.ts` (1): `gbrain repair take-supersession` reprojection: a receipted `managed_maintenance_take_reproject` request on managed brains, `maintenanceTransaction` on unmanaged ones; fence edits go through a revision-bound `put_page`.
- `src/core/repair/timeline-comments.ts` (1): `gbrain repair timeline-comments` row cleanup: `withCoordinatedWrite` under the page key on managed brains, `maintenanceTransaction` otherwise.
- `src/core/repair/url-clone-fences.ts` (2): `gbrain repair url-clone-fences` (#6946), unmanaged brains only (a managed brain previews nothing); keeping the appended fence rows database-only (clearing `row_num`, inserting a row the database lost) runs in one `maintenanceTransaction` under the page lock after the preview recheck; HEAD's bytes then import through `importFromContent` (a HEAD that asks for private in a spelling page privacy does not read is held: not imported, and the apply reports `held`, #7897).
+- `src/core/repair/unwithdrawn-facts.ts` (1): `gbrain repair unwithdrawn-facts` (#8819) puts back the ledger preimage of each preview-approved fact a fence generation retired though no fence held it: a database-only `managed_maintenance_restore_unwithdrawn_facts` request on managed brains, one `maintenanceTransaction` under the page lock on unmanaged and repo-less brains.
- `src/core/repair/visibility.ts` (1): `gbrain repair visibility --apply` tightening of database-only world facts from a private source: a receipted `managed_maintenance_tighten_fact_visibility` request on managed brains, `maintenanceTransaction` on unmanaged ones; fenced rows change through a revision-bound `put_page`.
- `src/core/schema-pack/page-to-alias.ts` (1): the page-to-alias conversion soft-deletes each converted page in `maintenanceTransaction`.
- `src/core/schema-pack/page-to-link.ts` (1): the page-to-link conversion soft-deletes each converted page in `maintenanceTransaction`.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 7eb5cce7dc..d162fb2a4c 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -8,7 +8,7 @@ can load, and Google source files other local users can read. `gbrain repair`
fixes those and the other kinds listed in
[What each kind fixes](#what-each-kind-fixes). Every run is a preview unless
you pass `--apply`.
-The explicit-only kinds, among them `google-file-modes`, `stale-atoms`, `atoms-restore`, `extractor-facts`,
+The explicit-only kinds, among them `google-file-modes`, `stale-atoms`, `atoms-restore`, `extractor-facts`, `unwithdrawn-facts`,
`captured-facts`, `agent-session-facts`, `redacted-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter`, `managed-sync-orphans`, `content-receipt-root`, `stuck-recovery`, `aliases`, `rename-identity` and `segmented-mirror`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and
`gbrain doctor --remediate --yes --include-repairs --expect <plan_hash>` runs them under a budget
@@ -125,8 +125,8 @@ gives each a fresh row number); it never deletes or rewrites a page.
| `--limit <n>` | Repair at most `n` items per kind in this run (a positive integer; with `--all`, up to `n` for each kind). Rerun the same command to continue. |
| `--no-embed` | `safe-chunks` and `contextual-mode`: skip the embedding provider. Run `gbrain embed --stale` later. `timeline` and `visibility` pages are re-embedded by their publication either way. |
| `--all` | Run every automatic kind in order. Explicit-only kinds are listed with their preview command, never run. |
-| `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms`, `atoms-restore`, `extractor-facts`, `captured-facts`, `redacted-facts`, `loop-facts`, `failed-writes`, `frontmatter`, `managed-sync-orphans` and `content-receipt-root`. |
-| `--include-ambiguous` | `extractor-facts`, `captured-facts` and `agent-session-facts`: widen the hashed set to `ambiguous` facts. `frontmatter`: add interpretive file changes. Pass it to both the preview and the apply. See [Extractor facts](#extractor-facts), [Captured facts](#captured-facts) and [Frontmatter](#frontmatter). |
+| `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms`, `atoms-restore`, `extractor-facts`, `unwithdrawn-facts`, `captured-facts`, `redacted-facts`, `loop-facts`, `failed-writes`, `frontmatter`, `managed-sync-orphans` and `content-receipt-root`. |
+| `--include-ambiguous` | `extractor-facts`, `unwithdrawn-facts`, `captured-facts` and `agent-session-facts`: widen the hashed set to `ambiguous` facts. `frontmatter`: add interpretive file changes. Pass it to both the preview and the apply. See [Extractor facts](#extractor-facts), [Captured facts](#captured-facts) and [Frontmatter](#frontmatter). |
| `--only <path>`, `--skip <path>` | `frontmatter` only: select source-relative files (repeatable). The hash covers the selection, so pass the same flags to the apply. |
| `--diff` | `frontmatter` only: print every per-file diff instead of one sample per class (`--json` always carries all of them). |
| `--yes` | `frontmatter --apply` only: the user agreed to the previewed file changes (destructive consent). Without it a terminal asks, and a run without a terminal exits 3 with the consent payload. |
@@ -2138,6 +2138,50 @@ The preview warns, naming the host, when a consumer older than v0.60.11.0
published writes after `writer_version_cutoff`: an old consumer expires
restored facts again. Upgrade and restart it first.
+<a id="unwithdrawn-facts"></a>
+### Unwithdrawn facts
+
+Before this fix, a page write or an `extract_facts` run retired every fact row
+attached to the page with a row number that the page's `## Facts` fence did not
+hold. That included rows that were never in the fence, such as facts a
+`put_page` writer attached to the page, so a write that changed nothing in the
+fence could expire them (`expired_at` set, `row_num` cleared, no
+`superseded_by`). When that was the page's first facts-fence generation,
+`gbrain repair generations --kind fact_fence` has no earlier generation to
+return to. `gbrain repair unwithdrawn-facts` restores these rows from the
+before-state the generation ledger recorded. It is explicit-only and
+preview-bound, and it works on a brain with or without a repository.
+
+```bash
+gbrain doctor # unwithdrawn_facts
+gbrain repair unwithdrawn-facts # preview: every candidate with its class
+gbrain repair unwithdrawn-facts --apply --expect <hash>
+gbrain doctor
+```
+
+A candidate is a fact a facts-fence generation retired that is still exactly as
+the retirement left it: expired at that generation's instant, row number
+cleared, same claim and visibility, not superseded. Conversation-extractor
+facts are left to [Extractor facts](#extractor-facts).
+
+| Class | Meaning | Restored |
+| --- | --- | --- |
+| `evidenced` | No fence of the page ever held the fact: no facts-fence generation recorded it, and neither the page nor any stored version of it carries it at the same row number, claim and visibility. | By `--apply --expect <hash>` |
+| `ambiguous` | The page's version history has a gap (pruned versions, or an import that consumed several commits), or it has more stored versions than one preview reads, so an earlier fence holding the fact cannot be ruled out. | Only with `--include-ambiguous` and that preview's hash |
+| `excluded:<reason>` | Page missing or deleted, superseded, withdrawn (`forget`), changed since the retirement, held by a fence (`fence_held`: an edit of the fence removed it, a genuine withdrawal), an active fact with the same text and entity already on the page, or an earlier candidate with the same text and entity. | Never |
+
+The preview binds each page's revision. If the page was written after the
+preview, the apply restores nothing for it and reports
+`changed_since_preview`; preview again. A fact that changed since the preview
+reports `changed_since_preview` and stays expired. A restored fact keeps its id
+and gets back its recorded `expired_at` (cleared), `valid_until`,
+`superseded_by` and consolidation marks, at its recorded row number, or at a
+fresh number above the page's rows when a fence row has taken it. No page or
+file is written. On a managed brain each page publishes one database-only
+`managed_maintenance_restore_unwithdrawn_facts` request; an unmanaged brain
+writes under the page lock. Page writes and managed `extract_facts` runs from
+this release on keep these rows active.
+
<a id="conversation-labels"></a>
### Conversation labels
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index 671901e904..4b9949be2b 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -391,6 +391,7 @@ export const timelineHistoryEntry: DoctorEntry = {
'generation_held',
'generation_pending',
'extractor_facts_expired',
+ 'unwithdrawn_facts',
'conversation_label_facts',
'conversation_outcomes_stale',
'captured_facts_active',
diff --git a/src/commands/doctor/checks/unwithdrawn-facts.ts b/src/commands/doctor/checks/unwithdrawn-facts.ts
new file mode 100644
index 0000000000..47b06e4ea6
--- /dev/null
+++ b/src/commands/doctor/checks/unwithdrawn-facts.ts
@@ -0,0 +1,32 @@
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+import { classifyUnwithdrawnFacts } from '../../../core/repair/unwithdrawn-facts.ts';
+
+/**
+ * #8819: facts a facts-fence generation retired although no fence of their page ever held them (often the page's first
+ * generation, which no generation restore can undo). Counts the restorable ones by class (evidenced, ambiguous) and
+ * names the explicit-only repair's preview; excluded ones (a fence held them, withdrawn, superseded, duplicated, page
+ * gone) are reported but never count as a finding. Read-only.
+ */
+export async function unwithdrawnFactsCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
+ try {
+ const sources = sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);
+ const facts = await classifyUnwithdrawnFacts(engine, sources);
+ const count = (klass: string) => facts.filter(f => f.class === klass).length;
+ const details = { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded'),
+ repair: 'unwithdrawn-facts', docs: 'docs/guides/repair.md#unwithdrawn-facts' };
+ if (!details.evidenced && !details.ambiguous) {
+ return { name: 'unwithdrawn_facts', status: 'ok', details,
+ message: `No fact is left retired by a facts-fence generation that no fence withdrew${details.excluded ? ` (${details.excluded} retired fact(s) a fence held or that are excluded stay retired)` : ''}.` };
+ }
+ return { name: 'unwithdrawn_facts', status: 'warn', details,
+ message: `${details.evidenced + details.ambiguous} fact(s) were retired by a facts-fence generation although no fence of their page held them `
+ + `(${details.evidenced} evidenced, ${details.ambiguous} ambiguous); recall no longer returns them. `
+ + 'Preview the restore on the brain host: gbrain repair unwithdrawn-facts — then run the apply command it prints after the user agrees '
+ + '(ambiguous rows only with gbrain repair unwithdrawn-facts --include-ambiguous).' };
+ } catch (error) {
+ return { name: 'unwithdrawn_facts', status: 'warn',
+ message: `Facts retired by facts-fence generations could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,
+ details: { count: 'unknown' } };
+ }
+}
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index 2b5b335f82..5730ca114e 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -358,6 +358,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
impact: 'Some conversation-extractor facts were expired by the pre-v0.60.11.0 canonical projection and recall no longer returns them',
run: async (engine, scope) => (await import('./checks/extractor-facts.ts')).extractorFactsCheck(engine, scope.sourceIds),
},
+ {
+ id: 'unwithdrawn_facts', resolution: 'repair', registration: 'wave',
+ hostOnly: 'Restoring facts a facts-fence generation retired without a withdrawal is a host-side, explicit-only repair.',
+ count: d => Number(d.evidenced ?? 0) + Number(d.ambiguous ?? 0),
+ impact: 'Some facts were retired by a facts-fence generation although no fence of their page held them, and recall no longer returns them',
+ run: async (engine, scope) => (await import('./checks/unwithdrawn-facts.ts')).unwithdrawnFactsCheck(engine, scope.sourceIds),
+ },
{
id: 'conversation_label_facts', resolution: 'repair', registration: 'wave',
hostOnly: 'Retiring label-misattributed conversation facts is a host-side, explicit-only repair.',
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index f3b9b8d65d..81ff383ad8 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -85,6 +85,7 @@ import { fenceUnfencedFacts, planUnfencedFacts } from '../facts/unfenced-facts.t
import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';
import { factsFenceView } from '../facts-fence.ts';
import { fenceReadOf, publishFenceGeneration, readFenceBlocks, FACT_FENCE_KIND, type FenceRead } from '../generations/fence.ts';
+import { factsFenceHeld, moveKeptRows } from '../generations/fence-evidence.ts';
import type { BodyStorage } from '../page-body/types.ts';
import { factFenceItems, factPreimages, factRetireItem } from '../generations/adapters/fact-rows.ts';
import { incrementalFactsFence, segmentedBodyMatchesFile } from '../page-body/segment-facts.ts';
@@ -386,6 +387,8 @@ interface FenceReconcilePlan {
stale: ExistingPageFact[];
updates: FenceExtractedFact[];
toInsert: FenceExtractedFact[];
+ /** #8819: stored rows with a row number no fence of the page ever held: never retired, moved when a new fence row claims their number. */
+ kept: number[];
chain: SupersessionChain;
/** Nothing to write: every row matches and every supersession pointer is in place. */
inSync: boolean;
@@ -395,8 +398,11 @@ interface FenceReconcilePlan {
* One page's reconcile plan against its stored rows. Null when the fence is
* not authoritative (warnings are appended): a warning-bearing parse or a
* fence in each section of the page (#6686: a split fence) preserves the page's existing index.
+ * `managed` (#8819): on a managed brain every page write projects its fence with the page it replaced as evidence, so a
+ * row no fence of the page ever held is not drift to wipe but a fact nobody withdrew; an unmanaged brain's reconcile
+ * keeps treating rows its fence lacks as drift.
*/
-async function planFenceReconcile(db: BrainEngine, page: PageFenceInput, slug: string, sourceId: string, warnings: string[]): Promise<FenceReconcilePlan | null> {
+async function planFenceReconcile(db: BrainEngine, page: PageFenceInput, slug: string, sourceId: string, warnings: string[], managed: boolean): Promise<FenceReconcilePlan | null> {
// A segmented page's view and fence text come from its fences rows: only runs changed since their row was written are read.
const segmented = isSegmentedPage(page) ? await incrementalFactsFence(db, page) : null;
const view = segmented?.view ?? factsFenceView(page);
@@ -457,9 +463,16 @@ async function planFenceReconcile(db: BrainEngine, page: PageFenceInput, slug: s
return fact !== undefined && factCellsDiffer(fact, f);
});
const toInsert = extracted.filter(f => !matched.has(f.row_num));
+ // #8819: on a managed brain, a stale row whose number and claim no fence of the page ever held was never in the fence,
+ // so no edit of it withdrew the row: it stays active, and a new fence row claiming its number takes that position.
+ const positioned = managed ? stale.filter(fact => fact.row_num != null)
+ .map(fact => ({ id: Number(fact.id), row_num: Number(fact.row_num), fact: fact.fact, visibility: fact.visibility })) : [];
+ const { held } = await factsFenceHeld(db, { sourceId, slug, rows: positioned });
+ const kept = positioned.filter(row => !held.has(row.id)).map(row => row.id);
+ const retired = stale.filter(fact => !kept.includes(Number(fact.id)));
const chain = supersessionChainOf(extracted, slug);
let inSync = false;
- if (stale.length === 0 && updates.length === 0 && toInsert.length === 0) {
+ if (retired.length === 0 && updates.length === 0 && toInsert.length === 0) {
const byRow = new Map([...matched].map(([row, fact]) => [row, { id: Number(fact.id), struck: fact.expired_at != null }]));
inSync = extracted.every(f => {
const stored = matched.get(f.row_num)!.superseded_by;
@@ -467,7 +480,7 @@ async function planFenceReconcile(db: BrainEngine, page: PageFenceInput, slug: s
});
}
const read: FenceRead = segmented ? fenceReadOf(segmented.blocks) : readFenceBlocks(page, 'facts');
- return { fenceRows: parsed.facts.length, read, extracted, matched, stale, updates, toInsert, chain, inSync };
+ return { fenceRows: parsed.facts.length, read, extracted, matched, stale: retired, updates, toInsert, kept, chain, inSync };
}
/**
@@ -528,6 +541,7 @@ async function writeFenceReconcile(tx: BrainEngine, sourceId: string, slug: stri
f.claim_metric ?? null, f.claim_value ?? null, f.claim_unit ?? null, f.claim_period ?? null],
);
}
+ await moveKeptRows(tx, sourceId, slug, plan.kept, writes.inserts.map(f => f.row_num));
const { inserted, allowed } = await insertReconciledFacts(tx, sourceId, slug, writes.inserts, derivation, tally);
const insertedRows = new Set(allowed.map(f => f.row_num));
const linked = await syncSupersession(tx, sourceId, slug, plan.extracted, plan.chain, insertedRows);
@@ -588,7 +602,7 @@ export async function prepareFenceFactsReconcile(engine: BrainEngine, row: Write
apply: async tx => {
const current = await tx.getPage(row.slug, { sourceId: row.source_id });
const warnings: string[] = [];
- const plan = current ? await planFenceReconcile(tx, current, row.slug, row.source_id, warnings) : null;
+ const plan = current ? await planFenceReconcile(tx, current, row.slug, row.source_id, warnings, true) : null;
if (!plan || plan.inSync) return { status: 'completed', inserted: 0, updated: 0, deleted: 0, deferred: false, warnings };
const signature = await resolveManagedFactsEmbedding(tx, config, true);
const vectors = new Map((intent?.embeddings ?? [])
@@ -982,7 +996,7 @@ export async function runExtractFacts(
revision = page.knowledge_revision ?? null;
// #6259: a quarantined page projects no fence facts; its existing index is left as it is.
if (isQuarantined(page.frontmatter as Record<string, unknown> | null)) return 'skipped';
- const plan = await planFenceReconcile(engine, page, slug, sourceId, result.warnings);
+ const plan = await planFenceReconcile(engine, page, slug, sourceId, result.warnings, managed);
if (!plan) return 'invalid';
if (plan.fenceRows > 0) result.pagesWithFacts += 1;
if (opts.dryRun) return 'skipped';
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 8f9bbce2a4..9440e9551e 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -100,6 +100,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
// GBRA-231: shared agents (doctor/checks/shared-agent-access.ts).
'access_may_act_for_wildcard',
'extractor_facts_expired',
+ 'unwithdrawn_facts',
'loop_facts_drift',
'ontology_facts_fenced',
'orphan_persistence_bindings',
diff --git a/src/core/generations/adapters/fact-rows.ts b/src/core/generations/adapters/fact-rows.ts
index a3ea2a1558..4425b7946d 100644
--- a/src/core/generations/adapters/fact-rows.ts
+++ b/src/core/generations/adapters/fact-rows.ts
@@ -19,6 +19,7 @@ import { readGenerationsConfig } from '../config.ts';
import type { GenerationAdapter, GenerationKey, ItemRow } from '../contract.ts';
import { factRowIdentity, fenceRowKey, FACT_FENCE_KIND, publishFenceGeneration, type FenceGenerationOutcome, type FenceItem, type FenceRead } from '../fence.ts';
import { activateGeneration, generationKeyLock, itemSetHash, readLiveGeneration, recordHeld } from '../publish.ts';
+import { factsFenceHeld, type FenceBody } from '../fence-evidence.ts';
export const CONSOLIDATION_KIND = 'consolidation';
@@ -28,7 +29,7 @@ const FACT_PREIMAGE_SQL = `jsonb_build_object('id', f.id, 'row_num', f.row_num,
'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to)`;
export type FactPreimage = { id: number; row_num: number | null; fact: string; visibility: string; expired_at: string | null; valid_until: string | null;
- superseded_by: number | null; consolidated_at: string | null; consolidated_into: number | null; entity_slug: string | null; attributed_to: string | null };
+ superseded_by: number | null; consolidated_at: string | null; consolidated_into: number | null; entity_slug: string | null; attributed_to: string | null; source?: string | null };
/** The fence rows of the new generation (one per row number; a duplicate number keeps its first row, as the reconcile does). */
export function factFenceItems(rows: ReadonlyArray<{ row_num: number; fact: string; visibility?: string | null }>): FenceItem[] {
@@ -58,20 +59,27 @@ export async function factPreimages(db: BrainEngine, sourceId: string, ids: read
/**
* The page publication's fence projection (persistence/canonical-projections.ts): the rows it would expire and detach
* are those attached to the page that the incoming fence no longer holds at the same number and claim (conversation
- * extractor rows only when a fence row claims their number, #5731). Held: the caller expires nothing.
+ * extractor rows only when a fence row claims their number, #5731). #8819: of the others, only a row some fence of the
+ * page held retires (fence-evidence.ts); a row the fence never held is `kept` active, since no fence edit withdrew it.
+ * Held: the caller expires nothing.
*/
export async function projectFactFenceGeneration(tx: BrainEngine, input: { sourceId: string; slug: string; read: FenceRead; incoming: string;
- rows: ReadonlyArray<{ row_num: number; fact: string; visibility?: string | null }>; writer: string }): Promise<FenceGenerationOutcome & { retiring: number }> {
- const retire = (await tx.executeRaw<{ preimage: FactPreimage }>(`SELECT ${FACT_PREIMAGE_SQL} AS preimage FROM facts f
+ rows: ReadonlyArray<{ row_num: number; fact: string; visibility?: string | null }>; writer: string; prior?: FenceBody | null }):
+ Promise<FenceGenerationOutcome & { retiring: number; retireIds: number[]; kept: number[] }> {
+ const candidates = (await tx.executeRaw<{ preimage: FactPreimage }>(`SELECT ${FACT_PREIMAGE_SQL} AS preimage FROM facts f
WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL
AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%'
OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num))
AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text)
WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)
- ORDER BY f.row_num, f.id`, [input.sourceId, input.slug, input.incoming])).map(row => factRetireItem(row.preimage));
+ ORDER BY f.row_num, f.id`, [input.sourceId, input.slug, input.incoming])).map(row => row.preimage);
+ const extractor = (row: FactPreimage) => (row.source ?? '').startsWith('cli:extract-conversation-facts');
+ const { held } = await factsFenceHeld(tx, { sourceId: input.sourceId, slug: input.slug, rows: candidates.filter(row => !extractor(row)), prior: input.prior });
+ const retire = candidates.filter(row => extractor(row) || held.has(Number(row.id)));
const outcome = await publishFenceGeneration(tx, { kind: FACT_FENCE_KIND, sourceId: input.sourceId, slug: input.slug, read: input.read,
- items: factFenceItems(input.rows), retire, writer: input.writer });
- return { ...outcome, retiring: retire.length };
+ items: factFenceItems(input.rows), retire: retire.map(factRetireItem), writer: input.writer });
+ return { ...outcome, retiring: retire.length, retireIds: retire.map(row => Number(row.id)),
+ kept: candidates.filter(row => !retire.includes(row)).map(row => Number(row.id)) };
}
/**
diff --git a/src/core/generations/fence-evidence.ts b/src/core/generations/fence-evidence.ts
new file mode 100644
index 0000000000..ae403b1215
--- /dev/null
+++ b/src/core/generations/fence-evidence.ts
@@ -0,0 +1,75 @@
+/**
+ * #8819: whether a page's `## Facts` fence ever held a fact row. A writer that retires the fact rows a fence no longer
+ * holds (the page publication's projection, the extract_facts reconcile) may retire only a row some fence held at the
+ * same row number, claim and visibility: a fact_fence generation of the page recorded it, the page body the writer read
+ * carried it, or a stored version of the page did. Any other row attached to the page with a row number (a put_page
+ * row, or one an older writer stamped) was never in the fence, so no fence edit can have withdrawn it; it stays active.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { scanCanonicalFences } from '../fence-repair/refusal.ts';
+import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';
+import { factRowIdentity, fenceOwnerKey, fenceRowKey, FACT_FENCE_KIND } from './fence.ts';
+
+export interface FenceRowRef { id: number; row_num: number | null; fact: string; visibility: string }
+export interface FenceBody { compiled_truth: string | null; timeline?: string | null; body_storage?: string | null }
+
+/** Stored versions read per batch, and at most in all, newest first. */
+const VERSION_BATCH = 50;
+const VERSIONS_MAX = 1000;
+
+const rowKey = (row: { row_num: number | null; fact: string; visibility?: string | null }) => `${Number(row.row_num)}\u0000${row.fact}\u0000${row.visibility ?? 'private'}`;
+
+/** The (row number, claim, visibility) of every row a body's facts fence holds; nothing for a body that was not read whole. */
+export function fenceRowKeys(body: FenceBody, slug: string, sourceId: string): Set<string> {
+ if (body.body_storage === 'segmented' || body.compiled_truth == null) return new Set();
+ const scan = scanCanonicalFences({ compiled_truth: body.compiled_truth, timeline: body.timeline ?? '' });
+ return new Set(extractFactsFromFenceText(scan.facts, slug, sourceId).map(rowKey));
+}
+
+/**
+ * The ids of `rows` some fence of the page held (see the module comment). `complete` is false when stored versions were
+ * left unread (more than VERSIONS_MAX), so a row outside `held` was only not found, not proven absent.
+ */
+export async function factsFenceHeld(db: BrainEngine, input: { sourceId: string; slug: string; rows: readonly FenceRowRef[]; prior?: FenceBody | null }):
+ Promise<{ held: Set<number>; complete: boolean }> {
+ const { sourceId, slug } = input;
+ const held = new Set<number>();
+ const open = () => input.rows.filter(row => row.row_num != null && !held.has(Number(row.id)));
+ if (!open().length) return { held, complete: true };
+ const keyOf = (row: FenceRowRef) => fenceRowKey(Number(row.row_num), factRowIdentity({ row_num: Number(row.row_num), fact: row.fact, visibility: row.visibility }));
+ const recorded = new Set((await db.executeRaw<{ item_key: string }>(`SELECT DISTINCT i.item_key FROM derived_generation_items i
+ JOIN derived_generations g ON g.id = i.generation_id
+ WHERE g.source_id = $1 AND g.kind = $2 AND g.owner_key = $3 AND g.state <> 'held' AND i.action <> 'retired' AND i.item_key = ANY($4::text[])`,
+ [sourceId, FACT_FENCE_KIND, fenceOwnerKey(slug), open().map(keyOf)])).map(row => row.item_key));
+ for (const row of open()) if (recorded.has(keyOf(row))) held.add(Number(row.id));
+ const markHeld = (keys: Set<string>) => { for (const row of open()) if (keys.has(rowKey(row))) held.add(Number(row.id)); };
+ if (input.prior) markHeld(fenceRowKeys(input.prior, slug, sourceId));
+ let before: number | null = null;
+ let complete = true;
+ for (let read = 0; open().length; read += VERSION_BATCH) {
+ if (read >= VERSIONS_MAX) { complete = false; break; }
+ const versions: Array<{ id: number; compiled_truth: string; timeline: string | null }> = await db.executeRaw(`SELECT v.id, v.compiled_truth, v.timeline FROM page_versions v
+ JOIN pages p ON p.id = v.page_id
+ WHERE p.source_id = $1 AND p.slug = $2 AND v.compiled_truth IS NOT NULL AND ($3::bigint IS NULL OR v.id < $3::bigint)
+ AND (strpos(v.compiled_truth, 'gbrain:facts:') > 0 OR strpos(COALESCE(v.timeline, ''), 'gbrain:facts:') > 0)
+ ORDER BY v.id DESC LIMIT $4`, [sourceId, slug, before, VERSION_BATCH]);
+ for (const version of versions) markHeld(fenceRowKeys(version, slug, sourceId));
+ if (versions.length < VERSION_BATCH) break;
+ before = Number(versions[versions.length - 1]!.id);
+ }
+ return { held, complete };
+}
+
+/**
+ * Moves the kept rows `ids` whose row number a fence row claims (`claimed`) to fresh numbers above every row of the
+ * page and every claimed number, so the fence row takes its position and the kept row stays active with its id.
+ */
+export async function moveKeptRows(tx: BrainEngine, sourceId: string, slug: string, ids: readonly number[], claimed: readonly number[]): Promise<void> {
+ if (!ids.length || !claimed.length) return;
+ await tx.executeRaw(`UPDATE facts f SET row_num = m.next FROM (
+ SELECT k.id, b.top + row_number() OVER (ORDER BY k.row_num, k.id) AS next FROM facts k,
+ (SELECT GREATEST(COALESCE((SELECT max(row_num) FROM facts WHERE source_id = $1 AND source_markdown_slug = $2), 0),
+ COALESCE((SELECT max(c) FROM unnest($4::integer[]) AS c), 0)) AS top) b
+ WHERE k.source_id = $1 AND k.id = ANY($3::bigint[]) AND k.row_num = ANY($4::integer[])) m
+ WHERE f.id = m.id`, [sourceId, slug, [...ids], [...claimed]]);
+}
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 6e7f50dff2..247c2fe76a 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -29,6 +29,7 @@ import { propagateFactLowering } from '../trust/propagation.ts';
import { loadWriteGateConfig } from '../trust/gate-outcomes.ts';
import { fenceOwnerKey, readFenceBlocks, TAKE_FENCE_KIND } from '../generations/fence.ts';
import { projectFactFenceGeneration } from '../generations/adapters/fact-rows.ts';
+import { moveKeptRows } from '../generations/fence-evidence.ts';
import { projectTakeFenceGeneration } from '../generations/adapters/take-rows.ts';
import { linksFenceProjectionRows, projectLinksFence } from '../links-fence-projection.ts';
@@ -729,13 +730,14 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
// Conversation-extractor rows share the page coordinate without a fence
// (#1928, as in the extract_facts reconcile); their replay owns them. A
// fence row that takes one of their row numbers wins that position.
+ // #8819: only the rows the fact generation found a fence held (`retireIds`) expire.
const incoming = JSON.stringify(factRows.map(f => ({ row_num: f.row_num, fact: f.fact, visibility: f.visibility })));
- const expireFacts = () => tx.executeRaw(`UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL
- WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL
+ const expireFacts = (ids: number[]) => () => tx.executeRaw(`UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL
+ WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL AND f.id=ANY($4::bigint[])
AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%'
OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num))
AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text)
- WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)`, [sourceId, slug, incoming]);
+ WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)`, [sourceId, slug, incoming, ids]);
// #6574: every fence row's fields refresh in one statement, not one round trip per row.
const fieldRows = JSON.stringify([...new Map(factRows.map(fact => [fact.row_num, fact])).values()].map(fact => ({ row_num: fact.row_num, kind: fact.kind, notability: fact.notability,
context: fact.context, valid_from: fact.valid_from?.toISOString() ?? null, valid_until: fact.valid_until?.toISOString() ?? null,
@@ -804,15 +806,18 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
// GBRA-161 PR 2: the fact and take generations decide first. A held one (its fence absent from this body) retires and
// overwrites nothing, so its rows stay as they are; every row a published one retires is recorded with its before-state.
const factGeneration = await step('fact_generation', () => projectFactFenceGeneration(tx, { sourceId, slug, read: fenceReads.facts, incoming, rows: factRows,
- writer: 'projection' }));
+ writer: 'projection', prior: prior?.page ?? null }));
const factsHeld = factGeneration.state === 'held';
+ // #8819: a row the fence never held stays active; a fence row claiming its number takes it, and the row moves past the page's rows.
+ const kept = factsHeld ? [] : factGeneration.kept;
+ if (kept.length) await step('fact_kept', () => moveKeptRows(tx, sourceId, slug, kept, factRows.map(f => f.row_num)));
const takesHeld = (await step('take_generation', () => projectTakeFenceGeneration(tx, { sourceId, slug, pageId: id, read: fenceReads.takes,
takes: projectedTakes, gone: takeRowsGone.filter(n => !heldRowNums.has(n)), writer: 'projection' }))).state === 'held';
// #5575: rows more trusted than the writer are never expired by it, and new rows pass the write gate (trust/fence-guard.ts).
// The timeline rows are independent of the fact and take rows, so they ride in the first pipeline. The expire uses the
// generation's retire predicate under the page lock, so it runs only when that generation found rows to retire.
- const guard = factsHeld ? { rows: [] as typeof factRows, finish: async () => [] as string[] } : await step('timeline', () => guardFenceRows(tx, { sourceId, slug, incoming, rows: factRows, cfg: loadWriteGateConfig },
- () => pipelined(tx, factGeneration.retiring ? [expireFacts, ...timelineRows] : timelineRows)));
+ const guard = factsHeld ? { rows: [] as typeof factRows, finish: async () => [] as string[] } : await step('timeline', () => guardFenceRows(tx, { sourceId, slug, incoming, rows: factRows, cfg: loadWriteGateConfig, kept },
+ () => pipelined(tx, factGeneration.retiring ? [expireFacts(factGeneration.retireIds), ...timelineRows] : timelineRows)));
if (factsHeld) await step('timeline', () => pipelined(tx, timelineRows));
if (guard.rows.length) await step('facts', () => tx.insertFacts(guard.rows, { source_id: sourceId })); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction
const contested = await step('fact_trust', () => guard.finish(tx));
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index de537161aa..e0d7a76cc4 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -580,6 +580,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, co
if (row.authority.remote) throw trustedCliRequired('Remote maintenance publication is not supported.');
enterClaimStep(clock, 'maintenance_dispatch');
if (row.intent?.kind === 'managed_maintenance_restore_extractor_facts') return (await import('../repair/extractor-facts.ts')).prepareExtractorFactsRestore(engine, row);
+ if (row.intent?.kind === 'managed_maintenance_restore_unwithdrawn_facts') return (await import('../repair/unwithdrawn-facts.ts')).prepareUnwithdrawnFactsRestore(engine, row);
if (row.intent?.kind === 'managed_maintenance_expire_captured_facts') return (await import('../repair/captured-facts.ts')).prepareCapturedFactsExpiry(engine, row);
if (row.intent?.kind === 'managed_maintenance_agent_session_facts') return (await import('../repair/agent-session-facts.ts')).prepareAgentSessionFactsWrite(engine, row);
if (row.intent?.kind === 'managed_maintenance_restore_redacted_facts') return (await import('../repair/redacted-facts.ts')).prepareRedactedFactsRestore(engine, row);
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index 749b231248..8813a8229a 100644
--- a/src/core/persistence/preview-approval.ts
+++ b/src/core/persistence/preview-approval.ts
@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';
/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */
export const APPROVAL_MAX_AGE_DAYS = 7;
-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'segmented-tiling' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'contact-rows' | 'provenance' | 'secret-spans' | 'rows-behind';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'unwithdrawn-facts' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'segmented-tiling' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'contact-rows' | 'provenance' | 'secret-spans' | 'rows-behind';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index ca9d4aeba7..12f0d04f7e 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -51,7 +51,7 @@ import { classifyItemFailure, ItemRun, type ItemFailure } from '../item-failure.
import type { ProgressReporter } from '../progress.ts';
import type { GenerationsSelection } from '../generations/repair.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'access'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'access'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.ts
index 089082c631..447394ed01 100644
--- a/src/core/repair/failed-writes.ts
+++ b/src/core/repair/failed-writes.ts
@@ -166,6 +166,7 @@ function producerCommand(producer: string, sourceId: string): string {
if (parts.includes('managed_maintenance_expire_captured_facts')) return `gbrain repair captured-facts --source ${sourceId}`;
if (parts.includes('managed_maintenance_agent_session_facts')) return `gbrain repair agent-session-facts --source ${sourceId}`;
if (parts.includes('managed_maintenance_restore_extractor_facts')) return `gbrain repair extractor-facts --source ${sourceId}`;
+ if (parts.includes('managed_maintenance_restore_unwithdrawn_facts')) return `gbrain repair unwithdrawn-facts --source ${sourceId}`;
if (parts.includes('managed_maintenance_restore_redacted_facts')) return `gbrain repair redacted-facts --source ${sourceId}`;
if (parts.includes('managed_maintenance_conversation_facts')) return `gbrain extract-conversation-facts --source-id ${sourceId} --dry-run`;
return 'the next `gbrain dream` cycle (or autopilot) produces it again';
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index e2984d33f7..9cedd007ce 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -55,6 +55,7 @@ import { googleFileModesRepair } from './google-file-modes.ts';
import { staleAtomsRepair } from './stale-atoms.ts';
import { atomsRestoreRepair } from './atoms-restore.ts';
import { extractorFactsRepair } from './extractor-facts.ts';
+import { unwithdrawnFactsRepair } from './unwithdrawn-facts.ts';
import { conversationLabelsRepair } from './conversation-labels.ts';
import { capturedFactsRepair } from './captured-facts.ts';
import { agentSessionFactsRepair, agentSessionFlagArgs } from './agent-session-facts.ts';
@@ -229,6 +230,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'without that evidence. Preview-bound: --apply --expect <hash> restores exactly the previewed set; a fact that changed since reports '
+ 'changed_since_preview and stays expired. Superseded, withdrawn and duplicated facts are never restored. Database-only; no page is rewritten.',
},
+ 'unwithdrawn-facts': {
+ handler: unwithdrawnFactsRepair, embeds: 'none', checks: ['unwithdrawn_facts'], explicit_only: true, preview_bound: true,
+ summary: 'Restore facts a facts-fence generation retired although no fence of their page ever held them (#8819), first generations included. '
+ + 'Restores the original fact ids and recorded lifecycle from the generation ledger; a fact a fence held (a genuine withdrawal), a withdrawn, '
+ + 'superseded or duplicated fact is never restored; --include-ambiguous adds facts of pages whose version history has a gap. Preview-bound: '
+ + '--apply --expect <hash> restores exactly the previewed set, bound to each page\'s revision; a changed page or fact reports changed_since_preview. '
+ + 'Database-only; no page is rewritten.',
+ },
'conversation-labels': {
handler: conversationLabelsRepair, embeds: 'none', checks: ['conversation_label_facts'], explicit_only: true, consent: 'destructive',
consentText: {
diff --git a/src/core/repair/unwithdrawn-facts.ts b/src/core/repair/unwithdrawn-facts.ts
new file mode 100644
index 0000000000..0799b616f1
--- /dev/null
+++ b/src/core/repair/unwithdrawn-facts.ts
@@ -0,0 +1,333 @@
+/**
+ * `gbrain repair unwithdrawn-facts` (#8819): restore fact rows a facts-fence generation retired although no fence of
+ * their page ever held them.
+ *
+ * Before the fix, the page publication's projection and the extract_facts reconcile retired every fact row attached to a
+ * page with a row number that the incoming fence did not hold. A put_page row (or one an older writer stamped) that was
+ * never in the fence was expired by a write that changed nothing in it, often the page's first fact generation, which
+ * has no predecessor for `repair generations --kind fact_fence` to restore. The ledger kept each retired row's
+ * before-state, which is what this kind restores.
+ *
+ * Candidates: a `retired` item with a fact preimage in a fact_fence generation, whose fact is still exactly as the
+ * retirement left it: expired at that generation's instant, row number cleared, same claim and visibility, not
+ * superseded, and not a conversation-extractor row (`repair extractor-facts` owns those). Each is classified:
+ * - excluded (listed, never restored): the page is missing or deleted; the fact was superseded or withdrawn
+ * (`fact_withdrawals`); a fence held it (a fact_fence generation recorded it, or the page or a stored version of it
+ * carries it at the same row number, claim and visibility: a genuine withdrawal); an active fact with the same
+ * text, visibility and entity is on the page; or another candidate with the same text is restored instead.
+ * - ambiguous (restored only with `--include-ambiguous` and that preview's hash): the page's version history has a
+ * gap (pruned, or an import that consumed several commits) or was not read whole, so an earlier fence holding the
+ * row cannot be ruled out.
+ * - evidenced: everything else.
+ *
+ * The preview binds each page's revision. The apply restores exactly the approved set under the page key: a managed
+ * brain publishes one database-only `managed_maintenance_restore_unwithdrawn_facts` request per page bound to the
+ * previewed revision; an unmanaged (or repo-less) brain checks the revision and writes in one page-locked maintenance
+ * transaction. A changed page refuses whole (`changed_since_preview`); each fact is reclassified and restored only when
+ * its class and evidence are unchanged. A restored fact keeps its id and gets back its recorded lifecycle (`expired_at`,
+ * `valid_until`, `superseded_by`, consolidation marks) and its row number, or a fresh number above the page's rows
+ * when a fence row took it. No page is rewritten; the fix keeps restored rows active on later writes.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import type { WriteRequest } from '../persistence/model.ts';
+import { opError, OperationError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { digest } from '../persistence/digest.ts';
+import { authorizeWrite } from '../persistence/authority.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { FACT_FENCE_KIND } from '../generations/fence.ts';
+import { factsFenceHeld } from '../generations/fence-evidence.ts';
+import type { FactPreimage } from '../generations/adapters/fact-rows.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';
+
+export const UNWITHDRAWN_FACTS_INTENT = 'managed_maintenance_restore_unwithdrawn_facts';
+const previewFix = (sourceId: string) => readFix('Previews the unwithdrawn-facts repair without changing anything.',
+ { argv: ['gbrain', 'repair', 'unwithdrawn-facts', '--source', sourceId, '--json'] });
+
+export type UnwithdrawnFactClass = 'evidenced' | 'ambiguous' | 'excluded';
+
+const INSTANT = (column: string) => `to_char(${column} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;
+
+/** One candidate as the preview showed it; the apply rechecks every field. */
+export interface UnwithdrawnFactCandidate {
+ id: number;
+ source_id: string;
+ slug: string;
+ class: UnwithdrawnFactClass;
+ reason: string;
+ /** The fact_fence generation that retired it, and that generation's instant (UTC, microseconds). */
+ generation_id: number;
+ generation: number;
+ retired_at: string;
+ /** Digest of the claim, visibility and entity, so an edited row is not restored. */
+ fact_hash: string;
+ /** The before-state the ledger recorded, restored as it is. */
+ preimage: FactPreimage;
+}
+
+/** One approved page: its revision at preview, its restorable facts and the request id its managed restore uses. */
+export interface UnwithdrawnFactsPage {
+ source_id: string;
+ slug: string;
+ page_id: number;
+ revision: string;
+ request_id: string;
+ include_ambiguous: boolean;
+ scope: string[];
+ facts: UnwithdrawnFactCandidate[];
+}
+
+interface PageItem extends RepairItem { page: UnwithdrawnFactsPage; hash: string; last: boolean }
+
+interface CandidateRow {
+ id: number | string; source_id: string; slug: string; fact: string; visibility: string; entity_slug: string | null; superseded: boolean;
+ generation_id: number | string; generation: number | string; retired_at: string; expired_at: string; preimage: FactPreimage;
+ page_id: number | string | null; page_deleted: boolean | null; history_gap: boolean | null; withdrawn: boolean; active_duplicate: boolean; fingerprint: string;
+}
+
+/** Every candidate of these sources (or of one page), classified, in (source, page, id) order. Read-only. */
+export async function classifyUnwithdrawnFacts(db: BrainEngine, sourceIds: string[], opts: { slug?: string } = {}): Promise<UnwithdrawnFactCandidate[]> {
+ const rows = await db.executeRaw<CandidateRow>(`
+ WITH retired AS (
+ SELECT DISTINCT ON ((i.preimage->>'id')::bigint) (i.preimage->>'id')::bigint AS fact_id, g.id AS generation_id, g.generation, g.source_id,
+ substr(g.owner_key, 6) AS slug, ${INSTANT('g.created_at')} AS retired_at, i.preimage
+ FROM derived_generation_items i JOIN derived_generations g ON g.id = i.generation_id
+ WHERE g.kind = $3 AND g.source_id = ANY($1::text[]) AND g.state <> 'held' AND i.action = 'retired' AND left(g.owner_key, 5) = 'page:'
+ AND jsonb_typeof(i.preimage) = 'object' AND i.preimage ? 'id' AND i.preimage->>'expired_at' IS NULL AND i.preimage->>'row_num' IS NOT NULL
+ AND ($2::text IS NULL OR g.owner_key = 'page:' || $2::text)
+ ORDER BY (i.preimage->>'id')::bigint, g.id DESC
+ )
+ SELECT f.id, r.source_id, r.slug, f.fact, f.visibility, f.entity_slug, f.superseded_by IS NOT NULL AS superseded, r.generation_id, r.generation,
+ r.retired_at, ${INSTANT('f.expired_at')} AS expired_at, r.preimage, gbrain_fact_fingerprint(f.fact) AS fingerprint,
+ p.id AS page_id, p.deleted_at IS NOT NULL AS page_deleted, p.version_history_gap_at IS NOT NULL AS history_gap,
+ EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id = f.source_id AND w.visibility = f.visibility
+ AND w.fact_hash IN (gbrain_fact_fingerprint(f.fact), gbrain_fact_fingerprint_v1(f.fact))
+ AND (w.subject = '*' OR w.subject = f.entity_slug)) AS withdrawn,
+ EXISTS (SELECT 1 FROM facts a WHERE a.source_id = f.source_id AND a.visibility = f.visibility AND a.source_markdown_slug = r.slug
+ AND a.expired_at IS NULL AND gbrain_fact_fingerprint(a.fact) = gbrain_fact_fingerprint(f.fact)
+ AND a.entity_slug IS NOT DISTINCT FROM f.entity_slug) AS active_duplicate
+ FROM retired r
+ JOIN facts f ON f.id = r.fact_id AND f.source_id = r.source_id
+ LEFT JOIN pages p ON p.source_id = r.source_id AND p.slug = r.slug
+ WHERE f.expired_at IS NOT NULL AND f.row_num IS NULL AND f.fact = r.preimage->>'fact' AND f.visibility = r.preimage->>'visibility'
+ AND COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%'
+ ORDER BY r.source_id, r.slug, f.id`, [sourceIds, opts.slug ?? null, FACT_FENCE_KIND]);
+ // A fence that held the row (a generation, the page, a stored version) means the row was withdrawn by an edit of it.
+ const evidence = new Map<string, { held: Set<number>; complete: boolean }>();
+ for (const row of rows) {
+ const key = `${row.source_id}\u0000${row.slug}`;
+ if (evidence.has(key) || row.page_id === null) continue;
+ const page = rows.filter(other => other.source_id === row.source_id && other.slug === row.slug);
+ const current = await db.executeRaw<{ compiled_truth: string | null; timeline: string | null; body_storage: string | null }>(
+ 'SELECT compiled_truth, timeline, body_storage FROM pages WHERE id = $1', [row.page_id]);
+ evidence.set(key, await factsFenceHeld(db, { sourceId: row.source_id, slug: row.slug, prior: current[0] ?? null,
+ rows: page.map(other => ({ id: Number(other.id), row_num: Number(other.preimage.row_num), fact: other.preimage.fact, visibility: other.preimage.visibility })) }));
+ }
+ const base = rows.map(row => classify(row, evidence.get(`${row.source_id}\u0000${row.slug}`)));
+ const key = (row: CandidateRow) => JSON.stringify([row.source_id, row.slug, row.visibility, row.entity_slug, row.fingerprint]);
+ const representative = new Map<string, number>();
+ for (const klass of ['evidenced', 'ambiguous'] as const) rows.forEach((row, i) => { if (base[i]![0] === klass && !representative.has(key(row))) representative.set(key(row), i); });
+ return rows.map((row, i) => {
+ const duplicate = base[i]![0] !== 'excluded' && representative.get(key(row)) !== i;
+ const [klass, reason] = duplicate ? ['excluded' as const, 'duplicate_candidate'] : base[i]!;
+ return { id: Number(row.id), source_id: row.source_id, slug: row.slug, class: klass, reason, generation_id: Number(row.generation_id),
+ generation: Number(row.generation), retired_at: row.retired_at, fact_hash: digest([row.fact, row.visibility, row.entity_slug]), preimage: row.preimage };
+ });
+}
+
+function classify(row: CandidateRow, evidence: { held: Set<number>; complete: boolean } | undefined): [UnwithdrawnFactClass, string] {
+ if (row.page_id === null || row.page_deleted || !evidence) return ['excluded', 'page_missing'];
+ if (row.superseded) return ['excluded', 'superseded'];
+ if (row.withdrawn) return ['excluded', 'withdrawn'];
+ if (row.expired_at !== row.retired_at) return ['excluded', 'changed_since_retirement'];
+ if (evidence.held.has(Number(row.id))) return ['excluded', 'fence_held'];
+ if (row.active_duplicate) return ['excluded', 'active_duplicate'];
+ if (row.history_gap) return ['ambiguous', 'version_history_gap'];
+ if (!evidence.complete) return ['ambiguous', 'version_history_unread'];
+ return ['evidenced', 'never_in_fence'];
+}
+
+const DETAILS: Record<string, string> = {
+ page_missing: 'its page is missing or deleted',
+ superseded: 'a newer fact superseded it',
+ withdrawn: 'its claim was withdrawn (forget)',
+ changed_since_retirement: 'it changed after the generation retired it',
+ fence_held: 'a fence of the page held it, so an edit of the fence withdrew it',
+ active_duplicate: 'an active fact with the same text and entity is already on the page',
+ duplicate_candidate: 'another candidate of the page with the same text and entity is restored instead',
+ version_history_gap: "the page's version history has a gap, so an earlier fence holding it cannot be ruled out",
+ version_history_unread: "the page has more stored versions than one preview reads, so an earlier fence holding it cannot be ruled out",
+};
+
+function detail(fact: UnwithdrawnFactCandidate): string {
+ if (fact.class !== 'evidenced') return DETAILS[fact.reason] ?? fact.reason;
+ return `retired at ${fact.retired_at} by facts-fence generation ${fact.generation} of the page; no fence of the page ever held it`;
+}
+
+async function previewCommand(engine: BrainEngine, scope: RepairScope, includeAmbiguous: boolean): Promise<string> {
+ const [{ n }] = await engine.executeRaw<{ n: number | string }>('SELECT count(*)::int AS n FROM sources WHERE archived IS NOT TRUE');
+ const narrowed = scope.source_ids.length === 1 && Number(n) > 1;
+ return `gbrain repair unwithdrawn-facts${narrowed ? ` --source ${scope.source_ids[0]}` : ''}${includeAmbiguous ? ' --include-ambiguous' : ''}`;
+}
+
+function requestIdFor(hash: string, page: Pick<UnwithdrawnFactsPage, 'source_id' | 'slug'>): string {
+ const h = digest(['unwithdrawn-facts-request-v1', hash, page.source_id, page.slug]);
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
+}
+
+async function hashParts(engine: BrainEngine, scope: RepairScope, includeAmbiguous: boolean, facts: UnwithdrawnFactCandidate[], revisions: Record<string, string>) {
+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>(
+ 'SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);
+ return { kind: 'unwithdrawn-facts-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids, include_ambiguous: includeAmbiguous },
+ facts: facts.map(({ preimage: _preimage, ...fact }) => fact), revisions };
+}
+
+function pageItem(page: UnwithdrawnFactsPage, hash: string, index: number, last: boolean): PageItem {
+ return { cursor: { phase: 0, id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0,
+ action: `restore ${page.facts.length} fact(s) no fence withdrew`, page, hash, last };
+}
+
+export const unwithdrawnFactsRepair: RepairHandler = {
+ kind: 'unwithdrawn-facts',
+ embeds: false,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const includeAmbiguous = opts?.includeAmbiguous === true;
+ if (!opts?.apply) {
+ const facts = await classifyUnwithdrawnFacts(engine, scope.source_ids);
+ const snapshots = new Map<string, { id: number; revision: string }>();
+ for (const fact of facts) {
+ const key = `${fact.source_id}\u0000${fact.slug}`;
+ if (fact.class === 'excluded' || snapshots.has(key)) continue;
+ const snapshot = await engine.readPageSnapshot(fact.slug, { sourceId: fact.source_id });
+ if (snapshot) snapshots.set(key, { id: snapshot.page.id, revision: snapshot.revision });
+ }
+ const revisions = Object.fromEntries([...snapshots].map(([key, value]) => [key, value.revision]));
+ const hash = previewHash(await hashParts(engine, scope, includeAmbiguous, facts, revisions));
+ const pages = new Map<string, UnwithdrawnFactsPage>();
+ for (const fact of facts) {
+ if (fact.class === 'excluded' || fact.class === 'ambiguous' && !includeAmbiguous) continue;
+ const key = `${fact.source_id}\u0000${fact.slug}`;
+ const snapshot = snapshots.get(key);
+ if (!snapshot) continue;
+ const page = pages.get(key) ?? { source_id: fact.source_id, slug: fact.slug, page_id: snapshot.id, revision: snapshot.revision,
+ request_id: requestIdFor(hash, fact), include_ambiguous: includeAmbiguous, scope: scope.source_ids, facts: [] };
+ page.facts.push(fact);
+ pages.set(key, page);
+ }
+ const approved = [...pages.values()];
+ if (approved.length) await saveApprovedSet(engine, { command: 'unwithdrawn-facts', hash }, approved);
+ const count = (klass: UnwithdrawnFactClass) => facts.filter(f => f.class === klass).length;
+ const listing: RepairListing[] = facts.map(fact => ({ item: `${fact.source_id}:${fact.slug}#${fact.id}`,
+ class: fact.class === 'excluded' ? `excluded:${fact.reason}` : fact.class, detail: detail(fact) }));
+ return { items: approved.map((page, index) => pageItem(page, hash, index, index === approved.length - 1)), preview_hash: hash,
+ residuals: { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded') }, listing };
+ }
+ const command = await previewCommand(engine, scope, includeAmbiguous);
+ if (!opts.expect) {
+ throw new OperationError('invalid_params', 'gbrain repair unwithdrawn-facts --apply restores only the set a preview printed.',
+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,
+ 'docs/guides/repair.md#explicit-only-repair-kinds');
+ }
+ const approved = await loadApprovedSet<UnwithdrawnFactsPage>(engine, { command: 'unwithdrawn-facts', hash: opts.expect, previewCommand: command,
+ emptyHash: async () => previewHash(await hashParts(engine, scope, includeAmbiguous, [], {})) });
+ const scopeKey = JSON.stringify(scope.source_ids);
+ if (approved.items.some(page => page.include_ambiguous !== includeAmbiguous || JSON.stringify(page.scope) !== scopeKey)) throw previewChangedError(opts.expect, command);
+ const items = approved.items.map((page, index) => pageItem(page, opts.expect!, index, index === approved.items.length - 1))
+ .filter(item => afterCursor(item.cursor, after));
+ if (!items.length) await clearApprovedSet(engine, { command: 'unwithdrawn-facts', hash: opts.expect });
+ return { items, preview_hash: opts.expect, residuals: { already_passed_pages: approved.items.length - items.length } };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { page, hash, last } = entry as PageItem;
+ const result = await managedPersistenceEnabled(ctx.engine)
+ ? await restoreManaged(ctx.engine, page, hash)
+ : await maintenanceTransaction(ctx.engine, async tx => {
+ await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);
+ const snapshot = await tx.readPageSnapshot(page.slug, { sourceId: page.source_id });
+ if (!snapshot || snapshot.page.id !== page.page_id || snapshot.revision !== page.revision) return { restored: [], changed: page.facts.map(f => f.id) };
+ return restorePageFacts(tx, page);
+ });
+ if (last) await clearApprovedSet(ctx.engine, { command: 'unwithdrawn-facts', hash });
+ const changed = page.facts.length - result.restored.length;
+ return { applied: result.restored.length > 0, outcome: !changed ? 'restored' : result.restored.length ? 'partially_restored' : 'changed_since_preview',
+ ...(changed ? { reason: `${result.restored.length} of ${page.facts.length} restored; changed since the preview: ${result.changed.join(', ')}` } : {}) };
+ },
+};
+
+interface RestoreResult { restored: number[]; changed: number[] }
+
+async function restoreManaged(engine: BrainEngine, page: UnwithdrawnFactsPage, hash: string): Promise<RestoreResult> {
+ const unchanged: RestoreResult = { restored: [], changed: page.facts.map(f => f.id) };
+ const authority = (await maintenancePreflight(engine, page.source_id))!;
+ try {
+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, page.slug,
+ { kind: UNWITHDRAWN_FACTS_INTENT, expected_revision: page.revision, preview_hash: hash, page }, page.request_id);
+ return { restored: (receipt.restored as number[] | undefined) ?? [], changed: (receipt.changed_since_preview as number[] | undefined) ?? [] };
+ } catch (error) {
+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return unchanged;
+ throw error;
+ }
+}
+
+/**
+ * Restores the page's approved facts that are still exactly as previewed, under the page key, inside the managed
+ * publication or the unmanaged transaction: each keeps its id and gets its recorded lifecycle back, at its recorded row
+ * number when that number is free on the page, else one above every row of the page and its fence.
+ */
+async function restorePageFacts(tx: BrainEngine, page: UnwithdrawnFactsPage): Promise<RestoreResult> {
+ const ids = page.facts.map(f => f.id);
+ await tx.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND id=ANY($2::bigint[]) FOR UPDATE', [page.source_id, ids]);
+ const live = new Map((await classifyUnwithdrawnFacts(tx, [page.source_id], { slug: page.slug })).map(f => [f.id, f]));
+ const result: RestoreResult = { restored: [], changed: [] };
+ for (const approved of page.facts) {
+ const current = live.get(approved.id);
+ const same = !!current && (['class', 'reason', 'generation_id', 'retired_at', 'fact_hash'] as const).every(field => current[field] === approved[field]);
+ const p = approved.preimage;
+ const updated = same ? await tx.executeRaw<{ id: number }>(`UPDATE facts f SET expired_at=$4::timestamptz, valid_until=$5::timestamptz, superseded_by=$6::bigint,
+ consolidated_at=$7::timestamptz, consolidated_into=$8::bigint,
+ row_num=CASE WHEN NOT EXISTS (SELECT 1 FROM facts o WHERE o.source_id=f.source_id AND o.source_markdown_slug=$10 AND o.row_num=$9::integer) THEN $9::integer
+ ELSE (SELECT COALESCE(max(o.row_num), 0) + 1 FROM facts o WHERE o.source_id=f.source_id AND o.source_markdown_slug=$10) END
+ WHERE f.source_id=$1 AND f.id=$2::bigint AND f.fact=$3 AND f.row_num IS NULL AND f.superseded_by IS NULL AND ${INSTANT('f.expired_at')}=$11
+ RETURNING f.id`, [page.source_id, approved.id, p.fact, p.expired_at, p.valid_until, p.superseded_by, p.consolidated_at, p.consolidated_into,
+ p.row_num, page.slug, approved.retired_at]) : [];
+ if (updated.length) result.restored.push(approved.id); else result.changed.push(approved.id);
+ }
+ return result;
+}
+
+/**
+ * Preparer for `managed_maintenance_restore_unwithdrawn_facts`: a database-only publication on the page key, bound to the
+ * revision the preview saw, that reclassifies and restores the approved facts of one page and reports the rest as
+ * `changed_since_preview`.
+ */
+export async function prepareUnwithdrawnFactsRestore(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ const intent = row.intent as { page?: UnwithdrawnFactsPage; preview_hash?: unknown } | null;
+ const page = intent?.page;
+ if (!page || page.source_id !== row.source_id || page.slug !== row.slug || typeof intent?.preview_hash !== 'string' || !Array.isArray(page.facts)) {
+ throw opError('invalid_params', 'The unwithdrawn facts restore intent does not name its page.',
+ `Request ${row.request_id} for ${row.slug} in source ${row.source_id} does not name the page and preview it restores, so nothing changed. Preview the repair again and apply the new preview after the user approves.`,
+ { fix: previewFix(row.source_id) });
+ }
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ if (!snapshot || snapshot.page.id !== Number(row.page_id) || snapshot.page.id !== page.page_id) {
+ throw opError('page_identity_changed', 'The page was deleted or replaced before its facts were restored.',
+ `Page ${row.slug} in source ${row.source_id} was deleted or replaced after the preview, so request ${row.request_id} restored nothing. Preview the repair again; it reflects the current pages.`,
+ { fix: previewFix(row.source_id) });
+ }
+ if (snapshot.revision !== page.revision) {
+ throw opError('revision_conflict', 'The page changed after the unwithdrawn-facts preview.',
+ `Page ${row.slug} in source ${row.source_id} was written after the preview, so request ${row.request_id} restored nothing. Preview the repair again; it reflects the current page.`,
+ { fix: previewFix(row.source_id) });
+ }
+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);
+ return { observedRevision: snapshot.revision, noop: true,
+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },
+ apply: async tx => {
+ const result = await restorePageFacts(tx, page);
+ return { status: 'completed', preview_hash: intent!.preview_hash, restored: result.restored, changed_since_preview: result.changed };
+ } };
+}
diff --git a/src/core/trust/fence-guard.ts b/src/core/trust/fence-guard.ts
index 28a4c37fbd..0d06922ac2 100644
--- a/src/core/trust/fence-guard.ts
+++ b/src/core/trust/fence-guard.ts
@@ -44,7 +44,8 @@ export interface FenceGuard<T extends FenceFact> {
* not supersede. `expired()` runs the caller's expiry; then guarded renumbers
* move and new rows are gated.
*/
-export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input: { sourceId: string; slug: string; incoming: string; rows: T[]; cfg: (db: BrainEngine) => Promise<WriteGateConfig> },
+export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input: { sourceId: string; slug: string; incoming: string; rows: T[]; cfg: (db: BrainEngine) => Promise<WriteGateConfig>;
+ /** #8819: rows the fence never held, which this write keeps as they are. */ kept?: readonly number[] },
expire: () => Promise<unknown>): Promise<FenceGuard<T>> {
const { sourceId, slug, incoming } = input;
const guarded = await tx.executeRaw<{ id: number; row_num: number; fact: string; visibility: string; trust_tier: string }>(
@@ -54,8 +55,8 @@ export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input
OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num))
AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text)
WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility)
- AND ${trustRankSql('f.trust_tier')} > ${WRITER_RANK}
- ORDER BY f.row_num FOR UPDATE`, [sourceId, slug, incoming]);
+ AND ${trustRankSql('f.trust_tier')} > ${WRITER_RANK} AND NOT (f.id = ANY($4::bigint[]))
+ ORDER BY f.row_num FOR UPDATE`, [sourceId, slug, incoming, [...(input.kept ?? [])]]);
if (guarded.length) await tx.executeRaw('UPDATE facts SET row_num = NULL WHERE id = ANY($1::bigint[])', [guarded.map(g => Number(g.id))]);
await expire();
// A fence with no rows and nothing guarded has nothing to place or gate (#6007: no reads on a fence-free publish).
diff --git a/test/eval-contradictions/no-valid-until-write.test.ts b/test/eval-contradictions/no-valid-until-write.test.ts
index 5e60c0d91a..8aeb7261a9 100644
--- a/test/eval-contradictions/no-valid-until-write.test.ts
+++ b/test/eval-contradictions/no-valid-until-write.test.ts
@@ -75,6 +75,11 @@ import { join } from 'node:path';
// a preview-approved `gbrain repair generations --mode restore` of a
// consolidation chain or a fence generation; local CLI, and the
// contradiction probe never calls it.
+// - repair/unwithdrawn-facts.ts (#8819) — `gbrain repair unwithdrawn-facts`
+// writes back the ledger preimage (valid_until included) of a fact the
+// first managed fence generation retired though no fence held it; local
+// CLI, explicit-only, preview-bound, and the contradiction probe never
+// calls it.
const VALID_UNTIL_WRITE_ALLOWLIST: ReadonlySet<string> = new Set([
'src/core/cycle/extract-facts.ts',
'src/core/cycle/phases/consolidate.ts',
@@ -93,6 +98,7 @@ const VALID_UNTIL_WRITE_ALLOWLIST: ReadonlySet<string> = new Set([
'src/core/postgres-engine.ts',
'src/core/pglite-engine.ts',
'src/core/repair/consolidate-ties.ts',
+ 'src/core/repair/unwithdrawn-facts.ts',
]);
function walkTs(dir: string, acc: string[] = []): string[] {
diff --git a/test/fence-first-generation-8819.test.ts b/test/fence-first-generation-8819.test.ts
new file mode 100644
index 0000000000..f6f2c0e08a
--- /dev/null
+++ b/test/fence-first-generation-8819.test.ts
@@ -0,0 +1,122 @@
+/**
+ * #8819: the first managed facts-fence generation retired fact rows the page's fence never held (put_page rows with a row
+ * number, no superseded_by), so a write that changed nothing in the fence expired them. A row retires only when a fence
+ * held it: a fact_fence generation recorded it, the page as the writer read it carried it, or a stored version of the
+ * page did. Any other row stays active with its id; a fence row claiming its number takes it and the row moves.
+ * Seeds write the page without a projection, so the managed write under test publishes generation 1 with no predecessor.
+ * PGLite; Postgres when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { pathologicalArms } from './pathological/harness.ts';
+import { FACTS_FENCE, managedSource, PERSON, type ManagedSource } from './pathological/managed-fixture.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+
+const SLUG = 'people/alice-example';
+const ROW = (n: number, claim: string) => `| ${n} | ${claim} | fact | 1.0 | private | medium | 2020-01-01 | | chat | |`;
+const FOUNDED = ROW(1, 'Alice founded acme-example');
+const CHESS = ROW(2, 'Alice plays chess');
+
+/**
+ * The page as a brain from before fact generations left it: written through `put`, then with its fact ledger cleared and
+ * `rows` attached with row numbers, as a fence projection or an older put_page writer stamped them.
+ */
+async function seedPage(s: ManagedSource, body: string, rows: Array<[number, string, string?]>): Promise<void> {
+ await s.put(SLUG, PERSON('Alice Example', body));
+ await s.engine.executeRaw("DELETE FROM derived_generations WHERE source_id=$1 AND kind='fact_fence'", [s.sourceId]);
+ await s.engine.executeRaw('DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [s.sourceId, SLUG]);
+ for (const [rowNum, fact, source] of rows) await factRow(s.engine, s.sourceId, rowNum, fact, source ?? 'mcp:put_page');
+}
+
+/** A fact row attached to the page with a row number, as a fence projection or a put_page writer stamped it. */
+async function factRow(engine: BrainEngine, sourceId: string, rowNum: number, fact: string, source = 'mcp:put_page'): Promise<number> {
+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug)
+ VALUES ($1, $2, $3, 'fact', 'private', $4, $5, $2) RETURNING id`, [sourceId, SLUG, fact, source, rowNum]);
+ return Number(row!.id);
+}
+
+async function facts(engine: BrainEngine, sourceId: string) {
+ return (await engine.executeRaw<{ fact: string; row_num: number | null; active: boolean }>(
+ 'SELECT fact, row_num, expired_at IS NULL AS active FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY id', [sourceId, SLUG]))
+ .map(row => [row.fact, row.row_num === null ? null : Number(row.row_num), row.active]);
+}
+
+async function generations(engine: BrainEngine, sourceId: string) {
+ return (await engine.executeRaw<{ generation: number; state: string; retired: number }>(`SELECT g.generation, g.state,
+ (SELECT count(*)::int FROM derived_generation_items i WHERE i.generation_id=g.id AND i.action='retired') AS retired
+ FROM derived_generations g WHERE g.source_id=$1 AND g.kind='fact_fence' AND g.owner_key=$2 ORDER BY g.id`, [sourceId, `page:${SLUG}`]))
+ .map(row => [Number(row.generation), row.state, Number(row.retired)]);
+}
+
+describe('#8819 first managed facts-fence generation', () => {
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test(`[${backend}] a write that leaves the fence alone keeps put_page rows the fence never held`, async () => {
+ await managedSource(databaseUrl, async s => {
+ await seedPage(s, `Alice is an example person.\n\n${FACTS_FENCE(FOUNDED)}`, [[1, 'Alice founded acme-example', 'chat'], [2, 'Alice plays chess'], [3, 'Alice lives in Lisbon']]);
+ }, async ({ engine, sourceId, put }) => {
+ expect(await generations(engine, sourceId)).toEqual([]);
+ await put(SLUG, PERSON('Alice Example', `Alice is an example person. An edit changed this paragraph.\n\n${FACTS_FENCE(FOUNDED)}`));
+ expect(await facts(engine, sourceId)).toEqual([['Alice founded acme-example', 1, true], ['Alice plays chess', 2, true], ['Alice lives in Lisbon', 3, true]]);
+ expect(await generations(engine, sourceId)).toEqual([[1, 'live', 0]]);
+ await put(SLUG, PERSON('Alice Example', `Alice is an example person. A second edit.\n\n${FACTS_FENCE(FOUNDED)}`));
+ expect((await facts(engine, sourceId)).every(row => row[2])).toBe(true);
+ });
+ }, 120_000);
+
+ test(`[${backend}] an empty fence on a first generation retires the rows it held and keeps the rest`, async () => {
+ await managedSource(databaseUrl, async s => {
+ await seedPage(s, FACTS_FENCE(FOUNDED), [[1, 'Alice founded acme-example', 'chat'], [2, 'Alice plays chess']]);
+ }, async ({ engine, sourceId, put }) => {
+ await put(SLUG, PERSON('Alice Example', FACTS_FENCE('')));
+ expect(await facts(engine, sourceId)).toEqual([['Alice founded acme-example', null, false], ['Alice plays chess', 2, true]]);
+ expect(await generations(engine, sourceId)).toEqual([[1, 'live', 1]]);
+ });
+ }, 120_000);
+
+ test(`[${backend}] a write that drops a row the prior fence held still retires it, with no generation before it`, async () => {
+ await managedSource(databaseUrl, async s => {
+ await seedPage(s, FACTS_FENCE([FOUNDED, CHESS].join('\n')), [[1, 'Alice founded acme-example', 'chat'], [2, 'Alice plays chess', 'chat'], [3, 'Alice lives in Lisbon']]);
+ }, async ({ engine, sourceId, put }) => {
+ await put(SLUG, PERSON('Alice Example', FACTS_FENCE(FOUNDED)));
+ expect(await facts(engine, sourceId)).toEqual([['Alice founded acme-example', 1, true], ['Alice plays chess', null, false], ['Alice lives in Lisbon', 3, true]]);
+ expect(await generations(engine, sourceId)).toEqual([[1, 'live', 1]]);
+ });
+ }, 120_000);
+
+ test(`[${backend}] a row an earlier edit removed from the fence retires on the stored version that held it`, async () => {
+ await managedSource(databaseUrl, async s => {
+ await s.put(SLUG, PERSON('Alice Example', FACTS_FENCE([FOUNDED, CHESS].join('\n'))));
+ await seedPage(s, FACTS_FENCE(FOUNDED), [[1, 'Alice founded acme-example', 'chat'], [2, 'Alice plays chess', 'chat']]);
+ }, async ({ engine, sourceId, put }) => {
+ await put(SLUG, PERSON('Alice Example', `An edit changed this paragraph.\n\n${FACTS_FENCE(FOUNDED)}`));
+ expect(await facts(engine, sourceId)).toEqual([['Alice founded acme-example', 1, true], ['Alice plays chess', null, false]]);
+ });
+ }, 120_000);
+
+ test(`[${backend}] a fence row that claims a kept row's number takes it; the kept row moves and stays active across later writes`, async () => {
+ await managedSource(databaseUrl, async s => {
+ await seedPage(s, FACTS_FENCE(FOUNDED), [[1, 'Alice founded acme-example', 'chat'], [2, 'Alice plays chess']]);
+ }, async ({ engine, sourceId, put }) => {
+ await put(SLUG, PERSON('Alice Example', FACTS_FENCE([FOUNDED, ROW(2, 'Alice speaks Portuguese')].join('\n'))));
+ expect(await facts(engine, sourceId)).toEqual([['Alice founded acme-example', 1, true], ['Alice plays chess', 3, true], ['Alice speaks Portuguese', 2, true]]);
+ await put(SLUG, PERSON('Alice Example', FACTS_FENCE(FOUNDED)));
+ expect(await facts(engine, sourceId)).toEqual([['Alice founded acme-example', 1, true], ['Alice plays chess', 3, true], ['Alice speaks Portuguese', null, false]]);
+ });
+ }, 120_000);
+
+ test(`[${backend}] the extract_facts reconcile keeps rows the fence never held and still retires a withdrawn one`, async () => {
+ await managedSource(databaseUrl, async s => {
+ await s.put(SLUG, PERSON('Alice Example', FACTS_FENCE([FOUNDED, CHESS, ROW(5, 'Alice ran a marathon')].join('\n'))));
+ await seedPage(s, FACTS_FENCE([FOUNDED, CHESS].join('\n')), [[1, 'Alice founded acme-example', 'chat'], [2, 'Alice speaks Portuguese'],
+ [3, 'Alice lives in Lisbon'], [5, 'Alice ran a marathon', 'chat']]);
+ }, async ({ engine, sourceId }) => {
+ await runExtractFacts(engine, { sourceId });
+ expect(await facts(engine, sourceId)).toEqual([['Alice founded acme-example', 1, true], ['Alice speaks Portuguese', 4, true], ['Alice lives in Lisbon', 3, true],
+ ['Alice ran a marathon', null, false], ['Alice plays chess', 2, true]]);
+ expect(await generations(engine, sourceId)).toEqual([[1, 'live', 1]]);
+ await runExtractFacts(engine, { sourceId });
+ expect((await facts(engine, sourceId)).filter(row => row[2]).length).toBe(4);
+ });
+ }, 120_000);
+ }
+});
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index ce81fc665a..bfdf58c17e 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -141,6 +141,7 @@
" [OK] generation_held: No derived generation is held.",
" [OK] generation_pending: No activated generation waits on a member request, and no orphan candidate exists.",
" [OK] extractor_facts_expired: No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection.",
+ " [OK] unwithdrawn_facts: No fact is left retired by a facts-fence generation that no fence withdrew.",
" [OK] conversation_label_facts: No conversation fact carries the pre-fix meeting-label signature (a 1970-01-01 segment on a label page).",
" [OK] conversation_outcomes_stale: No conversation extraction outcome predates extractor version 1.",
" [OK] captured_facts_active: No active fact from a gbrain self-capture or paste candidate remains. This counts facts in the database; the self_capture check counts corpus files.",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 06a512f7c2..b0feb1cd9a 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -1891,6 +1891,20 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#unwithdrawn-facts",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "unwithdrawn-facts"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No fact is left retired by a facts-fence generation that no fence withdrew.",
+ "name": "unwithdrawn_facts",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index e0a046b3bb..59e4a5c85e 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -2070,6 +2070,20 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#unwithdrawn-facts",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "unwithdrawn-facts"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No fact is left retired by a facts-fence generation that no fence withdrew.",
+ "name": "unwithdrawn_facts",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -7140,6 +7154,20 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#unwithdrawn-facts",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "unwithdrawn-facts"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No fact is left retired by a facts-fence generation that no fence withdrew.",
+ "name": "unwithdrawn_facts",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index d0987bb85f..82898cfc76 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -2075,6 +2075,20 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#unwithdrawn-facts",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "unwithdrawn-facts"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No fact is left retired by a facts-fence generation that no fence withdrew.",
+ "name": "unwithdrawn_facts",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -7146,6 +7160,20 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#unwithdrawn-facts",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "unwithdrawn-facts"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No fact is left retired by a facts-fence generation that no fence withdrew.",
+ "name": "unwithdrawn_facts",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 5f5b99f440..17851392f3 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -1768,6 +1768,20 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#unwithdrawn-facts",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "unwithdrawn-facts"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No fact is left retired by a facts-fence generation that no fence withdrew.",
+ "name": "unwithdrawn_facts",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 1148782d65..e51af67e77 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -1824,6 +1824,20 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#unwithdrawn-facts",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "unwithdrawn-facts"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No fact is left retired by a facts-fence generation that no fence withdrew.",
+ "name": "unwithdrawn_facts",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 8550797000..267bdb6968 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -1829,6 +1829,20 @@
"name": "extractor_facts_expired",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#unwithdrawn-facts",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "unwithdrawn-facts"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No fact is left retired by a facts-fence generation that no fence withdrew.",
+ "name": "unwithdrawn_facts",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index dbe187e7ad..118ed2f089 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -609,6 +609,10 @@
"category": "brain",
"name": "extractor_facts_expired"
},
+ {
+ "category": "brain",
+ "name": "unwithdrawn_facts"
+ },
{
"category": "brain",
"name": "conversation_label_facts"
diff --git a/test/repair-unwithdrawn-facts-8819.test.ts b/test/repair-unwithdrawn-facts-8819.test.ts
new file mode 100644
index 0000000000..405446a07c
--- /dev/null
+++ b/test/repair-unwithdrawn-facts-8819.test.ts
@@ -0,0 +1,120 @@
+/**
+ * `gbrain repair unwithdrawn-facts` (#8819), PGLite; Postgres when DATABASE_URL is set.
+ *
+ * Protects: facts a facts-fence generation retired although no fence of their page held them come back with their
+ * original ids and lifecycle, also when that generation was the page's first (no predecessor to restore); a row a
+ * stored version's fence held (a genuine withdrawal) is never restored; the apply restores exactly the previewed set,
+ * bound to the page revision the preview saw, so a page written since restores nothing; a managed brain and an
+ * unmanaged brain with a database-only page (no repository) both restore; doctor names the lane and clears after it.
+ * Seam: the pre-fix projection's retirement is reproduced by its effect, as it ran: a fact_fence generation recorded
+ * through publishFenceGeneration with each row's before-state, and the rows expired and detached in that transaction.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { pathologicalArms } from './pathological/harness.ts';
+import { FACTS_FENCE, managedSource, PERSON, type ManagedSource } from './pathological/managed-fixture.ts';
+import { resolveRepairScope, type RepairResult } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { publishFenceGeneration, readFenceBlocks, FACT_FENCE_KIND } from '../src/core/generations/fence.ts';
+import { factFenceItems, factPreimages, factRetireItem } from '../src/core/generations/adapters/fact-rows.ts';
+import { unwithdrawnFactsCheck } from '../src/commands/doctor/checks/unwithdrawn-facts.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+
+const SLUG = 'people/alice-example';
+const ROW = (n: number, claim: string) => `| ${n} | ${claim} | fact | 1.0 | private | medium | 2020-01-01 | | chat | |`;
+const FOUNDED = ROW(1, 'Alice founded acme-example');
+const quiet = { info: () => {}, warn: () => {}, error: () => {} };
+
+async function repair(engine: BrainEngine, sourceId: string, opts: { expect?: string; includeAmbiguous?: boolean } = {}): Promise<RepairResult & { listing?: Array<{ item: string; class: string }> }> {
+ const scope = await resolveRepairScope(engine, sourceId);
+ return (await repairRunner(engine, { apply: opts.expect !== undefined, noEmbed: true, logger: quiet })).run('unwithdrawn-facts', scope,
+ { explicit: true, sourceFlag: sourceId, ...opts }) as Promise<RepairResult & { listing?: Array<{ item: string; class: string }> }>;
+}
+const hashOf = (result: RepairResult) => result.apply_command.match(/--expect ([0-9a-f]+)/)![1]!;
+
+async function factRow(engine: BrainEngine, sourceId: string, rowNum: number, fact: string, source = 'mcp:put_page'): Promise<number> {
+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug)
+ VALUES ($1, $2, $3, 'fact', 'private', $4, $5, $2) RETURNING id`, [sourceId, SLUG, fact, source, rowNum]);
+ return Number(row!.id);
+}
+
+/** What the pre-fix projection did on a page's first fact generation: record it, retiring `ids` with their before-states, and expire them. */
+async function prefixRetire(engine: BrainEngine, sourceId: string, ids: number[]): Promise<void> {
+ await engine.transaction(async tx => {
+ const page = (await tx.readPageSnapshot(SLUG, { sourceId }))!.page;
+ await publishFenceGeneration(tx, { kind: FACT_FENCE_KIND, sourceId, slug: SLUG, read: readFenceBlocks(page, 'facts'),
+ items: factFenceItems([{ row_num: 1, fact: 'Alice founded acme-example', visibility: 'private' }]),
+ retire: (await factPreimages(tx, sourceId, ids)).map(factRetireItem), writer: 'projection' });
+ await tx.executeRaw('UPDATE facts SET expired_at=now(), row_num=NULL WHERE source_id=$1 AND id=ANY($2::bigint[])', [sourceId, ids]);
+ });
+}
+
+async function state(engine: BrainEngine, ids: number[]) {
+ return (await engine.executeRaw<{ id: number; row_num: number | null; active: boolean }>(
+ 'SELECT id, row_num, expired_at IS NULL AS active FROM facts WHERE id=ANY($1::bigint[]) ORDER BY id', [ids]))
+ .map(row => [Number(row.id), row.row_num === null ? null : Number(row.row_num), row.active]);
+}
+
+/** A page whose fence once held a marathon row (removed by an edit) and never held two put_page rows; all three retired by generation 1. */
+async function seed(s: ManagedSource): Promise<{ chess: number; lisbon: number; marathon: number }> {
+ await s.put(SLUG, PERSON('Alice Example', FACTS_FENCE([FOUNDED, ROW(5, 'Alice ran a marathon')].join('\n'))));
+ await s.put(SLUG, PERSON('Alice Example', FACTS_FENCE(FOUNDED)));
+ await s.engine.executeRaw("DELETE FROM derived_generations WHERE source_id=$1 AND kind='fact_fence'", [s.sourceId]);
+ await s.engine.executeRaw('DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [s.sourceId, SLUG]);
+ await factRow(s.engine, s.sourceId, 1, 'Alice founded acme-example', 'chat');
+ const ids = { chess: await factRow(s.engine, s.sourceId, 2, 'Alice plays chess'), lisbon: await factRow(s.engine, s.sourceId, 3, 'Alice lives in Lisbon'),
+ marathon: await factRow(s.engine, s.sourceId, 5, 'Alice ran a marathon', 'chat') };
+ await prefixRetire(s.engine, s.sourceId, Object.values(ids));
+ return ids;
+}
+
+describe('gbrain repair unwithdrawn-facts (#8819)', () => {
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test(`[${backend}] managed: restores first-generation retirements no fence withdrew, never a withdrawn one, bound to the previewed revision`, async () => {
+ let ids!: { chess: number; lisbon: number; marathon: number };
+ await managedSource(databaseUrl, async s => { ids = await seed(s); }, async ({ engine, sourceId, put }) => {
+ const all = [ids.chess, ids.lisbon, ids.marathon];
+ expect(await state(engine, all)).toEqual([[ids.chess, null, false], [ids.lisbon, null, false], [ids.marathon, null, false]]);
+ const check = await unwithdrawnFactsCheck(engine, [sourceId]);
+ expect([check.status, check.details]).toEqual(['warn', { evidenced: 2, ambiguous: 0, excluded: 1, repair: 'unwithdrawn-facts', docs: 'docs/guides/repair.md#unwithdrawn-facts' }]);
+
+ const stale = await repair(engine, sourceId);
+ await put(SLUG, PERSON('Alice Example', `An edit after the preview.\n\n${FACTS_FENCE(FOUNDED)}`));
+ const refused = await repair(engine, sourceId, { expect: hashOf(stale) });
+ expect(refused.applied).toBe(0);
+ expect(await state(engine, all)).toEqual([[ids.chess, null, false], [ids.lisbon, null, false], [ids.marathon, null, false]]);
+
+ const preview = await repair(engine, sourceId);
+ expect(preview.listing!.map(row => [row.item, row.class])).toEqual([[`${sourceId}:${SLUG}#${ids.chess}`, 'evidenced'],
+ [`${sourceId}:${SLUG}#${ids.lisbon}`, 'evidenced'], [`${sourceId}:${SLUG}#${ids.marathon}`, 'excluded:fence_held']]);
+ const applied = await repair(engine, sourceId, { expect: hashOf(preview) });
+ expect(applied.applied).toBe(1);
+ const [request] = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_maintenance_restore_unwithdrawn_facts' AND state='committed'", [sourceId]);
+ expect(request?.state).toBe('committed');
+ expect(await state(engine, all)).toEqual([[ids.chess, 2, true], [ids.lisbon, 3, true], [ids.marathon, null, false]]);
+ expect((await unwithdrawnFactsCheck(engine, [sourceId])).status).toBe('ok');
+
+ await put(SLUG, PERSON('Alice Example', `A later edit.\n\n${FACTS_FENCE(FOUNDED)}`));
+ expect(await state(engine, all)).toEqual([[ids.chess, 2, true], [ids.lisbon, 3, true], [ids.marathon, null, false]]);
+ });
+ }, 180_000);
+ }
+
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test(`[${backend}] unmanaged brain, database-only page: the same restore with no repository`, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const sourceId = 'default';
+ await engine.putPage(SLUG, { type: 'person', title: 'Alice Example', compiled_truth: FACTS_FENCE(FOUNDED) }, { sourceId });
+ await factRow(engine, sourceId, 1, 'Alice founded acme-example', 'chat');
+ const chess = await factRow(engine, sourceId, 2, 'Alice plays chess');
+ await prefixRetire(engine, sourceId, [chess]);
+ const preview = await repair(engine, sourceId);
+ expect(preview.listing!.map(row => row.class)).toEqual(['evidenced']);
+ expect((await repair(engine, sourceId, { expect: hashOf(preview) })).applied).toBe(1);
+ expect(await state(engine, [chess])).toEqual([[chess, 2, true]]);
+ } finally { await close(); }
+ }, 120_000);
+ }
+});