Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(key-files): keep core-utilities-2.md under its 60000-byte cap; the #7602 failed-writes fact-row rules move to the facts entry

garrytan0c1cea6b8093
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.md
index 7d6c24357a..65905c2306 100644
--- a/docs/architecture/key-files/core-persistence-facts.md
+++ b/docs/architecture/key-files/core-persistence-facts.md
@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
Managed facts extraction: the entity-intent preparer and publisher, conversation facts batches and the unmanaged derived index. The extraction pipeline itself is in [Google and Loops (continued)](google-and-loops-continued.md) (`src/core/facts/backstop.ts`) and [Core Services (2/3)](core-services-2.md) (`src/core/facts/extract.ts`).
- `src/core/facts/bulk-days.ts` — #7247 the one rule doctor `fact_bulk_dates` and `gbrain repair fact-claim-dates` share. `findBulkFactDays` (one read-only aggregate over active facts of active sources, optionally scoped) returns each UTC `valid_from` day holding at least `BULK_DAY_RULE` (200 facts, 25% of the source, 20 entities) with counts, top source tags and `dated_claims`. `claimDate` returns a claim's only `YYYY-MM-DD` token when it is a real date from 1900 to the day before; the aggregate's SQL applies the same token and bounds.
-- `src/core/persistence/{facts-maintenance,facts-prepare}.ts` — the managed facts publisher and preparer behind the backstop's `publishManagedFacts` / `resumeManagedFacts` and the explicit fact writers (`managed-fact-write.ts`, `remember`); the shared maintenance dispatch they ride is in [Core Persistence](core-persistence.md). Each `ManagedFactsSession` carries one `MaintenanceWriteWait` (`maintenance-wait.ts`) built from the caller's `FactsBackstopCtx.deadlineAtMs` (the facts-absorb job passes its deadline; other callers get the 30 s base) and its abort signal: `collectManagedFacts` waits that long for each accepted request through `awaitWrite`, a cancelled job stops waiting at once, and a request still nonterminal after the wait leaves as `write_pending` with its receipt (#6778, `test/facts-absorb-publish-wait-6778.test.ts`). GBRA-130 A-36: `collectManagedFacts` awaits every row before it throws. An entity request that ended on a code of its own page (`ENTITY_REFUSAL_CODES`: `revision_conflict`, `invalid_fence`, `page_body_segmented`, …; not a file-check or withdrawal refusal, which the follow-up walks own) is reported as `refused` (slug, code, request id) on `ManagedFactsResult` and the `extract_facts` result when the session sets `reportRefusals` and another entity of the batch committed (the backstop sets it; `managed-fact-write.ts` and `remember` do not and keep the refusal), and the completion receipt refused only as incomplete is not a failure of its own; any other terminal row, then a pending one, then a refusal with nothing committed beside it, throws as its receipt. Test: `test/pathological/a-36-facts-batch-partial-refusal.test.ts` (PGLite and Postgres). `facts-maintenance.ts` / `facts-prepare.ts` (#6506): an automatic extraction's entity intent carries `withdrawn: 'skip'` (set by the backstop's `publishManagedFacts` call, never by `managed-fact-write.ts` or `remember`), under which `prepareManagedFactsMutation` skips a candidate `isFactWithdrawn` matches (after `assertFactNotPurged`, which still refuses `purged_content`) and counts it as `withdrawn_skipped` on the entity outcome, summed into the completion outcome, `ManagedFactsResult` and the `extract_facts` result (the unmanaged pipeline counts its own B-10 skip into the same field); without the flag the refusal stands. At locked validation the per-entry purge and withdrawal checks run before the page's fence re-validation, and under the flag a claim forgotten since preparation refuses `revision_conflict` with `error.withdrawn` (so the receipt's `error_detail.origin` is `withdrawal`); no `extract_facts` request is re-prepared. `resumeManagedFacts` runs `followWithdrawalRefusals` for an input-keyed session (`inputKeyed`, no request id): the `followFileRefusals` walk generalized as `followRefusals`, matching entity refusals by `withdrawnFromDetail(error_detail)` or the pre-detail `invalid_params` + `FACT_WITHDRAWN_MESSAGE` pair, re-admitting the retained facts under `digest([batchKey, 'withdrawal-retry', n])` with the flag (`readmitWithdrawnFacts`: a fact forgotten at its retained visibility keeps that visibility so preparation skips it instead of narrowing it to private), bounded by `MAX_FILE_REFUSAL_RETRIES`, historical receipts untouched. Tests: `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts` (PGLite and Postgres). #7602: an automatic extraction with no caller request id (`entityMoveRetry`, set by the backstop; explicit writers keep the refusal) also runs `followEntityMoves`, after admission in `publishManagedFacts` and on resume: an entity request refused `revision_conflict` because another write moved its entity page (`FACTS_ENTITY_MOVED_MESSAGES` in `verb-errors.ts`: changed after admission, changed during preparation, deduplication state changed, the coordinator's `PAGE_CHANGED_DURING_PREPARATION_MESSAGE`, which `coordinator.ts` and `group-publish.ts` throw, and the page layer's `PAGE_CHANGED_AFTER_READ_MESSAGE`, how a move during preparation was stored before the fix; `isEntityMovedRefusal` is the one predicate the walk and the repair preview share) is re-admitted under `digest([batchKey, 'entity-moved-retry', n])` at the page's current revision with its retained intent (`readmitMovedFacts`; a deleted or replaced page keeps the refusal), no model call, each batch settled first so a follow-up that loses again is followed in the same run, bounded by `MAX_FILE_REFUSAL_RETRIES`; a follow-up refused for another reason (a held file) is not re-admitted, and the walk carries every request it did not follow. A follow-up's source-page check in `facts-prepare.ts` accepts a source page moved only by a committed request of the same extraction (same principal and input digest, at the page's current revision), such as a fact the batch wrote onto its own source page; any other change still refuses `The source page changed during fact extraction.` A refusal `collectManagedFacts` still throws after the walks is marked `retryable: false`, so the worker ends the facts-absorb job dead on its first attempt (`jobRefusal`; `revision_conflict` is not in `DETERMINISTIC_WRITE_REFUSALS`, so this is not the `facts_absorb_write_refused` path). Test: `test/facts-entity-moved-7602.test.ts` (PGLite and Postgres).
+- `src/core/persistence/{facts-maintenance,facts-prepare}.ts` — the managed facts publisher and preparer behind the backstop's `publishManagedFacts` / `resumeManagedFacts` and the explicit fact writers (`managed-fact-write.ts`, `remember`); the shared maintenance dispatch they ride is in [Core Persistence](core-persistence.md). Each `ManagedFactsSession` carries one `MaintenanceWriteWait` (`maintenance-wait.ts`) built from the caller's `FactsBackstopCtx.deadlineAtMs` (the facts-absorb job passes its deadline; other callers get the 30 s base) and its abort signal: `collectManagedFacts` waits that long for each accepted request through `awaitWrite`, a cancelled job stops waiting at once, and a request still nonterminal after the wait leaves as `write_pending` with its receipt (#6778, `test/facts-absorb-publish-wait-6778.test.ts`). GBRA-130 A-36: `collectManagedFacts` awaits every row before it throws. An entity request that ended on a code of its own page (`ENTITY_REFUSAL_CODES`: `revision_conflict`, `invalid_fence`, `page_body_segmented`, …; not a file-check or withdrawal refusal, which the follow-up walks own) is reported as `refused` (slug, code, request id) on `ManagedFactsResult` and the `extract_facts` result when the session sets `reportRefusals` and another entity of the batch committed (the backstop sets it; `managed-fact-write.ts` and `remember` do not and keep the refusal), and the completion receipt refused only as incomplete is not a failure of its own; any other terminal row, then a pending one, then a refusal with nothing committed beside it, throws as its receipt. Test: `test/pathological/a-36-facts-batch-partial-refusal.test.ts` (PGLite and Postgres). `facts-maintenance.ts` / `facts-prepare.ts` (#6506): an automatic extraction's entity intent carries `withdrawn: 'skip'` (set by the backstop's `publishManagedFacts` call, never by `managed-fact-write.ts` or `remember`), under which `prepareManagedFactsMutation` skips a candidate `isFactWithdrawn` matches (after `assertFactNotPurged`, which still refuses `purged_content`) and counts it as `withdrawn_skipped` on the entity outcome, summed into the completion outcome, `ManagedFactsResult` and the `extract_facts` result (the unmanaged pipeline counts its own B-10 skip into the same field); without the flag the refusal stands. At locked validation the per-entry purge and withdrawal checks run before the page's fence re-validation, and under the flag a claim forgotten since preparation refuses `revision_conflict` with `error.withdrawn` (so the receipt's `error_detail.origin` is `withdrawal`); no `extract_facts` request is re-prepared. `resumeManagedFacts` runs `followWithdrawalRefusals` for an input-keyed session (`inputKeyed`, no request id): the `followFileRefusals` walk generalized as `followRefusals`, matching entity refusals by `withdrawnFromDetail(error_detail)` or the pre-detail `invalid_params` + `FACT_WITHDRAWN_MESSAGE` pair, re-admitting the retained facts under `digest([batchKey, 'withdrawal-retry', n])` with the flag (`readmitWithdrawnFacts`: a fact forgotten at its retained visibility keeps that visibility so preparation skips it instead of narrowing it to private), bounded by `MAX_FILE_REFUSAL_RETRIES`, historical receipts untouched. Tests: `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts` (PGLite and Postgres). #7602: an automatic extraction with no caller request id (`entityMoveRetry`, set by the backstop; explicit writers keep the refusal) also runs `followEntityMoves`, after admission in `publishManagedFacts` and on resume: an entity request refused `revision_conflict` because another write moved its entity page (`FACTS_ENTITY_MOVED_MESSAGES` in `verb-errors.ts`: changed after admission, changed during preparation, deduplication state changed, the coordinator's `PAGE_CHANGED_DURING_PREPARATION_MESSAGE`, which `coordinator.ts` and `group-publish.ts` throw, and the page layer's `PAGE_CHANGED_AFTER_READ_MESSAGE`, how a move during preparation was stored before the fix; `isEntityMovedRefusal` is the one predicate the walk and the repair preview share) is re-admitted under `digest([batchKey, 'entity-moved-retry', n])` at the page's current revision with its retained intent (`readmitMovedFacts`; a deleted or replaced page keeps the refusal), no model call, each batch settled first so a follow-up that loses again is followed in the same run, bounded by `MAX_FILE_REFUSAL_RETRIES`; a follow-up refused for another reason (a held file) is not re-admitted, and the walk carries every request it did not follow. A follow-up's source-page check in `facts-prepare.ts` accepts a source page moved only by a committed request of the same extraction (same principal and input digest, at the page's current revision), such as a fact the batch wrote onto its own source page; any other change still refuses `The source page changed during fact extraction.` A refusal `collectManagedFacts` still throws after the walks is marked `retryable: false`, so the worker ends the facts-absorb job dead on its first attempt (`jobRefusal`; `revision_conflict` is not in `DETERMINISTIC_WRITE_REFUSALS`, so this is not the `facts_absorb_write_refused` path). Test: `test/facts-entity-moved-7602.test.ts` (PGLite and Postgres). `gbrain repair failed-writes` (`failed-writes.ts`, [Core Utilities (2/2)](core-utilities-2.md)) lists refused fact extractions. #7602: fact rows (moved-entity refusals included) use `factsRecovery`: `recover:` (retry-dead reset) only while the page write's facts-absorb job is dead and the entity page is the one admitted, `pending:` while that job runs, `not recoverable:` for a deleted page, and `re-extract:` otherwise (replaced page, completed or missing job, exhausted follow-ups, a page write the job's own `readFactsBackstopJobPage` check now skips (written again since, or a narrowed writer grant), an extraction whose open entity requests are not all moved-entity or all held-file refusals, a guard refusal). Only the preview reads fact rows (`failedWrites(..., { facts: true })`); the sync-time remember replay and apply-by-id keep the guard/drift query.
- `src/core/facts/same-page-shadow.ts` — #6333 the shadow counter both fact writers share. `samePageRewording(engine, sourceId, fact, embedding)` re-reads the entity's nearest live same-visibility candidate (`listSupersessionCandidates`, the pool and filters of `decideSingleFact`'s cosine pass) and answers whether `wouldDedupSamePage` (capture-dedup.ts: same lane, same `source_session`, same visibility, cosine ≥ 0.85, no diverging guard token) would have called the fact a rewording; `warnSamePageShadow` is the one stderr spelling (`[facts-backstop] #6333 shadow: …; both kept`). `facts-prepare.ts` calls it for every candidate `decideSingleFact` did not match and counts `would_dedup_same_page` on the entity outcome, the completion outcome, `ManagedFactsResult` and the `extract_facts` result; the count is frozen in the receipt, so a replay reports it and does not recount. Nothing is dropped; this is the managed mirror of the unmanaged backstop's counter (`backstop.ts`), which never fired on a managed brain. Tests: `test/backstop-same-page-shadow-managed-6333.test.ts` (PGLite and Postgres), `test/backstop-same-page-shadow-6333.test.ts` (unmanaged).
- `src/core/persistence/derived-facts.ts` — `writeDerivedFacts`: the unmanaged conversation fact index commits in one maintenance transaction under the maintenance principal; on a managed brain it refuses with `writer_coordinator_required`, because every managed facts/takes writer publishes a receipted maintenance request (`test/receipt-coverage.test.ts` lists every coordinated write site). Tests: `test/write-attribution-misc.test.ts`.
- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` batch requests (`submitDatabaseMaintenanceIntent` on `ANCHOR_SLUG`, a dot-led slug no page can hold, dispatched from `prepareMaintenanceMutation`). Each page's frozen entry (`buildConversationPage`: `FrozenExtractedFact` rows, its generation and attempt, vectors only under the brain's facts embedding signature) joins the run's batch; `enqueueManagedPage` publishes it once `DEFAULT_BATCH_CAPS` is reached (25 pages, 10 with extracted facts, 8 MiB) and `flushManagedBatch` at the end of the run. The generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, selectors, newest extractor row id) is checked before model work by `startManagedPage` against `loadGenerationIndex` (the writer's unsettled and failed batches on the anchor, read once per run): a member of an unsettled batch waits and replays its receipt, a member of a retryably failed batch is resubmitted from its stored entry, a deterministic failure of a batch that held it alone or three failed batches block it (GBRA-130 A-51: `publishBatch` re-publishes a multi-page batch that failed deterministically in halves, so only the page that fails alone takes the code; `test/pathological/a-51-conversation-batch-booking.test.ts`); all without model calls. The batch request id digests its members' (generation, attempt) pairs; `submitConversationPages` raises every member's attempt past an id another write holds, or whose receipt lost its intent without committing (#7516: a redacted `purged_content` refusal or a compacted failure takes the attempt history `loadGenerationIndex` reads, so the same id came back on every run as `idempotency_conflict` after a paid extraction; test `test/conversation-facts-redacted-batch-7516.test.ts`, + Postgres arm). The preparer locks every member's key and applies each on its own (`applyEntry`): a deleted, replaced or moved page is skipped and reported, a page whose rows fail validation gets a durable `blocked:` not-extractable outcome, vectors under another signature are dropped; none fails the batch. `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest entry cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the run's planned batches and before each new batch. `publishConversationFacts` (the managed apply and the unmanaged writer) passes fact rows through the write gate at the page's derived tier and retires the prior batch only for a complete replacement (#7013: `full` scope, at least one fact, nothing held or rejected) or on a page with no active extractor facts, through `replaceConversationFacts`, which deletes the page's extractor rows (expiring referenced and keeping label-retired ones) and inserts the rows numbered above every remaining row, failing on a lost insert. Otherwise the prior facts stay: the outcome row replaces the page's prior outcome rows (so the page is not paid for again), a `window` run (`--since` dropped messages) adds its facts beside them, and a `partial` run (a `--segment-limit` cut, a page changed mid-run) publishes no facts over them. Each entry carries its `scope`; an entry frozen without one is `partial` without its outcome, `window` with a `--since` selector, else `full`. Tests: `test/pathological/h4-conversation-facts-zero-yield.test.ts` (managed and unmanaged, + Postgres arm). Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index d0fb587d49..bf10249e2f 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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).
- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.
-- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id, and `file_database_drift` (W4.11) when its last replay attempt was refused `source_changed` and the page has not been written since (`lastFailedAttempt`; the detail and an apply's `file_database_drift` outcome name `gbrain sources reconcile <source> <slug> --preview`; `test/repair-failed-writes-drift-w411.test.ts`); owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). #7602: fact rows (moved-entity refusals included) use `factsRecovery`: `recover:` (retry-dead reset) only while the page write's facts-absorb job is dead and the entity page is the one admitted, `pending:` while that job runs, `not recoverable:` for a deleted page, and `re-extract:` otherwise (replaced page, completed or missing job, exhausted follow-ups, a page write the job's own `readFactsBackstopJobPage` check now skips (written again since, or a narrowed writer grant), an extraction whose open entity requests are not all moved-entity or all held-file refusals, a guard refusal). Only the preview reads fact rows (`failedWrites(..., { facts: true })`); the sync-time remember replay and apply-by-id keep the guard/drift query. The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969). The superseded / already-written / duplicate rule lives in `persistence/terminal-classify.ts`, shared with the #6650 terminal-failure readers.
+- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id, and `file_database_drift` (W4.11) when its last replay attempt was refused `source_changed` and the page has not been written since (`lastFailedAttempt`; the detail and an apply's `file_database_drift` outcome name `gbrain sources reconcile <source> <slug> --preview`; `test/repair-failed-writes-drift-w411.test.ts`); owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). #7602 fact rows: `factsRecovery` ([Facts](core-persistence-facts.md)). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969). The superseded / already-written / duplicate rule lives in `persistence/terminal-classify.ts`, shared with the #6650 terminal-failure readers.
- `src/core/repair/ontology-facts.ts` — `gbrain repair ontology-facts` (#6264), explicit-only and preview-bound (`--apply --expect <hash>`). `classifyOntologyFacts` (read-only; also doctor `ontology_facts_fenced`) takes ontology rows (`dimension IS NOT NULL`) carrying the pre-fix fence step's signature, a `row_num` or a `source_markdown_slug` that differs from `source` (`mergeOntologyFact` writes them equal and never sets `row_num`), and classes each `fenced` or `retired`, or excluded as `withdrawn` (`fact_withdrawals`), `consolidated` or `duplicate` (restoring would collide with the ontology dedup key). The apply sets `row_num` NULL, `source_markdown_slug = source` and `expired_at` NULL in one statement that rechecks row number, page, expiry and the dedup key (`changed_since_preview` otherwise), through `coordinatedDatabaseWrite('ontology_propose')` on the entity and page keys on a managed brain or one maintenance transaction otherwise; the withdrawal trigger re-expires a claim forgotten after the preview (`withdrawn`). Page text is never rewritten. Tests: `test/ontology-fence-sweep.test.ts`.
- `src/core/repair/timeline-comments.ts` — `gbrain repair timeline-comments` (#6184), explicit-only. The plan lists pages with timeline rows whose source, summary or detail carries `<!--`/`-->` or whose body has a materialized bullet carrying markup (`dropCommentBullets`), with residuals `comment_only_rows`, `comment_bearing_rows`, `pages_with_comment_bullets`. Apply: one revision-bound `put_page` per page dropping those generated bullets (user-written bullets are left), then one transaction under the page lock (`withCoordinatedWrite` with maintenance attribution on managed brains) that deletes comment-only rows and rewrites the rest to their stripped tuple, or deletes them when the page already has it. Idempotent. `timeline.ts` warns `timeline_comment_markup` naming this kind while such rows exist. Rows on a segmented page are not planned (the apply rewrites a whole body): residuals `segmented_pages` / `segmented_rows` and a warning naming them.
- `src/core/repair/aliases.ts` — `gbrain repair aliases` (#6619), explicit-only, projection publication, wired to doctor `dangling_aliases`. One item per (source, target slug) whose alias rows (`page_aliases.slug`, `slug_aliases.canonical_slug`) point at a slug with no page row at all; apply rechecks that under the page key lock and deletes both tables' rows for it, inside `withCoordinatedWrite` on a managed brain (both tables carry the managed writer guard). Aliases of soft-deleted pages are the `soft_deleted_target` residual; rename redirects (`alias_slug` = the missing slug) are never touched. Exports `ORPHANED_ALIAS_COUNTS_SQL` / `SOFT_DELETED_ALIAS_COUNT_SQL`, which `checkDanglingAliases` (`src/core/onboard/checks.ts`) reports apart, naming `repairPreviewCommand('aliases', {source})` per source instead of raw SQL. Test: `test/purge-aliases-6619.test.ts`.