Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): name fact_withdrawn on remember instead of an opaque failed write

garrytane994974d816d
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index f4bbbef1c6..ae8c244bdb 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -9,7 +9,7 @@
- `src/core/serve-service.ts` — the persistent-service half of `mcp expose`, everything under `gbrainPath('serve')` (`serveDir`, `adminTokenPath`, `wrapperPath`, `receiptPath`, `serveLogPath`, `serveErrPath`) so `GBRAIN_HOME` is honored. `SERVE_LAUNCHD_LABEL = 'com.gbrain.serve'`, `SERVE_SYSTEMD_UNIT = 'gbrain-serve.service'`, `detectServiceTarget(signals)` → `'macos' | 'linux-systemd' | 'none'` (a working user bus is required for systemd; cloud sandboxes and ephemeral containers fall to `none`). `renderServeWrapper` produces the 0755 launcher that sources the shell profiles and `~/.gbrain/env`, prepends the Bun dir to `PATH`, reads the admin token from its file at run time into `GBRAIN_ADMIN_BOOTSTRAP_TOKEN` (the token is never written into the wrapper, plist or unit), resolves `gbrain` the way autopilot's wrapper does (baked installer path, `type -P gbrain` fallback) and `exec`s `serve --http --port N --public-url URL [--surface] [--enable-dcr]`. `resolveServeGbrainCommand({ which, execPath, argv1, metaUrl, fileExists })` picks the baked program: a `gbrain` on PATH wins; a COMPILED binary — `import.meta.url` (or the injected `metaUrl`) under `/$bunfs/`, or an `execPath` that is not the bun runtime while `argv[1]` is absent/virtual — is `[execPath]` whatever its basename (release assets are renamed); otherwise the `[bun, <cli.ts>]` dev form only when that `cli.ts` exists on disk, else `[execPath]` rather than a path that cannot run; `renderServeLaunchdPlist` (RunAtLoad, KeepAlive, ThrottleInterval 30, logs to `serve.log` / `serve.err`, local `escapeXml`) and `renderServeSystemdUnit` (After=network-online.target, Restart=always, RestartSec=10, start-limit window; systemd specifiers escaped — `%` → `%%` in `ExecStart` and both `append:` log paths, `$` → `$$` in `ExecStart`). `ensureAdminToken` (0700 dir, 0600 file created with `wx` semantics, 64 hex chars; reuse a file matching the exported `ADMIN_TOKEN_SHAPE` = `^[A-Za-z0-9_-]{32,}$` — the same regex `serve-http.ts`'s `resolveBootstrapToken` accepts, so the file and the env var can never disagree on what a valid token is — unlink and regenerate otherwise), `installServeService` (launchd: domain-explicit `launchctl bootout gui/<uid> <plist>` — failure ignored — then `launchctl bootstrap gui/<uid> <plist>`, both through the one `launchctl(run, uid, plist, { modern, legacy })` helper whose legacy `launchctl unload` / `load` fallback is used ONLY when the modern verb exits non-zero with stderr matching `/Unknown command|unrecognized|not found/i`, never on a genuine failure or a killed call, and which reports the `verb` whose result it returns; a bootstrap that fails with stderr matching `LAUNCHCTL_SETTLE_RE` (`Input/output error`, `already in progress`, `\b5\b`, `\b37\b` — launchd still unloading the previous job) is retried up to `LAUNCHCTL_SETTLE_RETRIES` (5) times, `LAUNCHCTL_SETTLE_MS` (1s) apart through the injectable `sleep` param (default `setTimeout`; `mcp-expose.ts` passes `d.sleep`), a success after retries is a note and an exhausted retry appends "(after N settle retries)" to `error`; systemd: `daemon-reload` → `enable` → `restart` so a regenerated wrapper takes effect; `loginctl enable-linger` best effort) / `uninstallServeService` (launchd: the same `bootout gui/<uid>` with the same fallback; a bootout that exits non-zero — or is killed — with stderr NOT matching `LAUNCHCTL_NOT_LOADED_RE` (`No such process|not loaded|Could not find|not find service`) pushes `launchctl <verb> failed: <describeFailure>` into `notes`, and the exported `launchdBootoutFailed(result)` recognizes that note so `mcp-expose.ts` can say the job may still be loaded) / `serveServiceState` (`launchctl print gui/<uid>/<label>` / `systemctl --user is-active`); all three take `uid?: number` defaulting to `process.getuid?.() ?? 501`, threaded from `mcp-expose.ts`. Every supervisor subprocess carries a timeout — 60s for `launchctl bootstrap/bootout` (and the legacy `load/unload`) and `systemctl --user enable/restart/disable`, 15s for `launchctl print`, `daemon-reload`, `is-active` and `loginctl enable-linger` — and a `status: null` (killed) result counts as a failure (`error` / note) or `unknown` state; a failed call is described by `describeFailure` (its stderr, else stdout, else `exit <status>`). `readExposeReceipt` / `writeExposeReceipt` (`expose.json`, 0600, version 1, no secrets): the reader is a structural shape guard, not just `version`/`port`/`public_url` — it also requires `mode` in `tailnet|funnel`, a `service` object with a string `wrapper_path`, a `target` in `macos|linux-systemd|none`, a string `state` and string-or-null `plist_path` / `unit_path`, a `tailscale` object whose `binary` / `dns_name` are string-or-null, and string `mcp_url` / `admin_url` / `admin_token_file`; anything less is null (absent), so `--status` / `--remove` never dereference a half-written receipt. The token, receipt, wrapper, plist and unit writers refuse (clear error) when the target path is a symlink (`lstatSync`) before any supervisor call runs. Uses `shellQuote` from `src/core/mcp-registration.ts`; every filesystem/exec effect is behind injectable deps.
- `src/core/harness/verify.ts` — Randomized server-side memory verification with revision-conditional cleanup and retained mutation UUIDs, with separate transport, identity, authority, read, write/readback, delegation and cleanup verdicts. Lost mutation responses are reconciled before retry; server success never certifies native-harness activation or cross-conversation behavior.
-- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Embedding preparation records the stored model/dimension generation and publication compares it under transaction row locks, preserving unchanged runtime overrides while refusing intervening migrations; fact vectors retain their actual provider model. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work; the call then rebuilds the withdrawn pages' text projections before acknowledging, because a CLI process has no resident projection worker (a failed rebuild stays queued). `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL; `test/withdrawal-followup-writes.test.ts` covers writes after a forget whose effects stay queued. #5836: an omitted `entity` is inferred before admission (`inferRememberTarget`), and the inferred slug is used only when `planRememberTarget`'s checks pass as predicates (plus withdrawal, fence parse, no owner claim); otherwise the save is unattributed with `warnings` (`NO_ENTITY`/`ENTITY_LINK_FAILED`) + `hint`. The `entity_inferred` intent marker makes preparation dedup exact text only (never supersede) and notes the context; `test/remember-entity-inference.test.ts`. `remember.replaces` (caller-directed replacement): `decideReplacement` (`facts/single-prepare.ts`) replaces the cosine decision when the intent names a target; it is checked at submission (fail fast) and again in `validate` with the target row locked `FOR UPDATE`, so two replacements of one fact serialize and the second sees `target_superseded`. Refusals are `invalid_params` with code prefixes (`target_withdrawn`, `target_superseded` naming the chain head, `target_expired`, `replaces_entity_mismatch`, `replaces_cross_page`, `replaces_duplicate`); remote callers get `not_found` for private targets; equal text is a `duplicate` no-op. Every `superseded` outcome carries `superseded_fact_id` (plus `replaced_by_caller` for `replaces`). `forget` responses gain `similar_active` (`facts/similar-active.ts`) after commit and on replay, and `semantic_review: false` keeps the claim out of overnight review. Pinned by `test/remember-replaces.test.ts`. remember's write intent carries the transport-resolved `ctx.sessionId` (MCP `_meta.session_id`, clamped to 256 characters), and preparation stores it as the fact's `source_session`, so `recall({session_id})` finds remembered facts; identity only, never an authorization input (`test/remember-session.test.ts`).
+- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Embedding preparation records the stored model/dimension generation and publication compares it under transaction row locks, preserving unchanged runtime overrides while refusing intervening migrations; fact vectors retain their actual provider model. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work; the call then rebuilds the withdrawn pages' text projections before acknowledging, because a CLI process has no resident projection worker (a failed rebuild stays queued). `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL; `test/withdrawal-followup-writes.test.ts` covers writes after a forget whose effects stay queued. #5836: an omitted `entity` is inferred before admission (`inferRememberTarget`), and the inferred slug is used only when `planRememberTarget`'s checks pass as predicates (plus withdrawal, fence parse, no owner claim); otherwise the save is unattributed with `warnings` (`NO_ENTITY`/`ENTITY_LINK_FAILED`) + `hint`. The `entity_inferred` intent marker makes preparation dedup exact text only (never supersede) and notes the context; `test/remember-entity-inference.test.ts`. `remember.replaces` (caller-directed replacement): `decideReplacement` (`facts/single-prepare.ts`) replaces the cosine decision when the intent names a target; it is checked at submission (fail fast) and again in `validate` with the target row locked `FOR UPDATE`, so two replacements of one fact serialize and the second sees `target_superseded`. Refusals are `invalid_params` with code prefixes (`target_withdrawn`, `target_superseded` naming the chain head, `target_expired`, `replaces_entity_mismatch`, `replaces_cross_page`, `replaces_duplicate`); remote callers get `not_found` for private targets; equal text is a `duplicate` no-op. Every `superseded` outcome carries `superseded_fact_id` (plus `replaced_by_caller` for `replaces`). `forget` responses gain `similar_active` (`facts/similar-active.ts`) after commit and on replay, and `semantic_review: false` keeps the claim out of overnight review. Pinned by `test/remember-replaces.test.ts`. remember's write intent carries the transport-resolved `ctx.sessionId` (MCP `_meta.session_id`, clamped to 256 characters), and preparation stores it as the fact's `source_session`, so `recall({session_id})` finds remembered facts; identity only, never an authorization input (`test/remember-session.test.ts`). R1 (Cat 40 Hard): 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`.
- `src/core/page-state/import-guard.ts` — imported canonical bytes publish only after source/page identity and knowledge-revision CAS, including unchanged-file and legacy hash-repair paths. Prepared same-hash imports compare full canonical metadata and additive tags, since captured timestamps are excluded from content hashes. Tests: `import-revision-concurrency.test.ts`.
- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. An unchanged per-tick refresh writes nothing: the registry directory and records are chmodded only when their mode differs and the directory is fsynced only when a record changed (`root-registry-idle-chmod-5297.test.ts`). The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints; an update that changes only embedding, telemetry or write-attribution columns of facts/takes is a physical projection and passes without the coordinator. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 23518cf8ca..f88ee76196 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -273,6 +273,12 @@ near-duplicates may insert; dedup and supersession ride embedding similarity).
supersedes the old ("X at acme-example" → "X left acme-example").
- Omitted optional inputs echo as `null`, never absent.
+A claim that was forgotten is refused with `invalid_params` and the message
+prefix `fact_withdrawn`: remembering the same text again does not restore it,
+and a claim forgotten without an entity is withdrawn for every entity. To link
+a fact saved without an entity, do not forget it; remember it with `entity`
+and `replaces` set to its id.
+
#### remember replaces (additive)
`replaces` (string): the `fact_id` of the fact this new fact replaces. It is a
@@ -280,7 +286,9 @@ caller-directed replacement: it says the old fact is no longer the current one,
not that the two texts mean the same. Zero model calls; the cosine rule does
not apply. The target must be an active fact in the same source, with the same
visibility (world only for remote callers, else `not_found`) and the same
-entity, on the same entity page. Refusals come back as `invalid_params` with a
+entity, on the same entity page. A target saved without an entity may be
+replaced by a fact with an entity: that links it (the unlinked fact is
+superseded, not forgotten, so the claim stays rememberable). Refusals come back as `invalid_params` with a
code prefix and a `suggestion`: `target_withdrawn` (forgotten facts are not
replaceable; remember without `replaces`), `target_superseded` (names the fact
that replaced it), `target_expired`, `replaces_entity_mismatch`,
diff --git a/llms-full.txt b/llms-full.txt
index 41991959fe..b6eee70b16 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -9136,6 +9136,12 @@ near-duplicates may insert; dedup and supersession ride embedding similarity).
supersedes the old ("X at acme-example" → "X left acme-example").
- Omitted optional inputs echo as `null`, never absent.
+A claim that was forgotten is refused with `invalid_params` and the message
+prefix `fact_withdrawn`: remembering the same text again does not restore it,
+and a claim forgotten without an entity is withdrawn for every entity. To link
+a fact saved without an entity, do not forget it; remember it with `entity`
+and `replaces` set to its id.
+
#### remember replaces (additive)
`replaces` (string): the `fact_id` of the fact this new fact replaces. It is a
@@ -9143,7 +9149,9 @@ caller-directed replacement: it says the old fact is no longer the current one,
not that the two texts mean the same. Zero model calls; the cosine rule does
not apply. The target must be an active fact in the same source, with the same
visibility (world only for remote callers, else `not_found`) and the same
-entity, on the same entity page. Refusals come back as `invalid_params` with a
+entity, on the same entity page. A target saved without an entity may be
+replaced by a fact with an entity: that links it (the unlinked fact is
+superseded, not forgotten, so the claim stays rememberable). Refusals come back as `invalid_params` with a
code prefix and a `suggestion`: `target_withdrawn` (forgotten facts are not
replaceable; remember without `replaces`), `target_superseded` (names the fact
that replaced it), `target_expired`, `replaces_entity_mismatch`,
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 755a95a145..6aa95c9d43 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -260,6 +260,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },
{ since: '0.60.100.0', text: '`gbrain doctor` has a new `fence_integrity` check: it counts malformed facts and takes fences still waiting (held files, stored pages, unsynced checkout files) by the tier that would fix them, and warns when a source had 20 or more fences normalized in 7 days. Each doctor run scans stored pages and source checkouts for up to 10 seconds (`GBRAIN_DOCTOR_FENCE_TIMEOUT_MS`) and resumes where it stopped; until a scan finishes the check reports partial instead of ok. New settings `fences.repair.max_usd_per_page` (0.05) and `fences.repair.max_usd_per_day` (1.00) cap model fence repair.' },
{ since: '0.60.102.0', text: `Malformed facts and takes fences are now repaired automatically: the maintenance run repairs held files and stored pages on the owner host, and its first run after upgrading repairs every malformed fence it finds in each source, rewriting and committing those files (\`gbrain doctor --only fence_integrity\` counts them; \`gbrain repair fences\` previews the plan). A fence only a rewrite can realign sends just its header and those rows, never the rest of the page, to the repair model, within $0.30 per page and $1.00 per day (\`fences.repair.max_usd_per_page\`, \`fences.repair.max_usd_per_day\`); every rewrite passes validation gates before it is written. With \`models.fence_repair\` unset, the repair model is the first model the fence-repair eval measured as accurate enough that has a provider key on the brain host (\`gbrain models\` names it); with none, model repair stays off until the user sets \`models.fence_repair\`. ${FENCE_REPAIR_MEASURED} \`gbrain config set fences.repair.llm false\` keeps fence rows away from the model; \`gbrain config set fences.repair.enabled false\` pauses automatic repair. On a managed source each repaired file is committed, so \`git revert\` undoes it (page history keeps the earlier version); turning these settings off stops future repairs and does not undo past ones.` },
+ { since: '0.60.104.0', text: '`remember` of a claim that was forgotten is now refused before it is accepted, with `invalid_params` and the message prefix `fact_withdrawn` (it used to be accepted and then fail with "The write did not commit"); a claim forgotten without an entity stays withdrawn for every entity. `replaces` now accepts a fact saved without an entity, so `remember` with `entity` and `replaces` links that fact instead of forgetting it. A failed write receipt names its cause instead of "Inspect its durable request on the source host".' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index 21f5df0783..9ee9090b3e 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -2,7 +2,7 @@ import type { BrainEngine, FactAttribution, FactRow } from '../engine.ts';
import { verbError } from '../ops/contract.ts';
import { isAvailable, embedOne, getEmbeddingModel } from '../ai/gateway.ts';
import { cosineSimilarity } from './classify.ts';
-import { isFactWithdrawn } from './withdrawal.ts';
+import { FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION, isFactWithdrawn } from './withdrawal.ts';
import { cosineVerdict } from './capture-dedup.ts';
export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };
@@ -25,8 +25,7 @@ export async function prepareFactEmbedding(fact: string, signal?: AbortSignal, d
}
export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: string, input: SingleFactIntent): Promise<void> {
if (await isFactWithdrawn(engine, sourceId, input.visibility, input.fact, input.entity_slug)) {
- throw verbError('invalid_params', 'fact_withdrawn: this exact claim was explicitly forgotten in this source and visibility.',
- 'Remember a corrected claim. Repeating the old claim does not restore withdrawn memory.');
+ throw verbError('invalid_params', FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION);
}
}
/**
@@ -96,7 +95,8 @@ export async function decideReplacement(engine: BrainEngine, sourceId: string, i
throw verbError('invalid_params', `target_expired: fact #${targetId} is no longer active.`,
'Remember the new claim without replaces.');
}
- if ((target.entity_slug ?? null) !== (input.entity_slug ?? null)) {
+ // R1: replacing a fact saved without an entity by the same claim with an entity links it (supersession, no withdrawal).
+ if (target.entity_slug != null && target.entity_slug !== (input.entity_slug ?? null)) {
throw verbError('invalid_params', `replaces_entity_mismatch: fact #${targetId} is about ${target.entity_slug ?? 'no entity'}, not ${input.entity_slug ?? 'no entity'}.`,
'Pass the same entity as the fact being replaced, or forget the old fact and remember the new one separately.');
}
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index 79152161d0..d16580ad7f 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -10,6 +10,15 @@ export interface WithdrawalCommit {
pages: Array<{ sourceId: string; slug: string; revision: string }>;
}
+export const FACT_WITHDRAWN_MESSAGE = 'fact_withdrawn: this exact claim was explicitly forgotten in this source and visibility.';
+/**
+ * R1: the refusal names why repeating the claim fails and the write that works. A claim forgotten
+ * without an entity is withdrawn for every entity, so "forget, then remember it with an entity" is refused.
+ */
+export const FACT_WITHDRAWN_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.';
+
/** DB-first: no filesystem ownership, provider work or root lock is required. */
/**
* Called inside the withdrawal transaction after the ledger row commits with
diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.ts
index 7cf54496d3..70b6194d7c 100644
--- a/src/core/facts/write-single.ts
+++ b/src/core/facts/write-single.ts
@@ -103,11 +103,10 @@ export async function writeSingleFact(
// resolver returned nothing (fail-closed — no live page was verified).
const resolutionSource = resolved?.source ?? null;
- const { isFactWithdrawn } = await import('./withdrawal.ts');
+ const { FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION, 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: this exact claim was explicitly forgotten in this source and visibility.',
- 'Remember a corrected claim. Repeating the old claim does not restore withdrawn memory.');
+ throw verbError('invalid_params', FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION);
}
// Embedding (NOT an LLM call): powers dedup + downstream recall. Fail-soft —
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index f44f1f9fd7..c71835a273 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -160,12 +160,13 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
// A source-scoped absent identity serializes subjectless facts. Bound writers
// cannot use it to escape their namespace grant.
const { slug, authority, snapshot, fence, binding, writeThrough } = linked?.target ?? await planRememberTarget(ctx, sourceId, source, entitySlug, null);
+ const { assertFactNotWithdrawn, decideReplacement } = await import('../facts/single-prepare.ts');
+ const factIntent = { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as never, visibility: (p.visibility ?? 'world') as never, entity_slug: entitySlug };
+ // Fail fast on an invalid target or a withdrawn claim; the coordinator re-checks both under its locks before publishing.
if (p.replaces !== undefined && p.replaces !== null) {
- // Fail fast on an invalid target; the coordinator re-checks it under the row lock before publishing.
- const { decideReplacement } = await import('../facts/single-prepare.ts');
- await decideReplacement(ctx.engine, sourceId, { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as never,
- visibility: (p.visibility ?? 'world') as never, entity_slug: entitySlug }, Number(p.replaces), { pageSlug: slug, remote: ctx.remote !== false });
+ await decideReplacement(ctx.engine, sourceId, factIntent, Number(p.replaces), { pageSlug: slug, remote: ctx.remote !== false });
}
+ await assertFactNotWithdrawn(ctx.engine, sourceId, factIntent);
const row = await admitWrite(ctx.engine, { principal, operation: 'remember', sourceId, sourceIncarnation: source.incarnation,
slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent,
// The transport's session (MCP `_meta.session_id`) is recorded on the fact, as extract_facts records
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index 022bc90802..0f864dda42 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -33,7 +33,7 @@ function candidateState(value: Awaited<ReturnType<typeof decideSingleFact>>): st
return JSON.stringify([value.status, c?.id, c?.fact, c?.kind, c?.visibility,
c?.valid_until ? new Date(c.valid_until).toISOString() : null, c?.source_markdown_slug, c?.row_num]);
}
-export const NO_ENTITY_HINT = 'Saved without an entity, so entity-scoped recall will not find it. Pass `entity` (the person, company or project this fact is about) to link it.';
+export const NO_ENTITY_HINT = 'Saved without an entity, so entity-scoped recall will not find it. To link it, remember it again with `entity` (the person, company or project it is about) and `replaces` set to its id; do not forget it first, because a forgotten claim cannot be saved again.';
function outcome(id: number, status: 'inserted' | 'duplicate' | 'superseded', entitySlug: string | null, validUntil: Date | string | null, degraded: boolean, p: Record<string, unknown>, supersededId?: number) {
const statusText = status === 'inserted' ? `remembered as fact #${id}` : status === 'duplicate'
? `already knew this — kept fact #${id}` : `updated — fact #${id} supersedes the previous version`;
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 216481ba56..ab275e0102 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -4,6 +4,7 @@ import { pendingWriteHint } from './health.ts';
import { UNBOUND_COLLISION_MESSAGE, UNBOUND_PUBLICATION_MESSAGE } from './unbound-source.ts';
import { isFrontmatterHoldMessage } from '../markdown.ts';
import { fenceLocationFromMessage, fenceWhere } from '../fence-repair/refusal.ts';
+import { FACT_WITHDRAWN_SUGGESTION } from '../facts/withdrawal.ts';
const FRONTMATTER_SLUG_CONFLICT = /^The frontmatter slug "[^"\n]{1,300}" in [^/"\n][^"\n]{0,1000} conflicts with its path, which expects slug "[^"\n]{1,300}"\. Remove `slug:` or make it match the path\.$/;
@@ -105,15 +106,17 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {
// #6188 (UC3): a company-brain source names the fence correction it will not write; the repository commit is the fix.
if (code === 'source_writeback_required' && message?.startsWith('Canonical preparation would normalize a facts or takes fence (')) return { reason: code, message,
suggestion: 'A company-brain source never rewrites repository files: fix the named fence in the repository, commit it, and resume the sync.' };
- const replaces = code === 'invalid_params' ? REPLACES_REFUSAL.exec(message ?? '') : null;
- if (replaces) return { reason: code, message: message!, suggestion: REPLACES_SUGGESTION[replaces[1]!]! };
- return { reason: isWriteErrorCode(code) ? code : 'storage_error', message: 'The write did not commit. Inspect its durable request on the source host.',
+ const memory = code === 'invalid_params' ? MEMORY_REFUSAL.exec(message ?? '') : null;
+ if (memory) return { reason: code, message: message!, suggestion: MEMORY_REFUSAL_SUGGESTION[memory[1]!]! };
+ const reason = isWriteErrorCode(code) ? code : 'storage_error';
+ return { reason, message: `The write did not commit: it ended with ${reason}, and nothing was saved.`,
suggestion: 'Resolve the reported write failure before starting a corrected attempt.' };
}
-/** `remember.replaces` refusals decided under the target row lock keep their code and next step. */
-const REPLACES_REFUSAL = /^(target_superseded|target_withdrawn|target_expired|replaces_entity_mismatch|replaces_cross_page|replaces_duplicate): /;
-const REPLACES_SUGGESTION: Record<string, string> = {
+/** `remember` refusals decided at preparation (withdrawal, `replaces` under the target row lock) keep their code and next step. */
+const MEMORY_REFUSAL = /^(fact_withdrawn|target_superseded|target_withdrawn|target_expired|replaces_entity_mismatch|replaces_cross_page|replaces_duplicate): /;
+const MEMORY_REFUSAL_SUGGESTION: Record<string, string> = {
+ fact_withdrawn: FACT_WITHDRAWN_SUGGESTION,
target_superseded: 'Recall the entity to check the current fact, then pass replaces with the fact id named here if the new claim replaces that one.',
target_withdrawn: 'Remember the new claim without replaces; the forgotten claim stays withdrawn.',
target_expired: 'Remember the new claim without replaces.',
diff --git a/src/core/remember-batch.ts b/src/core/remember-batch.ts
index a43403d0e5..3ddeadb026 100644
--- a/src/core/remember-batch.ts
+++ b/src/core/remember-batch.ts
@@ -95,7 +95,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 } : {}) } });
+ 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 } : {}) } });
}
}
const failed = results.filter(r => r.status === 'failed').length;
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 0bc2a5d0dc..5eb48e95f7 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -97,7 +97,7 @@ const remember: Operation = {
enum: ['world', 'private'],
description: 'world (default) or private (local CLI only).',
},
- replaces: { type: 'string', description: 'fact_id this fact replaces (same entity).', fullSurfaceOnly: true },
+ replaces: { type: 'string', description: 'fact_id this fact replaces (same entity, or none).', fullSurfaceOnly: true },
},
mutating: true,
scope: 'write',
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 13de54f1f9..266b0b7a5e 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 207549,
- "stdoutSha256": "ba03674e7846f4d445030acf6a2bb53cd5544abdff7f8d28e480903f1e852586",
+ "stdoutBytes": 207558,
+ "stdoutSha256": "2854faaa1fe72eaed133c401bbd785584cb5e006a56e20ea3f0ec6b7fa26c324",
"toolNames": [
"remember",
"entity",
@@ -234,7 +234,7 @@
"type": "string"
},
"replaces": {
- "description": "fact_id this fact replaces (same entity).",
+ "description": "fact_id this fact replaces (same entity, or none).",
"type": "string"
},
"request_id": {
diff --git a/test/remember-withdrawn-claim.test.ts b/test/remember-withdrawn-claim.test.ts
new file mode 100644
index 0000000000..373744656d
--- /dev/null
+++ b/test/remember-withdrawn-claim.test.ts
@@ -0,0 +1,138 @@
+/**
+ * R1 (Cat 40 Hard): `remember` after `forget` of the same claim. In the held-out
+ * run agents saved facts without an entity, forgot them "to re-save with an
+ * entity", then remembered the same text with the entity. A claim forgotten
+ * without an entity is withdrawn for every entity, so each re-save was admitted
+ * and then failed with an opaque "The write did not commit" message that
+ * get_write_request did not explain either.
+ *
+ * Pins: the refusal names `fact_withdrawn` and the write that works, before
+ * admission and (when a withdrawal races admission) on the failed receipt,
+ * the batch item error and get_write_request; and the supported link path,
+ * `replaces` from a fact saved without an entity, supersedes it without
+ * withdrawing the claim.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } 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 { writeFailureDiagnostic } from '../src/core/persistence/verb-errors.ts';
+import { FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION } from '../src/core/facts/withdrawal.ts';
+import { NO_ENTITY_HINT } from '../src/core/persistence/memory-prepare.ts';
+
+let engine: PGLiteEngine;
+const CLAIM = 'Alice Example is the procurement lead at Acme Example.';
+
+async function call(name: string, params: Record<string, unknown>) {
+ const res = await dispatchToolCall(engine, name, params, { remote: true, takesHoldersAllowList: ['world'], sourceId: 'default' });
+ return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text!) as Record<string, any> };
+}
+async function requestCount(): Promise<number> {
+ const [row] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE operation='remember'");
+ return Number(row!.n);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { resetGateway(); __setEmbedTransportForTests(null); await engine.disconnect(); });
+beforeEach(async () => {
+ await disposePersistenceConsumer(engine);
+ await resetPgliteState(engine);
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ await dispatchToolCall(engine, 'put_page', { slug: 'crm/acme-example',
+ content: '---\ntitle: Acme Example\ntype: company\n---\n# Acme Example\n\nA company.\n' }, { remote: false });
+});
+
+describe('remember after forget of the same claim', () => {
+ test('held-out shape: forget an unlinked fact, re-save it with an entity -> fact_withdrawn with the working write, nothing admitted', async () => {
+ const saved = await call('remember', { items: [{ fact: CLAIM, provenance: 'team update' }], infer_entity: false });
+ expect(saved.body.items[0]).toMatchObject({ status: 'inserted', entity_slug: null });
+ expect(saved.body.hints).toEqual([NO_ENTITY_HINT]);
+ expect(NO_ENTITY_HINT).toContain('replaces');
+ const forgot = await call('forget', { id: saved.body.items[0].id, reason: 're-saving with entity' });
+ expect(forgot.body.expired).toBe(true);
+
+ const before = await requestCount();
+ const resave = await call('remember', { fact: CLAIM, entity: 'crm/acme-example', provenance: 'team update' });
+ expect(resave.isError).toBe(true);
+ expect(resave.body.code).toBe('invalid_params');
+ expect(resave.body.message).toBe(FACT_WITHDRAWN_MESSAGE);
+ expect(resave.body.message).not.toContain('did not commit');
+ expect(resave.body.suggestion).toBe(FACT_WITHDRAWN_SUGGESTION);
+ expect(await requestCount()).toBe(before);
+
+ const batch = await call('remember', { items: [{ fact: CLAIM, entity: 'crm/acme-example', provenance: 'team update' }] });
+ expect(batch.body.failed).toBe(1);
+ expect(batch.body.items[0].error).toMatchObject({ code: 'invalid_params', message: FACT_WITHDRAWN_MESSAGE, suggestion: FACT_WITHDRAWN_SUGGESTION });
+ });
+
+ test('a withdrawal that lands after admission fails the receipt with fact_withdrawn, readable through get_write_request', async () => {
+ // The trigger withdraws the claim inside the admission transaction, after the admission check passed.
+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION r1_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 r1_withdraw_on_admit AFTER INSERT ON persistence_requests
+ FOR EACH ROW WHEN (NEW.operation = 'remember') EXECUTE FUNCTION r1_withdraw_on_admit()`);
+ try {
+ const requestId = '0b6f3c2a-4d5e-4f60-8a71-92b3c4d5e6f7';
+ const res = await call('remember', { fact: CLAIM, entity: 'crm/acme-example', provenance: 'team update', request_id: requestId });
+ expect(res.isError).toBe(true);
+ 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' });
+ expect(res.body.suggestion).toContain(FACT_WITHDRAWN_SUGGESTION);
+ const receipt = await call('get_write_request', { request_id: requestId });
+ expect(receipt.isError).toBe(false);
+ expect(receipt.body).toMatchObject({ request_id: requestId, state: 'failed', write_error: 'invalid_params', write_error_message: FACT_WITHDRAWN_MESSAGE });
+ } finally {
+ await engine.executeRaw('DROP TRIGGER IF EXISTS r1_withdraw_on_admit ON persistence_requests');
+ await engine.executeRaw('DROP FUNCTION IF EXISTS r1_withdraw_on_admit()');
+ }
+ });
+
+ test('replaces links a fact saved without an entity: superseded, not withdrawn', async () => {
+ const unlinked = await call('remember', { fact: CLAIM, provenance: 'team update', infer_entity: false });
+ expect(unlinked.body).toMatchObject({ status: 'inserted', entity_slug: null });
+ const linked = await call('remember', { fact: CLAIM, entity: 'crm/acme-example', provenance: 'team update', replaces: unlinked.body.id });
+ expect(linked.isError).toBe(false);
+ expect(linked.body).toMatchObject({ status: 'superseded', entity_slug: 'crm/acme-example', superseded_fact_id: unlinked.body.id, replaced_by_caller: true });
+ const rows = await engine.executeRaw<{ id: number; entity_slug: string | null; expired: boolean; superseded_by: number | null }>(
+ 'SELECT id,entity_slug,expired_at IS NOT NULL AS expired,superseded_by FROM facts ORDER BY id');
+ expect(rows.map(r => ({ ...r, id: Number(r.id), superseded_by: r.superseded_by == null ? null : Number(r.superseded_by) }))).toEqual([
+ { id: Number(unlinked.body.id), entity_slug: null, expired: true, superseded_by: Number(linked.body.id) },
+ { id: Number(linked.body.id), entity_slug: 'crm/acme-example', expired: false, superseded_by: null },
+ ]);
+ const [withdrawals] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM fact_withdrawals');
+ expect(Number(withdrawals!.n)).toBe(0);
+ const recall = await call('recall', { entity: 'crm/acme-example' });
+ expect(JSON.stringify(recall.body.facts)).toContain(CLAIM);
+ });
+
+ test('replacing a fact about one entity with another entity is still refused', async () => {
+ await dispatchToolCall(engine, 'put_page', { slug: 'crm/widget-co',
+ content: '---\ntitle: Widget Co\ntype: company\n---\n# Widget Co\n\nA company.\n' }, { remote: false });
+ const a = await call('remember', { fact: CLAIM, entity: 'crm/acme-example', provenance: 'team update' });
+ const moved = await call('remember', { fact: CLAIM, entity: 'crm/widget-co', provenance: 'team update', replaces: a.body.id });
+ expect(moved.isError).toBe(true);
+ expect(moved.body.message).toContain('replaces_entity_mismatch');
+ });
+});
+
+describe('writeFailureDiagnostic', () => {
+ test('fact_withdrawn keeps its message and next step; unknown causes name the code without raw text', () => {
+ expect(writeFailureDiagnostic('invalid_params', FACT_WITHDRAWN_MESSAGE)).toEqual({ reason: 'invalid_params',
+ message: FACT_WITHDRAWN_MESSAGE, suggestion: FACT_WITHDRAWN_SUGGESTION });
+ const generic = writeFailureDiagnostic('invalid_params', 'Refused /home/alice-example/private/notes.md');
+ expect(generic.message).toBe('The write did not commit: it ended with invalid_params, and nothing was saved.');
+ expect(generic.message).not.toContain('Inspect its durable request');
+ expect(writeFailureDiagnostic('not_a_code', 'x').message).toBe('The write did not commit: it ended with storage_error, and nothing was saved.');
+ });
+});
diff --git a/test/sync-frontmatter-slug-conflict.test.ts b/test/sync-frontmatter-slug-conflict.test.ts
index c083cd642c..1abc4bc582 100644
--- a/test/sync-frontmatter-slug-conflict.test.ts
+++ b/test/sync-frontmatter-slug-conflict.test.ts
@@ -84,7 +84,7 @@ test('only the slug-conflict shape passes through; other invalid_params causes k
expect(writeFailureDiagnostic('invalid_params', expected)).toEqual({ reason: 'invalid_params', message: expected,
suggestion: 'Correct the frontmatter in the file and commit the change.' });
for (const message of [expected.replace('books/fairml/ch01.md', '/private/books/ch01.md'), 'limit must be an integer from 1 to 100.', `${expected} credential=redacted`]) {
- expect(writeFailureDiagnostic('invalid_params', message).message).toBe('The write did not commit. Inspect its durable request on the source host.');
+ expect(writeFailureDiagnostic('invalid_params', message).message).toBe('The write did not commit: it ended with invalid_params, and nothing was saved.');
}
expect(writeFailureDiagnostic('storage_error', expected).message).not.toContain('books/other-chapter');
});