Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): managed automatic extraction skips a forgotten claim instead of refusing the entity group (#6506)
garrytanc6148108d86e
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex a254308058..6315cca10f 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -15,7 +15,7 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.-- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`.+- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. `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/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.Atom completion admits replacement and revision-pinned stale-atom deletion children together.Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex b8c48058fd..58e4e29d92 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -126,6 +126,23 @@ and [isolated local backup guide](in-agent-setup.md#6-back-up-the-complete-localthe same source and visibility, and its row is struck in the page's Markdown.The text stays in the row, the file, page history and backups.+Automatic extraction (sync import, `put_page`, `extract_facts`, the sweep)+skips a candidate whose exact claim was forgotten in that source and visibility+and still saves the other facts it found about the same entity; the entity and+completion write receipts and the extraction result count the skips as+`withdrawn_skipped`, and a group of only forgotten claims completes with nothing+inserted. Explicitly remembering the forgotten claim still refuses with+`fact_withdrawn`, and a purge tombstone still refuses the whole write with+`purged_content`. A claim forgotten after an extraction's facts were prepared+refuses that entity's write with `revision_conflict` and a detail naming the+withdrawal; nothing is published. An extraction keyed by its input alone (sync+import or the sweep, which have no request id) recovers on its next run from+such a refusal, and from a batch an older release refused for a forgotten+claim, by re-admitting the retained facts without another model call (at most+three follow-ups per batch, each visible as its own write receipt; the refused+receipts stay as they were). An extraction admitted under a request id replays+its receipt; give it a new `request_id` to extract again.+`gbrain forget <id> --purge` **purges**: an owner-only command on the brainhost that removes the claim from the live stores gbrain controls and returns areceipt. It is a separate operation (`purge_fact`), never a mode of thediff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 215c8b656f..3ff6430f39 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -473,6 +473,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// #6529 (GBRA-79). `since` is provisional: stamped at the current VERSION because a `since` past VERSION discloses on every fresh brain (goldens, notice tests); the integrator restamps both rows to the release (0.60.182.0 placeholder) at the merge slot.{ since: '0.60.182.0', text: 'With `GBRAIN_EMBEDDING_MULTIMODAL=true`, managed sync now imports image files through the coordinated image importer (OCR text, image vector and `source_path` at import) instead of holding them as `managed_image_sync_unsupported`; existing image holds are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. With it off, images stay held as before.' },{ since: '0.60.182.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0); the folded sweep only reports fileless pages. Doctor gains `image_embedding_coverage`.' },+ // wave 16 (GBRA-79)+ { since: '0.60.183.0', text: 'On a managed brain, automatic fact extraction (sync import, `put_page`, `extract_facts`, the sweep) now skips a candidate whose exact claim was forgotten in that source and visibility and publishes the other facts of the same entity, counting the skips as `withdrawn_skipped` on the entity and completion write receipts and the extraction result; before, one forgotten claim refused the entity\'s whole group with `fact_withdrawn`. Explicitly remembering the forgotten claim still refuses, and a purge tombstone still refuses the whole write. A claim forgotten after the facts were prepared refuses that entity\'s write with `revision_conflict` and a detail naming the withdrawal, publishing nothing. An extraction keyed by its input alone (no request id) recovers from such a refusal, and from a batch an older release refused for a forgotten claim, on its next run: the retained facts are re-admitted as a follow-up batch with no model call, at most three times per batch, and the refused receipts stay as they were. An extraction admitted under a request id replays its receipt; a new request_id extracts again.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex faa6de8170..f11784c728 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -173,6 +173,8 @@ export type FactsBackstopResult =fence_refused?: number;/** #6333 shadow (never a drop): facts the same-page rewording rule would have treated as duplicates. */would_dedup_same_page?: number;+ /** #6506: candidates skipped because the exact claim was forgotten in this source and visibility. */+ withdrawn_skipped?: number;};/** One pipeline run's input: the turn text plus its page provenance and observation date. */@@ -543,6 +545,8 @@ export async function runFactsPipeline(fence_refused?: number;/** #6333 shadow (never a drop): facts the same-page rewording rule would have treated as duplicates. */would_dedup_same_page?: number;+ /** #6506: candidates skipped because the exact claim was forgotten in this source and visibility. */+ withdrawn_skipped?: number;}> {return runPipelineWithBody({turnText,@@ -564,7 +568,7 @@ async function runPipeline(parsedPage: ParsedPageInput,ctx: FactsBackstopCtx,abortSignal?: AbortSignal,-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number }> {+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number; withdrawn_skipped?: number }> {return runPipelineWithBody({turnText: parsedPage.compiled_truth,@@ -611,7 +615,7 @@ async function runPipelineWithBody(input: PipelineInput,ctx: FactsBackstopCtx,abortSignal?: AbortSignal,-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number }> {+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number; withdrawn_skipped?: number }> {// #4210: outside a withBudgetTracker scope (extract_facts op, sweep,// put_page backstop, checkpoint harvest, file/code import) the gateway's// chat/embed calls were budget no-ops — real spend, zero audit rows.@@ -633,6 +637,14 @@ async function runPipelineWithBody(return runPipelineBodyInner(input, ctx, abortSignal);}+/** The unmanaged pipeline's running counters; `withdrawn_skipped` rides along only once a forgotten claim was skipped. */+interface PipelineCounts { inserted: number; duplicate: number; superseded: number; fact_ids: number[]; withdrawn_skipped?: number }++/** #6506: the unmanaged pipeline counts a skipped forgotten claim the way the managed publisher does (B-10 kept it silent). */+function countWithdrawnSkip(counts: PipelineCounts): void {+ counts.withdrawn_skipped = (counts.withdrawn_skipped ?? 0) + 1;+}+/*** #5575 B3: the unmanaged pipeline's gated writers. Every row passes the write* gate at the extraction's declared tier (ENG-18); the extractor rewrites@@ -674,7 +686,7 @@ async function runPipelineBodyInner(input: PipelineInput,ctx: FactsBackstopCtx,abortSignal?: AbortSignal,-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number }> {+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number; withdrawn_skipped?: number }> {const { extractFactsFromTurnWithOutcome, FactsExtractionError } = await import('./extract.ts');const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');const { cosineSimilarity } = await import('./classify.ts');@@ -756,9 +768,9 @@ async function runPipelineBodyInner(// #5888: one exact-duplicate check for the capture lanes, before either writer.const { facts, dropped } = await dedupCapturedFacts(ctx, await inferMissingSubjects(ctx, outcome.facts, visibility, input.pageSlug, managed), visibility, resolveEntitySlugWithSource);if (!managed) await assertAmbientCaptureAdmissible(ctx.engine, ctx.source);- if (managed) return withCaptureDrops(dropped, facts.length || !dropped.length ? await publishManagedFacts(ctx.engine, managed, ctx, facts, visibility, input.pageSlug) : null);+ if (managed) return withCaptureDrops(dropped, facts.length || !dropped.length ? await publishManagedFacts(ctx.engine, managed, ctx, facts, visibility, input.pageSlug, { withdrawn: 'skip' }) : null);- const counts = { inserted: 0, duplicate: dropped.length, superseded: 0, fact_ids: [...dropped] };+ const counts: PipelineCounts = { inserted: 0, duplicate: dropped.length, superseded: 0, fact_ids: [...dropped] };let wouldDedupSamePageCount = 0;const writer = await derivedFactWriter(ctx, input, derivation, counts);const { insertDerivedFact, write_gate } = writer;@@ -790,7 +802,7 @@ async function runPipelineBodyInner(// B-10: a withdrawn claim for this entity is never re-written; the// fence writer rechecks under its page lock.- if (await isFactWithdrawn(ctx.engine, ctx.sourceId, visibility, f.fact, resolvedSlug)) continue;+ if (await isFactWithdrawn(ctx.engine, ctx.sourceId, visibility, f.fact, resolvedSlug)) { countWithdrawnSkip(counts); continue; }// Dedup against DB candidates (correct per Codex Q7: fence rows// have no embeddings; FS lock + sync invariant means DB == fencediff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex fcc0f94929..8ac30f11a8 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -191,6 +191,7 @@ const extract_facts: Operation = {superseded: r.superseded,fact_ids: r.fact_ids,...(r.write_requests ? { write_requests: r.write_requests } : {}),+ ...(r.withdrawn_skipped ? { withdrawn_skipped: r.withdrawn_skipped } : {}),...hintAccounting,};},diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.tsindex 174e120325..c438880fd6 100644--- a/src/core/persistence/facts-maintenance.ts+++ b/src/core/persistence/facts-maintenance.ts@@ -14,6 +14,7 @@ import { resolveEntitySlugWithSource } from '../entities/resolve.ts';import { appendContextNote, type InferredVia } from '../facts/subject-infer.ts';import { inferenceNote } from '../facts/subject-infer-write.ts';import { resolveDefaultVisibility } from '../facts/visibility.ts';+import { FACT_WITHDRAWN_MESSAGE, isFactWithdrawn, withdrawnFromDetail } from '../facts/withdrawal.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from './authority.ts';@@ -35,6 +36,8 @@ import type { TaintInput, WriteTrust } from '../trust/tier.ts';export interface ManagedFactsResult {inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; write_requests: WriteReceipt[];+ /** #6506: candidates the automatic extraction skipped because the exact claim was forgotten in this source and visibility. */+ withdrawn_skipped?: number;}export interface ManagedFactOrigin { slug: string; pageId: number; revision: string; }export type FrozenExtractedFact = Omit<NewFact, 'embedding' | 'valid_from' | 'valid_until' | 'expired_at'> & {@@ -48,6 +51,13 @@ export interface ManagedFactIntent extends Record<string, unknown> {expected_revision?: string; facts?: FrozenExtractedFact[]; children?: string[];/** Direct single-fact writes keep writeSingleFact's supersession rule. */supersede?: true;+ /**+ * #6506: automatic extraction only. A candidate whose exact claim was forgotten in this source and visibility is+ * skipped and counted (`withdrawn_skipped`) instead of refusing the entity's whole group; a purge tombstone still+ * refuses. Explicit writers (remember, the fence writers) never set it and keep the refusal. Frozen in the stored+ * intent, so a replay and a resumed batch decide exactly as the admission did.+ */+ withdrawn?: 'skip';/*** writeSingleFact only: a `memory/unattributed` row keeps the resolver's* fallback slug as its entity (no row number), so dedup stays per entity.@@ -66,6 +76,8 @@ export interface ManagedFactsSession {embedding?: FactEmbeddingSignature | null;/** #6048: the batch is keyed by its input alone and the caller asked to re-admit facts the canonical file check refused. */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;/** #6091: set when the facts come from an ambient capture lane. */captureSource?: string;derivation?: DerivationDeclaration;@@ -259,6 +271,7 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,batchKey, inputDigest, origin, originalRequestId: ctx.persistenceRequestId ?? null,completionRequestId: ctx.requestId ? requireUuid(ctx.requestId) : managedFactRequestId(batchKey, '__managed_facts_complete__'),fileRefusalRetry: ctx.reAdmitFileRefusals === true && seed === inputDigest,+ inputKeyed: seed === inputDigest,...(captureGateLaneForSource(ctx.source) ? { captureSource: ctx.source } : {}),...(derivation ? { derivation: declareDerivation(derivation.trust, derivation.inputs) } : {}) };const prior = await getWriteRequest(engine, authority.principal, session.completionRequestId);@@ -282,6 +295,7 @@ async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSesresult.duplicate += Number(out.duplicate ?? 0);result.superseded += Number(out.superseded ?? 0);result.fact_ids.push(...(out.fact_ids as number[] ?? []));+ if (out.withdrawn_skipped) result.withdrawn_skipped = (result.withdrawn_skipped ?? 0) + Number(out.withdrawn_skipped);if (out.inserted && out.fenced) result.entity_slugs.push(row.slug);}}@@ -290,7 +304,9 @@ async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSesexport async function resumeManagedFacts(engine: BrainEngine, session: ManagedFactsSession): Promise<ManagedFactsResult | null> {const stored = await storedBatch(engine, session);- return stored && collectManagedFacts(engine, session, session.fileRefusalRetry ? await followFileRefusals(engine, session, stored) : stored);+ 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);}/** Every request journaled under the session's batch key, once its completion receipt validates; null when nothing was accepted. */@@ -320,18 +336,49 @@ const isEntityRequest = (row: WriteRequest) => (row.intent?.kind ?? row.outcome?* all requests of the latest one, for collectManagedFacts to report.*/async function followFileRefusals(engine: BrainEngine, session: ManagedFactsSession, stored: WriteRequest[]): Promise<WriteRequest[]> {+ return followRefusals(engine, session, stored, 'file-refusal-retry', row => row.error_code === 'source_changed', readmitRefusedFacts);+}++/**+ * #6506 (UC1): the same walk for an input-keyed batch whose entity request was+ * refused because a candidate's exact claim had been forgotten. Older batches+ * were admitted before automatic extraction skipped withdrawn candidates, so+ * the stored refusal (`invalid_params` with the fact_withdrawn message, or the+ * typed `error_detail.origin = 'withdrawal'`, which a withdrawal committed+ * between preparation and locked validation also leaves) would replay on every+ * run of the unchanged input. The follow-up re-admits the retained facts under+ * `withdrawn: 'skip'`; no extraction runs again and the historical receipts+ * stay as they were.+ */+async function followWithdrawalRefusals(engine: BrainEngine, session: ManagedFactsSession, stored: WriteRequest[]): Promise<WriteRequest[]> {+ return followRefusals(engine, session, stored, 'withdrawal-retry', withdrawalRefusal, readmitWithdrawnFacts);+}++function withdrawalRefusal(row: WriteRequest): boolean {+ return withdrawnFromDetail(row.error_detail) !== undefined || row.error_code === 'invalid_params' && row.error_message === FACT_WITHDRAWN_MESSAGE;+}++/**+ * 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.+ */+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[]> {const carried: WriteRequest[] = [];let latest = stored;for (let retry = 1; retry <= MAX_FILE_REFUSAL_RETRIES; retry++) {if (latest.some(row => !isTerminal(row))) break;- const refused = latest.filter(row => isEntityRequest(row) && row.state !== 'committed');- const retained = refused.map(row => row.intent as ManagedFactIntent | null);- if (!refused.length || refused.some((row, i) => row.error_code !== 'source_changed' || !retained[i]?.facts?.length+ 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 followUpKey = digest([session.batchKey, 'file-refusal-retry', retry]);+ 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 readmitRefusedFacts(engine, followUp, refused);+ 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;@@ -374,9 +421,37 @@ async function readmitRefusedFacts(engine: BrainEngine, followUp: ManagedFactsSereturn admitManagedFactsBatch(engine, followUp, entities, entities.some(entity => entity.intent.facts!.some(fact => fact.embedding != null)));}+/**+ * #6506: admit the refused requests' retained facts as `followUp` with+ * `withdrawn: 'skip'`. Each refused request must still be authorized under+ * its stored authority and its page under the current writer grant; facts+ * target the entity page's current revision (the retained origin revision is+ * re-checked at preparation) and are never wider than the current default+ * visibility. No extraction runs again.+ */+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 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 });+ const { expected_revision: _refusedRevision, facts, ...kept } = row.intent as ManagedFactIntent;+ if (!page && (row.page_id !== null || facts!.some(fact => fact.entity_slug === row.slug))) return null;+ entities.push({ slug: row.slug, pageId: page?.page.id ?? null, intent: { ...kept, batchKey: followUp.batchKey, withdrawn: 'skip',+ ...(page ? { expected_revision: page.revision } : {}), facts: await Promise.all(facts!.map(narrowed)) } });+ }+ return admitManagedFactsBatch(engine, followUp, 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 } = {}): Promise<ManagedFactsResult> {+ options: { supersede?: boolean; explicitContext?: boolean; attributeFallback?: boolean; withdrawn?: 'skip' } = {}): Promise<ManagedFactsResult> {const embedded = facts.some(fact => fact.embedding !== null && fact.embedding !== undefined);if (embedded) await assertManagedFactsEmbedding(engine, session.config, session.embedding);const sourceId = session.authority.sourceId;@@ -408,6 +483,7 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedFinputDigest: session.inputDigest, origin: session.origin, originalRequestId: session.originalRequestId,embedding: session.embedding ?? null, ...(options.supersede ? { supersede: true as const } : {}),...(options.attributeFallback ? { attribute_fallback: true as const } : {}),+ ...(options.withdrawn === 'skip' ? { withdrawn: 'skip' as const } : {}),...(session.captureSource ? { capture_source: session.captureSource } : {}),...(session.derivation ? { derivation: session.derivation } : {}),...(snapshot ? { expected_revision: snapshot.revision } : {}), facts: group } });diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex 812ddb3b9f..96a604b03a 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -7,7 +7,8 @@ import type { Action } from '../agent-output.ts';import type { RegistryCode } from '../error-registry.ts';import { parseFactsFence, upsertFactRow, formatFenceDate, renderFactsTable, replaceOrInsertFactsFence } from '../facts-fence.ts';import { serializePageToMarkdown } from '../markdown.ts';-import { assertFactNotWithdrawn, decideSingleFact, type FactCandidate } from '../facts/single-prepare.ts';+import { assertFactNotWithdrawn, decideSingleFact, factWithdrawnRefusal, type FactCandidate } from '../facts/single-prepare.ts';+import { assertFactNotPurged, isFactWithdrawn } from '../facts/withdrawal.ts';import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';import { authorizeWrite } from './authority.ts';import { authorizePageVisibility } from './page-visibility.ts';@@ -116,14 +117,16 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writconst additionalPageKeys = p.origin ? [{ sourceId: row.source_id, slug: p.origin.slug }] : [];if (p.kind === 'managed_facts_complete') return { observedRevision: null, noop: true, additionalPageKeys, validate, apply: async tx => {const children = p.children ?? [];- const done = await tx.executeRaw<{ outcome: { inserted?: number; duplicate?: number; fact_ids?: number[] } }>(`SELECT outcome FROM persistence_requests WHERE id=ANY($1::uuid[]) AND source_incarnation=$2::uuid+ const done = await tx.executeRaw<{ outcome: { inserted?: number; duplicate?: number; fact_ids?: number[]; withdrawn_skipped?: number } }>(`SELECT outcome FROM persistence_requests WHERE id=ANY($1::uuid[]) AND source_incarnation=$2::uuidAND state='committed' AND COALESCE(intent->>'batchKey',outcome->>'batch_key')=$3 AND operation='extract_facts'`, [children, row.source_incarnation, p.batchKey]);if (done.length !== children.length) throw factsRefusal('revision_conflict', 'Some extracted facts have not committed.', row,`${children.length - done.length} of the batch's ${children.length} per-entity fact requests have not committed, so the extraction cannot be recorded as complete.`,'once the entity requests are final, run extract_facts again for the same turn with a new request_id only if facts are still missing.');+ const withdrawnSkipped = done.reduce((sum, item) => sum + Number(item.outcome.withdrawn_skipped ?? 0), 0);return { status: 'completed', entity_requests: children.length, kind: p.kind, batch_key: p.batchKey, input_digest: p.inputDigest,inserted: done.reduce((sum, item) => sum + Number(item.outcome.inserted ?? 0), 0),duplicate: done.reduce((sum, item) => sum + Number(item.outcome.duplicate ?? 0), 0),+ ...(withdrawnSkipped ? { withdrawn_skipped: withdrawnSkipped } : {}),fact_ids: done.flatMap(item => item.outcome.fact_ids ?? []) };} };const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });@@ -152,8 +155,14 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writconst taint = await managedFactsTrust(engine, p);const gateCfg = taint ? await derivedGateConfig(engine) : null;const blocked: GatedRowDecision[] = [];+ // #6506: automatic extraction skips a forgotten claim and keeps the rest of the group; a purge tombstone still+ // refuses the group, as it does for every writer; explicit writers (no flag) refuse the forgotten claim.+ let withdrawnSkipped = 0;for (const fact of facts) {- await assertFactNotWithdrawn(engine, row.source_id, fact);+ if (p.withdrawn === 'skip') {+ await assertFactNotPurged(engine, row.source_id, fact);+ if (await isFactWithdrawn(engine, row.source_id, fact.visibility, fact.fact, fact.entity_slug)) { withdrawnSkipped++; continue; }+ } else await assertFactNotWithdrawn(engine, row.source_id, fact);const key = JSON.stringify([fact.fact, fact.visibility, fact.entity_slug]);const earlier = (seen.get(key) ?? []).find(i => attributionCompatible(entries[i].fact.attributed_to, fact.attributed_to));if (earlier !== undefined) { entries.push({ fact, duplicateId: null, duplicateOf: earlier }); continue; }@@ -204,14 +213,26 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ...(taint ? { trust: taint.trust } : {}),additionalPageKeys, validate: async tx => {await validate(tx, true);- await page?.validate?.(tx);for (const entry of entries) {- await assertFactNotWithdrawn(tx, row.source_id, entry.fact);+ // #6506 (R15): under `withdrawn: 'skip'` a claim forgotten between preparation and this locked validation is a+ // terminal revision_conflict whose detail names the withdrawal (the fence body is already rendered, and an+ // extract_facts request is never re-prepared); an input-keyed batch recovers through its follow-up batch.+ if (p.withdrawn !== 'skip') await assertFactNotWithdrawn(tx, row.source_id, entry.fact);+ else {+ await assertFactNotPurged(tx, row.source_id, entry.fact);+ if (await isFactWithdrawn(tx, row.source_id, entry.fact.visibility, entry.fact.fact, entry.fact.entity_slug)) {+ const refusal = factsRefusal('revision_conflict', 'A claim was forgotten after these facts were prepared.', row,+ `A claim in this group was forgotten in source ${row.source_id} after the facts were prepared, so none of these facts were published; the forgotten claim stays withdrawn.`);+ refusal.withdrawn = (await factWithdrawnRefusal(tx, row.source_id, entry.fact)).withdrawn;+ throw refusal;+ }+ }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,`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);}, apply: async tx => {if (page) await withPageTierKept(tx, { sourceId: row.source_id, slug: row.slug }, () => page!.apply(tx));const ids: number[] = [];@@ -238,6 +259,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writconst write_gate = emptyGateTally();for (const gate of blocked) await applyGateDecision(tx, gate, { table: 'facts', sourceId: row.source_id }, async () => null, write_gate);return { status: 'completed', inserted, duplicate: entries.length - inserted, superseded, fact_ids: ids, ...(blocked.length ? { write_gate } : {}),+ ...(withdrawnSkipped ? { withdrawn_skipped: withdrawnSkipped } : {}),fenced: page !== undefined, kind: p.kind, batch_key: p.batchKey, input_digest: p.inputDigest,...(page && target?.fixes.length ? { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: target.fixes,writer: row.principal_kind, path: snapshot?.page.source_path ?? null, remote: row.authority.remote }) } : {}) };diff --git a/test/managed-facts-withdrawal-recovery-6506.test.ts b/test/managed-facts-withdrawal-recovery-6506.test.tsnew file mode 100644index 0000000000..36a06abfe3--- /dev/null+++ b/test/managed-facts-withdrawal-recovery-6506.test.ts@@ -0,0 +1,312 @@+/**+ * #6506 (UC1): a managed facts batch keyed by its input (sync import of an+ * unchanged page: no request id) whose entity request was refused for a+ * withdrawn claim replayed that stored refusal on every later run, with zero+ * model calls and zero facts, forever.+ *+ * 1. Protects: a stored batch whose entity request failed on a withdrawal+ * (the pre-detail receipt shape `invalid_params` + the fact_withdrawn+ * message, and the typed `error_detail.origin = 'withdrawal'` shape) is+ * followed by a batch under `digest([batchKey, 'withdrawal-retry', n])`+ * that re-admits the retained facts with `withdrawn: 'skip'`; the novel+ * claim publishes once, the withdrawn claim stays absent, no model call+ * runs, the historical receipts stay byte-identical, the completion is+ * honest; at most three follow-ups, then the refusal stands; an origin page+ * edited in between refuses and publishes nothing; a batch admitted under a+ * request id replays its receipt instead.+ * 2. Fails when: the refusal replays forever (master), a follow-up re-runs the+ * model, a refusal of another kind or without retained facts is followed,+ * the cap is exceeded, or the historical receipts change.+ * 3. test/managed-facts-withdrawn-skip-6506.test.ts covers new batches;+ * test/managed-sweep-refused-window-retry.test.ts covers the file-check+ * follow-up route the recovery mirrors.+ * 4. Seams: gateway test transports and the persistence fault hook.+ *+ * Runs on PGLite; also on Postgres when DATABASE_URL is set (testBackends).+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';+import { runFactsBackstop, type FactsBackstopCtx } from '../src/core/facts/backstop.ts';+import { FACT_WITHDRAWN_MESSAGE, recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';+import { prepareManagedFactsSession, type FrozenExtractedFact, type ManagedFactIntent } from '../src/core/persistence/facts-maintenance.ts';+import { admitWriteInTransaction } from '../src/core/persistence/journal.ts';+import { digest } from '../src/core/persistence/digest.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';+import { waitFor } from './helpers/wait-for.ts';++const ENTITY = 'people/alice-example';+const ORIGIN = 'meetings/synthetic-workshop';+const COMPLETE = '__managed_facts_complete__';+const WITHDRAWN = 'Alice-example agreed to provide twelve sample kits for the synthetic workshop.';+const NOVEL = 'Alice-example will verify the synthetic room booking in November.';+const BODY = `# Synthetic workshop\n\nNotes from the synthetic workshop planning call, kept for the regression. ${WITHDRAWN} ${NOVEL}\n`;++const engines: BrainEngine[] = [];+const dbDir = mkdtempSync(join(tmpdir(), 'gbrain-withdrawal-recovery-db-'));+let closePostgres: (() => Promise<void>) | undefined;+let calls = 0;++beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });+ __setChatTransportForTests(async (): Promise<ChatResult> => {+ calls++;+ return { text: JSON.stringify({ facts: [WITHDRAWN, NOVEL].map(fact => ({ fact, entity: ENTITY, kind: 'fact', confidence: 1, notability: 'high' })) }),+ blocks: [], stopReason: 'end', usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'test:stub', providerId: 'test' };+ });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => Array(1536).fill(0.01)) })) as never);+ for (const backend of testBackends()) {+ if (backend === 'pglite') {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dbDir });+ await engine.initSchema();+ engines.push(engine);+ } else {+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(isolated.engine);+ closePostgres = isolated.close;+ }+ }+}, 120_000);++afterEach(() => { installFaultHook(undefined); });++afterAll(async () => {+ __setChatTransportForTests(null);+ __setEmbedTransportForTests(null);+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ resetGateway();+ rmSync(dbDir, { recursive: true, force: true });+});++/**+ * A managed, database-only source with an entity page, an origin page whose body+ * the sync import extracts, and the withdrawn claim already forgotten. The+ * extraction runs like sync's post-import hook: inline, keyed by its input.+ */+async function recoverySource(engine: BrainEngine) {+ const sourceId = `w6506r-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ await engine.putPage(ENTITY, { type: 'person', title: 'Alice Example', compiled_truth: '# Alice Example\n\nFictional person for the regression.\n' }, { sourceId });+ await engine.putPage(ORIGIN, { type: 'meeting', title: 'Synthetic workshop', compiled_truth: BODY }, { sourceId });+ const saved = await engine.insertFact({ fact: WITHDRAWN, entity_slug: ENTITY, visibility: 'world', kind: 'fact', source: 'fixture' }, { source_id: sourceId });+ expect((await recordFactWithdrawal(engine, saved.id, sourceId, false, { semanticReview: false })).withdrawn).toBe(true);+ await engine.setConfig('facts.default_visibility', 'world');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const ctx: FactsBackstopCtx = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId, sessionId: `sync:${ORIGIN}`,+ source: 'sync:import', mode: 'inline', notabilityFilter: 'high-only', remote: false, visibility: 'world' };+ const page = () => engine.getPage(ORIGIN, { sourceId }).then(p => p!);+ const run = async (as: FactsBackstopCtx = ctx) => {+ const parsed = await page();+ return runFactsBackstop({ slug: ORIGIN, type: parsed.type, compiled_truth: parsed.compiled_truth, frontmatter: parsed.frontmatter ?? {} }, as) as+ Promise<{ inserted: number; duplicate: number; fact_ids: number[]; withdrawn_skipped?: number; write_requests?: Array<{ request_id: string; state: string }> }>;+ };+ const quiet = () => waitFor(async () => (await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering')`, [sourceId]))[0].n === 0,+ { timeoutMs: 30_000, label: 'fact requests settled' });+ const journal = async () => {+ await quiet();+ return engine.executeRaw<{ id: string; slug: string; state: string; error_code: string | null; error_message: string | null; error_detail: unknown;+ batch_key: string; flag: string | null; outcome: Record<string, unknown> | null }>(+ `SELECT id,slug,state,error_code,error_message,error_detail,COALESCE(intent->>'batchKey',outcome->>'batch_key') AS batch_key,+ intent->>'withdrawn' AS flag,outcome FROM persistence_requests WHERE source_id=$1 AND operation='extract_facts' ORDER BY sequence`, [sourceId]);+ };+ const summary = async () => (await journal()).map(row => `${row.slug}:${row.state}${row.error_code ? `:${row.error_code}` : ''}${row.flag ? `:${row.flag}` : ''}`);+ const receipts = (ids: string[]) => engine.executeRaw<{ row: string }>(+ `SELECT to_jsonb(r)::text AS row FROM persistence_requests r WHERE id = ANY($1::uuid[]) ORDER BY sequence`, [ids]).then(rows => rows.map(row => row.row));+ const active = () => engine.executeRaw<{ fact: string }>('SELECT fact FROM facts WHERE source_id=$1 AND expired_at IS NULL ORDER BY id', [sourceId]).then(rows => rows.map(row => row.fact));+ const activeWithVisibility = () => engine.executeRaw<{ fact: string; visibility: string }>('SELECT fact,visibility FROM facts WHERE source_id=$1 AND expired_at IS NULL ORDER BY id', [sourceId])+ .then(rows => rows.map(row => `${row.fact}:${row.visibility}`));+ const entityFence = async () => (await engine.getPage(ENTITY, { sourceId }))!.compiled_truth;+ /**+ * The batch master left behind: the input-keyed session's batch key and completion id,+ * entity and completion requests admitted with the retained facts and no skip flag.+ */+ const seedLegacyBatch = async (as: FactsBackstopCtx = ctx) => {+ const session = (await prepareManagedFactsSession(as, { turnText: BODY, pageSlug: ORIGIN }))!;+ const origin = await engine.readPageSnapshot(ORIGIN, { sourceId });+ const entity = await engine.readPageSnapshot(ENTITY, { sourceId });+ const facts: FrozenExtractedFact[] = [WITHDRAWN, NOVEL].map(fact => ({ fact, entity_slug: ENTITY, visibility: 'world', kind: 'fact', source: 'sync:import',+ notability: 'high', confidence: 1, context: ORIGIN, source_session: `sync:${ORIGIN}`, embedding: null, valid_from: new Date().toISOString(), valid_until: null }));+ const shared = { batchKey: session.batchKey, inputDigest: session.inputDigest, origin: { slug: ORIGIN, pageId: origin!.page.id, revision: origin!.revision }, originalRequestId: null };+ const admission = { principal: session.authority.principal, authority: session.authority, operation: 'extract_facts', sourceId, sourceIncarnation: session.authority.sourceIncarnation };+ await engine.transaction(async tx => {+ const entityIntent: ManagedFactIntent = { kind: 'managed_facts_entity', ...shared, embedding: null, expected_revision: entity!.revision, facts };+ const row = await admitWriteInTransaction(tx, { ...admission, requestId: randomUUID(), slug: ENTITY, pageId: entity!.page.id, callerIntent: entityIntent, intent: entityIntent });+ const completion: ManagedFactIntent = { kind: 'managed_facts_complete', ...shared, children: [row.id] };+ await admitWriteInTransaction(tx, { ...admission, requestId: session.completionRequestId, slug: COMPLETE, pageId: null, callerIntent: completion, intent: completion });+ });+ return session;+ };+ return { sourceId, ctx, run, journal, summary, receipts, active, activeWithVisibility, entityFence, seedLegacyBatch, quiet };+}++async function onEachEngine(label: string, body: (engine: BrainEngine) => Promise<void>) {+ for (const engine of engines) {+ const home = mkdtempSync(join(tmpdir(), `gbrain-withdrawal-recovery-${label}-`));+ calls = 0;+ try {+ await withEnv({ GBRAIN_HOME: home }, () => body(engine));+ } finally {+ installFaultHook(undefined);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(home, { recursive: true, force: true });+ }+ }+}++const legacyRefusal = [`${ENTITY}:failed:invalid_params`, `${COMPLETE}:conflict:revision_conflict`];++describe('a stored facts batch refused for a withdrawn claim (#6506, UC1)', () => {+ for (const shape of ['typed detail', 'pre-detail receipt'] as const) {+ test(`${shape}: the next run follows up with the retained facts, skipping the withdrawn claim, with no model call`, async () => {+ await onEachEngine(shape === 'typed detail' ? 'typed' : 'legacy', async engine => {+ const s = await recoverySource(engine);+ const session = await s.seedLegacyBatch();+ await expect(s.run()).rejects.toMatchObject({ code: 'invalid_params', message: FACT_WITHDRAWN_MESSAGE });+ expect(await s.summary()).toEqual(legacyRefusal);+ expect(calls).toBe(0);+ if (shape === 'pre-detail receipt') await engine.executeRaw('UPDATE persistence_requests SET error_detail=NULL WHERE source_id=$1 AND slug=$2', [s.sourceId, ENTITY]);+ const legacy = await s.journal();+ expect(legacy[0].error_message).toBe(FACT_WITHDRAWN_MESSAGE);+ expect(legacy[0].error_detail).toEqual(shape === 'typed detail' ? expect.objectContaining({ origin: 'withdrawal' }) : null);+ const legacyRows = await s.receipts(legacy.map(row => row.id));+ const fenceBefore = await s.entityFence();++ const recovered = await s.run();+ expect(recovered).toMatchObject({ inserted: 1, duplicate: 0, withdrawn_skipped: 1 });+ expect(recovered.fact_ids).toHaveLength(1);+ expect(await s.active()).toEqual([NOVEL]);+ expect(await s.entityFence()).toContain(NOVEL);+ expect(await s.entityFence()).not.toBe(fenceBefore);+ expect(calls).toBe(0);+ const after = await s.journal();+ expect(after.map(row => `${row.slug}:${row.state}${row.error_code ? `:${row.error_code}` : ''}${row.flag ? `:${row.flag}` : ''}`))+ .toEqual([...legacyRefusal, `${ENTITY}:committed:skip`, `${COMPLETE}:committed`]);+ expect(await s.receipts(legacy.map(row => row.id))).toEqual(legacyRows);+ const followUpKey = digest([session.batchKey, 'withdrawal-retry', 1]);+ expect(after.slice(2).map(row => row.batch_key)).toEqual([followUpKey, followUpKey]);+ expect(after[2].outcome).toMatchObject({ inserted: 1, withdrawn_skipped: 1 });+ expect(after[3].outcome).toMatchObject({ status: 'completed', inserted: 1, withdrawn_skipped: 1, entity_requests: 1 });++ const replay = await s.run();+ expect(replay).toEqual(recovered);+ expect(calls).toBe(0);+ expect(await s.journal()).toHaveLength(4);+ });+ }, 180_000);+ }++ test('a default visibility narrowed to private since the refusal narrows the novel claim but never re-saves the forgotten one', async () => {+ await onEachEngine('narrow', async engine => {+ const s = await recoverySource(engine);+ await s.seedLegacyBatch();+ await expect(s.run()).rejects.toMatchObject({ code: 'invalid_params' });+ expect(await s.summary()).toEqual(legacyRefusal);+ await engine.setConfig('facts.default_visibility', 'private');+ const recovered = await s.run();+ expect(recovered).toMatchObject({ inserted: 1, withdrawn_skipped: 1 });+ expect(await s.activeWithVisibility()).toEqual([`${NOVEL}:private`]);+ expect(await s.summary()).toEqual([...legacyRefusal, `${ENTITY}:committed:skip`, `${COMPLETE}:committed`]);+ expect(calls).toBe(0);+ });+ }, 180_000);++ test('a follow-up that keeps racing a withdrawal gets three attempts, then the refusal stands with nothing published', async () => {+ await onEachEngine('cap', async engine => {+ const s = await recoverySource(engine);+ await s.seedLegacyBatch();+ await expect(s.run()).rejects.toMatchObject({ code: 'invalid_params' });+ expect(await s.summary()).toEqual(legacyRefusal);+ const unforget = () => engine.executeRaw(`DELETE FROM fact_withdrawals WHERE source_id=$1 AND fact_hash=gbrain_fact_fingerprint($2)`, [s.sourceId, NOVEL]);+ installFaultHook(async (point, detail) => {+ if (point !== 'consumer:prepared' || detail.operation !== 'extract_facts' || detail.sourceId !== s.sourceId) return;+ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash) VALUES($1,'world',$2,gbrain_fact_fingerprint($3)) ON CONFLICT DO NOTHING`,+ [s.sourceId, ENTITY, NOVEL]);+ });+ const fenceBefore = await s.entityFence();+ for (let followUps = 1; followUps <= 3; followUps++) {+ await expect(s.run()).rejects.toMatchObject({ code: 'revision_conflict' });+ const journal = await s.journal();+ expect(journal).toHaveLength(2 * (followUps + 1));+ expect(journal.slice(-2).map(row => `${row.slug}:${row.state}:${row.error_code}`)).toEqual([`${ENTITY}:conflict:revision_conflict`, `${COMPLETE}:conflict:revision_conflict`]);+ expect(journal.at(-2)!.error_detail).toMatchObject({ origin: 'withdrawal', withdrawn: { subject: ENTITY, visibility: 'world' } });+ await unforget();+ }+ installFaultHook(undefined);+ await expect(s.run()).rejects.toMatchObject({ code: 'revision_conflict' });+ expect(await s.journal()).toHaveLength(8);+ expect(await s.active()).toEqual([]);+ expect(await s.entityFence()).toBe(fenceBefore);+ expect(calls).toBe(0);+ });+ }, 240_000);++ test('an origin page whose revision moved since the refusal admits the follow-up but publishes nothing from the stale text', async () => {+ await onEachEngine('origin', async engine => {+ const s = await recoverySource(engine);+ await s.seedLegacyBatch();+ await expect(s.run()).rejects.toMatchObject({ code: 'invalid_params' });+ expect(await s.summary()).toEqual(legacyRefusal);+ // A title change moves the page revision while the extracted body stays the same, so the input digest (and the batch) is unchanged.+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.putPage(ORIGIN, { type: 'meeting', title: 'Synthetic workshop (renamed)', compiled_truth: BODY }, { sourceId: s.sourceId });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const fenceBefore = await s.entityFence();+ await expect(s.run()).rejects.toMatchObject({ code: 'revision_conflict' });+ const journal = await s.journal();+ expect(journal.map(row => `${row.slug}:${row.state}:${row.error_code}`)).toEqual([...legacyRefusal, `${ENTITY}:conflict:revision_conflict`, `${COMPLETE}:conflict:revision_conflict`]);+ expect(journal[2].error_message).toContain('source page changed');+ expect(journal[2].flag).toBe('skip');+ expect(await s.active()).toEqual([]);+ expect(await s.entityFence()).toBe(fenceBefore);+ expect(calls).toBe(0);+ });+ }, 180_000);++ test('a refusal of another kind, or one without retained facts, is not followed up', async () => {+ await onEachEngine('other', async engine => {+ for (const tamper of [`error_code='invalid_params', error_message='invalid_params: something else', error_detail=NULL`, `intent = intent - 'facts'`]) {+ const s = await recoverySource(engine);+ await s.seedLegacyBatch();+ await expect(s.run()).rejects.toMatchObject({ code: 'invalid_params' });+ expect(await s.summary()).toEqual(legacyRefusal);+ await engine.executeRaw(`UPDATE persistence_requests SET ${tamper} WHERE source_id=$1 AND slug=$2`, [s.sourceId, ENTITY]);+ const before = await s.receipts((await s.journal()).map(row => row.id));+ await expect(s.run()).rejects.toMatchObject({ code: 'invalid_params' });+ expect(await s.summary()).toEqual(legacyRefusal);+ expect(await s.receipts((await s.journal()).map(row => row.id))).toEqual(before);+ expect(await s.active()).toEqual([]);+ expect(calls).toBe(0);+ }+ });+ }, 240_000);++ test('a batch admitted under a request id replays its receipt; the follow-up route is for input-keyed batches', async () => {+ await onEachEngine('keyed', async engine => {+ const s = await recoverySource(engine);+ const keyed: FactsBackstopCtx = { ...s.ctx, requestId: randomUUID() };+ await s.seedLegacyBatch(keyed);+ await expect(s.run(keyed)).rejects.toMatchObject({ code: 'invalid_params', message: FACT_WITHDRAWN_MESSAGE });+ expect(await s.summary()).toEqual(legacyRefusal);+ const before = await s.receipts((await s.journal()).map(row => row.id));+ await expect(s.run(keyed)).rejects.toMatchObject({ code: 'invalid_params', message: FACT_WITHDRAWN_MESSAGE });+ expect(await s.summary()).toEqual(legacyRefusal);+ expect(await s.receipts((await s.journal()).map(row => row.id))).toEqual(before);+ expect(await s.active()).toEqual([]);+ expect(calls).toBe(0);+ });+ }, 180_000);+});diff --git a/test/managed-facts-withdrawn-skip-6506.test.ts b/test/managed-facts-withdrawn-skip-6506.test.tsnew file mode 100644index 0000000000..f6269441a4--- /dev/null+++ b/test/managed-facts-withdrawn-skip-6506.test.ts@@ -0,0 +1,254 @@+/**+ * #6506: on a managed brain, one withdrawn candidate refused an entity's whole+ * automatic fact batch, so an unrelated new fact in the same group was never+ * published and every re-extraction of the unchanged page refused again.+ *+ * 1. Protects: automatic extraction (`withdrawn: 'skip'` frozen in the intent)+ * skips a withdrawn candidate and publishes the rest; the entity and+ * completion receipts count `withdrawn_skipped`; an all-withdrawn group+ * commits a no-op receipt; a replay under the same request id costs no+ * model call; purge tombstones still refuse (`purged_content`) at+ * preparation and at locked validation; `remember` and the explicit fence+ * writers keep the refusal; a withdrawal committed between preparation and+ * the locked validation is a terminal `revision_conflict` whose detail+ * names the withdrawal, with nothing published.+ * 2. Fails when: the withdrawn candidate refuses the group (master), the skip+ * leaks into explicit writers, the purge check is skipped, the flag is+ * stored as a JSON scalar, or the race publishes around the withdrawal.+ * 3. test/managed-facts-backstop.test.ts covers the managed contract cases+ * without withdrawals; test/managed-facts-withdrawal-recovery-6506.test.ts+ * covers the follow-up route for batches that already failed.+ * 4. Seams: gateway test transports and the persistence fault hook.+ *+ * Runs on PGLite; also on Postgres when DATABASE_URL is set (testBackends).+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';+import { operationsByName } from '../src/core/operations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';+import { writeFactsToFence } from '../src/core/facts/fence-write.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';+import { waitFor } from './helpers/wait-for.ts';++const SLUG = 'people/alice-example';+const WITHDRAWN = 'Alice-example agreed to provide twelve sample kits for the synthetic workshop.';+const NOVEL = 'Alice-example will verify the synthetic room booking in November.';+const PURGED = 'Alice-example holds a synthetic obsolete workshop credential.';++const engines: BrainEngine[] = [];+const dbDir = mkdtempSync(join(tmpdir(), 'gbrain-withdrawn-skip-db-'));+let closePostgres: (() => Promise<void>) | undefined;+let calls = 0;+let extracted: string[] = [];++beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });+ __setChatTransportForTests(async (): Promise<ChatResult> => {+ calls++;+ return { text: JSON.stringify({ facts: extracted.map(fact => ({ fact, entity: SLUG, kind: 'fact', confidence: 1, notability: 'medium' })) }),+ blocks: [], stopReason: 'end', usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'test:stub', providerId: 'test' };+ });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => Array(1536).fill(0.01)) })) as never);+ for (const backend of testBackends()) {+ if (backend === 'pglite') {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dbDir });+ await engine.initSchema();+ engines.push(engine);+ } else {+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(isolated.engine);+ closePostgres = isolated.close;+ }+ }+}, 120_000);++afterEach(() => { installFaultHook(undefined); });++afterAll(async () => {+ __setChatTransportForTests(null);+ __setEmbedTransportForTests(null);+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ resetGateway();+ rmSync(dbDir, { recursive: true, force: true });+});++/**+ * A managed, database-only source with one entity page; every test gets its own+ * source. Withdrawals and purge tombstones are seeded before the brain turns+ * managed (a managed brain refuses direct fact inserts).+ */+async function managedSource(engine: BrainEngine, seed: { withdraw?: string[]; purge?: string[] } = {}) {+ const sourceId = `w6506-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ await engine.putPage(SLUG, { type: 'person', title: 'Alice Example', compiled_truth: '# Alice Example\n\nFictional person for the regression.\n' }, { sourceId });+ for (const fact of seed.withdraw ?? []) {+ const saved = await engine.insertFact({ fact, entity_slug: SLUG, visibility: 'world', kind: 'fact', source: 'fixture' }, { source_id: sourceId });+ expect((await recordFactWithdrawal(engine, saved.id, sourceId, false, { semanticReview: false })).withdrawn).toBe(true);+ }+ for (const fact of seed.purge ?? []) await purge(engine, sourceId, fact);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true }, remote: false as const, sourceId, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;+ const page = async () => (await engine.getPage(SLUG, { sourceId }))!.compiled_truth;+ const active = () => engine.executeRaw<{ id: number; fact: string }>('SELECT id,fact FROM facts WHERE source_id=$1 AND expired_at IS NULL ORDER BY id', [sourceId])+ .then(rows => rows.map(row => ({ id: Number(row.id), fact: row.fact })));+ const quiet = () => waitFor(async () => (await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering')`, [sourceId]))[0].n === 0,+ { timeoutMs: 30_000, label: 'fact requests settled' });+ const journal = async () => {+ await quiet();+ return engine.executeRaw<{ slug: string; state: string; error_code: string | null; error_detail: unknown; outcome: Record<string, unknown> | null; intent: Record<string, unknown> | null }>(+ `SELECT slug,state,error_code,error_detail,outcome,intent FROM persistence_requests WHERE source_id=$1 AND operation='extract_facts' ORDER BY sequence`, [sourceId]);+ };+ const flagTypes = () => engine.executeRaw<{ kind: string; flag: string | null; value: string | null }>(+ `SELECT intent->>'kind' AS kind, jsonb_typeof(intent->'withdrawn') AS flag, intent->>'withdrawn' AS value FROM persistence_requests+ WHERE source_id=$1 AND operation='extract_facts' ORDER BY sequence`, [sourceId]);+ const extract = (facts: string[], requestId: string) => {+ extracted = facts;+ return operationsByName.extract_facts.handler(ctx, { turn_text: `A synthetic workshop record. ${WITHDRAWN} ${NOVEL}`, visibility: 'world', request_id: requestId }) as+ Promise<{ inserted: number; duplicate: number; fact_ids: number[]; withdrawn_skipped?: number }>;+ };+ return { sourceId, ctx, page, active, journal, flagTypes, extract };+}++/** A purge tombstone for `fact` about the entity, the row `purge_fact` leaves behind. */+function purge(engine: BrainEngine, sourceId: string, fact: string) {+ return engine.executeRaw(`INSERT INTO fact_purges(source_id,visibility,subject,fact_hash,actor,reason) VALUES($1,'world',$2,gbrain_fact_fingerprint($3),'fixture','regression')+ ON CONFLICT DO NOTHING`, [sourceId, SLUG, fact]);+}++async function onEachEngine(label: string, body: (engine: BrainEngine) => Promise<void>) {+ for (const engine of engines) {+ const home = mkdtempSync(join(tmpdir(), `gbrain-withdrawn-skip-${label}-`));+ calls = 0;+ try {+ await withEnv({ GBRAIN_HOME: home }, () => body(engine));+ } finally {+ installFaultHook(undefined);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(home, { recursive: true, force: true });+ }+ }+}++describe('managed automatic extraction meets a withdrawn claim (#6506)', () => {+ test('a withdrawn candidate is skipped and counted while the novel claim publishes; the replay costs no model call', async () => {+ await onEachEngine('mixed', async engine => {+ const s = await managedSource(engine, { withdraw: [WITHDRAWN] });+ const fenceBefore = await s.page();+ const requestId = randomUUID();+ const first = await s.extract([WITHDRAWN, NOVEL], requestId);+ expect(first).toMatchObject({ inserted: 1, duplicate: 0, withdrawn_skipped: 1 });+ const active = await s.active();+ expect(active.map(row => row.fact)).toEqual([NOVEL]);+ expect(first.fact_ids.map(Number)).toEqual(active.map(row => row.id));+ expect(await s.page()).not.toBe(fenceBefore);+ expect(await s.page()).toContain(NOVEL);+ expect(await s.page()).not.toContain(WITHDRAWN);+ const journal = await s.journal();+ expect(journal.map(row => [row.slug, row.state, row.outcome?.withdrawn_skipped])).toEqual([[SLUG, 'committed', 1], ['__managed_facts_complete__', 'committed', 1]]);+ expect(await s.flagTypes()).toEqual([{ kind: 'managed_facts_entity', flag: 'string', value: 'skip' }, { kind: 'managed_facts_complete', flag: null, value: null }]);+ expect(calls).toBe(1);+ const replay = await s.extract([WITHDRAWN, NOVEL], requestId);+ expect(replay).toEqual(first);+ expect(calls).toBe(1);+ expect(await s.active()).toEqual(active);++ await expect(operationsByName.remember.handler(s.ctx, { fact: WITHDRAWN, entity: SLUG, visibility: 'world', provenance: 'Synthetic withdrawal regression.' }))+ .rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('fact_withdrawn') });+ expect(await s.active()).toEqual(active);+ });+ }, 180_000);++ test('an all-withdrawn group commits a no-op entity receipt and leaves the page untouched', async () => {+ await onEachEngine('all', async engine => {+ const s = await managedSource(engine, { withdraw: [WITHDRAWN] });+ const fenceBefore = await s.page();+ const result = await s.extract([WITHDRAWN], randomUUID());+ expect(result).toMatchObject({ inserted: 0, duplicate: 0, withdrawn_skipped: 1, fact_ids: [] });+ expect(await s.active()).toEqual([]);+ expect(await s.page()).toBe(fenceBefore);+ const journal = await s.journal();+ expect(journal.map(row => [row.slug, row.state, row.error_code, row.outcome?.inserted, row.outcome?.withdrawn_skipped]))+ .toEqual([[SLUG, 'committed', null, 0, 1], ['__managed_facts_complete__', 'committed', null, 0, 1]]);+ expect(calls).toBe(1);+ });+ }, 180_000);++ test('explicit fence writers never carry the skip flag and remember still refuses', async () => {+ await onEachEngine('explicit', async engine => {+ const s = await managedSource(engine, { withdraw: [WITHDRAWN] });+ const result = await writeFactsToFence(engine, { sourceId: s.sourceId, slug: SLUG, localPath: null, resolutionSource: 'exact_page' }, [+ { fact: WITHDRAWN, kind: 'fact', source: 'fixture', visibility: 'world', notability: 'medium', embedding: null, sessionId: null },+ { fact: NOVEL, kind: 'fact', source: 'fixture', visibility: 'world', notability: 'medium', embedding: null, sessionId: null },+ ]);+ expect(result).toMatchObject({ inserted: 1, withdrawnSkipped: 1 });+ expect((await s.active()).map(row => row.fact)).toEqual([NOVEL]);+ expect(result.ids).toEqual((await s.active()).map(row => row.id));+ expect((await s.flagTypes()).map(row => row.flag)).toEqual([null, null]);+ expect(await s.journal()).toHaveLength(2);+ });+ }, 180_000);++ test('a purge tombstone still refuses the group at preparation', async () => {+ await onEachEngine('purged', async engine => {+ const s = await managedSource(engine, { purge: [PURGED] });+ const fenceBefore = await s.page();+ await expect(s.extract([PURGED, NOVEL], randomUUID())).rejects.toMatchObject({ code: 'purged_content' });+ expect(await s.active()).toEqual([]);+ expect(await s.page()).toBe(fenceBefore);+ const journal = await s.journal();+ expect(journal.map(row => [row.slug, row.state, row.error_code])).toEqual([[SLUG, 'failed', 'purged_content'], ['__managed_facts_complete__', 'conflict', 'revision_conflict']]);+ });+ }, 180_000);++ test('a purge tombstone written between preparation and locked validation still refuses purged_content', async () => {+ await onEachEngine('purged-race', async engine => {+ const s = await managedSource(engine);+ const fenceBefore = await s.page();+ installFaultHook(async (point, detail) => {+ if (point !== 'consumer:prepared' || detail.operation !== 'extract_facts' || detail.sourceId !== s.sourceId) return;+ await purge(engine, s.sourceId, NOVEL);+ });+ await expect(s.extract([NOVEL], randomUUID())).rejects.toMatchObject({ code: 'purged_content' });+ expect(await s.active()).toEqual([]);+ expect(await s.page()).toBe(fenceBefore);+ expect((await s.journal()).map(row => [row.slug, row.state, row.error_code])).toEqual([[SLUG, 'failed', 'purged_content'], ['__managed_facts_complete__', 'conflict', 'revision_conflict']]);+ });+ }, 180_000);++ test('a withdrawal committed between preparation and locked validation is a terminal revision_conflict naming the withdrawal', async () => {+ await onEachEngine('race', async engine => {+ const s = await managedSource(engine);+ const fenceBefore = await s.page();+ installFaultHook(async (point, detail) => {+ if (point !== 'consumer:prepared' || detail.operation !== 'extract_facts' || detail.sourceId !== s.sourceId) return;+ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash) VALUES($1,'world',$2,gbrain_fact_fingerprint($3)) ON CONFLICT DO NOTHING`,+ [s.sourceId, SLUG, WITHDRAWN]);+ });+ await expect(s.extract([WITHDRAWN, NOVEL], randomUUID())).rejects.toMatchObject({ code: 'revision_conflict' });+ expect(await s.active()).toEqual([]);+ expect(await s.page()).toBe(fenceBefore);+ const journal = await s.journal();+ expect(journal.map(row => [row.slug, row.state, row.error_code])).toEqual([[SLUG, 'conflict', 'revision_conflict'], ['__managed_facts_complete__', 'conflict', 'revision_conflict']]);+ expect(journal[0].error_detail).toMatchObject({ origin: 'withdrawal', withdrawn: { subject: SLUG, visibility: 'world' } });+ expect((journal[0].intent as { facts: unknown[] }).facts).toHaveLength(2);+ expect(calls).toBe(1);+ });+ }, 180_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 62207336c5..183198b526 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -57,6 +57,8 @@ test/link-cross-source.test.tstest/link-preparation-shared-index.test.tstest/links-attendance-blocked.test.tstest/managed-cycle-pull-upstream.test.ts+test/managed-facts-withdrawal-recovery-6506.test.ts+test/managed-facts-withdrawn-skip-6506.test.tstest/managed-lint.test.tstest/managed-maintenance-links.test.tstest/managed-sweep-corpus-windows.test.ts