Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(memory): fact_withdrawn refusals carry when and how widely the claim was forgotten
garrytan27dc19790e42
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bb9e2da9a2..ab3bad81c1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased: withdrawn refusal detail, version stamped at merge] - 2026-10-12++**When `remember` refuses a forgotten claim, the refusal now says when and how widely it was forgotten.** An agent that re-saves a claim the user forgot gets `fact_withdrawn` as before, and the refusal now carries `withdrawn: { at, subject, visibility }`, where `subject` is the entity the claim was forgotten for or `all_entities`. The agent can tell the user "you asked me to forget that on <date>" instead of retrying. The object rides the immediate refusal, the batch item error, the failed write receipt and `get_write_request`. It covers the exact claim only, the message, code and suggestion are unchanged, and nothing is ever restored.++### Itemized changes++- `src/core/facts/single-prepare.ts` (`factWithdrawnRefusal`): the object comes from the withdrawal ledger only (never a purge): the named entity's withdrawal over `all_entities`, then the newest, among withdrawals whose forgotten rows the caller can read. When it cannot read them, the refusal is the one v0.60.176.0 returns, with no object. `src/core/facts/write-single.ts` applies the same rule, fail-closed when the caller is unknown.+- `src/core/ops/contract.ts`, `src/core/agent-output.ts`, `src/core/remember-batch.ts`, `src/core/persistence/verb-errors.ts`: `withdrawn` on `OperationError`, the agent envelope (stdio, HTTP, CLI) and batch item errors.+- `src/core/facts/withdrawal.ts`, `src/core/persistence/coordinator.ts`, `src/core/persistence/service.ts`, `src/core/ops/persistence.ts`: a refusal at preparation stores the object in the receipt's versioned `error_detail`, read back by the failed response, replay and `get_write_request`.+- `src/core/verbs.ts` (`ERROR_SCHEMA.withdrawn`), the conformance fixture for re-remembering a forgotten claim, the `gbrain errors fact_withdrawn` row, MEMORY_VERBS v1 "remember withdrawn refusal detail (additive)".+- Tests: `test/withdrawn-detail.test.ts` (PGLite) and `test/e2e/withdrawn-detail-postgres.test.ts` (Postgres) share `test/helpers/withdrawn-detail-scenarios.ts`; `test/agent-contract-goldens.test.ts` pins one object on stdio, HTTP and CLI.+## [0.60.178.0] - 2026-10-12**Batch entity lookups respect quarantine.** `entity` with `names` now hides quarantined pages from remote callers the way a single-name `entity` lookup and `get_page` already do, whichever way the name resolves, and a quarantined identity sibling no longer appears beside a page for remote callers, in batch rows or in a single-name card. Trusted local callers see the same results as before. No migration, no paid call.diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.mdindex 8b3fe14259..2108c98112 100644--- a/docs/architecture/key-files/memory-purge.md+++ b/docs/architecture/key-files/memory-purge.md@@ -17,4 +17,4 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu- `src/core/ops/purge.ts` — `purge_fact`, `list_page_purges`, `unpurge_page`: admin scope, `cliOnly` (every MCP route gets `trusted_local_only`). The resident owner runs them only for its verified local CLI registration (`LOCAL_CLI_OWNER_OPERATIONS` in `persistence/ipc.ts`, checked in `persistence/provider.ts`).- `src/commands/forget-purge.ts` + `src/commands/pages-purges.ts` — the CLI fronts. `runForgetPurge` always runs the dry run, then a typed token on a terminal or `--yes` plus `--request-id` without one; `--match` lists ids, `--status` polls completion; `PURGE_FAMILY_HELP` is the purge-family table shown by `gbrain forget --help`. `gbrain pages purges list` and `gbrain pages unpurge <slug>` run the page-tombstone ops as the trusted CLI.-- Withdrawn-claim refusal on `remember` (`persistence/memory-mutations.ts`, `memory-prepare.ts`) — admission refuses a withdrawn claim (`fact_withdrawn`, `FACT_WITHDRAWN_MESSAGE`/`_SUGGESTION` in `src/core/facts/withdrawal.ts`) before a request exists, and preparation re-checks it; `writeFailureDiagnostic` allowlists that prefix, so a failed receipt and `get_write_request` name it. `replaces` accepts a target saved without an entity (links it by supersession). Test: `test/remember-withdrawn-claim.test.ts`. (R1, Cat 40 Hard.)+- Withdrawn-claim refusal on `remember` (`persistence/memory-mutations.ts`, `memory-prepare.ts`) — admission refuses a withdrawn claim (`fact_withdrawn`, `FACT_WITHDRAWN_MESSAGE`/`_SUGGESTION` in `src/core/facts/withdrawal.ts`) before a request exists, and preparation re-checks it; `writeFailureDiagnostic` allowlists that prefix, so a failed receipt and `get_write_request` name it. `replaces` accepts a target saved without an entity (links it by supersession). Test: `test/remember-withdrawn-claim.test.ts`. (R1, Cat 40 Hard.) The refusal carries an additive `withdrawn` object (`factWithdrawnRefusal` in `facts/single-prepare.ts`, from `fact_withdrawals` only: the named entity's row over `all_entities`, then the newest, omitted when the caller cannot read the forgotten rows); `withdrawalFailureDetail`/`withdrawnFromDetail` in `facts/withdrawal.ts` keep it in the failed receipt's `error_detail` for `get_write_request` and replay. Tests: `test/withdrawn-detail.test.ts`, `test/e2e/withdrawn-detail-postgres.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 59296caa9d..f49588dd3a 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -15,6 +15,7 @@ Under contract v1 an `error` value never changes. Where a surface sends a legacy| `error` (frozen) | `code` (canonical) | Meaning ||---|---|---|+| `invalid_params` | `fact_withdrawn` | `remember` refused a claim that was explicitly forgotten for this subject (wire `invalid_params`, message prefix `fact_withdrawn:`); nothing was saved. || `permission_denied` | `insufficient_scope` | The connection lacks the OAuth scope the operation requires. || `invalid_params` | `invalid_fence` | A facts or takes fence in the page cannot be imported without dropping or guessing rows, so the page (or the file) was not written. || `invalid_params` | `not_found` | The requested resource does not exist or is not visible to this caller. |@@ -954,6 +955,14 @@ More: [docs/guides/move-to-postgres.md#graduated-datastore](../../docs/guides/mo|---|---|---|---|---|---|---|| Fact not found. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### fact_withdrawn++<a id="fact_withdrawn"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| `remember` refused a claim that was explicitly forgotten for this subject (wire `invalid_params`, message prefix `fact_withdrawn:`); nothing was saved. | A forgotten claim stays withdrawn: remembering the same normalized text does not restore it, and a claim forgotten without an entity is withdrawn for every entity. The additive `withdrawn` object (`at`, `subject`: an entity slug or `all_entities`, `visibility`) says when and how widely the exact claim was forgotten; it covers that exact claim only, and its absence carries no meaning. | Do not retry the same text. Tell the user the claim was forgotten (withdrawn.at, withdrawn.subject); if it is still true, remember it in new words. To link a fact saved without an entity, remember it with entity and replaces set to its fact id instead of forgetting it. | agent | `repeat the read that failed` | 1 | no |+### facts_absorb_write_refused<a id="facts_absorb_write_refused"></a>diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex 9fc8ccbbff..0c71583e6d 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -304,6 +304,18 @@ and a claim forgotten without an entity is withdrawn for every entity. To linka fact saved without an entity, do not forget it; remember it with `entity`and `replaces` set to its id.+#### remember withdrawn refusal detail (additive)++A `fact_withdrawn` refusal may carry `withdrawn: { at, subject, visibility }`:+`at` is when the claim was forgotten (ISO 8601), `subject` the entity slug it+was forgotten for or `all_entities` (forgotten without an entity), and+`visibility` the forgotten fact's. When several withdrawals match, the one for+the named entity wins over `all_entities`, then the newest. The same object+rides the immediate refusal, the `items[]` error, the failed write receipt and+`get_write_request`. It covers the exact normalized claim only, never a+paraphrase, and its absence carries no meaning: the message prefix, code and+suggestion are unchanged.+#### remember replaces (additive)`replaces` (string): the `fact_id` this fact replaces, caller-directed: thediff --git a/llms-full.txt b/llms-full.txtindex d19692b31f..4bda4b309a 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -8800,6 +8800,18 @@ and a claim forgotten without an entity is withdrawn for every entity. To linka fact saved without an entity, do not forget it; remember it with `entity`and `replaces` set to its id.+#### remember withdrawn refusal detail (additive)++A `fact_withdrawn` refusal may carry `withdrawn: { at, subject, visibility }`:+`at` is when the claim was forgotten (ISO 8601), `subject` the entity slug it+was forgotten for or `all_entities` (forgotten without an entity), and+`visibility` the forgotten fact's. When several withdrawals match, the one for+the named entity wins over `all_entities`, then the newest. The same object+rides the immediate refusal, the `items[]` error, the failed write receipt and+`get_write_request`. It covers the exact normalized claim only, never a+paraphrase, and its absence carries no meaning: the message prefix, code and+suggestion are unchanged.+#### remember replaces (additive)`replaces` (string): the `fact_id` this fact replaces, caller-directed: thediff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex 251ecaa4ae..3cb4c181e9 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -13,7 +13,7 @@import { existsSync } from 'node:fs';import { join } from 'node:path';import { VERSION } from '../version.ts';-import { OperationError, __registerOperationErrorRenderer } from './ops/contract.ts';+import { OperationError, __registerOperationErrorRenderer, type WithdrawnDetail } from './ops/contract.ts';import { StructuredAgentError } from './errors.ts';import { canonicalCodeFor, codeEntry, codeClass, codeRetryable, exitCodeForCode } from './error-catalogue.ts';import { VERB_NAMES } from './verbs.ts';@@ -97,6 +97,8 @@ export interface AgentEnvelope {detail?: string; protocol_version?: 1; write_request?: unknown; write_error?: string;/** #6188: a fence refusal's location and blocking issues (location and class only). */fence?: Record<string, unknown>; fence_issues?: Array<Record<string, unknown>>;+ /** A `fact_withdrawn` refusal's withdrawal (`at`, `subject`, `visibility`). */+ withdrawn?: WithdrawnDetail;}export interface RenderContext {@@ -368,6 +370,7 @@ export interface EnvelopeParts {retryable?: boolean;fence?: Record<string, unknown>;fence_issues?: Array<Record<string, unknown>>;+ withdrawn?: WithdrawnDetail;}/** Replace each occurrence of `bare` that is a whole command (not followed by a word, path or more flags). */@@ -416,6 +419,7 @@ export function buildEnvelope(p: EnvelopeParts, ctx: RenderContext): AgentEnvelo...(p.write_error !== undefined ? { write_error: p.write_error } : {}),...(p.fence !== undefined ? { fence: p.fence } : {}),...(p.fence_issues?.length ? { fence_issues: p.fence_issues } : {}),+ ...(p.withdrawn !== undefined ? { withdrawn: p.withdrawn } : {}),...(p.reason !== undefined ? { reason: p.reason } : {}),...(p.why !== undefined ? { why: p.why } : {}),...(fix ? { fix } : {}),@@ -558,6 +562,7 @@ const ROWS: Row[] = [protocol_version: e.protocolVersion === 1 ? 1 : undefined,write_request: j.write_request, write_error: e.writeError,...(e.fence ? { fence: e.fence } : {}), ...(e.fenceIssues?.length ? { fence_issues: e.fenceIssues } : {}),+ ...(e.withdrawn ? { withdrawn: e.withdrawn } : {}),...(e.retryable !== undefined ? { retryable: e.retryable } : {}),};},diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 13077c7ba1..54501d9628 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -466,6 +466,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.177.0', text: 'Fact extraction on explicit lanes (sync import, put_page) now measures same-page rewordings: when a page is re-extracted and a new claim sits within cosine 0.85 of a fact the same page produced earlier without changing a number, date, amount or negation, the run counts it as `would_dedup_same_page` and prints one stderr line naming the matched fact id. Nothing is dropped or expired; the counter exists so the rule\'s false-positive rate can be measured before any automatic dedup ships.' },{ since: '0.60.177.0', text: 'The atom-extraction phase (`extract_atoms`) now honors a schema pack that declares one of the built-in extractable types (meeting, source, article, video, book, original) as `extractable: false`, the way facts extraction already did: such pages are no longer mined into atoms. gbrain-base declares meeting and source extractable and is unchanged; on gbrain-recommended, `source` pages stop being atom-extracted. A pack that does not mention a built-in type keeps it extractable.' },// Fix wave 15 group 1 (managed sync authority and data safety).+ // Cat 40 next wave, Part 3 step 1. `since` is provisional; the integrator restamps it at the merge slot.+ { since: '0.60.177.0', text: 'A `remember` refused with `fact_withdrawn` now carries an additive `withdrawn` object (`at`, `subject`: the entity slug or `all_entities`, `visibility`) on the immediate refusal, the batch item error, the failed write receipt and `get_write_request`, so an agent can tell the user when and how widely the exact claim was forgotten instead of retrying. The message, code and suggestion are unchanged; the object is absent when the caller cannot read the forgotten rows.' },{ since: '0.60.177.0', text: 'A brain whose persistence mode cannot be read (no `persistence_brain` row, more than one, or an `enabled` value that is not a boolean) now refuses every write, sync, connector run, activation and maintenance step that depends on it with `storage_error` (`detail: persistence_mode_unknown`, fix: `gbrain sources writer status --probe --json`) instead of treating the brain as unmanaged and writing around the owner; only a well-formed `enabled: false` row selects the unmanaged path. A managed `gbrain sync --full` tree walk no longer soft-deletes a page it imported from an untracked working-tree file: a page whose stored import provenance is the working tree, or is unknown, is kept while its file is still present (`working_tree_kept` in the result), and a page imported from a Git blob still follows Git. A soft deletion is not harmless (recall stops at once and the purge lifecycle follows), so this applies on the next sync without opt-in. A first sync, a `--full` sync or one commit that alone exceeds the 100,000-entry / 16 MiB cursor bound now completes in path slices (every import slice, then bounded deletion slices, pinned at one target; the slice cursor is checkpointed with each slice and `last_commit` moves only when the whole target settles) instead of refusing with `request_too_large`; a scheduled sync takes one slice per run and `gbrain sync --drain` takes them all. One file whose manifest entry alone exceeds the byte bound still refuses by name.' },];diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex a2df2162a5..1d1834c163 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -175,6 +175,7 @@ export const CODES = {export_limit: { class: 'caller', summary: "This migration is bounded to 5,000 active pages per source; split or use a reviewed bulk export." },extraction_failed: { class: 'server', summary: "The accepted atom extraction failed (malformed output, or a response stopped before the end); a new attempt needs approval.", why: "The drain retries a failed managed atom batch on its own up to 3 times per content (then holds it, code held_failed); this code reports a failed explicit retry, or a failure the drain cannot attribute to a checkpoint, so the same input is not paid for again without approval." },extractor_identity_mismatch: { class: 'server', summary: "The approved extractor differs from the installed extractor; this receipt cannot resume or admit another revision." },+ fact_withdrawn: { class: 'caller', summary: "`remember` refused a claim that was explicitly forgotten for this subject (wire `invalid_params`, message prefix `fact_withdrawn:`); nothing was saved.", why: "A forgotten claim stays withdrawn: remembering the same normalized text does not restore it, and a claim forgotten without an entity is withdrawn for every entity. The additive `withdrawn` object (`at`, `subject`: an entity slug or `all_entities`, `visibility`) says when and how widely the exact claim was forgotten; it covers that exact claim only, and its absence carries no meaning.", legacy_error: 'invalid_params', suggestion: 'Do not retry the same text. Tell the user the claim was forgotten (withdrawn.at, withdrawn.subject); if it is still true, remember it in new words. To link a fact saved without an entity, remember it with entity and replaces set to its fact id instead of forgetting it.' },fact_already_expired: { class: 'caller', summary: "The fact had already expired before this write." },fence_unrenderable: { class: 'server', summary: "A legacy fact row was not adopted into its page's facts fence because the fence codec reads the rendered row back as something other than the stored fact.", why: "The fence trims a claim, folds CRLF to LF, reads `~~x~~` as a struck row and `<br>` as a line break; a claim the codec would change by more than whitespace cannot be written into the fence without changing what it says, so the row stays a legacy row (active and searchable, nothing is lost) and is counted by doctor fence_integrity as unrenderable_legacy_facts. The same code names a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input.", docs: 'docs/guides/write-refusals.md#fence_unrenderable', suggestion: 'Nothing to fix in the page: the rows stay active and searchable. Report the page slug and the reason class with the gbrain version; do not forget or expire a row to clear this count.', fix: { argv: ['gbrain', 'doctor', '--only', 'fence_integrity', '--json'], consent: [], actor: 'agent', why: 'Lists the pages whose legacy fact rows cannot be adopted into their fence and why (by fact id and reason class, never the claim text), read-only.', requires_exclusive: false } },fact_not_found: { class: 'caller', summary: "Fact not found." },diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.tsindex 700ff873de..94584ddbec 100644--- a/src/core/facts/single-prepare.ts+++ b/src/core/facts/single-prepare.ts@@ -1,5 +1,5 @@import type { BrainEngine, FactAttribution, FactRow } from '../engine.ts';-import { verbError } from '../ops/contract.ts';+import { verbError, type OperationError } from '../ops/contract.ts';import { isAvailable, embedOne, getEmbeddingModel } from '../ai/gateway.ts';import { cosineSimilarity } from './classify.ts';import { FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION, isFactWithdrawn } from './withdrawal.ts';@@ -35,7 +35,15 @@ export async function prepareFactEmbedding(fact: string, signal?: AbortSignal, d*/export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: string, input: SingleFactIntent, opts: { excludePrivate?: boolean } = {}): Promise<void> {await assertFactNotPurged(engine, sourceId, input);- if (!await isFactWithdrawn(engine, sourceId, input.visibility, input.fact, input.entity_slug)) return;+ if (await isFactWithdrawn(engine, sourceId, input.visibility, input.fact, input.entity_slug)) throw await factWithdrawnRefusal(engine, sourceId, input, opts);+}++/**+ * The refusal for a claim `isFactWithdrawn` matched. `withdrawn` comes from the withdrawal ledger alone (never a purge):+ * the most specific subject first, then the newest withdrawal, among withdrawals the caller can see the withdrawn rows of+ * (or that no row backs). It covers the exact normalized claim only.+ */+export async function factWithdrawnRefusal(engine: BrainEngine, sourceId: string, input: SingleFactIntent, opts: { excludePrivate?: boolean } = {}): Promise<OperationError> {if (opts.excludePrivate) {const [backing] = await engine.executeRaw<{ visible: boolean; hidden: boolean }>(`SELECTCOALESCE(bool_or(${privateProvenanceFilterFragment('f')}), false) AS visible,@@ -46,9 +54,20 @@ export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: striWHERE f.source_id=$1 AND f.visibility=$2 AND f.expired_at IS NOT NULLAND gbrain_fact_fingerprint(f.fact)=gbrain_fact_fingerprint($3) AND (w.subject='*' OR w.subject=$4::text)`,[sourceId, input.visibility, input.fact, input.entity_slug]);- if (backing?.hidden && !backing.visible) throw pageNotVisibleError();+ if (backing?.hidden && !backing.visible) return pageNotVisibleError();}- throw verbError('invalid_params', FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION);+ const [row] = await engine.executeRaw<{ subject: string; withdrawn_at: string; visibility: 'world' | 'private' }>(`SELECT w.subject,w.visibility,w.withdrawn_at::text AS withdrawn_at+ FROM fact_withdrawals w LEFT JOIN facts f ON f.source_id=w.source_id AND f.visibility=w.visibility AND f.expired_at IS NOT NULL+ AND w.fact_hash IN (gbrain_fact_fingerprint(f.fact),gbrain_fact_fingerprint_v1(f.fact)) AND (w.subject='*' OR w.subject=COALESCE(f.entity_slug,'*'))+ WHERE w.source_id=$1 AND w.visibility=$2 AND w.fact_hash IN (gbrain_fact_fingerprint($3),gbrain_fact_fingerprint_v1($3))+ AND (w.subject='*' OR w.subject=$4::text)+ GROUP BY w.subject,w.visibility,w.withdrawn_at+ HAVING $5::boolean=false OR COALESCE(bool_or(${privateProvenanceFilterFragment('f')}), false) OR NOT COALESCE(bool_or(f.id IS NOT NULL), false)+ ORDER BY (w.subject<>'*') DESC, w.withdrawn_at DESC LIMIT 1`,+ [sourceId, input.visibility, input.fact, input.entity_slug, opts.excludePrivate === true]);+ const error = verbError('invalid_params', FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION);+ if (row) error.withdrawn = { at: new Date(row.withdrawn_at).toISOString(), subject: row.subject === '*' ? 'all_entities' : row.subject, visibility: row.visibility };+ return error;}export const CANDIDATE_FUSION_KEY = 'facts.candidate_fusion';export type CandidateFusion = 'rrf_free' | 'interleave';diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.tsindex 96dd86b8c7..7ac588c4ac 100644--- a/src/core/facts/withdrawal.ts+++ b/src/core/facts/withdrawal.ts@@ -1,6 +1,6 @@import type { BrainEngine } from '../engine.ts';import { renderFactsTable, type ParsedFact } from '../facts-fence.ts';-import { OperationError, opError } from '../ops/contract.ts';+import { OperationError, opError, type WithdrawnDetail } from '../ops/contract.ts';import { fenceOperationError } from '../fence-repair/refusal.ts';import { withdrawnFact, withdrawalFenceBlocks } from './withdrawal-overlay.ts';import { ambiguousFenceClaims, discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';@@ -208,3 +208,20 @@ export async function assertFactNotPurged(engine: BrainEngine, sourceId: string,throw opError('purged_content', 'purged_content: this claim was purged from this source and cannot be saved again.','Purged content stays out of the brain. If it is still true, remember it in new words; only the owner can clear a purge tombstone.');}++export const WITHDRAWN_DETAIL_VERSION = 1;+/** The bounded, versioned `error_detail` a `fact_withdrawn` refusal stores, so a failed receipt keeps its `withdrawn` object. */+export interface WithdrawalFailureDetail { origin: 'withdrawal'; withdrawn: WithdrawnDetail & { version: typeof WITHDRAWN_DETAIL_VERSION } }++export function withdrawalFailureDetail(error: Pick<OperationError, 'withdrawn'>): WithdrawalFailureDetail | undefined {+ return error.withdrawn ? { origin: 'withdrawal', withdrawn: { version: WITHDRAWN_DETAIL_VERSION, ...error.withdrawn } } : undefined;+}++/** The `withdrawn` object a stored `error_detail` carries, validated field by field, or undefined. */+export function withdrawnFromDetail(detail: unknown): WithdrawnDetail | undefined {+ if (!detail || typeof detail !== 'object' || (detail as { origin?: unknown }).origin !== 'withdrawal') return undefined;+ const w = (detail as { withdrawn?: Record<string, unknown> }).withdrawn;+ if (!w || w.version !== WITHDRAWN_DETAIL_VERSION || typeof w.at !== 'string' || !Number.isFinite(Date.parse(w.at))) return undefined;+ if (typeof w.subject !== 'string' || !w.subject || w.subject.length > 500 || (w.visibility !== 'world' && w.visibility !== 'private')) return undefined;+ return { at: w.at, subject: w.subject, visibility: w.visibility };+}diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.tsindex a1a8f42458..b58e2fe9d2 100644--- a/src/core/facts/write-single.ts+++ b/src/core/facts/write-single.ts@@ -134,10 +134,11 @@ export async function writeSingleFact(// resolver returned nothing (fail-closed — no live page was verified).const resolutionSource = resolved?.source ?? null;- const { FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION, isFactWithdrawn } = await import('./withdrawal.ts');+ const { isFactWithdrawn } = await import('./withdrawal.ts');if (await isFactWithdrawn(engine, sourceId, visibility, factText, resolvedSlug)) {- const { verbError } = await import('../ops/contract.ts');- throw verbError('invalid_params', FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION);+ const { factWithdrawnRefusal } = await import('./single-prepare.ts');+ throw await factWithdrawnRefusal(engine, sourceId, { fact: factText, kind, visibility, entity_slug: resolvedSlug },+ { excludePrivate: await resolveExcludePrivatePages(engine, input.remote) });}// Embedding (NOT an LLM call): powers dedup + downstream recall. Fail-soft —diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 83c5464844..917d5e6ac5 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -65,6 +65,9 @@ export type ErrorCode =// eslint-disable-next-line @typescript-eslint/ban-types| (string & {}); // OPEN union for forward-compat (eE7 / D13)+/** `withdrawn` on a `fact_withdrawn` refusal: `subject` is the entity slug, or `all_entities` for a claim forgotten without one. */+export interface WithdrawnDetail { at: string; subject: string; visibility: 'world' | 'private' }+export class OperationError extends Error {/*** MEMORY_VERBS v1: verb handlers set `protocolVersion` (=1) and may set@@ -89,6 +92,8 @@ export class OperationError extends Error {/** #6188 (D16, D18): a fence refusal's location and its blocking issues; location and class only, never a cell value. */public fence?: Record<string, unknown>;public fenceIssues?: Array<Record<string, unknown>>;+ /** A `fact_withdrawn` refusal's withdrawal: when and for which subject the exact claim was forgotten. Absence carries no meaning. */+ public withdrawn?: WithdrawnDetail;/** Set to 1 by opError(); toJSON() emits `contract_version` only when set. */public contractVersion?: 1;/**@@ -151,6 +156,7 @@ export class OperationError extends Error {...(this.notices?.length ? { notices: this.notices.map(n => wireRenderer ? wireRenderer.notice(n) : n) } : {}),...(this.fence ? { fence: this.fence } : {}),...(this.fenceIssues?.length ? { fence_issues: this.fenceIssues } : {}),+ ...(this.withdrawn ? { withdrawn: this.withdrawn } : {}),...(this.contractVersion !== undefined ? { contract_version: this.contractVersion } : {}),};}diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.tsindex 01936d889c..cd9ee52b75 100644--- a/src/core/ops/persistence.ts+++ b/src/core/ops/persistence.ts@@ -112,11 +112,13 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: WprocessingOptions: intent?.processingOptions, syncOptions: intent?.syncOptions, repoPath: intent?.repoPath }) : null;// #5929: a trusted local reader learns when the owner that ran the attempt is on another build.const mismatch = ctx.remote === false ? (await import('../persistence/publication-failure.ts')).ownerBuildMismatch(row.error_detail, (await import('../../version.ts')).VERSION) : null;+ const withdrawn = (await import('../facts/withdrawal.ts')).withdrawnFromDetail(row.error_detail);return {...publicWriteReceipt(receiptFor(row, facts)),operation: row.operation, source_id: row.source_id, slug: row.slug,...(mismatch ? { owner_build: mismatch } : {}),...(isWriteErrorCode(row.error_code) ? { write_error: row.error_code, write_error_message: writeFailureDiagnostic(row.error_code, row.error_message).message } : {}),+ ...(withdrawn ? { withdrawn } : {}),...(checkpoint ? { detail: checkpoint.detail, suggestion: checkpoint.suggestion, docs: checkpoint.docs } : {}),effects: (await publicEffectsForRequest(ctx.engine, row.id)).map(effect => {const hint = effect.reason ? receiptDeliveredHint({ error_code: effect.reason, source_id: row.source_id, slug: row.slug }) : null;diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 1415413c65..3b2e658462 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -38,6 +38,7 @@ import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guimport { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';import { fenceFailureDetail } from '../fence-repair/refusal.ts';+import { withdrawalFailureDetail } from '../facts/withdrawal.ts';import { faultPoint, withFaultPoints } from './fault-points.ts';import { recordPublicationFenceTrend } from '../fence-repair/census-store.ts';@@ -126,8 +127,8 @@ export { fileHash as persistenceFileHash, publishFile as publishPersistenceFilefunction requestError(error: unknown): PublicationFailure {if (error instanceof OperationError) {// #6188: a typed fence refusal keeps its location in the bounded detail, which outlives receipt compaction.- const fence = fenceFailureDetail(error);- return { code: error.code, message: error.message, ...(fence ? { detail: fence } : {}) };+ const detail = fenceFailureDetail(error) ?? withdrawalFailureDetail(error);+ return { code: error.code, message: error.message, ...(detail ? { detail } : {}) };}const refusal = databaseRefusal(error);if (refusal) return refusal;diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex 6f00f803e2..0c7ca6beea 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -1,6 +1,7 @@import { OperationError } from '../ops/contract.ts';import { writerStamp } from './writer-versions.ts';import type { FenceFailureDetail } from '../fence-repair/refusal.ts';+import type { WithdrawalFailureDetail } from '../facts/withdrawal.ts';import type { Action } from '../agent-output.ts';/**@@ -34,7 +35,9 @@ export type FenceRefusalDetail = FenceFailureDetail & Pick<PublicationFailureDetexport interface OwnerExceptionDetail extends Pick<PublicationFailureDetail, 'stage' | 'attempt'> {origin: 'owner_exception'; error_class?: string; errno?: string; frame?: string;}-export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | OwnerExceptionDetail }+/** A `fact_withdrawn` refusal's `withdrawn` object (`facts/withdrawal.ts`), plus the attempt stamp. */+export type WithdrawalRefusalDetail = WithdrawalFailureDetail & Pick<PublicationFailureDetail, 'stage' | 'attempt'>;+export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | WithdrawalRefusalDetail | OwnerExceptionDetail }const IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;const ident = (value: unknown) => typeof value === 'string' && IDENT.test(value) ? value : undefined;diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex a9fe73d0c8..89890125db 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -21,6 +21,7 @@ import { receiptDeliveredHint } from './connector-errors.ts';import type { PgAccessReason } from '../pg-access-classify.ts';import { contentRefusalFromReceipt } from '../import-screen.ts';import { fenceIssuesFromDetail, fenceLocationFromDetail } from '../fence-repair/refusal.ts';+import { withdrawnFromDetail } from '../facts/withdrawal.ts';import { heldFileDiagnostic } from './verb-errors.ts';import { isMissingPageMessage } from './page-identity.ts';import { registerPersistenceConsumerConfig } from '../embedding-disabled.ts';@@ -353,6 +354,8 @@ export function writeResponse(row: WriteRequest, hints: { retryAfterMs?: number}if (content.key || content.line !== undefined) error.detail = [content.key ? `key ${content.key}` : '', content.line !== undefined ? `line ${content.line}` : ''].filter(Boolean).join(', ');}+ const withdrawn = isTerminal(row) ? withdrawnFromDetail(row.error_detail) : undefined;+ if (withdrawn) error.withdrawn = withdrawn;if (reason === 'page_identity_changed' && isMissingPageMessage(row.error_message)) error.canonical = 'page_not_found';error.receiptFields = { operation: row.operation, source_id: row.source_id, slug: row.slug || null, principal_kind: row.principal_kind, principal_id: row.principal_id };error.writeRequest = receipt as WriteReceipt;diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex afcbeda654..b3a52b813c 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -142,6 +142,7 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {const frozen = frozenVerbWriteError(error.writeRequest, error.writeError, error.message);// #6188: the frozen v1 code stays; the fence refusal's reason, location and issues ride along additively.if (error.canonicalCode === 'invalid_fence') Object.assign(frozen, { reason: error.reason, fence: error.fence, fenceIssues: error.fenceIssues });+ if (error.withdrawn) frozen.withdrawn = error.withdrawn;throw frozen;}// #5575: the frozen wire code stays invalid_params; the envelope's canonical code is purged_content.diff --git a/src/core/remember-batch.ts b/src/core/remember-batch.tsindex e7d340bc77..e5ee465bf8 100644--- a/src/core/remember-batch.ts+++ b/src/core/remember-batch.ts@@ -103,7 +103,7 @@ export async function runRememberBatch(ctx: OperationContext, p: Record<string,});} catch (e) {if (!(e instanceof OperationError)) throw e;- results.push({ index, request_id: child, status: 'failed', error: { code: e.code, message: e.message, ...(e.detail ? { detail: e.detail } : {}), ...(e.suggestion ? { suggestion: e.suggestion } : {}) } });+ results.push({ index, request_id: child, status: 'failed', error: { code: e.code, message: e.message, ...(e.detail ? { detail: e.detail } : {}), ...(e.suggestion ? { suggestion: e.suggestion } : {}), ...(e.withdrawn ? { withdrawn: e.withdrawn } : {}) } });}}const failed = results.filter(r => r.status === 'failed').length;diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex b823f7eab3..8069dd5845 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -987,5 +987,15 @@ export const ERROR_SCHEMA: Record<string, unknown> = {protocol_version: { type: 'integer', const: MEMORY_VERBS_VERSION },write_request: WRITE_RECEIPT_SCHEMA,write_error: { type: 'string', enum: [...WRITE_ERROR_CODES] },+ withdrawn: {+ type: 'object',+ required: ['at', 'subject', 'visibility'],+ description: 'Additive, on a fact_withdrawn refusal: when and for which subject (an entity slug, or all_entities) the exact claim was forgotten. Absence carries no meaning.',+ properties: {+ at: { type: 'string' },+ subject: { type: 'string' },+ visibility: { type: 'string', enum: ['world', 'private'] },+ },+ },},};diff --git a/src/core/verbs/conformance-fixtures.ts b/src/core/verbs/conformance-fixtures.tsindex d601519ce0..38b39b31f5 100644--- a/src/core/verbs/conformance-fixtures.ts+++ b/src/core/verbs/conformance-fixtures.ts@@ -218,6 +218,17 @@ export const CONFORMANCE_CASES: ConformanceCase[] = [validateSchema: true,expect: [{ path: 'expired', equals: false }],},+ {+ name: 'remember of the forgotten claim is refused invalid_params with a suggestion (a withdrawn object, when present, is schema-valid)',+ verb: 'remember',+ params: {+ fact: 'conformance {{marker}}: expiring fact',+ provenance: 'conformance run {{marker}}',+ entity: 'people/conformance-{{marker}}',+ },+ expectErrorCode: 'invalid_params',+ expectSuggestion: true,+ },{name: 'forget unknown id returns not_found with a suggestion',verb: 'forget',diff --git a/test/agent-contract-goldens.test.ts b/test/agent-contract-goldens.test.tsindex 860cbafc4e..23ecb8d4b2 100644--- a/test/agent-contract-goldens.test.ts+++ b/test/agent-contract-goldens.test.ts@@ -16,7 +16,8 @@ import {__setDocsRefForTests, docsUrl, fallbackJsonDocument, noticeBlock, renderNotice, toAgentError,toolErrorResult, toolResultWithNotices, withAgentSiblings, type Notice, type RenderContext,} from '../src/core/agent-output.ts';-import { opError, OperationError } from '../src/core/ops/contract.ts';+import { opError, OperationError, verbError } from '../src/core/ops/contract.ts';+import { FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION } from '../src/core/facts/withdrawal.ts';import '../src/core/operations.ts'; // registers shared-op CLI names for the A1 routing pin, as every gbrain process doesimport { confirmationPayload } from '../src/core/consent.ts';import { withEnv } from './helpers/with-env.ts';@@ -146,6 +147,17 @@ describe('agent contract v1 goldens', () => {golden('receipt-error.json', toolErrorResult(toAgentError(e, { transport: 'stdio', op: 'put_page', mutating: true, outcome: 'pending', render: stdio })));});+ test('fact_withdrawn refusal: one identical withdrawn object on stdio, HTTP and CLI', () => {+ const e = verbError('invalid_params', FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION);+ e.withdrawn = { at: '2026-10-12T00:00:00.000Z', subject: 'all_entities', visibility: 'world' };+ const envs = [stdio, http, cli].map(render => toAgentError(e, { transport: render.transport, op: 'remember', mutating: true, render }));+ for (const env of envs) {+ expect(env.withdrawn).toEqual(e.withdrawn);+ expect([env.error, env.code, env.message]).toEqual(['invalid_params', 'invalid_params', FACT_WITHDRAWN_MESSAGE]);+ }+ golden('withdrawn-refusal.json', toolErrorResult(envs[0]!));+ });+test('legacy frozen error value with the new canonical code', () => {const e = opError('unknown_tool', 'Unknown: list_pagez', 'Call request_tools to see the tools this connection can call.', { legacy_error: 'unknown_operation' });const env = toAgentError(e, { transport: 'http', render: http });diff --git a/test/e2e/withdrawn-detail-postgres.test.ts b/test/e2e/withdrawn-detail-postgres.test.tsnew file mode 100644index 0000000000..66cde62902--- /dev/null+++ b/test/e2e/withdrawn-detail-postgres.test.ts@@ -0,0 +1,30 @@+/**+ * Postgres twin of test/withdrawn-detail.test.ts: `fact_withdrawn` refusals carry+ * a typed `withdrawn` object. One isolated database per scenario.+ */+import { afterEach, beforeEach, describe, test } from 'bun:test';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { hasDatabase } from './helpers.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { detailOnEverySurface, hiddenBackingOmitsDetail, mostSpecificSubjectFirst, receiptKeepsDetail,+ singleWriterSameRule } from '../helpers/withdrawn-detail-scenarios.ts';++const d = hasDatabase() ? describe : describe.skip;+let engine: PostgresEngine;+let close: () => Promise<void>;++d('fact_withdrawn refusals carry the withdrawal (Postgres)', () => {+ beforeEach(async () => {+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ configureGateway({ env: {} } as never);+ }, 120_000);+ afterEach(async () => { resetGateway(); await disposePersistenceConsumer(engine); await close(); });++ test('one identical object on stdio, HTTP, local and batch refusals', () => detailOnEverySurface(engine), 60_000);+ test('the most specific subject first, then the newest', () => mostSpecificSubjectFirst(engine), 60_000);+ test('no object when the caller cannot read the withdrawn rows', () => hiddenBackingOmitsDetail(engine), 60_000);+ test('a failed receipt keeps the object for get_write_request and replay', () => receiptKeepsDetail(engine), 60_000);+ test('the single-fact writer applies the same rule; a purge supplies no object', () => singleWriterSameRule(engine), 60_000);+});diff --git a/test/fixtures/agent-contract/v1/withdrawn-refusal.json b/test/fixtures/agent-contract/v1/withdrawn-refusal.jsonnew file mode 100644index 0000000000..be29daabbb--- /dev/null+++ b/test/fixtures/agent-contract/v1/withdrawn-refusal.json@@ -0,0 +1,9 @@+{+ "content": [+ {+ "type": "text",+ "text": "{\n \"error\": \"invalid_params\",\n \"code\": \"invalid_params\",\n \"message\": \"fact_withdrawn: this exact claim was explicitly forgotten in this source and visibility.\",\n \"suggestion\": \"A forgotten claim stays withdrawn, and remembering the same text again is refused; a claim forgotten without an entity is withdrawn for every entity. If it is still true, remember it in new words. To link a fact saved without an entity, do not forget it: remember it with entity and replaces set to its fact id.\",\n \"docs\": \"{{DOCS_BASE}}/docs/guides/error-codes.md#invalid_params\",\n \"protocol_version\": 1,\n \"withdrawn\": {\n \"at\": \"2026-10-12T00:00:00.000Z\",\n \"subject\": \"all_entities\",\n \"visibility\": \"world\"\n },\n \"docs_cmd\": [\n \"gbrain\",\n \"errors\",\n \"invalid_params\"\n ],\n \"class\": \"caller\",\n \"retryable\": false,\n \"contract_version\": 1\n}"+ }+ ],+ "isError": true+}diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex e90dc65f77..61543b7033 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6123,7 +6123,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"schema_lock_blocked\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"schema_lock_blocked\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",@@ -6142,8 +6142,9 @@"retryable?: boolean | undefined","stack?: string | undefined","suggestion?: string | undefined",- "toJSON: () => { contract_version?: 1 | undefined; fence_issues?: Record<string, unknown>[] | undefined; fence?: Record<string, unknown> | undefined; notices?: unknown[] | undefined; fix?: unknown; why?: string | undefined; reason?: string | undefined; write_error?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | undefined; write_request?: WriteReceipt | undefined; error: ErrorCode; code: string; message: string; suggestion: string | undefined; docs: string | undefined; detail: string | undefined; protocol_version: number | undefined; }",+ "toJSON: () => { contract_version?: 1 | undefined; withdrawn?: WithdrawnDetail | undefined; fence_issues?: Record<string, unknown>[] | undefined; fence?: Record<string, unknown> | undefined; notices?: unknown[] | undefined; fix?: unknown; why?: string | undefined; reason?: string | undefined; write_error?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | undefined; write_request?: WriteReceipt | undefined; error: ErrorCode; code: string; message: string; suggestion: string | undefined; docs: string | undefined; detail: string | undefined; protocol_version: number | undefined; }","why?: string | undefined",+ "withdrawn?: WithdrawnDetail | undefined","writeError?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | undefined","writeRequest?: WriteReceipt | undefined"],diff --git a/test/fixtures/memory-verbs/cases.json b/test/fixtures/memory-verbs/cases.jsonindex 8cfa64ffad..2020ebdc5a 100644--- a/test/fixtures/memory-verbs/cases.json+++ b/test/fixtures/memory-verbs/cases.json@@ -277,6 +277,17 @@}]},+ {+ "name": "remember of the forgotten claim is refused invalid_params with a suggestion (a withdrawn object, when present, is schema-valid)",+ "verb": "remember",+ "params": {+ "fact": "conformance {{marker}}: expiring fact",+ "provenance": "conformance run {{marker}}",+ "entity": "people/conformance-{{marker}}"+ },+ "expectErrorCode": "invalid_params",+ "expectSuggestion": true+ },{"name": "forget unknown id returns not_found with a suggestion","verb": "forget",diff --git a/test/helpers/withdrawn-detail-scenarios.ts b/test/helpers/withdrawn-detail-scenarios.tsnew file mode 100644index 0000000000..6cea44fa0a--- /dev/null+++ b/test/helpers/withdrawn-detail-scenarios.ts@@ -0,0 +1,137 @@+/**+ * Engine-parametrized scenarios for the `withdrawn` object on `fact_withdrawn`+ * refusals (test/withdrawn-detail.test.ts on PGLite,+ * test/e2e/withdrawn-detail-postgres.test.ts on Postgres). Each scenario+ * expects a fresh brain. Zero model calls.+ */+import { expect } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION } from '../../src/core/facts/withdrawal.ts';+import { writeSingleFact } from '../../src/core/facts/write-single.ts';+import { OperationError } from '../../src/core/ops/contract.ts';++const CLAIM = 'Acme Example renewed for three years at 40 seats.';++type Caller = 'remote' | 'http' | 'local';+async function call(engine: BrainEngine, name: string, params: Record<string, unknown>, caller: Caller = 'remote') {+ const ctx = caller === 'local' ? { remote: false }+ : { remote: true, transport: caller === 'http' ? 'http' : 'stdio', takesHoldersAllowList: ['world'], sourceId: 'default' };+ const res = await dispatchToolCall(engine as never, name, params, ctx as never);+ return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text!) as Record<string, any> };+}++async function seedPages(engine: BrainEngine): Promise<void> {+ for (const [slug, title, extra] of [['crm/acme-example', 'Acme Example', ''], ['crm/hidden-co', 'Hidden Co', 'visibility: private\n']]) {+ await dispatchToolCall(engine as never, 'put_page', { slug, content: `---\ntitle: ${title}\ntype: company\n${extra}---\n# ${title}\n\nA company.\n` }, { remote: false });+ }+}+const ledger = async (engine: BrainEngine, subject: string) => {+ const [row] = await engine.executeRaw<{ at: string }>('SELECT withdrawn_at::text AS at FROM fact_withdrawals WHERE subject=$1', [subject]);+ return new Date(row!.at).toISOString();+};+const remember = (engine: BrainEngine, caller: Caller = 'remote', extra: Record<string, unknown> = {}) =>+ call(engine, 'remember', { fact: CLAIM, entity: 'crm/acme-example', provenance: 'call notes', ...extra }, caller);++/** Every surface carries one identical object; the frozen code, message and suggestion are unchanged. */+export async function detailOnEverySurface(engine: BrainEngine): Promise<void> {+ await seedPages(engine);+ const saved = await call(engine, 'remember', { fact: CLAIM, provenance: 'call notes', infer_entity: false });+ expect((await call(engine, 'forget', { id: String(saved.body.id) })).body.expired).toBe(true);+ const withdrawn = { at: await ledger(engine, '*'), subject: 'all_entities', visibility: 'world' };+ for (const caller of ['remote', 'http', 'local'] as const) {+ const r = await remember(engine, caller);+ expect(r.isError).toBe(true);+ expect(r.body).toMatchObject({ code: 'invalid_params', message: FACT_WITHDRAWN_MESSAGE, suggestion: FACT_WITHDRAWN_SUGGESTION });+ expect(r.body.withdrawn).toEqual(withdrawn);+ }+ const batch = await call(engine, 'remember', { items: [{ fact: CLAIM, entity: 'crm/acme-example', provenance: 'call notes' }] });+ expect(batch.body.items[0].error).toMatchObject({ code: 'invalid_params', message: FACT_WITHDRAWN_MESSAGE, withdrawn });+}++/** Several ledger rows: the entity's own withdrawal outranks a newer one for all entities. */+export async function mostSpecificSubjectFirst(engine: BrainEngine): Promise<void> {+ await seedPages(engine);+ const linked = await remember(engine);+ expect((await call(engine, 'forget_fact', { id: Number(linked.body.id) })).body.expired).toBe(true);+ const unlinked = await call(engine, 'remember', { fact: CLAIM, provenance: 'call notes', infer_entity: false });+ expect(unlinked.body.status).toBe('inserted');+ expect((await call(engine, 'forget', { id: String(unlinked.body.id) })).body.expired).toBe(true);+ const acmeAt = await ledger(engine, 'crm/acme-example');+ expect(Date.parse(await ledger(engine, '*'))).toBeGreaterThanOrEqual(Date.parse(acmeAt));+ expect((await remember(engine)).body.withdrawn).toEqual({ at: acmeAt, subject: 'crm/acme-example', visibility: 'world' });+ // Without the entity, only the all-entities withdrawal applies.+ const bare = await call(engine, 'remember', { fact: CLAIM, provenance: 'call notes', infer_entity: false });+ expect(bare.body.withdrawn.subject).toBe('all_entities');+}++/** A withdrawal whose rows the caller cannot read gives no detail; #6509's refusal is unchanged. */+export async function hiddenBackingOmitsDetail(engine: BrainEngine): Promise<void> {+ await seedPages(engine);+ const hiddenPage = await call(engine, 'remember', { fact: CLAIM, entity: 'crm/hidden-co', provenance: 'call notes' });+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,kind,visibility,entity_slug,source_markdown_slug,source,confidence,valid_from)+ VALUES ('default',$1,'fact','world','crm/acme-example','crm/hidden-co','meeting notes',1,now()) RETURNING id`, [CLAIM]);+ expect((await call(engine, 'forget_fact', { id: Number(row!.id) }, 'local')).body.expired).toBe(true);+ const remote = await remember(engine);+ for (const key of ['code', 'error', 'message', 'suggestion']) expect(remote.body[key]).toEqual(hiddenPage.body[key]);+ expect(remote.body.withdrawn).toBeUndefined();+ const local = await remember(engine, 'local');+ expect(local.body.withdrawn).toEqual({ at: await ledger(engine, 'crm/acme-example'), subject: 'crm/acme-example', visibility: 'world' });+ // A visible withdrawal for all entities: the remote caller is told about that one, never the hidden one.+ const unlinked = await call(engine, 'remember', { fact: CLAIM, provenance: 'call notes', infer_entity: false });+ expect((await call(engine, 'forget', { id: String(unlinked.body.id) })).body.expired).toBe(true);+ const mixed = await remember(engine);+ expect(mixed.body.message).toBe(FACT_WITHDRAWN_MESSAGE);+ expect(mixed.body.withdrawn).toEqual({ at: await ledger(engine, '*'), subject: 'all_entities', visibility: 'world' });+ expect((await remember(engine, 'local')).body.withdrawn.subject).toBe('crm/acme-example');+}++/** A withdrawal that lands after admission fails the receipt; the object rides the response and get_write_request. */+export async function receiptKeepsDetail(engine: BrainEngine): Promise<void> {+ await seedPages(engine);+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION wd_withdraw_on_admit() RETURNS trigger AS $$+ BEGIN+ INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash)+ VALUES (NEW.source_id,'world','*',gbrain_fact_fingerprint(NEW.intent->>'fact')) ON CONFLICT DO NOTHING;+ RETURN NEW;+ END $$ LANGUAGE plpgsql`);+ await engine.executeRaw(`CREATE TRIGGER wd_withdraw_on_admit AFTER INSERT ON persistence_requests+ FOR EACH ROW WHEN (NEW.operation = 'remember') EXECUTE FUNCTION wd_withdraw_on_admit()`);+ try {+ const requestId = '7d1e2f3a-4b5c-4d6e-8f70-81a2b3c4d5e6';+ const res = await remember(engine, 'remote', { request_id: requestId });+ expect(res.body).toMatchObject({ code: 'invalid_params', write_error: 'invalid_params', message: FACT_WITHDRAWN_MESSAGE });+ expect(res.body.write_request).toMatchObject({ request_id: requestId, state: 'failed' });+ const withdrawn = { at: await ledger(engine, '*'), subject: 'all_entities', visibility: 'world' };+ expect(res.body.withdrawn).toEqual(withdrawn);+ const receipt = await call(engine, 'get_write_request', { request_id: requestId });+ expect(receipt.body).toMatchObject({ request_id: requestId, state: 'failed', write_error_message: FACT_WITHDRAWN_MESSAGE, withdrawn });+ const replay = await remember(engine, 'remote', { request_id: requestId });+ expect(replay.body.withdrawn).toEqual(withdrawn);+ } finally {+ await engine.executeRaw('DROP TRIGGER IF EXISTS wd_withdraw_on_admit ON persistence_requests');+ await engine.executeRaw('DROP FUNCTION IF EXISTS wd_withdraw_on_admit()');+ }+}++/** The single-fact writer applies the same predicate (fail-closed when `remote` is unset); a purge never supplies the object. */+export async function singleWriterSameRule(engine: BrainEngine): Promise<void> {+ await seedPages(engine);+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,kind,visibility,entity_slug,source_markdown_slug,source,confidence,valid_from)+ VALUES ('default',$1,'fact','world','crm/acme-example','crm/hidden-co','meeting notes',1,now()) RETURNING id`, [CLAIM]);+ expect((await call(engine, 'forget_fact', { id: Number(row!.id) }, 'local')).body.expired).toBe(true);+ const write = (remote?: boolean) => writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'call notes', entity: 'crm/acme-example', visibility: 'world', ...(remote === undefined ? {} : { remote }) })+ .then(() => null, (e: unknown) => e as OperationError);+ const local = await write(false);+ expect(local?.message).toBe(FACT_WITHDRAWN_MESSAGE);+ expect(local?.withdrawn).toEqual({ at: await ledger(engine, 'crm/acme-example'), subject: 'crm/acme-example', visibility: 'world' });+ const unset = await write();+ expect(unset?.message).toBe('Page not found.');+ expect(unset?.withdrawn).toBeUndefined();+ const purged = 'Acme Example moved its headquarters.';+ await engine.executeRaw(`INSERT INTO fact_purges(source_id,visibility,subject,fact_hash) VALUES ('default','world','*',gbrain_fact_fingerprint($1))`, [purged]);+ const refused = await writeSingleFact(engine, 'default', { fact: purged, provenance: 'call notes', entity: 'crm/acme-example', visibility: 'world', remote: false })+ .then(() => null, (e: unknown) => e as OperationError);+ expect(refused).toBeInstanceOf(OperationError);+ expect(refused?.withdrawn).toBeUndefined();+}diff --git a/test/withdrawn-detail.test.ts b/test/withdrawn-detail.test.tsnew file mode 100644index 0000000000..a110bd7c63--- /dev/null+++ b/test/withdrawn-detail.test.ts@@ -0,0 +1,35 @@+/**+ * `fact_withdrawn` refusals carry a typed `withdrawn` object (PGLite).+ * Scenarios: test/helpers/withdrawn-detail-scenarios.ts; the Postgres twin is+ * test/e2e/withdrawn-detail-postgres.test.ts.+ */+import { afterAll, beforeAll, beforeEach, describe, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { detailOnEverySurface, hiddenBackingOmitsDetail, mostSpecificSubjectFirst, receiptKeepsDetail,+ singleWriterSameRule } from './helpers/withdrawn-detail-scenarios.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => { resetGateway(); await disposePersistenceConsumer(engine); await engine.disconnect(); });+beforeEach(async () => {+ await disposePersistenceConsumer(engine);+ await resetPgliteState(engine);+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+});++describe('fact_withdrawn refusals carry the withdrawal', () => {+ test('one identical object on stdio, HTTP, local and batch refusals', () => detailOnEverySurface(engine));+ test('the most specific subject first, then the newest', () => mostSpecificSubjectFirst(engine));+ test('no object when the caller cannot read the withdrawn rows', () => hiddenBackingOmitsDetail(engine));+ test('a failed receipt keeps the object for get_write_request and replay', () => receiptKeepsDetail(engine));+ test('the single-fact writer applies the same rule; a purge supplies no object', () => singleWriterSameRule(engine));+});