Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): a conversation-facts batch never reuses a request id a compacted receipt holds (#7516)

garrytan9407df766188
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.md
index 86da216372..dc9afd1966 100644
--- a/docs/architecture/key-files/core-persistence-facts.md
+++ b/docs/architecture/key-files/core-persistence-facts.md
@@ -8,7 +8,7 @@ Managed facts extraction: the entity-intent preparer and publisher, conversation
- `src/core/persistence/{facts-maintenance,facts-prepare}.ts` — the managed facts publisher and preparer behind the backstop's `publishManagedFacts` / `resumeManagedFacts` and the explicit fact writers (`managed-fact-write.ts`, `remember`); the shared maintenance dispatch they ride is in [Core Persistence](core-persistence.md). Each `ManagedFactsSession` carries one `MaintenanceWriteWait` (`maintenance-wait.ts`) built from the caller's `FactsBackstopCtx.deadlineAtMs` (the facts-absorb job passes its deadline; other callers get the 30 s base) and its abort signal: `collectManagedFacts` waits that long for each accepted request through `awaitWrite`, a cancelled job stops waiting at once, and a request still nonterminal after the wait leaves as `write_pending` with its receipt (#6778, `test/facts-absorb-publish-wait-6778.test.ts`). GBRA-130 A-36: `collectManagedFacts` awaits every row before it throws. An entity request that ended on a code of its own page (`ENTITY_REFUSAL_CODES`: `revision_conflict`, `invalid_fence`, `page_body_segmented`, …; not a file-check or withdrawal refusal, which the follow-up walks own) is reported as `refused` (slug, code, request id) on `ManagedFactsResult` and the `extract_facts` result when the session sets `reportRefusals` and another entity of the batch committed (the backstop sets it; `managed-fact-write.ts` and `remember` do not and keep the refusal), and the completion receipt refused only as incomplete is not a failure of its own; any other terminal row, then a pending one, then a refusal with nothing committed beside it, throws as its receipt. Test: `test/pathological/a-36-facts-batch-partial-refusal.test.ts` (PGLite and Postgres). `facts-maintenance.ts` / `facts-prepare.ts` (#6506): an automatic extraction's entity intent carries `withdrawn: 'skip'` (set by the backstop's `publishManagedFacts` call, never by `managed-fact-write.ts` or `remember`), under which `prepareManagedFactsMutation` skips a candidate `isFactWithdrawn` matches (after `assertFactNotPurged`, which still refuses `purged_content`) and counts it as `withdrawn_skipped` on the entity outcome, summed into the completion outcome, `ManagedFactsResult` and the `extract_facts` result (the unmanaged pipeline counts its own B-10 skip into the same field); without the flag the refusal stands. At locked validation the per-entry purge and withdrawal checks run before the page's fence re-validation, and under the flag a claim forgotten since preparation refuses `revision_conflict` with `error.withdrawn` (so the receipt's `error_detail.origin` is `withdrawal`); no `extract_facts` request is re-prepared. `resumeManagedFacts` runs `followWithdrawalRefusals` for an input-keyed session (`inputKeyed`, no request id): the `followFileRefusals` walk generalized as `followRefusals`, matching entity refusals by `withdrawnFromDetail(error_detail)` or the pre-detail `invalid_params` + `FACT_WITHDRAWN_MESSAGE` pair, re-admitting the retained facts under `digest([batchKey, 'withdrawal-retry', n])` with the flag (`readmitWithdrawnFacts`: a fact forgotten at its retained visibility keeps that visibility so preparation skips it instead of narrowing it to private), bounded by `MAX_FILE_REFUSAL_RETRIES`, historical receipts untouched. Tests: `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts` (PGLite and Postgres).
- `src/core/facts/same-page-shadow.ts` — #6333 the shadow counter both fact writers share. `samePageRewording(engine, sourceId, fact, embedding)` re-reads the entity's nearest live same-visibility candidate (`listSupersessionCandidates`, the pool and filters of `decideSingleFact`'s cosine pass) and answers whether `wouldDedupSamePage` (capture-dedup.ts: same lane, same `source_session`, same visibility, cosine ≥ 0.85, no diverging guard token) would have called the fact a rewording; `warnSamePageShadow` is the one stderr spelling (`[facts-backstop] #6333 shadow: …; both kept`). `facts-prepare.ts` calls it for every candidate `decideSingleFact` did not match and counts `would_dedup_same_page` on the entity outcome, the completion outcome, `ManagedFactsResult` and the `extract_facts` result; the count is frozen in the receipt, so a replay reports it and does not recount. Nothing is dropped; this is the managed mirror of the unmanaged backstop's counter (`backstop.ts`), which never fired on a managed brain. Tests: `test/backstop-same-page-shadow-managed-6333.test.ts` (PGLite and Postgres), `test/backstop-same-page-shadow-6333.test.ts` (unmanaged).
- `src/core/persistence/derived-facts.ts` — `writeDerivedFacts`: the unmanaged conversation fact index commits in one maintenance transaction under the maintenance principal; on a managed brain it refuses with `writer_coordinator_required`, because every managed facts/takes writer publishes a receipted maintenance request (`test/receipt-coverage.test.ts` lists every coordinated write site). Tests: `test/write-attribution-misc.test.ts`.
-- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` batch requests (`submitDatabaseMaintenanceIntent` on `ANCHOR_SLUG`, a dot-led slug no page can hold, dispatched from `prepareMaintenanceMutation`). Each page's frozen entry (`buildConversationPage`: `FrozenExtractedFact` rows, its generation and attempt, vectors only under the brain's facts embedding signature) joins the run's batch; `enqueueManagedPage` publishes it once `DEFAULT_BATCH_CAPS` is reached (25 pages, 10 with extracted facts, 8 MiB) and `flushManagedBatch` at the end of the run. The generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, selectors, newest extractor row id) is checked before model work by `startManagedPage` against `loadGenerationIndex` (the writer's unsettled and failed batches on the anchor, read once per run): a member of an unsettled batch waits and replays its receipt, a member of a retryably failed batch is resubmitted from its stored entry, a deterministic failure of a batch that held it alone or three failed batches block it (GBRA-130 A-51: `publishBatch` re-publishes a multi-page batch that failed deterministically in halves, so only the page that fails alone takes the code; `test/pathological/a-51-conversation-batch-booking.test.ts`); all without model calls. The batch request id digests its members' (generation, attempt) pairs. The preparer locks every member's key and applies each on its own (`applyEntry`): a deleted, replaced or moved page is skipped and reported, a page whose rows fail validation gets a durable `blocked:` not-extractable outcome, vectors under another signature are dropped; none fails the batch. `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest entry cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the run's planned batches and before each new batch. `publishConversationFacts` (the managed apply and the unmanaged writer) passes fact rows through the write gate at the page's derived tier and retires the prior batch only for a complete replacement (#7013: `full` scope, at least one fact, nothing held or rejected) or on a page with no active extractor facts, through `replaceConversationFacts`, which deletes the page's extractor rows (expiring referenced and keeping label-retired ones) and inserts the rows numbered above every remaining row, failing on a lost insert. Otherwise the prior facts stay: the outcome row replaces the page's prior outcome rows (so the page is not paid for again), a `window` run (`--since` dropped messages) adds its facts beside them, and a `partial` run (a `--segment-limit` cut, a page changed mid-run) publishes no facts over them. Each entry carries its `scope`; an entry frozen without one is `partial` without its outcome, `window` with a `--since` selector, else `full`. Tests: `test/pathological/h4-conversation-facts-zero-yield.test.ts` (managed and unmanaged, + Postgres arm). Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.
+- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` batch requests (`submitDatabaseMaintenanceIntent` on `ANCHOR_SLUG`, a dot-led slug no page can hold, dispatched from `prepareMaintenanceMutation`). Each page's frozen entry (`buildConversationPage`: `FrozenExtractedFact` rows, its generation and attempt, vectors only under the brain's facts embedding signature) joins the run's batch; `enqueueManagedPage` publishes it once `DEFAULT_BATCH_CAPS` is reached (25 pages, 10 with extracted facts, 8 MiB) and `flushManagedBatch` at the end of the run. The generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, selectors, newest extractor row id) is checked before model work by `startManagedPage` against `loadGenerationIndex` (the writer's unsettled and failed batches on the anchor, read once per run): a member of an unsettled batch waits and replays its receipt, a member of a retryably failed batch is resubmitted from its stored entry, a deterministic failure of a batch that held it alone or three failed batches block it (GBRA-130 A-51: `publishBatch` re-publishes a multi-page batch that failed deterministically in halves, so only the page that fails alone takes the code; `test/pathological/a-51-conversation-batch-booking.test.ts`); all without model calls. The batch request id digests its members' (generation, attempt) pairs; `submitConversationPages` raises every member's attempt past an id another write holds, or whose receipt lost its intent without committing (#7516: a redacted `purged_content` refusal or a compacted failure takes the attempt history `loadGenerationIndex` reads, so the same id came back on every run as `idempotency_conflict` after a paid extraction; test `test/conversation-facts-redacted-batch-7516.test.ts`, + Postgres arm). The preparer locks every member's key and applies each on its own (`applyEntry`): a deleted, replaced or moved page is skipped and reported, a page whose rows fail validation gets a durable `blocked:` not-extractable outcome, vectors under another signature are dropped; none fails the batch. `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest entry cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the run's planned batches and before each new batch. `publishConversationFacts` (the managed apply and the unmanaged writer) passes fact rows through the write gate at the page's derived tier and retires the prior batch only for a complete replacement (#7013: `full` scope, at least one fact, nothing held or rejected) or on a page with no active extractor facts, through `replaceConversationFacts`, which deletes the page's extractor rows (expiring referenced and keeping label-retired ones) and inserts the rows numbered above every remaining row, failing on a lost insert. Otherwise the prior facts stay: the outcome row replaces the page's prior outcome rows (so the page is not paid for again), a `window` run (`--since` dropped messages) adds its facts beside them, and a `partial` run (a `--segment-limit` cut, a page changed mid-run) publishes no facts over them. Each entry carries its `scope`; an entry frozen without one is `partial` without its outcome, `window` with a `--since` selector, else `full`. Tests: `test/pathological/h4-conversation-facts-zero-yield.test.ts` (managed and unmanaged, + Postgres arm). Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.
- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text (lowercase Unicode page-slug letters without combining marks; a literal glued to further letters is not a literal), resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).
- `src/core/facts/conversation-subject-infer.ts` — #6764 write-time subject inference for `gbrain extract-conversation-facts` (both the classic and managed branches, trusted local only) and the free conversation relink. `inferConversationSubject` is the per-fact rule (a withdrawn claim misses as `withdrawn`); `inferConversationSubjects(engine, sourceId, visibility, rows)` gives each row the extractor left without an entity the slug `inferFactSubject` proves in `write` mode (mention tier; `excludePrivate` for world rows) plus the `entity inferred from <tier>` context note, unless `facts.entity_inference` is off or the claim was withdrawn. The row stays a derived row of the conversation page (`entity_slug` column only). Test: `test/conversation-facts-unlinked-6764.test.ts`.
- `src/core/facts/conversation-relink.ts` — `gbrain facts relink --conversation [--source] [--slugs] [--dry-run] [--json]` (#6764, dispatched from `src/commands/facts.ts`): the free relink of the conversation extractor's unlinked derived rows, which plain relink never examines. Pages are the named `--slugs`, else the 50 with the most unlinked rows not yet tried (`conversationRelinkPages`). Each row runs `inferConversationSubject` (write mode, visibility-filtered, withdrawn claims skipped; no model); a row the assistant or a third party said is never linked, never picks a page, and is counted as `not_user_attributed` (#7270). A page's links are one write: a managed brain publishes one database-only `managed_maintenance_conversation_relink` request on the anchor `.maintenance/conversation-relink` holding the page key (`prepareConversationRelink`, dispatched in `persistence/prepared-maintenance.ts`; the request id comes from the planned links, and a failed attempt retries under the next id), an unmanaged brain one `writeDerivedFacts` transaction. The write sets `entity_slug` and appends `entity relinked from <tier>` only on rows still exactly as planned (same claim, unlinked, active, target page live) and records a `linked` attempt; unresolved rows get a `conversation_unresolved` memo in `fact_relink_attempts` (reason the miss), which moves doctor `unlinked_facts` to the paid re-extraction fallback, and the report prints that command for their pages. Test: `test/conversation-relink-6764.test.ts`.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 63bc53cc6a..2de3e09baf 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1246,6 +1246,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.437.0', text: 'A chat-connector cookie or token holding a line break, NUL, another control character or a non-ASCII character is refused before any request (`invalid_header_value`): `connectors auth` reports it and `connectors sync` returns `auth_required` with that hint and stamps the auth error. A request that fails before a response is reported by its error code (`ECONNREFUSED`, `TypeError`), never by the runtime\'s message, so a header value can never be echoed into probe output, sync hints or logs (#7483).' },
// GBRA-133 G2 (superseded remote blobs). `since` is stamped at the merge slot.
{ since: '0.60.438.0', text: '`gbrain git commit-push` now keeps this machine\'s version of a file the remote changed back to a version this checkout already had at that path and later replaced (a stale clone or writer pushing an old copy, often inside a merge), instead of stopping with `integrate_conflict`. It reads the last 200 commits that changed the file. The push lists those files in `superseded_remote_paths` and the merge message names them. A version this checkout never had, a remote deletion and a file named with `--resolve` still conflict; when both kinds meet, `integrate_conflict` lists only the real conflicts and `detail.superseded` names the others.' },
+ // #7516 (GBRA-197 lane B). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'A managed conversation-facts batch whose receipt lost its stored intent (a `purged_content` refusal the journal redacts, a purge, or receipt compaction) no longer sticks its pages. `gbrain extract-conversation-facts` derived the same batch request id again, so every run paid a model call, failed with `idempotency_conflict` (or got the old failure back) and inserted nothing. The batch now publishes under its pages\' next attempt after one more model call, and the next run makes none. A crashed run that resubmits the same batch still replays its receipt.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index e8dab83253..018d0a3eb5 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -23,7 +23,9 @@
* (`--since`, `--segment-limit`) and the page's newest extractor row id (so
* every committed batch, an approved repair or `--force` after a commit
* starts the next generation). A batch's request id is the digest of its
- * members' (generation, attempt) pairs. Before a page's model work the run
+ * members' (generation, attempt) pairs; an id another write already holds,
+ * or a receipt that lost its intent without committing, moves the batch to
+ * its members' next attempt (#7516). Before a page's model work the run
* consults the writer's unsettled and failed batch requests (loaded once per
* run; compacted ones drop out):
* - a member of a still-unsettled batch (a crash after admission) waits for
@@ -63,7 +65,7 @@ import { readFix } from '../ops/op-fix.ts';
import { authorizeStoredRequest, authorizeWrite } from '../persistence/authority.ts';
import { digest, jsonBytes } from '../persistence/digest.ts';
import { receiptReservation } from '../persistence/receipt-bytes.ts';
-import { getWriteRequestById } from '../persistence/journal.ts';
+import { getWriteRequestById, intentDigest } from '../persistence/journal.ts';
import { journalLimitKey, oneYearCapacity, readJournalLimits } from '../persistence/limits.ts';
import { principalKey } from '../persistence/model.ts';
import { PERSISTENCE_IPC_MAX_BYTES } from '../persistence/ipc.ts';
@@ -199,6 +201,27 @@ function batchRequestId(sourceIncarnation: string, pages: ReadonlyArray<Pick<Con
return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
}
+/**
+ * #7516: the batch at the first attempt, from its members' own upward, whose request id is unspent: unused, or used by
+ * this very batch (a replay) whose receipt still holds its intent or committed. A receipt without its intent (a
+ * purged_content refusal the journal redacts, retention compaction) takes its members' attempt history with it, so
+ * startManagedPage can derive an attempt whose id admission would refuse as idempotency_conflict or answer with the
+ * compacted failure, on every run. Each step raises every member's attempt by one, and the journal's rows are finite.
+ */
+async function unspentBatch(engine: BrainEngine, authority: MaintenanceAuthority, pages: ConversationPageEntry[]): Promise<{ intent: ConversationFactsIntent; requestId: string }> {
+ const { principal, sourceId, sourceIncarnation } = authority.writer;
+ for (let raise = 0; ; raise++) {
+ const members = pages.map(entry => ({ ...entry, attempt: entry.attempt + raise }));
+ const intent: ConversationFactsIntent = { kind: CONVERSATION_FACTS_INTENT, protocol: CONVERSATION_FACTS_PROTOCOL, expected_revision: null, pages: members };
+ const requestId = batchRequestId(sourceIncarnation, members);
+ const [spent] = await engine.executeRaw<{ request_id: string }>(`SELECT request_id::text AS request_id FROM persistence_requests
+ WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid AND (digest<>$4 OR (compacted AND state<>'committed'))`,
+ [principal.kind, principal.id, requestId, intentDigest({ operation: 'submit_job', sourceId, slug: ANCHOR_SLUG, callerIntent: intent })]);
+ if (!spent) return { intent, requestId };
+ log(`batch request ${spent.request_id} already belongs to another or a compacted write; publishing the batch at its members' next attempt`);
+ }
+}
+
/** What this writer's unsettled and failed batch requests say about one generation. */
interface GenerationHistory {
/** An admitted batch that has not settled yet. */
@@ -357,14 +380,14 @@ export async function buildConversationPage(engine: BrainEngine, config: GBrainC
* pending after the job's wait throws `write_pending`.
*/
export async function submitConversationPages(engine: BrainEngine, authority: MaintenanceAuthority, pages: ConversationPageEntry[]): Promise<Record<string, unknown>> {
- const intent: ConversationFactsIntent = { kind: CONVERSATION_FACTS_INTENT, protocol: CONVERSATION_FACTS_PROTOCOL, expected_revision: null, pages };
+ const { intent, requestId } = await unspentBatch(engine, authority, pages);
const limit = await conversationIntentByteLimit(engine);
const bytes = jsonBytes(intent);
if (bytes > limit) {
throw opError('request_too_large', 'The frozen fact batch exceeds the request size limit; the pages\' prior facts were kept.',
`The batch of ${pages.map(p => p.slug).join(', ')} is ${bytes} bytes, over the ${limit}-byte limit for one request, so nothing was submitted. Narrow the run with --segment-limit, or raise persistence.limits.principal_intent_bytes (the user's call).`);
}
- return submitDatabaseMaintenanceIntent(engine, authority, ANCHOR_SLUG, intent, batchRequestId(authority.writer.sourceIncarnation, pages));
+ return submitDatabaseMaintenanceIntent(engine, authority, ANCHOR_SLUG, intent, requestId);
}
function invalid(row: WriteRequest, cause: string): OperationError {
diff --git a/test/conversation-facts-redacted-batch-7516.test.ts b/test/conversation-facts-redacted-batch-7516.test.ts
new file mode 100644
index 0000000000..0a5a1b7816
--- /dev/null
+++ b/test/conversation-facts-redacted-batch-7516.test.ts
@@ -0,0 +1,196 @@
+/**
+ * #7516: a conversation-facts batch request whose receipt lost its intent
+ * (the journal redacts a purged_content refusal, #5575; retention compaction
+ * drops any terminal intent) takes its members' attempt history with it,
+ * because that history is read from the stored intent. The next run derived
+ * attempt 0 again, and so the same batch request id as the compacted
+ * request: a fresh extraction (a paid model call) failed with
+ * idempotency_conflict, identical rows replayed the stored failure, and both
+ * repeated on every run. A spent request id is now skipped: the batch
+ * publishes under the next unspent attempt, and the run after makes no model
+ * call. Runs on PGLite, and on Postgres through
+ * test/e2e/conversation-facts-redacted-batch-7516-postgres.test.ts.
+ */
+import { afterEach, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
+import type { ExtractedFact } from '../src/core/facts/extract.ts';
+import { runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
+import { ANCHOR_SLUG, buildConversationPage, conversationGeneration, submitConversationPages, type ConversationPageEntry } from '../src/core/facts/conversation-publication.ts';
+import { currentConversationVersionToken } from '../src/commands/extract-conversation-facts.ts';
+import { maintenancePreflight } from '../src/core/persistence/prepared-maintenance.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { compactReceipt } from '../src/core/persistence/journal.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { managedBrain, type ManagedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const SLUG = 'meetings/2026-09-28-plan-sync';
+const KEPT = 'Owner Example sends the quarterly plan on Thursday';
+const PURGED = 'Alice Example reviews plans on Mondays';
+const transcript = [
+ '---', 'title: Plan sync', 'type: meeting', 'date: 2026-09-28', '---',
+ '**Alice Example:** Can you send me the quarterly plan before the review?',
+ '**Owner Example:** Yes, I will send it on Thursday with the finance appendix.',
+ '**Alice Example:** Good. I review plans on Mondays, so that works.',
+ '**Owner Example:** I will flag any launch date changes in the summary.', '',
+].join('\n');
+
+afterEach(() => { installFaultHook(undefined); });
+
+async function putPage(brain: ManagedBrain): Promise<void> {
+ await submitPageMutation(brain.ctx, { operation: 'put_page', params: { slug: SLUG, request_id: randomUUID(), content: transcript } });
+ await disposePersistenceConsumer(brain.engine);
+}
+
+/** One run with a counting, deterministic model stub; returns its result and the idempotency_conflict lines it logged. */
+async function extract(engine: BrainEngine, calls: { n: number }, facts: string[]) {
+ const lines: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ process.stderr.write = ((chunk: string | Uint8Array) => { lines.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ try {
+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [SLUG], sleepMs: 0, overrideDisabled: true, workers: 1,
+ extractor: async () => {
+ calls.n++;
+ return facts.map(fact => ({ fact, kind: 'fact', confidence: 0.9, entity_slug: null, source: 'test', notability: 'high',
+ valid_from: new Date('2026-09-28T10:00:00Z') } as ExtractedFact));
+ } });
+ return { result, conflicts: lines.filter(line => line.includes('idempotency_conflict')) };
+ } finally {
+ process.stderr.write = write;
+ await disposePersistenceConsumer(engine);
+ }
+}
+
+/** Fails the next batch publication once with `error`, as the owner meets it. */
+function failNextPublication(error: Error): void {
+ let armed = true;
+ installFaultHook(async point => {
+ if (point !== 'consumer:prepared' || !armed) return;
+ armed = false;
+ throw error;
+ });
+}
+/** What the facts insert guard raised for a purged claim before #7485 left such claims out. */
+const PURGED_GUARD = () => Object.assign(new Error('purged_content: this claim was purged from this source and cannot be saved again'), { code: 'P0001' });
+
+async function batches(engine: BrainEngine) {
+ return engine.executeRaw<Pick<WriteRequest, 'id' | 'request_id' | 'principal_kind' | 'principal_id' | 'state' | 'error_code' | 'compacted'> & { has_intent: boolean }>(
+ `SELECT id::text AS id, request_id::text AS request_id, principal_kind, principal_id::text AS principal_id, state, error_code, compacted,
+ intent IS NOT NULL AS has_intent
+ FROM persistence_requests WHERE slug=$1 ORDER BY sequence`, [ANCHOR_SLUG]);
+}
+
+async function factsOf(engine: BrainEngine) {
+ return (await engine.executeRaw<{ fact: string }>(`SELECT fact FROM facts WHERE source_id='default' AND source_markdown_slug=$1
+ AND source LIKE 'cli:extract-conversation-facts%' AND expired_at IS NULL ORDER BY row_num`, [SLUG])).map(r => r.fact);
+}
+
+/** A partial entry (no outcome row) frozen directly, so two submissions of it are byte-identical. */
+async function frozenEntry(engine: BrainEngine) {
+ const authority = (await maintenancePreflight(engine, 'default'))!;
+ const page = (await engine.getPage(SLUG, { sourceId: 'default' }))!;
+ const versionToken = await currentConversationVersionToken(engine, page);
+ const generation = await conversationGeneration(engine, authority, { slug: SLUG, page, versionToken, since: null, segmentLimit: 1 });
+ const entry: ConversationPageEntry = await buildConversationPage(engine, { engine: engine.kind },
+ { slug: SLUG, generation, attempt: 0, versionToken, since: null, segmentLimit: 1, scope: 'partial' },
+ [{ fact: KEPT, kind: 'fact', source: 'cli:extract-conversation-facts', row_num: 0, source_markdown_slug: SLUG, valid_from: new Date('2026-09-28T10:00:00Z') }],
+ { newestEnd: null, visibility: 'private' });
+ return { authority, entry };
+}
+
+async function purge(engine: BrainEngine, text: string): Promise<void> {
+ const [{ visibility }] = await engine.executeRaw<{ visibility: string }>(
+ `SELECT COALESCE((SELECT value FROM config WHERE key='facts.default_visibility'), 'private') AS visibility`);
+ await engine.executeRaw(`INSERT INTO fact_purges(source_id, visibility, subject, fact_hash) VALUES ('default', $1, '*', gbrain_fact_fingerprint($2))`,
+ [visibility, text]);
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ test(`${backend}: a batch refused purged_content and redacted by the journal publishes next run, and the run after makes no model call`, async () => {
+ await managedBrain(async brain => {
+ const { engine } = brain;
+ await putPage(brain);
+ const calls = { n: 0 };
+ failNextPublication(PURGED_GUARD());
+ expect((await extract(engine, calls, [KEPT, PURGED])).result.pages_failed).toBe(1);
+ expect(calls.n).toBe(1);
+ await purge(engine, PURGED);
+ // The stuck state: the refusal's receipt keeps its request id and digest, but no intent and so no attempt history.
+ expect(await batches(engine)).toMatchObject([{ state: 'failed', error_code: 'purged_content', compacted: true, has_intent: false }]);
+
+ const next = await extract(engine, calls, [KEPT, PURGED]);
+ expect(next.conflicts).toEqual([]);
+ expect(next.result).toMatchObject({ pages_processed: 1, pages_failed: 0, facts_inserted: 1, facts_skipped_purged: 1 });
+ expect(calls.n).toBe(2);
+ expect(await factsOf(engine)).toEqual([KEPT, 'EXTRACTION_COMPLETE']);
+ const [spent, published] = await batches(engine);
+ expect(published).toMatchObject({ state: 'committed' });
+ expect(published!.request_id).not.toBe(spent!.request_id);
+
+ const after = await extract(engine, calls, [KEPT, PURGED]);
+ expect(after.result).toMatchObject({ pages_skipped_completed: 1, pages_failed: 0 });
+ expect(calls.n).toBe(2);
+ expect((await batches(engine)).length).toBe(2);
+ }, { databaseUrl });
+ }, 120_000);
+
+ test(`${backend}: a failed batch compacted by retention publishes next run instead of reusing its request id`, async () => {
+ await managedBrain(async brain => {
+ const { engine } = brain;
+ await putPage(brain);
+ const calls = { n: 0 };
+ failNextPublication(Object.assign(new Error('simulated owner crash'), { code: 'storage_error' }));
+ expect((await extract(engine, calls, [KEPT])).result.pages_failed).toBe(1);
+ const [failed] = await batches(engine);
+ expect(await compactReceipt(engine, failed!)).not.toHaveProperty('skipped');
+ expect(await batches(engine)).toMatchObject([{ state: 'failed', error_code: 'storage_error', compacted: true, has_intent: false }]);
+
+ const next = await extract(engine, calls, [KEPT]);
+ expect(next.conflicts).toEqual([]);
+ expect(next.result).toMatchObject({ pages_processed: 1, pages_failed: 0, facts_inserted: 1 });
+ expect(calls.n).toBe(2);
+ expect(await factsOf(engine)).toEqual([KEPT, 'EXTRACTION_COMPLETE']);
+
+ const after = await extract(engine, calls, [KEPT]);
+ expect(after.result).toMatchObject({ pages_skipped_completed: 1 });
+ expect(calls.n).toBe(2);
+ }, { databaseUrl });
+ }, 120_000);
+
+ test(`${backend}: an identical batch is not answered with a compacted request's stored failure`, async () => {
+ await managedBrain(async brain => {
+ const { engine } = brain;
+ await putPage(brain);
+ const { authority, entry } = await frozenEntry(engine);
+ failNextPublication(Object.assign(new Error('simulated owner crash'), { code: 'storage_error' }));
+ await expect(submitConversationPages(engine, authority, [entry])).rejects.toMatchObject({ code: 'storage_error' });
+ const [failed] = await batches(engine);
+ expect(await compactReceipt(engine, failed!)).not.toHaveProperty('skipped');
+ const receipt = await submitConversationPages(engine, authority, [entry]);
+ expect(receipt).toMatchObject({ state: 'committed', committed: 1 });
+ expect(receipt.request_id).not.toBe(failed!.request_id);
+ expect(await factsOf(engine)).toEqual([KEPT]);
+ }, { databaseUrl });
+ }, 120_000);
+
+ test(`${backend}: a genuine replay of the same batch still dedupes, before and after its committed receipt is compacted`, async () => {
+ await managedBrain(async brain => {
+ const { engine } = brain;
+ await putPage(brain);
+ const { authority, entry } = await frozenEntry(engine);
+ const first = await submitConversationPages(engine, authority, [entry]);
+ expect(first).toMatchObject({ state: 'committed', committed: 1 });
+ expect((await submitConversationPages(engine, authority, [entry])).request_id).toBe(first.request_id);
+ const [committed] = await batches(engine);
+ expect(await compactReceipt(engine, committed!)).not.toHaveProperty('skipped');
+ expect((await submitConversationPages(engine, authority, [entry])).request_id).toBe(first.request_id);
+ expect((await batches(engine)).length).toBe(1);
+ expect(await factsOf(engine)).toEqual([KEPT]);
+ }, { databaseUrl });
+ }, 120_000);
+}
diff --git a/test/e2e/conversation-facts-redacted-batch-7516-postgres.test.ts b/test/e2e/conversation-facts-redacted-batch-7516-postgres.test.ts
new file mode 100644
index 0000000000..fc4682667e
--- /dev/null
+++ b/test/e2e/conversation-facts-redacted-batch-7516-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../conversation-facts-redacted-batch-7516.test.ts'));