Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): a facts batch that lost the race on its entity page is re-admitted at the current revision; a standing refusal is not retried (#7602)

garrytan26edacc91af1
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.md
index dc9afd1966..006014caa0 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).
+- `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: a session with no caller request id (`entityMoveRetry`) 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/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 2b81eaa96a..94fa85b74d 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`). 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`. 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.md
index 36a7a550ee..982549359e 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2180,7 +2180,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`). |
+| `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. |
The apply replays exactly the previewed set. Each write is classified again
and its original caller's authority is checked again first: a write that
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 0b17ccaedf..dff7aad980 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -93,7 +93,7 @@ of making a duplicate.
| <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |
| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | `gbrain sources refresh <source>` (the printed `fix` fills in the source). It drains writes to the source's checkout, fast-forwards it to its upstream and runs the managed sync for every source bound to that checkout; see [worktree refresh refusals](#worktree-refresh-refusals) for what it can refuse. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. |
| <a id="managed_sync_flag_refused"></a>`managed_sync_flag_refused` (`detail` = the flag) | `managed_sync_flag_refused` | A managed source keeps every failed-receipt and ignored-file guard, so `gbrain sync --skip-failed` and `gbrain sync --include-gitignored` have no managed meaning. A strict (git-canonical, `config.canonical = "git"`) source also refuses `gbrain sync --working-tree`, because it indexes committed bytes only; that refusal comes from the managed-sync guard, which reads the source row. The refusal names the flag and comes before anything runs: at parse in `gbrain sync` (before a legacy ledger row is acknowledged or the cost gate runs, `--all` included), before the serve-delegation ladder looks for the serve's socket, and in the managed-sync guard that sync jobs, MCP `sync_brain` and the cycle reach. Nothing is admitted and no cursor is written. | Rerun the printed `fix` (the same command without the flag). A failed file is fixed and then retried by the plain `gbrain sync --source <source> --no-pull`; an ignored file syncs once it is committed and not ignored, and an edit on a strict source syncs once it is committed (`gbrain git commit-push`). `gbrain sync status --source <source> --json` shows the source's failures and holds. |
-| <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. Two outcomes are not refusals and are logged under their own reasons, which doctor never counts toward its threshold: `write_pending_accepted`, a facts write that was accepted and whose receipt is still queued, running or recovering when the job stopped waiting (the job waits up to 30 s, bounded by its deadline; the write commits later), and `write_deferred_unadmitted`, a canonical writer that was busy before anything was admitted (`writer_lock_unavailable`, no receipt; the job retries). Doctor warns about deferrals only when they persist (see the check's `gbrain sources writer status` fix). Doctor's incident count is a historical metric: it counts the `facts:absorb` rows of a rolling 24 h window, says when they age out, and keeps counting them after the cause is fixed and the job retried, so a warning there does not by itself mean anything is still broken; the threshold (`facts.absorb_warn_threshold`) is unchanged. The current state is the check's `jobs still dead` count: facts-absorb jobs that went dead or failed in the last 24 h and that no later job for the same page completed after, each named with `gbrain jobs retry <id>`. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). |
+| <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; so does an entity refusal the facts batch still holds after its follow-ups (#7602: an entity page that kept moving or was deleted, `revision_conflict`, marked not retryable), because every retry replays the same stored receipt; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. Two outcomes are not refusals and are logged under their own reasons, which doctor never counts toward its threshold: `write_pending_accepted`, a facts write that was accepted and whose receipt is still queued, running or recovering when the job stopped waiting (the job waits up to 30 s, bounded by its deadline; the write commits later), and `write_deferred_unadmitted`, a canonical writer that was busy before anything was admitted (`writer_lock_unavailable`, no receipt; the job retries). Doctor warns about deferrals only when they persist (see the check's `gbrain sources writer status` fix). Doctor's incident count is a historical metric: it counts the `facts:absorb` rows of a rolling 24 h window, says when they age out, and keeps counting them after the cause is fixed and the job retried, so a warning there does not by itself mean anything is still broken; the threshold (`facts.absorb_warn_threshold`) is unchanged. The current state is the check's `jobs still dead` count: facts-absorb jobs that went dead or failed in the last 24 h and that no later job for the same page completed after, each named with `gbrain jobs retry <id>`. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). |
| <a id="no_context_ceiling"></a>`no_context_ceiling` | `no_context_ceiling` | A queued job under a cost cap you set stopped before a provider call: the model has a registered price, but gbrain knows no context-token ceiling for it, so it cannot reserve the most one call could cost. OpenRouter models hit this, because that provider declares no context window per model. The message names the model, and the JSON `fix` asks you before it reruns the command without your cap. Re-registering the price does not help. | Choose one. Rerun the command without your cap (the `fix` command, which replaces `--max-usd` with `--yes`): the default cap applies and this model runs unmetered with a warning. Or keep your cap: look up the model's context window on the provider's model page (OpenRouter lists it as `context_length`) and give it to the brain-host operator. `gbrain jobs list --group <id> --json` shows the stopped job. |
| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
| <a id="managed_raw_upload"></a>raw upload on a managed brain | `writer_coordinator_required` | `gbrain files upload-raw` of a small (git-storage) file whose `.raw/` destination is inside a managed canonical worktree. The persistence coordinator does not publish raw files yet, so the worktree refuses writes from outside it; starting a `gbrain serve` owner does not change that. The refusal comes before anything is created: no `.raw/` directory and no `files` row. With no storage backend, `file_upload` for such a page no longer suggests `upload-raw`. | Configure `storage` (supabase, s3 or local) in the gbrain config, then run the printed `gbrain files upload <file> --page <slug>`; check it with `gbrain files list <slug>`. |
diff --git a/src/core/minions/handlers/facts-absorb.ts b/src/core/minions/handlers/facts-absorb.ts
index 0f620aba3d..442ef32805 100644
--- a/src/core/minions/handlers/facts-absorb.ts
+++ b/src/core/minions/handlers/facts-absorb.ts
@@ -61,8 +61,10 @@ export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {
const { writeFactsAbsorbFailure, writeRefusalCode, DETERMINISTIC_WRITE_REFUSALS } = await import('../../facts/absorb-log.ts');
await writeFactsAbsorbFailure(engine, slug, err, sourceId);
// #5362: a deterministic write refusal goes straight to dead; retrying re-runs inference before the same refusal.
+ // #7602: so does a journaled refusal marked not retryable: every retry replays the same stored receipt.
const refusal = writeRefusalCode(err);
- if (refusal && DETERMINISTIC_WRITE_REFUSALS.includes(refusal)) {
+ const replayed = (err as { retryable?: boolean; writeRequest?: unknown }).retryable === false && (err as { writeRequest?: unknown }).writeRequest !== undefined;
+ if (refusal && (DETERMINISTIC_WRITE_REFUSALS.includes(refusal) || replayed)) {
throw new UnrecoverableError(`facts_absorb_write_refused (${refusal}): ${(err as Error).message} Not retried. ` +
`Fix the cause (gbrain sources writer status ${sourceId}), then gbrain jobs retry ${job.id}. See ${ERROR_CATALOGUE.facts_absorb_write_refused.docs}`);
}
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index 841c8a4000..c976c23f60 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -30,7 +30,7 @@ import { MaintenanceWriteWait } from './maintenance-wait.ts';
import { digest, requireUuid, sha256 } from './digest.ts';
import { isTerminal, type WriteAuthority, type WriteRequest } from './model.ts';
import type { WriteReceipt } from './types.ts';
-import { FACTS_BATCH_INCOMPLETE_MESSAGE } from './verb-errors.ts';
+import { FACTS_BATCH_INCOMPLETE_MESSAGE, FACTS_ENTITY_MOVED_MESSAGES } from './verb-errors.ts';
import { assertAmbientCaptureAdmissible, captureGateLaneForSource } from '../facts/capture-sources.ts';
import { declareDerivation, type DerivationDeclaration } from '../trust/taint.ts';
import type { TaintInput, WriteTrust } from '../trust/tier.ts';
@@ -92,6 +92,8 @@ export interface ManagedFactsSession {
fileRefusalRetry?: boolean;
/** #6506: the batch is keyed by its input alone (no request id), so a stored withdrawal refusal would replay on every run. */
inputKeyed?: boolean;
+ /** #7602: no caller request id, so an entity request refused because its entity page moved is re-admitted at the current revision. */
+ entityMoveRetry?: boolean;
/** #6091: set when the facts come from an ambient capture lane. */
captureSource?: string;
/**
@@ -310,6 +312,7 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
// returning its own recorded outcome, so it never rechecks.
fileRefusalRetry: !ctx.requestId && (!!ctx.persistenceRequestId || ctx.reAdmitFileRefusals === true && seed === inputDigest),
inputKeyed: seed === inputDigest,
+ entityMoveRetry: !ctx.requestId,
wait: new MaintenanceWriteWait(ctx.deadlineAtMs ?? null), ...(ctx.abortSignal ? { signal: ctx.abortSignal } : {}),
...(captureGateLaneForSource(ctx.source) ? { captureSource: ctx.source } : {}),
...(derivation ? { derivation: declareDerivation(derivation.trust, derivation.inputs) } : {}) };
@@ -364,7 +367,12 @@ async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSes
if (out.inserted && out.fenced && !result.entity_slugs.includes(row.slug)) result.entity_slugs.push(row.slug);
}
}
- for (const row of [failed, pending, session.reportRefusals && committed ? null : refused[0]]) if (row) writeResponse(row);
+ 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) result.refused = refused.map(row => ({ slug: row.slug, code: row.error_code!, request_id: row.request_id }));
return result;
}
@@ -372,8 +380,9 @@ async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSes
export async function resumeManagedFacts(engine: BrainEngine, session: ManagedFactsSession): Promise<ManagedFactsResult | null> {
const stored = await storedBatch(engine, session);
if (!stored) return null;
- const rows = session.fileRefusalRetry ? await followFileRefusals(engine, session, stored) : stored;
- return collectManagedFacts(engine, session, session.inputKeyed ? await followWithdrawalRefusals(engine, session, rows) : rows);
+ const files = session.fileRefusalRetry ? await followFileRefusals(engine, session, stored) : stored;
+ const rows = session.inputKeyed ? await followWithdrawalRefusals(engine, session, files) : files;
+ return collectManagedFacts(engine, session, session.entityMoveRetry ? await followEntityMoves(engine, session, rows) : rows);
}
/** Every request journaled under the session's batch key, once its completion receipt validates; null when nothing was accepted. */
@@ -422,6 +431,27 @@ async function followWithdrawalRefusals(engine: BrainEngine, session: ManagedFac
return followRefusals(engine, session, stored, 'withdrawal-retry', withdrawalRefusal, readmitWithdrawnFacts);
}
+/**
+ * #7602: two extractions target one entity page and the other publishes first, so this batch's entity request, admitted
+ * at the revision it read, is refused `revision_conflict` at preparation or publication. The retained facts never
+ * depended on the entity's content: the follow-up re-admits them at the page's current revision, no extraction runs
+ * again, and the historical receipt stays as it was. A page deleted or replaced since keeps the refusal. Each batch is
+ * settled first, so a follow-up that loses the race again is followed within the same run.
+ */
+async function followEntityMoves(engine: BrainEngine, session: ManagedFactsSession, rows: WriteRequest[]): Promise<WriteRequest[]> {
+ const settle = async (batch: WriteRequest[]) => {
+ const settled: WriteRequest[] = [];
+ for (const row of batch) settled.push(isTerminal(row) ? row
+ : 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);
+}
+
+function entityMovedRefusal(row: WriteRequest): boolean {
+ return row.error_code === 'revision_conflict' && FACTS_ENTITY_MOVED_MESSAGES.includes(row.error_message ?? '');
+}
+
function withdrawalRefusal(row: WriteRequest): boolean {
return withdrawnFromDetail(row.error_detail) !== undefined || row.error_code === 'invalid_params' && row.error_message === FACT_WITHDRAWN_MESSAGE;
}
@@ -434,7 +464,8 @@ function withdrawalRefusal(row: WriteRequest): boolean {
*/
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>): Promise<WriteRequest[]> {
+ readmit: (engine: BrainEngine, followUp: ManagedFactsSession, refused: WriteRequest[]) => Promise<WriteRequest[] | null>,
+ settle?: (batch: WriteRequest[]) => Promise<WriteRequest[]>): Promise<WriteRequest[]> {
const carried: WriteRequest[] = [];
let latest = stored;
for (let retry = 1; retry <= MAX_FILE_REFUSAL_RETRIES; retry++) {
@@ -449,7 +480,7 @@ async function followRefusals(engine: BrainEngine, session: ManagedFactsSession,
const admitted = await storedBatch(engine, followUp) ?? await readmit(engine, followUp, uncommitted);
if (!admitted) break;
carried.push(...latest.filter(row => isEntityRequest(row) && row.state === 'committed'));
- latest = admitted;
+ latest = settle ? await settle(admitted) : admitted;
}
return [...carried, ...latest];
}
@@ -499,11 +530,7 @@ async function readmitRefusedFacts(engine: BrainEngine, followUp: ManagedFactsSe
*/
async function readmitWithdrawnFacts(engine: BrainEngine, followUp: ManagedFactsSession, refused: WriteRequest[]): Promise<WriteRequest[] | null> {
const { sourceId } = followUp.authority;
- const privateOnly = await resolveDefaultVisibility(engine) === 'private';
- // A fact forgotten at its retained visibility keeps that visibility, so preparation skips and counts it; narrowing it
- // to private would re-save a forgotten claim under a visibility the ledger never covered.
- const narrowed = async (fact: FrozenExtractedFact): Promise<FrozenExtractedFact> => privateOnly && fact.visibility !== 'private'
- && !await isFactWithdrawn(engine, sourceId, fact.visibility ?? 'private', fact.fact, fact.entity_slug ?? null) ? { ...fact, visibility: 'private' } : fact;
+ const narrowed = await retainedVisibility(engine, sourceId);
const entities: ManagedFactsEntityInput[] = [];
for (const row of refused) {
await authorizeStoredRequest(engine, row);
@@ -517,6 +544,39 @@ async function readmitWithdrawnFacts(engine: BrainEngine, followUp: ManagedFacts
return admitManagedFactsBatch(engine, followUp, regroupParts(followUp.batchKey, entities), entities.some(entity => entity.intent.facts!.some(fact => fact.embedding != null)));
}
+/**
+ * Retained facts are never wider than the current default visibility. A fact forgotten at its retained visibility keeps
+ * that visibility, so preparation skips and counts it; narrowing it to private would re-save a forgotten claim under a
+ * visibility the ledger never covered.
+ */
+async function retainedVisibility(engine: BrainEngine, sourceId: string): Promise<(fact: FrozenExtractedFact) => Promise<FrozenExtractedFact>> {
+ const privateOnly = await resolveDefaultVisibility(engine) === 'private';
+ return async fact => privateOnly && fact.visibility !== 'private'
+ && !await isFactWithdrawn(engine, sourceId, fact.visibility ?? 'private', fact.fact, fact.entity_slug ?? null) ? { ...fact, visibility: 'private' } : fact;
+}
+
+/**
+ * #7602: admit the refused requests' retained facts as `followUp` at each entity page's current revision, or return null
+ * (nothing admitted) when a page was deleted or replaced since admission. Each refused request must still be authorized
+ * under its stored authority and its page under the current writer grant; the retained intent is otherwise kept as
+ * admitted. No extraction runs again.
+ */
+async function readmitMovedFacts(engine: BrainEngine, followUp: ManagedFactsSession, refused: WriteRequest[]): Promise<WriteRequest[] | null> {
+ const { sourceId } = followUp.authority;
+ const narrowed = await retainedVisibility(engine, sourceId);
+ const entities: ManagedFactsEntityInput[] = [];
+ for (const row of refused) {
+ await authorizeStoredRequest(engine, row);
+ await authorizeWrite(engine, followUp.authority, 'extract_facts', row.slug);
+ const page = await engine.readPageSnapshot(row.slug, { sourceId });
+ if ((page?.page.id ?? null) !== row.page_id) return null;
+ const { expected_revision: _movedRevision, facts, ...kept } = row.intent as ManagedFactIntent;
+ entities.push({ slug: row.slug, pageId: row.page_id, intent: { ...kept, batchKey: followUp.batchKey,
+ ...(page ? { expected_revision: page.revision } : {}), facts: await Promise.all(facts!.map(narrowed)) } });
+ }
+ return admitManagedFactsBatch(engine, followUp, regroupParts(followUp.batchKey, entities), entities.some(entity => entity.intent.facts!.some(fact => fact.embedding != null)));
+}
+
export async function publishManagedFacts(engine: BrainEngine, session: ManagedFactsSession, ctx: FactsBackstopCtx,
facts: ExtractedFact[], visibility: 'private' | 'world', pageSlug?: string,
options: { supersede?: boolean; explicitContext?: boolean; attributeFallback?: boolean; withdrawn?: 'skip' } = {}): Promise<ManagedFactsResult> {
@@ -557,7 +617,8 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedF
...(snapshot ? { expected_revision: snapshot.revision } : {}), facts: group };
inputs.push(...entityParts(session.batchKey, { slug, pageId: snapshot?.page.id ?? null, intent }));
}
- return collectManagedFacts(engine, session, await admitManagedFactsBatch(engine, session, inputs, embedded, ctx.abortSignal));
+ const admitted = await admitManagedFactsBatch(engine, session, inputs, embedded, ctx.abortSignal);
+ return collectManagedFacts(engine, session, session.entityMoveRetry ? await followEntityMoves(engine, session, admitted) : admitted);
}
interface ManagedFactsEntityInput { slug: string; pageId: number | null; intent: ManagedFactIntent }
diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.ts
index f4b6b2b973..f63120095d 100644
--- a/src/core/persistence/facts-prepare.ts
+++ b/src/core/persistence/facts-prepare.ts
@@ -18,7 +18,7 @@ import { authorizePageVisibility } from './page-visibility.ts';
import { authorizeFactsBackstop } from './effect-facts.ts';
import { getWriteRequestById } from './journal.ts';
import { preparePageMutation } from './page-prepare.ts';
-import { FACTS_BATCH_INCOMPLETE_MESSAGE } from './verb-errors.ts';
+import { FACTS_BATCH_INCOMPLETE_MESSAGE, FACTS_DEDUP_CHANGED_MESSAGE, FACTS_ENTITY_CHANGED_IN_PREPARATION_MESSAGE, FACTS_ENTITY_CHANGED_MESSAGE } from './verb-errors.ts';
import type { PreparedMutation } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
import type { ManagedFactIntent, FrozenExtractedFact } from './facts-maintenance.ts';
@@ -153,7 +153,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
const stored = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
if (stored?.page.deleted_at || (stored?.page.id ?? null) !== row.page_id || (stored?.revision ?? null) !== (p.expected_revision ?? null)
&& (stored?.revision ?? null) !== await predecessorPartRevision(engine, row, p)) {
- throw factsRefusal('revision_conflict', 'The fact entity changed after extraction admission.', row,
+ throw factsRefusal('revision_conflict', FACTS_ENTITY_CHANGED_MESSAGE, row,
`Entity page ${row.slug} changed or was deleted after these facts were admitted, so none were published.`);
}
const facts = (p.facts ?? []).map(fact => ({ ...thawFact(fact), embedding_model: fact.embedding ? p.embedding?.model ?? null : null }));
@@ -239,7 +239,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
page = await withPendingFenceRows({ sourceId: row.source_id, slug: row.slug, rowNums, tier: fenceAppendPendingTier(taint?.trust.tier) },
() => preparePageMutation(engine, { ...row, intent: { ...p, expected_revision: snapshot.revision,
content: serializePageToMarkdown({ ...snapshot.page, ...next }, snapshot.tags) } }, config));
- if (page.observedRevision !== snapshot.revision) throw factsRefusal('revision_conflict', 'The fact entity changed during preparation.', row,
+ if (page.observedRevision !== snapshot.revision) throw factsRefusal('revision_conflict', FACTS_ENTITY_CHANGED_IN_PREPARATION_MESSAGE, row,
`Entity page ${row.slug} changed while its ## Facts table was being prepared, so none of these facts were published.`);
}
return { observedRevision: snapshot?.revision ?? null, file: page?.file, ...(page?.exclusiveSources ? { exclusiveSources: page.exclusiveSources } : {}), noop: entries.every(entry => entry.duplicateId !== null || entry.duplicateOf !== undefined),
@@ -262,7 +262,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
}
if (entry.duplicateOf !== undefined) continue;
const current = await decideSingleFact(tx, row.source_id, entry.fact, dedupEmbedding(entry.fact), entry.fact.embedding_model, entry.fact.source);
- if ((current.candidate?.id ?? null) !== (entry.duplicateId ?? entry.supersedes?.id ?? null)) throw factsRefusal('revision_conflict', 'The fact deduplication state changed before publication.', row,
+ if ((current.candidate?.id ?? null) !== (entry.duplicateId ?? entry.supersedes?.id ?? null)) throw factsRefusal('revision_conflict', FACTS_DEDUP_CHANGED_MESSAGE, row,
`A matching fact in source ${row.source_id} was added or retired before publication, so the deduplication decision for ${row.slug} is stale and none of these facts were published.`);
}
await page?.validate?.(tx);
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 9e3bfb1597..cfa3310d7d 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -10,6 +10,12 @@ import { CHECKPOINT_MOVED_MESSAGE } from './sync-slug-mode.ts';
/** The refusal of a fact-batch completion request whose per-entity requests did not all commit (facts-prepare.ts). */
export const FACTS_BATCH_INCOMPLETE_MESSAGE = 'Some extracted facts have not committed.';
+/** facts-prepare.ts: an entity request admitted at a revision another write moved (or a deleted or replaced entity page). */
+export const FACTS_ENTITY_CHANGED_MESSAGE = 'The fact entity changed after extraction admission.';
+export const FACTS_ENTITY_CHANGED_IN_PREPARATION_MESSAGE = 'The fact entity changed during preparation.';
+export const FACTS_DEDUP_CHANGED_MESSAGE = 'The fact deduplication state changed before publication.';
+/** #7602: entity request refusals a follow-up batch re-admits at the entity's current revision (facts-maintenance.ts). */
+export const FACTS_ENTITY_MOVED_MESSAGES: readonly string[] = [FACTS_ENTITY_CHANGED_MESSAGE, FACTS_ENTITY_CHANGED_IN_PREPARATION_MESSAGE, FACTS_DEDUP_CHANGED_MESSAGE];
const FRONTMATTER_SLUG_CONFLICT = /^The frontmatter slug "[^"\n]{1,300}" in [^/"\n][^"\n]{0,1000} conflicts with its path, which expects slug "[^"\n]{1,300}"\. Remove `slug:` or make it match the path\.$/;
diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.ts
index a914d4f07e..e154fa659c 100644
--- a/src/core/repair/failed-writes.ts
+++ b/src/core/repair/failed-writes.ts
@@ -54,6 +54,7 @@ import { submitRememberMutation } from '../persistence/memory-mutations.ts';
import { getWorktreeBinding } from '../persistence/ownership.ts';
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 { 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';
@@ -67,10 +68,17 @@ const GUARD_REFUSAL = `(r.state='failed' AND (r.error_code='writer_coordinator_r
OR (r.error_code='storage_error' AND r.error_message LIKE 'Publication failed (P0001)%')))`;
/** #6429: a refusal from prepareFileTarget (page-prepare.ts); the receipt keeps the code, not the refusal's detail. */
const DRIFT_REFUSAL = `(r.state='conflict' AND r.error_code='source_changed')`;
+/** #7602: a managed fact request refused because its entity page moved; extraction re-admits these since, but older ones stayed refused. */
+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'
+ AND c.source_id=r.source_id AND c.slug=r.slug AND c.state='committed' AND c.sequence>r.sequence
+ AND COALESCE(c.intent->>'inputDigest', c.outcome->>'input_digest')=r.intent->>'inputDigest'))`;
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;
+ intent: Record<string, unknown>; authority: WriteAuthority; created_at: string; producer: string | null; error_code: string | null;
/** #6693: the refusal's recorded origin (`pending_import`, `sync_held`), when the receipt carries one. */
origin?: string | null;
}
@@ -83,6 +91,26 @@ function previewCommand(scope: RepairScope): string {
return `gbrain repair failed-writes${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;
}
+/**
+ * #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.
+ */
+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;
+ 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 refusals = 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);
+ if (refusals.length > 1) 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' : ''})`;
+}
+
/** The command that produces an owner-internal write again, from current content. */
function producerCommand(producer: string, sourceId: string): string {
const parts = producer.split(':');
@@ -90,17 +118,17 @@ function producerCommand(producer: string, sourceId: string): string {
if (parts.includes('canonical_reconcile')) return `gbrain sources reconcile ${sourceId} --audit`;
if (parts.includes('managed_file_repair')) return `gbrain repair frontmatter --source ${sourceId} (a frontmatter repair) or gbrain repair fences --source ${sourceId} (a fence repair)`;
if (parts.includes('relink_facts')) return `gbrain facts relink --source ${sourceId} --dry-run`;
- if (parts.some(part => part.includes('facts'))) return `gbrain extract --stale --source-id ${sourceId} --json`;
return 'the next `gbrain dream` cycle (or autopilot) produces it again';
}
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,
+ 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,
CASE WHEN r.operation = ANY($2::text[]) AND NOT (r.operation='put_page' AND r.intent ? 'kind') THEN NULL
ELSE r.operation || COALESCE(':' || (r.intent->>'kind'), '') END AS producer
FROM persistence_requests r
- WHERE r.source_id = ANY($1::text[]) AND NOT r.compacted AND r.intent IS NOT NULL AND (${GUARD_REFUSAL} OR ${DRIFT_REFUSAL})
+ WHERE r.source_id = ANY($1::text[]) AND NOT r.compacted AND r.intent IS NOT NULL AND (${GUARD_REFUSAL} OR ${DRIFT_REFUSAL} OR ${FACTS_MOVED_REFUSAL})
+ AND NOT ${FACTS_RECOVERED}
${id ? 'AND r.id=$3::uuid' : ''}
ORDER BY r.sequence`, id ? [sourceIds, REPLAYABLE, id] : [sourceIds, REPLAYABLE]);
if (id) return rows;
@@ -312,8 +340,10 @@ export const failedWritesRepair: RepairHandler = {
const label = `${write.source_id}:${write.slug} ${write.operation} (${write.state} ${write.created_at}, request ${write.id})`;
if (write.producer) {
residuals[`producer_owned:${write.producer}`] = (residuals[`producer_owned:${write.producer}`] ?? 0) + 1;
- producers.set(`${write.producer} in ${write.source_id}`, producerCommand(write.producer, write.source_id));
- listing.push({ item: label, class: 'producer_owned', detail: `re-run: ${producerCommand(write.producer, write.source_id)}` });
+ const facts = write.operation === 'extract_facts';
+ const run = facts ? await factsRecovery(engine, write, rows) : producerCommand(write.producer, write.source_id);
+ producers.set(`${write.producer} in ${write.source_id}`, facts ? 'each listed request names the command that recovers its facts' : run);
+ listing.push({ item: label, class: 'producer_owned', detail: facts ? run : `re-run: ${run}` });
continue;
}
const verdict = await disposition(engine, write);
diff --git a/test/facts-entity-moved-7602.test.ts b/test/facts-entity-moved-7602.test.ts
new file mode 100644
index 0000000000..0cf59aa531
--- /dev/null
+++ b/test/facts-entity-moved-7602.test.ts
@@ -0,0 +1,233 @@
+/**
+ * #7602: two extractions from different source pages target the same entity page. One publishes first; the other's
+ * entity request, admitted at the revision it read, is refused `revision_conflict` at preparation. The batch is keyed
+ * by the page write it extracts from, so every facts-absorb retry replayed the same stored refusal until the job died
+ * and the facts were dropped.
+ *
+ * 1. Protects: the refused request's retained facts are re-admitted at the entity's current revision and publish in the
+ * same run, with no second model call; a retry replays that outcome and admits nothing; the historical receipt is
+ * left as it was. A page that keeps moving is followed at most three times, a deleted entity page is not followed,
+ * and the refusal that stands is not retryable, so the job dead-letters on its first attempt instead of five.
+ * 2. Fails when: the refusal replays (master before the fix), a follow-up re-runs the model, the cap is exceeded, a
+ * deleted page is re-targeted, or a standing refusal is retried.
+ * 3. test/facts-absorb-stalled-receipt-7439.test.ts and test/managed-facts-withdrawal-recovery-6506.test.ts cover the
+ * file-check and withdrawal follow-ups this walk mirrors.
+ * 4. Seams: the race is made deterministic by publishing the competing extraction while the losing one reads the
+ * entity page (the snapshot it then admits against is the one from before); gateway test transports.
+ */
+import { afterEach, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { configureGateway, resetGateway, __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import type { FactsBackstopCtx } from '../src/core/facts/backstop.ts';
+import { UnrecoverableError } from '../src/core/minions/errors.ts';
+import { makeFactsAbsorbHandler } from '../src/core/minions/handlers/facts-absorb.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { prepareManagedFactsSession, publishManagedFacts, resumeManagedFacts } from '../src/core/persistence/facts-maintenance.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.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';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const TARGET = 'people/alice-example';
+const CLAIM_B = 'Alice-example owns the synthetic onboarding checklist.';
+const BODY = 'Notes from a synthetic planning chat about the onboarding checklist and the launch date, kept for the regression.';
+
+afterEach(() => { __setChatTransportForTests(null); resetGateway(); });
+
+async function put(ctx: ManagedBrain['ctx'], slug: string, type: string) {
+ const requestId = randomUUID();
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: requestId,
+ content: `---\ntype: ${type}\ntitle: Example\n---\n${BODY} (${slug})\n` } });
+ const [write] = await ctx.engine.executeRaw<{ id: string }>('SELECT id FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ return write!.id;
+}
+
+const fact = (claim: string) => ({ fact: claim, kind: 'fact' as const, source: 'mcp:put_page', entity_slug: TARGET, confidence: 0.9, notability: 'high' as const, embedding: null });
+
+/** A committed write of a source page and its extraction: the backstop context, the input and a fresh session per run. */
+async function extraction({ engine, ctx }: ManagedBrain, slug: string) {
+ const write = await put(ctx, slug, 'meeting');
+ const backstop: FactsBackstopCtx = { engine, sourceId: 'default', source: 'mcp:put_page', sessionId: null, persistenceRequestId: write, operationContext: ctx };
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ const input = { turnText: snapshot.page.compiled_truth, pageSlug: slug };
+ return { slug, write, snapshot, backstop, input, session: async () => (await prepareManagedFactsSession(backstop, input))! };
+}
+
+/**
+ * The race: while the losing extraction reads the entity page before admitting (and again before each follow-up),
+ * `move` publishes a competing write of that page, and the read returns the snapshot from before it.
+ */
+function raceEntityReads(engine: ManagedBrain['engine'], times: number, move: (n: number) => Promise<void>) {
+ const read = engine.readPageSnapshot;
+ let moves = 0, moving = false;
+ engine.readPageSnapshot = (async function (this: typeof engine, slug: string, opts?: Parameters<typeof read>[1]) {
+ const reader = /publishManagedFacts|readmitMovedFacts/.test(new Error().stack ?? '');
+ const before = await read.call(this, slug, opts);
+ if (this !== engine || slug !== TARGET || !reader || moving || moves >= times) return before;
+ moving = true;
+ try { await move(moves++); } finally { moving = false; }
+ return before;
+ }) as typeof engine.readPageSnapshot;
+ return { moves: () => moves, restore: () => { delete (engine as { readPageSnapshot?: unknown }).readPageSnapshot; } };
+}
+
+/** Each move publishes another extraction's fact onto the entity page, as a concurrent facts-absorb job would. */
+async function competitors(brain: ManagedBrain, count: number) {
+ const list: Array<Awaited<ReturnType<typeof extraction>>> = [];
+ for (let i = 0; i < count; i++) list.push(await extraction(brain, `chats/source-${String.fromCharCode(97 + i)}`));
+ return async (n: number) => {
+ const competitor = list[n]!;
+ const published = await publishManagedFacts(brain.engine, await competitor.session(), competitor.backstop,
+ [fact(`Alice-example confirmed synthetic item ${n + 1}.`)], 'private', competitor.slug);
+ expect(published.inserted).toBe(1);
+ };
+}
+
+const entityRequests = (engine: ManagedBrain['engine']) => engine.executeRaw<{ request_id: string; state: string; error_code: string | null; error_message: string | null }>(
+ "SELECT request_id, state, error_code, error_message FROM persistence_requests WHERE operation='extract_facts' AND slug=$1 AND intent->>'origin' LIKE '%chats/source-loser%' ORDER BY sequence", [TARGET]);
+const claimB = (engine: ManagedBrain['engine']) => engine.executeRaw<{ fact: string; source_markdown_slug: string | null }>(
+ 'SELECT fact, source_markdown_slug FROM facts WHERE fact=$1', [CLAIM_B]);
+
+/** The `gbrain repair failed-writes` preview rows for the losing extraction's entity requests. */
+async function factsListing(engine: ManagedBrain['engine']) {
+ const preview = await (await repairRunner(engine, { apply: false, logger: { info() {}, warn() {}, error() {} } }))
+ .run('failed-writes', await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default' });
+ return (preview.listing ?? []).filter(entry => entry.item.includes(`${TARGET} extract_facts`));
+}
+
+function jobContext(loser: Awaited<ReturnType<typeof extraction>>, id: number): MinionJobContext {
+ const signal = new AbortController().signal;
+ return { id, name: 'facts-absorb', attempts_made: 0, signal, deadlineAtMs: null, shutdownSignal: signal,
+ data: { slug: loser.slug, sourceId: 'default', source: 'mcp:put_page', sessionId: `put_page:${loser.slug}`, visibility: 'private',
+ persistence_request_id: loser.write, page_id: loser.snapshot.page.id, revision: loser.snapshot.revision },
+ updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {}, isActive: async () => true, readInbox: async () => [] } as unknown as MinionJobContext;
+}
+
+/** A keyed chat stub that extracts CLAIM_B about the entity; returns the call counter. */
+async function stubExtraction(engine: ManagedBrain['engine']) {
+ const calls = { n: 0 };
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
+ __setChatTransportForTests(async (): Promise<ChatResult> => {
+ calls.n++;
+ return { text: JSON.stringify({ facts: [{ fact: CLAIM_B, kind: 'fact', entity: TARGET, confidence: 0.9, notability: 'high' }] }),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' };
+ });
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ await engine.setConfig('embedding_disabled', 'true');
+ return calls;
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const setup = async (brain: ManagedBrain, competing: number) => {
+ await put(brain.ctx, TARGET, 'person');
+ const move = await competitors(brain, competing);
+ return { move, loser: await extraction(brain, 'chats/source-loser') };
+ };
+
+ test(`#7602 [${backend}]: an extraction that lost the race on its entity page publishes its retained facts in the same run`, () => managedBrain(async brain => {
+ const { engine } = brain;
+ const { move, loser } = await setup(brain, 1);
+ const race = raceEntityReads(engine, 1, move);
+ const first = await publishManagedFacts(engine, await loser.session(), loser.backstop, [fact(CLAIM_B)], 'private', loser.slug).finally(race.restore);
+ expect(race.moves()).toBe(1);
+ expect(first.inserted).toBe(1);
+ expect(first.refused).toBeUndefined();
+ expect(await claimB(engine)).toEqual([{ fact: CLAIM_B, source_markdown_slug: TARGET }]);
+ expect((await engine.readPageSnapshot(TARGET, { sourceId: 'default' }))!.page.compiled_truth).toContain(CLAIM_B);
+ const requests = await entityRequests(engine);
+ expect(requests.map(row => [row.state, row.error_code, row.error_message])).toEqual([
+ ['conflict', 'revision_conflict', 'The fact entity changed after extraction admission.'], ['committed', null, null]]);
+ for (let retry = 0; retry < 4; retry++) expect((await resumeManagedFacts(engine, await loser.session()))?.inserted).toBe(1);
+ expect(await entityRequests(engine)).toEqual(requests);
+ expect(await claimB(engine)).toHaveLength(1);
+ 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);
+ const race = raceEntityReads(engine, 4, move);
+ 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(4);
+ expect(refused.code).toBe('revision_conflict');
+ expect(refused.retryable).toBe(false);
+ const requests = await entityRequests(engine);
+ expect(requests).toHaveLength(4);
+ expect(requests.every(row => row.state === 'conflict' && row.error_code === 'revision_conflict')).toBe(true);
+ const retry = await resumeManagedFacts(engine, await loser.session()).catch(error => error);
+ expect([retry.code, retry.retryable]).toEqual(['revision_conflict', false]);
+ expect(await entityRequests(engine)).toEqual(requests);
+ expect(await claimB(engine)).toEqual([]);
+ const listing = await factsListing(engine);
+ expect(listing).toHaveLength(4);
+ for (const entry of listing) {
+ expect(entry.class).toBe('producer_owned');
+ expect(entry.detail).toStartWith(`re-extract: gbrain call extract_facts again on the current text of ${loser.slug} with a new request_id`);
+ expect(entry.detail).not.toContain('extract --stale');
+ }
+ }, { 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 => {
+ const { engine } = brain;
+ const { move, loser } = await setup(brain, 1);
+ const before = await loser.session();
+ before.entityMoveRetry = false;
+ 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 [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}'`);
+ 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 }]);
+ expect(await factsListing(engine)).toEqual([]);
+ }, { 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);
+ 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, request_id: randomUUID() } });
+ });
+ const refused = await publishManagedFacts(engine, await loser.session(), loser.backstop, [fact(CLAIM_B)], 'private', loser.slug).catch(error => error).finally(race.restore);
+ 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([`not recoverable: entity page ${TARGET} was deleted after these facts were admitted`]);
+ }, { databaseUrl }), 120_000);
+
+ test(`#7602 [${backend}]: the facts-absorb job that lost the race completes in one attempt with one model call`, () => managedBrain(async brain => {
+ const { engine } = brain;
+ const { move, loser } = await setup(brain, 1);
+ const calls = await stubExtraction(engine);
+ const race = raceEntityReads(engine, 1, move);
+ const result = await makeFactsAbsorbHandler(engine)(jobContext(loser, 1)).finally(race.restore) as { inserted: number };
+ expect(race.moves()).toBe(1);
+ expect(result.inserted).toBe(1);
+ expect(calls.n).toBe(1);
+ expect(await claimB(engine)).toEqual([{ fact: CLAIM_B, source_markdown_slug: TARGET }]);
+ }, { databaseUrl }), 120_000);
+
+ test(`#7602 [${backend}]: a standing refusal dead-letters the facts-absorb job on its first attempt; a retry calls no model`, () => managedBrain(async brain => {
+ const { engine } = brain;
+ const { move, loser } = await setup(brain, 4);
+ const calls = await stubExtraction(engine);
+ const race = raceEntityReads(engine, 4, move);
+ const handler = makeFactsAbsorbHandler(engine);
+ const first: Error = await handler(jobContext(loser, 1)).then(() => new Error('the job completed')).catch(error => error).finally(race.restore);
+ expect(first).toBeInstanceOf(UnrecoverableError);
+ expect(first.message).toContain('facts_absorb_write_refused (revision_conflict)');
+ expect(calls.n).toBe(1);
+ const requests = await entityRequests(engine);
+ expect(await handler(jobContext(loser, 1)).catch(error => error)).toBeInstanceOf(UnrecoverableError);
+ expect(calls.n).toBe(1);
+ expect(await entityRequests(engine)).toEqual(requests);
+ expect(await claimB(engine)).toEqual([]);
+ }, { databaseUrl }), 120_000);
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index bf80cad9e3..0bf1fed5b7 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -71,6 +71,7 @@ test/fact-embedding-oversized-7211.test.ts
test/fact-fence-adoption-exits.test.ts
test/fact-purge-lookup-timeout-6511.test.ts
test/facts-absorb-stalled-receipt-7439.test.ts
+test/facts-entity-moved-7602.test.ts
test/facts-insert-guards-7105.test.ts
test/facts-publication-large-fence-6898.test.ts
test/facts-subject-infer-7405.test.ts