Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): pre-landing review fixes for #7602
garrytan9ae7bb5c4c8c
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex dff7aad980..0b17ccaedf 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; 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="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="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.tsindex 442ef32805..0f620aba3d 100644--- a/src/core/minions/handlers/facts-absorb.ts+++ b/src/core/minions/handlers/facts-absorb.ts@@ -61,10 +61,8 @@ 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);- const replayed = (err as { retryable?: boolean; writeRequest?: unknown }).retryable === false && (err as { writeRequest?: unknown }).writeRequest !== undefined;- if (refusal && (DETERMINISTIC_WRITE_REFUSALS.includes(refusal) || replayed)) {+ if (refusal && DETERMINISTIC_WRITE_REFUSALS.includes(refusal)) {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.tsindex 0101811433..a6ad68be3d 100644--- a/src/core/persistence/facts-maintenance.ts+++ b/src/core/persistence/facts-maintenance.ts@@ -115,7 +115,7 @@ export interface ManagedFactsSession {}/** #6048: follow-up batches one input-keyed extraction may admit for file-check refusals. */-const MAX_FILE_REFUSAL_RETRIES = 3;+export const MAX_FILE_REFUSAL_RETRIES = 3;/*** #6898 follow-up: the most facts one entity request publishes. A publication holds the brain-wide@@ -447,7 +447,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);+ return followRefusals(engine, session, await settle(rows), 'entity-moved-retry', entityMovedRefusal, readmitMovedFacts, { settle, partial: true });}function entityMovedRefusal(row: WriteRequest): boolean {@@ -462,27 +462,31 @@ 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.+ * 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.*/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>,- settle?: (batch: WriteRequest[]) => Promise<WriteRequest[]>): Promise<WriteRequest[]> {+ options: { settle?: (batch: WriteRequest[]) => Promise<WriteRequest[]>; partial?: boolean } = {}): Promise<WriteRequest[]> {const carried: WriteRequest[] = [];let latest = stored;for (let retry = 1; retry <= MAX_FILE_REFUSAL_RETRIES; retry++) {if (latest.some(row => !isTerminal(row))) break;const uncommitted = latest.filter(row => isEntityRequest(row) && row.state !== 'committed');- const retained = uncommitted.map(row => row.intent as ManagedFactIntent | null);- if (!uncommitted.length || uncommitted.some((row, i) => !refused(row) || !retained[i]?.facts?.length- || retained[i]!.inputDigest !== session.inputDigest || !sameSignature(retained[i]!.embedding, retained[0]!.embedding))) break;+ 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+ || 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, uncommitted);+ const admitted = await storedBatch(engine, followUp) ?? await readmit(engine, followUp, followed);if (!admitted) break;- carried.push(...latest.filter(row => isEntityRequest(row) && row.state === 'committed'));- latest = settle ? await settle(admitted) : admitted;+ 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;}return [...carried, ...latest];}@@ -558,8 +562,8 @@ async function retainedVisibility(engine: BrainEngine, sourceId: string): Promis}/**- * #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+ * #7602: admit the refused requests' retained facts as `followUp` at each entity page's current revision. A request whose+ * page was deleted or replaced since admission is left out and keeps its refusal; null when none is left. 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.*/@@ -571,11 +575,12 @@ async function readmitMovedFacts(engine: BrainEngine, followUp: ManagedFactsSessawait 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;+ if ((page?.page.id ?? null) !== row.page_id) continue;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)) } });}+ if (!entities.length) return null;return admitManagedFactsBatch(engine, followUp, regroupParts(followUp.batchKey, entities), entities.some(entity => entity.intent.facts!.some(fact => fact.embedding != null)));}diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex f63120095d..1b56daebcc 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -18,6 +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 { PageRevisionConflictError } from '../page-state/types.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';@@ -236,11 +237,15 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writif (snapshot && entries.some(entry => entry.rowNum !== undefined)) {// #5575 ENG-1: the appended rows have no facts rows yet; their chunks are cut at the append's tier.const rowNums = entries.flatMap(entry => entry.rowNum === undefined ? [] : [entry.rowNum]);+ const moved = () => 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.`);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', 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.`);+ content: serializePageToMarkdown({ ...snapshot.page, ...next }, snapshot.tags) } }, config)).catch(error => {+ // #7602: the page preparation refuses a move before the check below sees it.+ throw error instanceof PageRevisionConflictError && error.code === 'revision_conflict' ? moved() : error;+ });+ if (page.observedRevision !== snapshot.revision) throw moved();}return { observedRevision: snapshot?.revision ?? null, file: page?.file, ...(page?.exclusiveSources ? { exclusiveSources: page.exclusiveSources } : {}), noop: entries.every(entry => entry.duplicateId !== null || entry.duplicateOf !== undefined),...(taint ? { trust: taint.trust } : {}),diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex cfa3310d7d..69fd8694ac 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -14,8 +14,11 @@ export const FACTS_BATCH_INCOMPLETE_MESSAGE = 'Some extracted facts have not comexport 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.';+/** The coordinator's refusal when the page moved between preparation and publication (coordinator.ts, group-publish.ts). */+export const PAGE_CHANGED_DURING_PREPARATION_MESSAGE = 'The page changed during preparation.';/** #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];+export const FACTS_ENTITY_MOVED_MESSAGES: readonly string[] = [FACTS_ENTITY_CHANGED_MESSAGE, FACTS_ENTITY_CHANGED_IN_PREPARATION_MESSAGE, FACTS_DEDUP_CHANGED_MESSAGE,+ PAGE_CHANGED_DURING_PREPARATION_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.tsindex e154fa659c..fe57122dfe 100644--- a/src/core/repair/failed-writes.ts+++ b/src/core/repair/failed-writes.ts@@ -55,6 +55,7 @@ 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 { MAX_FILE_REFUSAL_RETRIES } from '../persistence/facts-maintenance.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';@@ -74,7 +75,8 @@ const FACTS_MOVED_REFUSAL = `(r.operation='extract_facts' AND r.state='conflict'/** #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'))`;+ AND 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'))`;interface FailedWrite {id: string; request_id: string; sequence: string; operation: string; source_id: string; slug: string; digest: string; state: string;@@ -104,9 +106,9 @@ async function factsRecovery(engine: BrainEngine, write: FailedWrite, rows: Failif (!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`;+ 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));+ 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' : ''})`;}@@ -118,6 +120,10 @@ 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.includes('managed_maintenance_expire_captured_facts')) return `gbrain repair captured-facts --source ${sourceId}`;+ if (parts.includes('managed_maintenance_restore_extractor_facts')) return `gbrain repair extractor-facts --source ${sourceId}`;+ if (parts.includes('managed_maintenance_restore_redacted_facts')) return `gbrain repair redacted-facts --source ${sourceId}`;+ if (parts.includes('managed_maintenance_conversation_facts')) return `gbrain extract-conversation-facts --source-id ${sourceId} --dry-run`;return 'the next `gbrain dream` cycle (or autopilot) produces it again';}diff --git a/test/facts-absorb-stalled-receipt-7439.test.ts b/test/facts-absorb-stalled-receipt-7439.test.tsindex 4aec2a08b5..c23e782ff9 100644--- a/test/facts-absorb-stalled-receipt-7439.test.ts+++ b/test/facts-absorb-stalled-receipt-7439.test.ts@@ -19,6 +19,8 @@ import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';import { runReconcileApply, runReconcilePreview } from '../src/core/persistence/reconcile.ts';import { readGitSourceHolds, 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';import { managedBrain } from './helpers/managed-brain.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';@@ -53,7 +55,14 @@ async function refusedPageBatch({ engine, ctx, root }: ManagedBrain) {expect(receipt[0]!.error_message).toContain('preparation_stalled');const retry = async () => resumeManagedFacts(engine, (await prepareManagedFactsSession(backstop, input))!);expect((await retry().catch(error => error)).code).toBe('source_changed');- return { file, pristine, receipt, retry };+ return { file, pristine, receipt, retry, write: write!.id };+}++/** The `gbrain repair failed-writes` preview rows for the target's fact 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`));}const factRows = (engine: ManagedBrain['engine']) => engine.executeRaw<{ fact: string }>('SELECT fact FROM facts WHERE fact=$1', [CLAIM]);@@ -63,8 +72,16 @@ for (const backend of testBackends()) {test(`#7439 [${backend}]: a page-triggered facts batch refused for a stalled hold publishes its retained facts once the reconcile clears the hold`, () => managedBrain(async brain => {const { engine } = brain;- const { file, pristine, receipt, retry } = await refusedPageBatch(brain);+ const { file, pristine, receipt, retry, write } = await refusedPageBatch(brain);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+ const [listed, ...others] = await factsListing(engine);+ expect(others).toEqual([]);+ expect(listed!.class).toBe('producer_owned');+ expect(listed!.detail).toStartWith(`recover: gbrain facts retry-dead --reset 'facts-absorb:write:${write}'`);+ expect(listed!.detail).toContain('once the file check passes');writeFileSync(file, pristine);await withVerifiedLocalRegistration(engine, await registerLocalWriter(engine, 'cli'), async () => {const preview = await runReconcilePreview(engine, { source_id: 'default', slug: TARGET });@@ -79,6 +96,7 @@ for (const backend of testBackends()) {expect(await engine.executeRaw('SELECT request_id, error_message FROM persistence_requests WHERE request_id=$1::uuid', [receipt[0]!.request_id])).toEqual(receipt);expect((await retry())?.inserted).toBe(1);expect(await factRows(engine)).toHaveLength(1);+ expect(await factsListing(engine)).toEqual([]);}, { databaseUrl }), 120_000);test(`#7439 [${backend}]: while the held file still differs, a retry keeps the refusal and admits nothing`, () => managedBrain(async brain => {diff --git a/test/facts-entity-moved-7602.test.ts b/test/facts-entity-moved-7602.test.tsindex 4559478838..ddd412004b 100644--- a/test/facts-entity-moved-7602.test.ts+++ b/test/facts-entity-moved-7602.test.ts@@ -18,12 +18,16 @@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 { FENCE_FACTS_INTENT } from '../src/core/cycle/extract-facts.ts';import type { FactsBackstopCtx } from '../src/core/facts/backstop.ts';-import { UnrecoverableError } from '../src/core/minions/errors.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';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 { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../src/core/persistence/prepared-maintenance.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.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';@@ -32,6 +36,8 @@ import { requirePostgresTestDatabase, testBackends } from './helpers/test-backenconst TARGET = 'people/alice-example';const CLAIM_B = 'Alice-example owns the synthetic onboarding checklist.';+const OTHER = 'companies/acme-example';+const CLAIM_OTHER = 'Acme-example runs the synthetic onboarding pilot.';const BODY = 'Notes from a synthetic planning chat about the onboarding checklist and the launch date, kept for the regression.';afterEach(() => { __setChatTransportForTests(null); resetGateway(); });@@ -190,6 +196,76 @@ for (const backend of testBackends()) {expect(await factsListing(engine)).toEqual([]);}, { databaseUrl }), 120_000);+ // Value: protects=a writer-guard-refused fact request is listed for re-extraction, never the job retry that would replay its refusal;+ // fails_when=factsRecovery offers retry-dead for any page-triggered request, or the listing names extract --stale again;+ // why_new=the #7602 listings cover conflict rows only; seam=none; no_claim=the guard refusal is stamped onto a stored receipt by SQL,+ // as test/repair-failed-writes-5983.test.ts does, not produced by a live writer guard+ test(`#7602 [${backend}]: a fact request the writer guard refused is listed for re-extraction, not a job retry`, () => 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);+ expect((await publishManagedFacts(engine, before, loser.backstop, [fact(CLAIM_B)], 'private', loser.slug).catch(error => error).finally(race.restore)).code).toBe('revision_conflict');+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(`UPDATE persistence_requests SET state='failed', error_code='writer_coordinator_required'+ WHERE operation='extract_facts' AND slug=$1 AND state='conflict' AND intent->>'origin' LIKE '%chats/source-loser%'`, [TARGET]);+ });+ expect((await factsListing(engine)).map(entry => [entry.class, entry.detail])).toEqual([['producer_owned',+ `re-extract: gbrain call extract_facts again on the current text of ${loser.slug} with a new request_id (one model call)`]]);+ }, { databaseUrl }), 120_000);++ // Value: protects=a re-admitted fact is never wider than the current default visibility, and keeps world under a world default;+ // fails_when=readmitMovedFacts re-admits the retained facts without narrowing them (or narrows unconditionally);+ // why_new=the other #7602 rows publish private facts only; seam=none; no_claim=the race is the wrapped entity read above+ for (const [defaultVisibility, published] of [[null, 'private'], ['world', 'world']] as const) {+ test(`#7602 [${backend}]: a world fact re-admitted after the race is ${published} under the ${defaultVisibility ?? 'unset'} default visibility`, () => managedBrain(async brain => {+ const { engine } = brain;+ if (defaultVisibility) await engine.setConfig(FACTS_DEFAULT_VISIBILITY_KEY, defaultVisibility);+ 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)], 'world', loser.slug).finally(race.restore);+ expect(race.moves()).toBe(1);+ expect(first.inserted).toBe(1);+ expect(await engine.executeRaw(`SELECT state, intent->'facts'->0->>'visibility' AS visibility FROM persistence_requests+ WHERE operation='extract_facts' AND slug=$1 AND intent->>'origin' LIKE '%chats/source-loser%' ORDER BY sequence`, [TARGET]))+ .toEqual([{ state: 'conflict', visibility: 'world' }, { state: 'committed', visibility: published }]);+ expect(await engine.executeRaw('SELECT visibility FROM facts WHERE fact=$1', [CLAIM_B])).toEqual([{ visibility: published }]);+ }, { databaseUrl }), 120_000);+ }++ // Value: protects=repair failed-writes names the command that produces each guard-refused maintenance facts write again;+ // fails_when=the listing sends a *_facts producer to gbrain extract --stale again (that sweep runs no fact producer), or a repair's+ // write to the dream cycle; why_new=no failed-writes test lists a maintenance producer; seam=none; no_claim=the guard refusal (and,+ // past the first row, the intent kind) is stamped onto a committed fence-facts receipt by SQL, as the writer-guard row above does+ const maintenanceProducers: Array<[kind: string, command: string]> = [+ [FENCE_FACTS_INTENT, 'the next `gbrain dream` cycle (or autopilot) produces it again'],+ ['managed_maintenance_expire_captured_facts', 'gbrain repair captured-facts --source default'],+ ['managed_maintenance_restore_extractor_facts', 'gbrain repair extractor-facts --source default'],+ ['managed_maintenance_restore_redacted_facts', 'gbrain repair redacted-facts --source default'],+ ['managed_maintenance_conversation_facts', 'gbrain extract-conversation-facts --source-id default --dry-run'],+ ];+ for (const [kind, command] of maintenanceProducers) {+ test(`#7602 [${backend}]: a guard-refused ${kind} write is listed with the command that produces it, not extract --stale`, () => managedBrain(async brain => {+ const { engine, ctx, root } = brain;+ await put(ctx, TARGET, 'person');+ const snapshot = (await engine.readPageSnapshot(TARGET, { sourceId: 'default' }))!;+ await submitDatabaseMaintenanceIntent(engine, (await maintenancePreflight(engine, 'default', root))!, TARGET,+ { kind: FENCE_FACTS_INTENT, expected_revision: snapshot.revision, page_id: snapshot.page.id, embeddings: [] }, randomUUID());+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ expect(await tx.executeRaw(`UPDATE persistence_requests SET state='failed', error_code='writer_coordinator_required',+ intent=jsonb_set(intent, '{kind}', to_jsonb($3::text)) WHERE slug=$1 AND intent->>'kind'=$2 RETURNING operation`, [TARGET, FENCE_FACTS_INTENT, kind]))+ .toEqual([{ operation: 'submit_job' }]);+ });+ const preview = await (await repairRunner(engine, { apply: false, logger: { info() {}, warn() {}, error() {} } }))+ .run('failed-writes', await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default' });+ expect((preview.listing ?? []).filter(entry => entry.item.includes(`${TARGET} submit_job`)).map(entry => [entry.class, entry.detail]))+ .toEqual([['producer_owned', `re-run: ${command}`]]);+ }, { 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);@@ -204,6 +280,26 @@ for (const backend of testBackends()) {expect((await factsListing(engine)).map(entry => entry.detail)).toEqual([`not recoverable: entity page ${TARGET} was deleted after these facts were admitted`]);}, { databaseUrl }), 120_000);+ // Value: protects=a moved entity is re-admitted though a sibling entity of the same extraction was deleted, and the sibling keeps its+ // refusal; fails_when=one deleted page abandons the whole follow-up (the moved entity's facts are dropped) or the deleted one is+ // re-targeted; why_new=the deleted-page test has a single entity; seam=none; no_claim=the move and the delete are direct writes in the race+ test(`#7602 [${backend}]: a moved entity is re-admitted beside a sibling whose page was deleted; the sibling stays refused`, () => managedBrain(async brain => {+ const { engine, ctx } = brain;+ const { move, loser } = await setup(brain, 1);+ await put(ctx, OTHER, 'company');+ const race = raceEntityReads(engine, 1, async n => {+ await move(n);+ const other = (await engine.readPageSnapshot(OTHER, { sourceId: 'default' }))!;+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: OTHER, expected_revision: other.revision, request_id: randomUUID() } });+ });+ const result = await publishManagedFacts(engine, await loser.session(), loser.backstop, [{ ...fact(CLAIM_OTHER), entity_slug: OTHER }, fact(CLAIM_B)],+ 'private', loser.slug).finally(race.restore);+ expect(race.moves()).toBe(1);+ expect({ inserted: result.inserted, refused: result.refused?.map(row => [row.slug, row.code]) }).toEqual({ inserted: 1, refused: [[OTHER, 'revision_conflict']] });+ expect(await claimB(engine)).toEqual([{ fact: CLAIM_B, source_markdown_slug: TARGET }]);+ expect(await engine.executeRaw('SELECT fact FROM facts WHERE fact=$1', [CLAIM_OTHER])).toEqual([]);+ }, { 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);@@ -223,11 +319,10 @@ for (const backend of testBackends()) {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(jobRefusal(first)).toMatchObject({ code: 'revision_conflict' });expect(calls.n).toBe(1);const requests = await entityRequests(engine);- expect(await handler(jobContext(loser, 1)).catch(error => error)).toBeInstanceOf(UnrecoverableError);+ expect(jobRefusal(await handler(jobContext(loser, 1)).catch(error => error))).toMatchObject({ code: 'revision_conflict' });expect(calls.n).toBe(1);expect(await entityRequests(engine)).toEqual(requests);expect(await claimB(engine)).toEqual([]);diff --git a/test/pathological/a-36-facts-batch-partial-refusal.test.ts b/test/pathological/a-36-facts-batch-partial-refusal.test.tsindex a322ac625e..7d0b382061 100644--- a/test/pathological/a-36-facts-batch-partial-refusal.test.ts+++ b/test/pathological/a-36-facts-batch-partial-refusal.test.ts@@ -28,6 +28,9 @@ import { disposePersistenceConsumer } from '../../src/core/persistence/service.timport { installFaultHook } from '../../src/core/persistence/fault-points.ts';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 { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';import { withEnv } from '../helpers/with-env.ts';import { requirePostgresTestDatabase, testBackends } from '../helpers/test-backends.ts';@@ -55,8 +58,8 @@ afterAll(() => { __setChatTransportForTests(null); resetGateway(); });type AtB = (engine: BrainEngine, sourceId: string) => Promise<void>;interface Source { sourceId: string; ctx: OperationContext; reachedB: () => number }-/** A managed, database-only source holding both entity pages and a bystander; `atB` runs once as B's first fact request is prepared. */-async function managedSource(engine: BrainEngine, atB: AtB, run: (s: Source) => Promise<void>) {+/** A managed, database-only source holding both entity pages and a bystander; `atB` runs once as B's first fact request reaches `at`. */+async function managedSource(engine: BrainEngine, atB: AtB, run: (s: Source) => Promise<void>, at: 'consumer:preparing' | 'consumer:prepared' = 'consumer:preparing') {const sourceId = `a36-${Math.random().toString(36).slice(2, 10)}`;const home = mkdtempSync(join(tmpdir(), 'gbrain-a36-'));let reached = 0;@@ -69,7 +72,7 @@ async function managedSource(engine: BrainEngine, atB: AtB, run: (s: Source) =>await engine.putPage(BYSTANDER, { type: 'note', title: 'Bystander', compiled_truth: 'An unrelated note.', timeline: '', frontmatter: {} }, { sourceId });await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');installFaultHook(async (point, detail) => {- if (point !== 'consumer:preparing' || detail.sourceId !== sourceId || detail.operation !== 'extract_facts' || reached) return;+ if (point !== at || detail.sourceId !== sourceId || detail.operation !== 'extract_facts' || reached) return;const [row] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM persistence_requests WHERE id=$1::uuid', [detail.writeId]);if (row?.slug !== B) return;reached++;@@ -91,6 +94,23 @@ async function managedSource(engine: BrainEngine, atB: AtB, run: (s: Source) =>const editB: AtB = (engine, sourceId) => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.putPage(B, { type: 'company', title: 'Acme Example',compiled_truth: 'Acme Example is a company. It moved offices.', timeline: '', frontmatter: {} }, { sourceId }), { requestId: null, principal: { kind: 'local_cli', id: 'a36-editor' } })).then(() => undefined);+/** B's fact request has read B; the edit lands as its fence edit is prepared (preparePageMutation's read sees the new revision). */+const editBDuringPreparation: AtB = async (engine, sourceId) => {+ const read = engine.readPageSnapshot;+ engine.readPageSnapshot = (async function (this: BrainEngine, slug: string, opts?: Parameters<typeof read>[1]) {+ if (this === engine && slug === B && /prepareInlineOrSegmentedMutation/.test(new Error().stack ?? '')) {+ delete (engine as { readPageSnapshot?: unknown }).readPageSnapshot;+ await editB(engine, sourceId);+ }+ return read.call(this, slug, opts);+ }) as typeof engine.readPageSnapshot;+};++/** Another write adds B's extracted claim after B's fact request decided it was new, before it publishes. */+const matchB: AtB = (engine, sourceId) => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.insertFact({ fact: 'Acme Example opened a second office.',+ kind: 'fact', entity_slug: B, visibility: 'world', source: 'test', confidence: 1, embedding: null }, { source_id: sourceId }),+ { requestId: null, principal: { kind: 'local_cli', id: 'a36-editor' } })).then(() => undefined);+/*** The fixture's pages are written before the brain turns managed, so the consumer's chunk projection catches them up* whenever it next runs; chunk counts are left out of the comparison here, content, liveness and links are not.@@ -165,6 +185,89 @@ for (const backend of testBackends()) {}, 180_000);}+ // 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+ // 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)+ for (const at of ['consumer:preparing', 'consumer:prepared'] as const) {+ test(`A-36 automatic (${at}): an automatic extraction re-admits the entity another write moved and publishes both entities' facts once`, async () => {+ await managedSource(engine, editB, async ({ sourceId, ctx, reachedB }) => {+ extractions = 0;+ const extract = () => runFactsPipeline('Synthetic meeting record about Alice Example and Acme Example.',+ { engine, operationContext: ctx, sourceId, sessionId: null, source: 'mcp:extract_facts', visibility: 'world', mode: 'inline' }) as Promise<{ inserted: number; refused?: unknown }>;+ const first = await expectUnitNotAborted(extract);+ expect(reachedB()).toBe(1);+ expect({ inserted: first.inserted, refused: first.refused }).toEqual({ inserted: 2, refused: undefined });+ 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());+ const replay = await expectUnitNotAborted(extract);+ expect({ inserted: replay.inserted, refused: replay.refused }).toEqual({ inserted: 2, refused: undefined });+ expect(extractions).toBe(1);+ expect(await requests(engine, sourceId)).toEqual(stored);+ expect(await factEntities(engine, sourceId)).toEqual([B, A].sort());+ }, at);+ }, 180_000);+ }++ // Value: protects=automatic extraction re-admits an entity refused because B moved mid-preparation or its dedup decision went stale,+ // and publishes once; fails_when=the follow-up does not recognise that refusal (e.g. a message missing from FACTS_ENTITY_MOVED_MESSAGES),+ // so B's refusal stands and is reported; why_new=the rows above move B only before or after preparation; seam=none; no_claim=the+ // mid-preparation move runs from a wrapped page read and the matching fact is a direct coordinated insert, not a concurrent+ // extraction (stub chat model). The mid-preparation row pins only the code: page preparation refuses before facts-prepare's own check.+ // The dedup row runs with a world default, so the re-admitted claim keeps world visibility and meets the matching fact+ // (re-admission narrows to the default: test/facts-entity-moved-7602.test.ts).+ const automaticRefusals: Array<{ name: string; at: 'consumer:preparing' | 'consumer:prepared'; atB: AtB; message?: string; inserted: number; worldDefault?: true }> = [+ { name: 'B moved while its fence edit was prepared', at: 'consumer:preparing', atB: editBDuringPreparation, inserted: 2 },+ { name: "a matching fact made B's deduplication stale", at: 'consumer:prepared', atB: matchB, message: FACTS_DEDUP_CHANGED_MESSAGE, inserted: 1, worldDefault: true },+ ];+ for (const { name, at, atB, message, inserted, worldDefault } of automaticRefusals) {+ test(`A-36 automatic (${name}): the refused entity is re-admitted and the extraction publishes once`, async () => {+ const prior = await engine.getConfig(FACTS_DEFAULT_VISIBILITY_KEY);+ if (worldDefault) await engine.setConfig(FACTS_DEFAULT_VISIBILITY_KEY, 'world');+ await managedSource(engine, atB, async ({ sourceId, ctx, reachedB }) => {+ extractions = 0;+ const extract = () => runFactsPipeline('Synthetic meeting record about Alice Example and Acme Example.',+ { engine, operationContext: ctx, sourceId, sessionId: null, source: 'mcp:extract_facts', visibility: 'world', mode: 'inline' }) as Promise<{ inserted: number; refused?: unknown }>;+ const first = await expectUnitNotAborted(extract).finally(() => { delete (engine as { readPageSnapshot?: unknown }).readPageSnapshot; });+ expect(reachedB()).toBe(1);+ const [refusal, ...more] = await engine.executeRaw<{ error_code: string; error_message: string }>(+ "SELECT error_code, error_message FROM persistence_requests WHERE source_id=$1 AND operation='extract_facts' AND slug=$2 AND state='conflict'", [sourceId, B]);+ expect({ code: refusal?.error_code, more: more.length }).toEqual({ code: 'revision_conflict', more: 0 });+ if (message) expect(refusal!.error_message).toBe(message);+ expect({ inserted: first.inserted, refused: first.refused }).toEqual({ inserted, refused: undefined });+ 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());+ const replay = await expectUnitNotAborted(extract);+ expect({ inserted: replay.inserted, refused: replay.refused }).toEqual({ inserted, refused: undefined });+ expect(extractions).toBe(1);+ expect(await requests(engine, sourceId)).toEqual(stored);+ }, at).finally(async () => {+ if (!worldDefault) return;+ if (prior === null) await engine.unsetConfig(FACTS_DEFAULT_VISIBILITY_KEY);+ else await engine.setConfig(FACTS_DEFAULT_VISIBILITY_KEY, prior);+ });+ }, 180_000);+ }++ // Value: protects=an extraction that carries its caller's request id keeps the moved entity's refusal (the request id is the+ // caller's one idempotent unit); fails_when=the backstop sets entityMoveRetry for a caller request id; why_new=the automatic rows+ // pass no request id and the explicit row calls publishManagedEntityFacts; seam=none; no_claim=stub chat model+ test('A-36 explicit request id: an extraction with a caller request id keeps the moved entity refused', async () => {+ await managedSource(engine, editB, async ({ sourceId, ctx, reachedB }) => {+ extractions = 0;+ const first = await expectUnitNotAborted(() => runFactsPipeline('Synthetic meeting record about Alice Example and Acme Example.',+ { engine, operationContext: ctx, sourceId, sessionId: null, source: 'mcp:extract_facts', visibility: 'world', mode: 'inline', requestId: randomUUID() }) as+ Promise<{ inserted: number; refused?: Array<{ slug: string; code: string }> }>);+ expect(reachedB()).toBe(1);+ expect({ inserted: first.inserted, refused: first.refused?.map(row => [row.slug, row.code]) }).toEqual({ inserted: 1, refused: [[B, 'revision_conflict']] });+ expect((await requests(engine, sourceId)).map(row => [row.slug, row.state])).toEqual([[A, 'committed'], [B, 'conflict'], [COMPLETE, 'conflict']]);+ expect(extractions).toBe(1);+ });+ }, 180_000);+test('A-36 explicit: a fact writer that names its entity still refuses when that entity changed after admission', async () => {await managedSource(engine, editB, async ({ sourceId, reachedB }) => {const facts = [{ fact: 'Acme Example hired a new CFO.', kind: 'fact', source: 'test', notability: 'high', sessionId: null, visibility: 'world', confidence: 1 }];