Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): second-pass review fixes for #7602 (dead-job, replaced-page and held-follow-up listings; shared coordinator message)
garrytan049fdee3dbcd
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.mdindex e99a621f2e..e52c8d1abf 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 CHANGELManaged 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) 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 refusal `collectManagedFacts` still throws after the walks is marked `retryable: false`, and the facts-absorb handler dead-letters such a journaled refusal on its first attempt. 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, and the coordinator's `PAGE_CHANGED_DURING_PREPARATION_MESSAGE`, which `coordinator.ts` and `group-publish.ts` throw) 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 refusal `collectManagedFacts` still throws after the walks is marked `retryable: false`, and the facts-absorb handler dead-letters such a journaled refusal on its first attempt. Test: `test/facts-entity-moved-7602.test.ts` (PGLite and Postgres).- `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.mdindex 94fa85b74d..849020985b 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`. 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 (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 follow-up refused for a held file, a guard refusal). 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`.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex a4386aa5ce..41ced1aa4e 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2181,7 +2181,7 @@ candidate one class:| `superseded` | A later write or delete of the page committed or is pending; for `put_page`, also a later failed `put_page` (newer content) or a page changed since the caller read it. | Kept; re-issue by hand if still wanted. || `unpinned_target` | A `remember` saved unattributed; replaying would infer its subject again and could pick another page. | Kept. Re-issue it with an explicit `entity` if it is still wanted. || `file_database_drift` | Its last replay hit `source_changed` and the file still differs from the database. | Kept until the file matches again (a reconcile that writes only the file counts) or the page changes; reconcile it first. |-| `producer_owned` | gbrain produced it (sync or file import, reconcile, relink, maintenance page, job). | Kept. The preview prints the command that produces it again from current content (sync: `gbrain sync --source <id> --no-pull`). A refused fact extraction (`extract_facts`, including one refused `revision_conflict` because another write moved its entity page) keeps its extracted facts: when its page write's facts-absorb job can recover them, the row says `recover: gbrain facts retry-dead --reset 'facts-absorb:write:<id>'` (the retried job re-admits the retained facts at the page's current revision without a model call); otherwise it says `re-extract:` with the `extract_facts` call to make (one model call), or `not recoverable:` when the entity page was deleted. A fact request a later request of the same extraction committed is not listed. |+| `producer_owned` | gbrain produced it (sync or file import, reconcile, relink, maintenance page, job). | Kept. The preview prints the command that produces it again from current content (sync: `gbrain sync --source <id> --no-pull`). A refused fact extraction (`extract_facts`, including one refused `revision_conflict` because another write moved its entity page) keeps its extracted facts: when its page write's facts-absorb job is dead and can recover them, the row says `recover: gbrain facts retry-dead --reset 'facts-absorb:write:<id>'` (the retried job re-admits the retained facts at the page's current revision without a model call); while that job still runs it says `pending:`; otherwise (the job completed or is gone, the entity page was replaced, or a follow-up was refused for a held file) it says `re-extract:` with the `extract_facts` call to make (one model call), or `not recoverable:` when the entity page was deleted. A fact request a later request of the same extraction committed is not listed. |The apply replays exactly the previewed set. Each write is classified againand its original caller's authority is checked again first: a write thatdiff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 76e4b1592e..491e74305e 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -754,7 +754,7 @@ async function runPipelineBodyInner(const derivation = await factsDerivation(ctx, input);const managed = await prepareManagedFactsSession(ctx, input, derivation);if (managed) {- Object.assign(managed, { reportRefusals: true, entityMoveRetry: !ctx.requestId });+ managed.reportRefusals = true; managed.entityMoveRetry = !ctx.requestId;const replay = await resumeManagedFacts(ctx.engine, managed);if (replay) return replay;const embedding = await resolveManagedFactsEmbedding(ctx.engine, managed.config);diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 1059475c27..77d851d916 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -38,6 +38,7 @@ import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFilimport { assertManagedFilesystemWrite } from './filesystem-guard.ts';import { beforeStagePath, fileContentBytes, fileContentHash, hashDescriptor, hashFile, isStreamedContent, LARGE_FILE_MIN_BYTES, stageBeforeCopy, stageStreamedContent, type StreamedFileContent } from './large-file.ts';import { declarePublication, publicationTransaction } from './publication-deadline.ts';+import { PAGE_CHANGED_DURING_PREPARATION_MESSAGE } from './verb-errors.ts';import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, isPersistenceDeclaration, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';@@ -536,7 +537,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr// uncoordinated edit.const current = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });if ((current?.revision ?? null) !== prepared.observedRevision) {- throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');+ throw new OperationError('revision_conflict', PAGE_CHANGED_DURING_PREPARATION_MESSAGE, 'Read its current revision and submit the updated intent with a new request_id.');}throw localEditRefusal('The canonical file changed after preparation.', row, skill, 'after the write was prepared, at an unchanged page revision');}@@ -575,7 +576,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prawait authorizePageVisibility(tx, row.authority, row.slug);if ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted page was deleted or recreated.');await assertUnboundPublication(tx, row, snapshot?.page.source_path);- if ((snapshot?.revision ?? null) !== prepared.observedRevision) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');+ if ((snapshot?.revision ?? null) !== prepared.observedRevision) throw new OperationError('revision_conflict', PAGE_CHANGED_DURING_PREPARATION_MESSAGE, 'Read its current revision and submit the updated intent with a new request_id.');}await prepared.validate?.(tx);// #5409: a file target prepared before the source became a read-only mirror is never published.diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.tsindex a6ad68be3d..e2becfcc7b 100644--- a/src/core/persistence/facts-maintenance.ts+++ b/src/core/persistence/facts-maintenance.ts@@ -371,9 +371,13 @@ async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSes}for (const row of [failed, pending]) if (row) writeResponse(row);// #7602: the refusal stands after every follow-up walk, so a retry replays the same stored receipt.- if (refused.length && !(session.reportRefusals && committed)) try { writeResponse(refused[0]); } catch (error) {- if (error instanceof OperationError) error.retryable = false;- throw error;+ if (refused.length && !(session.reportRefusals && committed)) {+ try {+ writeResponse(refused[0]);+ } catch (error) {+ if (error instanceof OperationError) error.retryable = false;+ throw error;+ }}if (refused.length) result.refused = refused.map(row => ({ slug: row.slug, code: row.error_code!, request_id: row.request_id }));return result;@@ -447,7 +451,7 @@ async function followEntityMoves(engine: BrainEngine, session: ManagedFactsSessi: session.wait.observe((await awaitWrite(engine, row, session.config, { waitMs: session.wait.ms(), signal: session.signal })).row));return settled;};- return followRefusals(engine, session, await settle(rows), 'entity-moved-retry', entityMovedRefusal, readmitMovedFacts, { settle, partial: true });+ return followRefusals(engine, session, await settle(rows), 'entity-moved-retry', entityMovedRefusal, readmitMovedFacts, settle);}function entityMovedRefusal(row: WriteRequest): boolean {@@ -462,14 +466,15 @@ function withdrawalRefusal(row: WriteRequest): boolean {* While every request of the latest batch is terminal and each uncommitted* entity request is a `refused` refusal that kept its facts for this input,* look for the next follow-up batch (`digest([batchKey, label, n])`), or admit- * it through `readmit`, at most MAX_FILE_REFUSAL_RETRIES times. With `partial`,- * only the matching refusals are followed; every other entity request of the- * batch, and a matching one `readmit` left out, is carried as it stands.+ * it through `readmit`, at most MAX_FILE_REFUSAL_RETRIES times. With `settle`+ * (partial mode), only the matching refusals are followed, each admitted batch+ * is settled before the next look, and every other entity request of the batch,+ * and a matching one `readmit` left out, is carried as it stands.*/async function followRefusals(engine: BrainEngine, session: ManagedFactsSession, stored: WriteRequest[], label: string,refused: (row: WriteRequest) => boolean,readmit: (engine: BrainEngine, followUp: ManagedFactsSession, refused: WriteRequest[]) => Promise<WriteRequest[] | null>,- options: { settle?: (batch: WriteRequest[]) => Promise<WriteRequest[]>; partial?: boolean } = {}): Promise<WriteRequest[]> {+ settle?: (batch: WriteRequest[]) => Promise<WriteRequest[]>): Promise<WriteRequest[]> {const carried: WriteRequest[] = [];let latest = stored;for (let retry = 1; retry <= MAX_FILE_REFUSAL_RETRIES; retry++) {@@ -478,15 +483,16 @@ async function followRefusals(engine: BrainEngine, session: ManagedFactsSession,const followed = uncommitted.filter(row => refused(row) && (row.intent as ManagedFactIntent | null)?.facts?.length&& (row.intent as ManagedFactIntent).inputDigest === session.inputDigest);const retained = followed.map(row => row.intent as ManagedFactIntent);- if (!followed.length || !options.partial && followed.length !== uncommitted.length+ if (!followed.length || !settle && followed.length !== uncommitted.length|| retained.some(intent => !sameSignature(intent.embedding, retained[0]!.embedding))) break;const followUpKey = digest([session.batchKey, label, retry]);const followUp: ManagedFactsSession = { ...session, batchKey: followUpKey, embedding: retained[0]!.embedding ?? null,completionRequestId: managedFactRequestId(followUpKey, '__managed_facts_complete__') };const admitted = await storedBatch(engine, followUp) ?? await readmit(engine, followUp, followed);if (!admitted) break;- carried.push(...latest.filter(row => isEntityRequest(row) && (row.state === 'committed' || !admitted.some(next => next.slug === row.slug))));- latest = options.settle ? await options.settle(admitted) : admitted;+ carried.push(...latest.filter(row => isEntityRequest(row)+ && (row.state === 'committed' || !followed.includes(row) || !admitted.some(next => next.slug === row.slug))));+ latest = settle ? await settle(admitted) : admitted;}return [...carried, ...latest];}diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex 181d96a100..cd15737174 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -81,6 +81,7 @@ import { importGroupReads, type ImportGroupReads } from './import-reads.ts';import { withScreeningPaths } from './screening-paths.ts';import { publicationBeliefOptions, withBeliefBatch } from '../belief/ledger.ts';import { markBeliefCommits } from '../belief/append.ts';+import { PAGE_CHANGED_DURING_PREPARATION_MESSAGE } from './verb-errors.ts';/** A `put_pages` or managed import group publishes at most this many pages per transaction, so one commit stays a few seconds long. */export const PAGE_BATCH_GROUP_MAX = 8;@@ -377,7 +378,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prawait authorizePageVisibility(tx, row.authority, row.slug);if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page was deleted or recreated.', 'Read the page again and submit a new intent with a new request_id.');await assertUnboundPublication(tx, row, snapshot?.page.source_path);- if ((snapshot?.revision ?? null) !== member.observedRevision) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');+ if ((snapshot?.revision ?? null) !== member.observedRevision) throw new OperationError('revision_conflict', PAGE_CHANGED_DURING_PREPARATION_MESSAGE, 'Read its current revision and submit the updated intent with a new request_id.');return snapshot;},async () => { if (sync) await member.validate?.(tx); },diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.tsindex fe57122dfe..b300f40076 100644--- a/src/core/repair/failed-writes.ts+++ b/src/core/repair/failed-writes.ts@@ -56,6 +56,7 @@ import { prepareFileTarget } from '../persistence/page-prepare.ts';import { PENDING_IMPORT, SYNC_HELD } from '../persistence/pending-import.ts';import { FACTS_ENTITY_MOVED_MESSAGES } from '../persistence/verb-errors.ts';import { MAX_FILE_REFUSAL_RETRIES } from '../persistence/facts-maintenance.ts';+import { factsRetryDeadCommand } from '../facts/dead-absorb-retry.ts';import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';import { resolveEntitySlugWithSource } from '../entities/resolve.ts';import { dispositionOf, PAGE_REMOVAL_OPERATIONS, supersessionOrderSql, supersessionSql } from '../persistence/terminal-classify.ts';@@ -73,14 +74,14 @@ const DRIFT_REFUSAL = `(r.state='conflict' AND r.error_code='source_changed')`;const FACTS_MOVED_REFUSAL = `(r.operation='extract_facts' AND r.state='conflict' AND r.error_code='revision_conflict'AND r.error_message IN (${FACTS_ENTITY_MOVED_MESSAGES.map(message => `'${message.replaceAll("'", "''")}'`).join(',')}))`;/** #7602: a refused fact request whose retained facts a later request of the same extraction committed on the same page. */-const FACTS_RECOVERED = `(r.operation='extract_facts' AND EXISTS (SELECT 1 FROM persistence_requests c WHERE c.operation='extract_facts'+const FACTS_RECOVERED = `EXISTS (SELECT 1 FROM persistence_requests c WHERE r.operation='extract_facts' AND c.operation='extract_facts'AND c.source_id=r.source_id AND c.slug=r.slug AND c.state='committed' AND c.sequence>r.sequenceAND COALESCE(c.intent->>'inputDigest', c.outcome->>'input_digest')=r.intent->>'inputDigest'- AND COALESCE(c.intent->>'batchKey', c.outcome->>'batch_key') IS DISTINCT FROM r.intent->>'batchKey'))`;+ AND COALESCE(c.intent->>'batchKey', c.outcome->>'batch_key') IS DISTINCT FROM r.intent->>'batchKey')`;interface FailedWrite {id: string; request_id: string; sequence: string; operation: string; source_id: string; slug: string; digest: string; state: string;- intent: Record<string, unknown>; authority: WriteAuthority; created_at: string; producer: string | null; error_code: string | null;+ intent: Record<string, unknown>; authority: WriteAuthority; created_at: string; producer: string | null; error_code: string | null; page_id: string | null;/** #6693: the refusal's recorded origin (`pending_import`, `sync_held`), when the receipt carries one. */origin?: string | null;}@@ -95,22 +96,33 @@ function previewCommand(scope: RepairScope): string {/*** #7602: a refused fact request keeps its extracted facts. A page-triggered one (its job is keyed by the page write) is- * recovered by retrying that job, which re-admits them at the entity page's current revision with no model call, once- * the cause clears. A batch whose follow-ups were refused too would replay the refusal, and a writer-guard refusal or- * a batch with no page write is never re-admitted: those are extracted again.+ * recovered by resetting that job once it is dead: its retry re-admits them at the entity page's current revision with+ * no model call, once the cause clears. A batch whose follow-ups were refused too, an entity page replaced since, a job+ * that completed or is gone, a writer-guard refusal and a batch with no page write would replay the refusal or have no+ * job to retry: those are extracted again.*/async function factsRecovery(engine: BrainEngine, write: FailedWrite, rows: FailedWrite[]): Promise<string> {const origin = (write.intent.origin as { slug?: string } | null | undefined)?.slug;const job = typeof write.intent.originalRequestId === 'string' ? write.intent.originalRequestId : null;const extractAgain = `re-extract: gbrain call extract_facts again on the current text of ${origin ?? 'the source turn'} with a new request_id (one model call)`;if (!job || write.state !== 'conflict') return extractAgain;+ const chain = rows.filter(row => row.operation === 'extract_facts' && row.source_id === write.source_id && row.slug === write.slug+ && row.intent.inputDigest === write.intent.inputDigest);+ if (chain.some(row => row.error_code === 'source_changed' && chain.some(prior => prior.error_code === 'revision_conflict' && Number(prior.sequence) < Number(row.sequence)))) {+ return `${extractAgain}; a follow-up of its moved-entity refusal was refused for a held file, which a job retry does not re-admit`;+ }if (write.error_code === 'revision_conflict') {- if (await pageRevision(engine, write.source_id, write.slug) === null) return `not recoverable: entity page ${write.slug} was deleted after these facts were admitted`;- const batches = new Set(rows.filter(row => row.operation === 'extract_facts' && row.error_code === 'revision_conflict' && row.source_id === write.source_id- && row.slug === write.slug && row.intent.inputDigest === write.intent.inputDigest).map(row => row.intent.batchKey));+ const [page] = await engine.executeRaw<{ id: string }>('SELECT id::text FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [write.source_id, write.slug]);+ if (!page && write.page_id !== null) return `not recoverable: entity page ${write.slug} was deleted after these facts were admitted`;+ if ((page?.id ?? null) !== write.page_id) return `${extractAgain}; entity page ${write.slug} was replaced after these facts were admitted, so a job retry replays the refusal`;+ const batches = new Set(chain.filter(row => row.error_code === 'revision_conflict').map(row => row.intent.batchKey));if (batches.size > MAX_FILE_REFUSAL_RETRIES) return `${extractAgain}; its follow-up batches were refused as well, so a job retry replays the refusal`;}- return `recover: gbrain facts retry-dead --reset 'facts-absorb:write:${job}' (the next facts_drain pass retries the page's facts-absorb job, which re-admits the retained facts without a model call${write.error_code === 'source_changed' ? ' once the file check passes' : ''})`;+ const key = `facts-absorb:write:${job}`;+ const [run] = await engine.executeRaw<{ status: string }>("SELECT status FROM minion_jobs WHERE name='facts-absorb' AND idempotency_key=$1 ORDER BY id DESC LIMIT 1", [key]);+ if (run && run.status !== 'dead' && run.status !== 'completed' && run.status !== 'cancelled') return `pending: its facts-absorb job (${key}) is ${run.status}; preview again once it ends`;+ if (run?.status !== 'dead') return `${extractAgain}; its facts-absorb job ${run ? `is ${run.status}` : 'is gone'}, so gbrain facts retry-dead has no dead job to reset`;+ return `recover: ${factsRetryDeadCommand('--reset', key)} (the next facts_drain pass retries the page's facts-absorb job, which re-admits the retained facts without a model call${write.error_code === 'source_changed' ? ' once the file check passes' : ''})`;}/** The command that produces an owner-internal write again, from current content. */@@ -129,7 +141,7 @@ function producerCommand(producer: string, sourceId: string): string {async function failedWrites(engine: BrainEngine, sourceIds: string[], id?: string): Promise<FailedWrite[]> {const rows = await engine.executeRaw<FailedWrite>(`SELECT r.id::text, r.request_id::text, r.sequence::text, r.operation, r.source_id, r.slug, r.digest, r.state, r.intent, r.authority,- to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS created_at, r.error_detail->>'origin' AS origin, r.error_code,+ to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS created_at, r.error_detail->>'origin' AS origin, r.error_code, r.page_id::text AS page_id,CASE WHEN r.operation = ANY($2::text[]) AND NOT (r.operation='put_page' AND r.intent ? 'kind') THEN NULLELSE r.operation || COALESCE(':' || (r.intent->>'kind'), '') END AS producerFROM persistence_requests rdiff --git a/test/facts-absorb-stalled-receipt-7439.test.ts b/test/facts-absorb-stalled-receipt-7439.test.tsindex c23e782ff9..beb6c37499 100644--- a/test/facts-absorb-stalled-receipt-7439.test.ts+++ b/test/facts-absorb-stalled-receipt-7439.test.ts@@ -14,6 +14,7 @@ import { readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import type { FactsBackstopCtx } from '../src/core/facts/backstop.ts';import { RECOVERY_VERSION } from '../src/core/markdown.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';import { prepareManagedFactsSession, publishManagedFacts, resumeManagedFacts } from '../src/core/persistence/facts-maintenance.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';@@ -76,7 +77,11 @@ for (const backend of testBackends()) {expect(await factRows(engine)).toEqual([]);// Value: protects=repair failed-writes lists a held-file fact refusal with the job retry that recovers it, then drops it once a// follow-up committed; fails_when=the listing names extract --stale, loses the file-check note, or keeps a recovered request;- // why_new=#7602 covers revision_conflict listings only; seam=none; no_claim=does not run the job retry itself+ // why_new=#7602 covers revision_conflict listings only; seam=the job died is set by SQL (the reset needs a dead job); no_claim=does+ // not run the job retry itself+ const key = `facts-absorb:write:${write}`;+ const job = await new MinionQueue(engine).add('facts-absorb', { slug: ORIGIN, sourceId: 'default', persistence_request_id: write }, { queue: 'default', idempotency_key: key });+ await engine.executeRaw("UPDATE minion_jobs SET status='dead' WHERE id=$1", [job.id]);const [listed, ...others] = await factsListing(engine);expect(others).toEqual([]);expect(listed!.class).toBe('producer_owned');diff --git a/test/facts-entity-moved-7602.test.ts b/test/facts-entity-moved-7602.test.tsindex ddd412004b..2d7a407f8b 100644--- a/test/facts-entity-moved-7602.test.ts+++ b/test/facts-entity-moved-7602.test.ts@@ -17,9 +17,12 @@*/import { afterEach, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';import { configureGateway, resetGateway, __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';import { FENCE_FACTS_INTENT } from '../src/core/cycle/extract-facts.ts';import type { FactsBackstopCtx } from '../src/core/facts/backstop.ts';+import { RECOVERY_VERSION } from '../src/core/markdown.ts';import { FACTS_DEFAULT_VISIBILITY_KEY } from '../src/core/facts/visibility.ts';import { makeFactsAbsorbHandler } from '../src/core/minions/handlers/facts-absorb.ts';import { jobRefusal } from '../src/core/minions/refusal.ts';@@ -28,6 +31,7 @@ import { prepareManagedFactsSession, publishManagedFacts, resumeManagedFacts } fimport { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../src/core/persistence/prepared-maintenance.ts';import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { writeGitHold } from '../src/core/persistence/sync-holds.ts';import { resolveRepairScope } from '../src/core/repair/core.ts';import { repairRunner } from '../src/core/repair/registry.ts';import type { ManagedBrain } from './helpers/managed-brain.ts';@@ -154,6 +158,23 @@ for (const backend of testBackends()) {expect(await factsListing(engine)).toEqual([]);}, { databaseUrl }), 120_000);+ // Value: protects=the third follow-up still runs and publishes when the page stops moving after three reads; fails_when=the walk+ // stops before MAX_FILE_REFUSAL_RETRIES follow-ups; why_new=the row below covers only the side where every follow-up loses;+ // seam=none; no_claim=the moves are direct publications from a read hook, not concurrent facts-absorb jobs+ test(`#7602 [${backend}]: a page that moves for the first three reads publishes on the third follow-up`, () => managedBrain(async brain => {+ const { engine } = brain;+ const { move, loser } = await setup(brain, 3);+ const race = raceEntityReads(engine, 3, move);+ const first = await publishManagedFacts(engine, await loser.session(), loser.backstop, [fact(CLAIM_B)], 'private', loser.slug).finally(race.restore);+ expect(race.moves()).toBe(3);+ expect(first.inserted).toBe(1);+ expect(first.refused).toBeUndefined();+ expect((await entityRequests(engine)).map(row => [row.state, row.error_code])).toEqual([+ ['conflict', 'revision_conflict'], ['conflict', 'revision_conflict'], ['conflict', 'revision_conflict'], ['committed', null]]);+ expect(await claimB(engine)).toEqual([{ fact: CLAIM_B, source_markdown_slug: TARGET }]);+ expect(await factsListing(engine)).toEqual([]);+ }, { databaseUrl }), 120_000);+test(`#7602 [${backend}]: a page that moves before every follow-up is followed three times, then the refusal stands and is not retryable`, () => managedBrain(async brain => {const { engine } = brain;const { move, loser } = await setup(brain, 4);@@ -178,7 +199,11 @@ for (const backend of testBackends()) {}}, { databaseUrl }), 120_000);- test(`#7602 [${backend}]: a refusal stored before the fix is listed with the job retry that recovers its facts, and the retry's replay publishes them`, () => managedBrain(async brain => {+ // Value: protects=repair failed-writes offers the job reset only for a dead facts-absorb job, and the reset's replay publishes the+ // retained facts; fails_when=a waiting or completed job is listed with retry-dead (a command that finds no dead job), or the replay+ // does not publish; why_new=the rows above never list a recoverable refusal; seam=the job's status is set by SQL; no_claim=does not+ // run the worker or facts_drain+ test(`#7602 [${backend}]: a refusal stored before the fix is listed with the job retry once its job is dead, and the retry's replay publishes them`, () => managedBrain(async brain => {const { engine } = brain;const { move, loser } = await setup(brain, 1);const before = await loser.session();@@ -186,10 +211,16 @@ for (const backend of testBackends()) {const race = raceEntityReads(engine, 1, move);const refused = await publishManagedFacts(engine, before, loser.backstop, [fact(CLAIM_B)], 'private', loser.slug).catch(error => error).finally(race.restore);expect(refused.code).toBe('revision_conflict');+ const key = `facts-absorb:write:${loser.write}`;+ const jobStatus = (status: string) => engine.executeRaw("UPDATE minion_jobs SET status=$2 WHERE name='facts-absorb' AND idempotency_key=$1 RETURNING id", [key, status]);+ expect((await factsListing(engine)).map(entry => entry.detail)).toEqual([`pending: its facts-absorb job (${key}) is waiting; preview again once it ends`]);+ expect(await jobStatus('completed')).toHaveLength(1);+ expect((await factsListing(engine)).map(entry => entry.detail)).toEqual([`re-extract: gbrain call extract_facts again on the current text of ${loser.slug} with a new request_id (one model call); its facts-absorb job is completed, so gbrain facts retry-dead has no dead job to reset`]);+ expect(await jobStatus('dead')).toHaveLength(1);const [entry, ...others] = await factsListing(engine);expect(others).toEqual([]);expect(entry!.class).toBe('producer_owned');- expect(entry!.detail).toStartWith(`recover: gbrain facts retry-dead --reset 'facts-absorb:write:${loser.write}'`);+ expect(entry!.detail).toStartWith(`recover: gbrain facts retry-dead --reset '${key}'`);const retried = await resumeManagedFacts(engine, await loser.session());expect(retried?.inserted).toBe(1);expect(await claimB(engine)).toEqual([{ fact: CLAIM_B, source_markdown_slug: TARGET }]);@@ -266,6 +297,52 @@ for (const backend of testBackends()) {}, { databaseUrl }), 120_000);}+ // Value: protects=an entity page replaced at its slug (a new page id) after admission is not re-targeted, and repair lists the+ // refusal for re-extraction, not the job retry that would replay it; fails_when=the replacement page gets the retained facts or the+ // listing offers retry-dead; why_new=the deleted-page row leaves no page at the slug; seam=none; no_claim=the replacement is a+ // direct purge and put in the race+ test(`#7602 [${backend}]: an entity page replaced after admission is not re-targeted and is listed for re-extraction`, () => managedBrain(async brain => {+ const { engine, ctx } = brain;+ const { loser } = await setup(brain, 0);+ const race = raceEntityReads(engine, 1, async () => {+ const snapshot = (await engine.readPageSnapshot(TARGET, { sourceId: 'default' }))!;+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: TARGET, expected_revision: snapshot.revision, purge: true, request_id: randomUUID() } });+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: TARGET, request_id: randomUUID(),+ content: '---\ntype: person\ntitle: Example\n---\nA different synthetic person page created at the same slug after the purge.\n' } });+ expect((await engine.readPageSnapshot(TARGET, { sourceId: 'default' }))!.page.id).not.toBe(snapshot.page.id);+ });+ const refused = await publishManagedFacts(engine, await loser.session(), loser.backstop, [fact(CLAIM_B)], 'private', loser.slug).catch(error => error).finally(race.restore);+ expect(race.moves()).toBe(1);+ expect([refused.code, refused.retryable]).toEqual(['revision_conflict', false]);+ expect((await entityRequests(engine)).map(row => row.state)).toEqual(['conflict']);+ expect(await claimB(engine)).toEqual([]);+ expect((await factsListing(engine)).map(entry => entry.detail)).toEqual([`re-extract: gbrain call extract_facts again on the current text of ${loser.slug} with a new request_id (one model call); entity page ${TARGET} was replaced after these facts were admitted, so a job retry replays the refusal`]);+ }, { databaseUrl }), 120_000);++ // Value: protects=when the entity's file is held between the move and the follow-up, repair lists the whole chain for+ // re-extraction instead of the job retry, which would replay the follow-up's file refusal; fails_when=either request is listed+ // with retry-dead; why_new=#7439 covers a held file on the original batch only; seam=the hold is written directly, as #7439 does;+ // no_claim=the follow-up is not re-admitted after the hold clears (a known limit: re-extraction recovers it)+ test(`#7602 [${backend}]: a moved entity whose file is held before the follow-up publishes is listed for re-extraction`, () => managedBrain(async brain => {+ const { engine, root } = brain;+ const { move, loser } = await setup(brain, 1);+ const race = raceEntityReads(engine, 2, async n => {+ if (n === 0) return move(0);+ const snapshot = (await engine.readPageSnapshot(TARGET, { sourceId: 'default' }))!;+ const path = `${TARGET}.md`, file = join(root, path);+ writeFileSync(file, readFileSync(file, 'utf8') + '\nAn unimported edit.\n');+ await engine.transaction(tx => writeGitHold(tx, { source_id: 'default', incarnation: snapshot.sourceIncarnation,+ path, source_path: path, slug: TARGET, page_id: null, code: 'preparation_stalled', message: 'The write owner stalled.',+ upstream_version: null, observed_at: new Date().toISOString(), run_id: null, mode: 'managed', meta: { recovery_version: RECOVERY_VERSION } }));+ });+ const refused = await publishManagedFacts(engine, await loser.session(), loser.backstop, [fact(CLAIM_B)], 'private', loser.slug).catch(error => error).finally(race.restore);+ expect(race.moves()).toBe(2);+ expect(refused.code).toBe('source_changed');+ expect((await entityRequests(engine)).map(row => [row.state, row.error_code])).toEqual([['conflict', 'revision_conflict'], ['conflict', 'source_changed']]);+ expect(await claimB(engine)).toEqual([]);+ expect((await factsListing(engine)).map(entry => entry.detail)).toEqual(Array(2).fill(`re-extract: gbrain call extract_facts again on the current text of ${loser.slug} with a new request_id (one model call); a follow-up of its moved-entity refusal was refused for a held file, which a job retry does not re-admit`));+ }, { databaseUrl }), 120_000);+test(`#7602 [${backend}]: an entity page deleted after admission is not re-targeted; the refusal is not retryable`, () => managedBrain(async brain => {const { engine, ctx } = brain;const { loser } = await setup(brain, 0);diff --git a/test/pathological/a-36-facts-batch-partial-refusal.test.ts b/test/pathological/a-36-facts-batch-partial-refusal.test.tsindex 7d0b382061..e373d6f9cb 100644--- a/test/pathological/a-36-facts-batch-partial-refusal.test.ts+++ b/test/pathological/a-36-facts-batch-partial-refusal.test.ts@@ -30,7 +30,7 @@ import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';import { publishManagedEntityFacts } from '../../src/core/facts/managed-fact-write.ts';import { runFactsPipeline } from '../../src/core/facts/backstop.ts';import { FACTS_DEFAULT_VISIBILITY_KEY } from '../../src/core/facts/visibility.ts';-import { FACTS_DEDUP_CHANGED_MESSAGE } from '../../src/core/persistence/verb-errors.ts';+import { FACTS_DEDUP_CHANGED_MESSAGE, FACTS_ENTITY_CHANGED_MESSAGE, PAGE_CHANGED_DURING_PREPARATION_MESSAGE } from '../../src/core/persistence/verb-errors.ts';import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';import { withEnv } from '../helpers/with-env.ts';import { requirePostgresTestDatabase, testBackends } from '../helpers/test-backends.ts';@@ -186,7 +186,8 @@ for (const backend of testBackends()) {}// Value: protects=automatic extraction (no request id) publishes both entities' facts in one run when another write moves one- // entity page before its fact request publishes, and a replay adds nothing; fails_when=the moved entity's refusal stands, the+ // entity page before its fact request publishes (refused at admission, or by the coordinator between preparation and+ // publication), and a replay adds nothing; fails_when=the moved entity's refusal stands or carries another message, the// committed entity is re-admitted or counted twice, or a replay re-runs the model; why_new=#7602 tests move a single entity and// only A-36 explicit callers move one of two; seam=none; no_claim=the move is a direct coordinated write in a fault hook, not a// concurrent facts-absorb job (stub chat model)@@ -199,6 +200,8 @@ for (const backend of testBackends()) {const first = await expectUnitNotAborted(extract);expect(reachedB()).toBe(1);expect({ inserted: first.inserted, refused: first.refused }).toEqual({ inserted: 2, refused: undefined });+ expect(await engine.executeRaw("SELECT error_code, error_message FROM persistence_requests WHERE source_id=$1 AND operation='extract_facts' AND slug=$2 AND state='conflict'", [sourceId, B]))+ .toEqual([{ error_code: 'revision_conflict', error_message: at === 'consumer:prepared' ? PAGE_CHANGED_DURING_PREPARATION_MESSAGE : FACTS_ENTITY_CHANGED_MESSAGE }]);const stored = await requests(engine, sourceId);expect(stored.map(row => [row.slug, row.state])).toEqual([[A, 'committed'], [B, 'conflict'], [COMPLETE, 'conflict'], [B, 'committed'], [COMPLETE, 'committed']]);expect(await factEntities(engine, sourceId)).toEqual([B, A].sort());