Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(remember): replaces, a checked caller-directed replacement
garrytanb9ea469f5c6b
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex cab0f99526..4a875aa216 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`.+- `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`.- `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.mdindex 6791cc0a29..967807c49c 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -268,6 +268,25 @@ 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.+#### remember replaces (additive)++`replaces` (string): the `fact_id` of the fact this new fact replaces. It is a+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+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`,+`replaces_cross_page` (forget the old fact, then remember), and+`replaces_duplicate` (another active fact already states the new claim). New+text equal to the target is `status: duplicate` and changes nothing. On success+`status` is `superseded`, `superseded_fact_id` names the replaced fact and+`replaced_by_caller` is `true`; the replaced fact is expired with+`superseded_by` and its `## Facts` row is struck with `superseded by #N` in+the same publication. Every `superseded` response carries `superseded_fact_id`.+#### remember entity attribution fields (additive)Optional response fields; clients must ignore any they do not know.diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.tsindex 2fd0d3a5b9..d1de9b2224 100644--- a/src/core/facts/single-prepare.ts+++ b/src/core/facts/single-prepare.ts@@ -62,3 +62,50 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, in}return { status: 'inserted', candidate: null };}++/**+ * `remember.replaces`: the caller names the fact the new one replaces. Checked,+ * zero-model: the target must be an active fact in this source with the same+ * visibility and entity, and on the same entity page; equal text is a no-op+ * duplicate. `lock` takes the target row lock inside the publishing transaction.+ */+export async function decideReplacement(engine: BrainEngine, sourceId: string, input: SingleFactIntent, targetId: number,+ opts: { pageSlug: string; remote: boolean; lock?: boolean }): Promise<FactDecision> {+ const notFound = () => verbError('not_found', `No fact with id "${targetId}" to replace.`,+ 'Pass the fact_id of an active fact from recall (facts[].fact_id) about the same entity, or omit replaces to save a new fact.');+ const [target] = await engine.executeRaw<FactCandidate & { withdrawn: boolean }>(`SELECT f.*,+ EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=f.source_id AND w.visibility=f.visibility+ 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,'*'))) AS withdrawn+ FROM facts f WHERE f.id=$1 AND f.source_id=$2${opts.lock ? ' FOR UPDATE OF f' : ''}`, [targetId, sourceId]);+ if (!target || (opts.remote && target.visibility !== 'world')) throw notFound();+ if (target.visibility !== input.visibility) throw notFound();+ const candidate: FactCandidate = { ...target, id: Number(target.id) };+ if (target.withdrawn) {+ throw verbError('invalid_params', `target_withdrawn: fact #${targetId} was forgotten, so it cannot be replaced.`,+ 'Remember the new claim without replaces; the forgotten claim stays withdrawn.');+ }+ if (target.expired_at || (target.valid_until && new Date(target.valid_until).getTime() <= Date.now())) {+ if (target.superseded_by != null) {+ throw verbError('invalid_params', `target_superseded: fact #${targetId} was already replaced by fact #${target.superseded_by}.`,+ `Recall the entity to check the current fact, then pass replaces: "${target.superseded_by}" if the new claim replaces that one.`);+ }+ 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)) {+ 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.');+ }+ if (candidate.source_markdown_slug && candidate.source_markdown_slug !== opts.pageSlug) {+ throw verbError('invalid_params', `replaces_cross_page: fact #${targetId} lives on page ${candidate.source_markdown_slug}.`,+ 'Forget the old fact, then remember the new one.');+ }+ const exact = await decideSingleFact(engine, sourceId, input, null);+ if (exact.status === 'duplicate') {+ if (exact.candidate!.id === candidate.id) return { status: 'duplicate', candidate };+ throw verbError('invalid_params', `replaces_duplicate: an active fact (#${exact.candidate!.id}) already states this claim.`,+ `Forget fact #${targetId} if it is no longer true; the existing fact #${exact.candidate!.id} already says the new claim.`);+ }+ return { status: 'superseded', candidate };+}diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 67872cc24a..562ffa18e3 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -159,6 +159,12 @@ 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);+ 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 });+ }const row = await admitWrite(ctx.engine, { principal, operation: 'remember', sourceId, sourceIncarnation: source.incarnation,slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent,intent: { ...callerIntent, entity_slug: entitySlug, fence, valid_from: new Date().toISOString(), valid_until: validUntil?.toISOString() ?? null,diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 458dd9b5d9..5b10cd36e2 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -7,7 +7,7 @@ import { pageIdentityError } from './page-identity.ts';import { assertPageRevision } from '../page-state/types.ts';import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, upsertFactRow, formatFenceDate } from '../facts-fence.ts';import { serializePageToMarkdown } from '../markdown.ts';-import { assertFactNotWithdrawn, decideSingleFact, prepareFactEmbedding, type SingleFactIntent } from '../facts/single-prepare.ts';+import { assertFactNotWithdrawn, decideReplacement, decideSingleFact, prepareFactEmbedding, type SingleFactIntent } from '../facts/single-prepare.ts';import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';import { preparePageMutation } from './page-prepare.ts';import type { PreparedMutation } from './coordinator.ts';@@ -31,10 +31,12 @@ function candidateState(value: Awaited<ReturnType<typeof decideSingleFact>>): stc?.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.';-function outcome(id: number, status: 'inserted' | 'duplicate' | 'superseded', entitySlug: string | null, validUntil: Date | string | null, degraded: boolean, p: Record<string, unknown>) {+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`;return { id: String(id), status, status_text: statusText, entity_slug: entitySlug,+ ...(status === 'superseded' && supersededId !== undefined ? { superseded_fact_id: String(supersededId) } : {}),+ ...(status === 'superseded' && p.replaces !== undefined && p.replaces !== null ? { replaced_by_caller: true } : {}),valid_until: validUntil ? new Date(validUntil).toISOString() : null,...(degraded ? { degraded_dedup: true } : {}),...(entitySlug !== null && p.entity_inferred ? { entity_inferred: p.entity_inferred as InferredVia } : {}),@@ -65,11 +67,16 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequesignal?.throwIfAborted();// #5836: an inferred link dedups exact text only, so it never supersedes or drops a similar fact.const dedupEmbedding = p.entity_inferred ? null : embedding;- const decision = await decideSingleFact(engine, row.source_id, input, dedupEmbedding, embedding_model);+ // `replaces`: the caller names the fact this one replaces (checked; the cosine rule does not apply).+ const replaces = p.replaces !== undefined && p.replaces !== null ? Number(p.replaces) : null;+ const decide = (e: BrainEngine, lock = false) => replaces !== null+ ? decideReplacement(e, row.source_id, input, replaces, { pageSlug: row.slug, remote: row.authority.remote === true, lock })+ : decideSingleFact(e, row.source_id, input, dedupEmbedding, embedding_model);+ const decision = await decide(engine);const validate = async (tx: BrainEngine) => {await assertFactNotWithdrawn(tx, row.source_id, input);if (embedding && JSON.stringify(await tx.executeRaw(`${embeddingConfigSql} FOR SHARE`)) !== observedEmbeddingConfig) conflict(row);- const current = await decideSingleFact(tx, row.source_id, input, dedupEmbedding, embedding_model);+ const current = await decide(tx, true);if (candidateState(current) !== candidateState(decision)) conflict(row);};if (decision.status === 'duplicate') {@@ -124,6 +131,6 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque}if (decision.status === 'superseded') await tx.executeRaw(`UPDATE facts SET expired_at=now(),superseded_by=$3WHERE id=$1 AND source_id=$2 AND expired_at IS NULL`, [decision.candidate!.id, row.source_id, id]);- return outcome(id, decision.status, input.entity_slug, validUntil, degraded, p);+ return outcome(id, decision.status, input.entity_slug, validUntil, degraded, p, decision.status === 'superseded' ? decision.candidate!.id : undefined);} };}diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex 1edcfb1269..7e9979042c 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -92,6 +92,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).' },},mutating: true,scope: 'write',@@ -138,6 +139,14 @@ const remember: Operation = {'Use "world" (default — agents can recall it) or "private" (local CLI reads only).',);}+ const replaces = typeof p.replaces === 'string' ? p.replaces.trim() : typeof p.replaces === 'number' ? String(p.replaces) : undefined;+ if (replaces !== undefined && (!/^\d+$/.test(replaces) || Number(replaces) <= 0)) {+ throw verbError(+ 'not_found',+ `No fact with id "${String(p.replaces)}" to replace.`,+ 'Pass the opaque fact_id from remember or recall (facts[].fact_id), or omit replaces.',+ );+ }if (ctx.dryRun) {parseTtlParam(p.ttl); // Dry runs still validate without admitting intent.return {@@ -150,7 +159,7 @@ const remember: Operation = {const { submitRememberMutation } = await import('./persistence/memory-mutations.ts');const { runMemoryWrite } = await import('./persistence/verb-errors.ts');- const result = await runMemoryWrite(() => submitRememberMutation(ctx, { ...p, fact, provenance, kind, visibility }));+ const result = await runMemoryWrite(() => submitRememberMutation(ctx, { ...p, fact, provenance, kind, visibility, ...(replaces !== undefined ? { replaces } : {}) }));// F8: the explanation the CLI formatter prints, as a model-visible notice.if ((result as { degraded_dedup?: boolean } | null)?.degraded_dedup) {const { degradedDedupNotice } = await import('./interop-notices.ts');@@ -485,6 +494,8 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {warnings: { type: 'array', items: { type: 'string', enum: ['NO_ENTITY', 'ENTITY_LINK_FAILED'] },description: 'NO_ENTITY: saved unattributed. ENTITY_LINK_FAILED: an inferred entity could not be linked; saved unattributed.' },hint: { type: 'string', description: 'Present with warnings: how to attribute the fact (pass `entity`).' },+ superseded_fact_id: { type: 'string', description: 'Present on status=superseded: the fact this one replaced.' },+ replaced_by_caller: { type: 'boolean', description: 'Present (true) when the caller named the replaced fact with `replaces`.' },write_request: WRITE_RECEIPT_SCHEMA,},},diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 1d27400c89..f1817ce9b8 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": 197008,- "stdoutSha256": "3f271e14e9933beb2044f28a4b8ea42dab752934fef26668d4e146a90e265a0b",+ "stdoutBytes": 197167,+ "stdoutSha256": "2e1d875b8209c6db39a492e119f2862c60d4b7eb50422f130b23c3af084c3b98","toolNames": ["remember","entity",@@ -177,6 +177,7 @@"infer_entity": "boolean?","kind": "string?","provenance": "string",+ "replaces": "string?","request_id": "string?","source_id": "string?","ttl": "string?",@@ -220,6 +221,10 @@"description": "Where the fact came from (max 500 chars).","type": "string"},+ "replaces": {+ "description": "fact_id this fact replaces (same entity).",+ "type": "string"+ },"request_id": {"description": "UUID; retry with it on timeout.","type": "string"diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.tsindex 1b6a1419a9..527a0efcaa 100644--- a/test/mcp-schema-budget.test.ts+++ b/test/mcp-schema-budget.test.ts@@ -54,7 +54,7 @@ const TOOL_BUDGETS: Record<string, number> = {get_backlinks: 430, get_ingest_log: 280, get_page: 810, get_recent_salience: 660, get_skill: 910,get_skill_asset: 790, get_write_request: 330, join_brain: 560, leave_brain: 540, list_brain_skillpack: 230,list_link_sources: 220, list_pages: 1090, list_skills: 670, list_write_requests: 450, put_page: 1320,- put_skill: 1420, query: 3250, recall: 1590, remember: 1370, request_tools: 560, resolve_slugs: 410, search: 1760,+ put_skill: 1420, query: 3250, recall: 1590, remember: 1420, request_tools: 560, resolve_slugs: 410, search: 1760,submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 680, whoami: 230,};diff --git a/test/remember-replaces.test.ts b/test/remember-replaces.test.tsnew file mode 100644index 0000000000..52fc45bd39--- /dev/null+++ b/test/remember-replaces.test.ts@@ -0,0 +1,102 @@+/**+ * `remember.replaces`: caller-directed replacement, zero model calls, checked+ * against the target under the publication's row lock. Protects every refusal+ * code, the same-text no-op, idempotent replay, the remote world-only rule, the+ * superseded chain head, and that the struck fence row and `superseded_by`+ * publish with the new fact.+ */+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';++let engine: PGLiteEngine;++async function call(name: string, params: Record<string, unknown>, remote = false) {+ const res = await dispatchToolCall(engine, name, params, remote+ ? { remote: true, takesHoldersAllowList: ['world'], sourceId: 'default' } : { remote: false });+ return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text!) as Record<string, any> };+}+async function remember(fact: string, extra: Record<string, unknown> = {}, remote = false) {+ return call('remember', { fact, provenance: 'test', entity: 'people/alice-example', ...extra }, remote);+}+async function factRow(id: string) {+ const [r] = await engine.executeRaw<{ expired: boolean; superseded_by: number | null }>(+ 'SELECT expired_at IS NOT NULL AS expired, superseded_by FROM facts WHERE id = $1', [Number(id)]);+ return r!;+}++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 call('put_page', { slug: 'people/alice-example', content: '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n\nA person.\n' });+ await call('put_page', { slug: 'people/bob-example', content: '---\ntitle: Bob Example\ntype: person\n---\n# Bob Example\n\nA person.\n' });+});++describe('remember replaces', () => {+ test('replaces the named fact: superseded_by, struck fence row, response fields', async () => {+ const old = await remember('Alice Example works at acme-example.');+ expect(old.isError).toBe(false);+ const res = await remember('Alice Example left acme-example in 2026.', { replaces: old.body.id });+ expect(res.isError).toBe(false);+ expect(res.body).toMatchObject({ status: 'superseded', superseded_fact_id: old.body.id, replaced_by_caller: true });+ expect(await factRow(old.body.id)).toEqual({ expired: true, superseded_by: Number(res.body.id) });+ const page = await call('get_page', { slug: 'people/alice-example', include_content: true });+ expect(String(page.body.content ?? page.body.compiled_truth)).toContain('superseded by #');+ });++ test('same text is a no-op duplicate; replay with the same request_id is idempotent', async () => {+ const old = await remember('Alice Example prefers async standups.');+ const same = await remember('Alice Example prefers async standups.', { replaces: old.body.id });+ expect(same.body).toMatchObject({ status: 'duplicate', id: old.body.id });+ const requestId = '6f1d2a4e-8b3c-4d5e-9f60-718293a4b5c6';+ const first = await remember('Alice Example prefers daily standups.', { replaces: old.body.id, request_id: requestId });+ const again = await remember('Alice Example prefers daily standups.', { replaces: old.body.id, request_id: requestId });+ expect(first.body.id).toBe(again.body.id);+ expect(first.body.status).toBe('superseded');+ });++ test('refusals carry a code prefix and a next step', async () => {+ const a = await remember('Alice Example lives in Lisbon.');+ const wrongEntity = await remember('Bob Example lives in Porto.', { replaces: a.body.id, entity: 'people/bob-example' });+ expect(wrongEntity.isError).toBe(true);+ expect(JSON.stringify(wrongEntity.body)).toContain('replaces_entity_mismatch');++ const replaced = await remember('Alice Example lives in Porto.', { replaces: a.body.id });+ const chain = await remember('Alice Example lives in Madrid.', { replaces: a.body.id });+ expect(chain.isError).toBe(true);+ expect(JSON.stringify(chain.body)).toContain('target_superseded');+ expect(JSON.stringify(chain.body)).toContain(`#${replaced.body.id}`);++ const forgotten = await remember('Alice Example plays chess.');+ await call('forget', { id: forgotten.body.id });+ const withdrawn = await remember('Alice Example plays go.', { replaces: forgotten.body.id });+ expect(JSON.stringify(withdrawn.body)).toContain('target_withdrawn');++ const missing = await remember('Alice Example plays tennis.', { replaces: '999999' });+ expect(missing.body.code ?? missing.body.error).toBe('not_found');++ const other = await remember('Alice Example plays piano.');+ const dup = await remember('Alice Example plays piano.', { replaces: (await remember('Alice Example plays violin.')).body.id });+ expect(JSON.stringify(dup.body)).toContain('replaces_duplicate');+ expect(other.isError).toBe(false);+ });++ test('a remote caller cannot replace a private fact (not_found, no existence leak)', async () => {+ const secret = await remember('Alice Example has a private appointment.', { visibility: 'private' });+ const res = await remember('Alice Example moved the appointment.', { replaces: secret.body.id }, true);+ expect(res.isError).toBe(true);+ expect(res.body.code ?? res.body.error).toBe('not_found');+ expect(await factRow(secret.body.id)).toEqual({ expired: false, superseded_by: null });+ });+});