Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(memory): re-saving a claim with its entity links the unlinked copy; forgetting that copy no longer withdraws the linked fact

garrytan8d3d2ec707d4
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index b13baa95a6..49965694ac 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -300,6 +300,13 @@ text equal to the target is `status: duplicate` and changes nothing. On success
`superseded_by` and its `## Facts` row is struck with `superseded by #N` in
the same publication. Every `superseded` response carries `superseded_fact_id`.
+Remembering a claim with an entity (given or inferred) when the same claim is
+an active fact saved without an entity, in the same source and visibility,
+links that copy as if `replaces` named it: `status: superseded`,
+`superseded_fact_id` names the unlinked copy, `replaced_by_caller` is absent,
+and `status_text` says there is nothing to forget. When `replaces` would refuse
+(for example `replaces_cross_page`), the fact is saved as a new one instead.
+
#### remember entity attribution fields (additive)
Optional response fields; clients must ignore any they do not know.
@@ -334,7 +341,7 @@ writes nothing twice.
Response: `{ protocol_version, request_id, client_request_id?, items[], saved, failed, partial,
hints?, next? }`. Each `items[]` entry is a compact receipt `{ index,
-request_id, status, id?, entity_slug?, warnings?, valid_until?, state? }`
+request_id, status, id?, entity_slug?, superseded_fact_id?, warnings?, valid_until?, state? }`
(`state` and `retry_after_ms` only when the write is not yet committed), or
`{ index, request_id, status: "failed", error: { code, message, suggestion? } }`. Hints the
single-fact response would repeat per item appear once in `hints`. `partial: true` means some items saved and some failed; resend
@@ -506,6 +513,12 @@ already-expired fact returns `expired: false` (success); unknown id ⇒
Response: `{ id, expired, reason, protocol_version }`.
+A fact saved without an entity withdraws its claim under every entity. When the
+same claim is active on entity-linked facts (same source and visibility),
+forgetting the unlinked fact is refused with `invalid_params`, message prefix
+`claim_linked:`, naming those facts, and nothing changes. The `suggestion`
+says to keep them, or to forget them first to withdraw the claim everywhere.
+
#### forget similar_active and semantic_review (additive)
`semantic_review` (boolean, default `true`): `false` keeps this claim out of
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index bc695913b7..48436d3ed7 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto';
import type { OperationContext } from '../ops/contract.ts';
+import type { BrainEngine } from '../engine.ts';
import { opError, OperationError, verbError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { enforceClientSlugFence, enforceSubagentSlugFence, validatePageSlug } from '../ops/context.ts';
@@ -182,6 +183,26 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
interface WithdrawalTarget { id: number; entity_slug: string | null; source_markdown_slug: string | null; expired_at: Date | null; }
+/**
+ * A fact saved without an entity says nothing about whom it concerns, so its
+ * withdrawal reaches the claim under every entity. When that claim is active
+ * on entity-linked facts, forgetting the unlinked copy would silently withdraw
+ * them too, and a withdrawn claim cannot be remembered again; refuse and name them.
+ */
+async function refuseUnlinkedForgetOfLinkedClaim(tx: BrainEngine, sourceId: string, id: number, remote: boolean): Promise<void> {
+ const linked = await tx.executeRaw<{ id: number; entity_slug: string }>(`SELECT l.id,l.entity_slug FROM facts u
+ JOIN facts l ON l.source_id=u.source_id AND l.visibility=u.visibility AND l.entity_slug IS NOT NULL AND l.id<>u.id
+ AND l.expired_at IS NULL AND (l.valid_until IS NULL OR l.valid_until > now())
+ AND gbrain_fact_fingerprint(l.fact)=gbrain_fact_fingerprint(u.fact)
+ WHERE u.id=$1 AND u.source_id=$2 AND ($3::boolean=false OR l.visibility='world')
+ ORDER BY l.id LIMIT 5`, [id, sourceId, remote]);
+ if (!linked.length) return;
+ const named = linked.map(row => `#${row.id} (${row.entity_slug})`).join(', ');
+ throw verbError('invalid_params',
+ `claim_linked: fact #${id} was saved without an entity, and the same claim is active as ${named}. Forgetting #${id} would withdraw those facts too, so nothing was forgotten.`,
+ `Keep the linked ${linked.length === 1 ? 'fact' : 'facts'}: the copy without an entity needs no cleanup (remember the claim with entity and replaces: "${id}" retires it). To withdraw the claim everywhere, forget ${linked.map(row => `#${row.id}`).join(', ')} first, then #${id}.`);
+}
+
/** Withdrawal commits independently of filesystem ownership and request FIFO. */
export async function submitForgetMutation(ctx: OperationContext, operation: 'forget' | 'forget_fact', params: Record<string, unknown>): Promise<Record<string, unknown>> {
const sub = await submission(ctx, operation, params);
@@ -216,6 +237,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
WHERE id=$1 AND source_id=$2 AND ($3::boolean=false OR visibility='world')`, [id, sourceId, ctx.remote !== false]);
if (!fact) throw verbError(operation === 'forget' ? 'not_found' : 'fact_not_found',
`No fact with id "${rawId}".`, 'Ids come from remember/recall. Recall the entity first to find the right fact.');
+ if (fact.entity_slug === null) await refuseUnlinkedForgetOfLinkedClaim(tx, sourceId, id, ctx.remote !== false);
const slug = fact.source_markdown_slug ?? fact.entity_slug ?? 'memory/unattributed';
enforceClientSlugFence(ctx, slug, operation); enforceSubagentSlugFence(ctx, slug, operation);
const authority = await submissionAuthority({ ...ctx, engine: tx }, operation, sourceId, source.incarnation, slug);
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index 0f864dda42..8db2527509 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -33,10 +33,12 @@ 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. 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) {
+export const NO_ENTITY_HINT = 'Saved without an entity, so entity-scoped recall will not find it. To link it, remember the same claim again with `entity` (the person, company or project it is about): that replaces this copy, so there is nothing to forget. Do not forget it: a claim forgotten without an entity is withdrawn for every entity and 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, linkedCopy = false) {
const statusText = status === 'inserted' ? `remembered as fact #${id}` : status === 'duplicate'
- ? `already knew this — kept fact #${id}` : `updated — fact #${id} supersedes the previous version`;
+ ? `already knew this — kept fact #${id}` : linkedCopy
+ ? `linked — fact #${id} replaces #${supersededId}, the same claim saved without an entity; nothing to forget`
+ : `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 } : {}),
@@ -47,6 +49,15 @@ function outcome(id: number, status: 'inserted' | 'duplicate' | 'superseded', en
protocol_version: 1 };
}
+/** The newest active fact in this source and visibility that states the same normalized claim without an entity. */
+async function activeUnlinkedCopy(engine: BrainEngine, sourceId: string, input: SingleFactIntent): Promise<number | null> {
+ const [row] = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts
+ WHERE source_id=$1 AND visibility=$2 AND entity_slug IS NULL AND expired_at IS NULL
+ AND (valid_until IS NULL OR valid_until > now()) AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3)
+ ORDER BY id DESC LIMIT 1`, [sourceId, input.visibility, input.fact]);
+ return row ? Number(row.id) : null;
+}
+
/** Every retry renders the semantic append from the latest coherent snapshot. */
export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal): Promise<PreparedMutation> {
signal?.throwIfAborted();
@@ -72,9 +83,19 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
const dedupEmbedding = p.entity_inferred ? null : embedding;
// `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 replace = (e: BrainEngine, target: number, lock: boolean) =>
+ decideReplacement(e, row.source_id, input, target, { pageSlug: row.slug, remote: row.authority.remote === true, lock });
+ const decide = async (e: BrainEngine, lock = false) => {
+ if (replaces !== null) return replace(e, replaces, lock);
+ // The same claim saved earlier without an entity is this fact unlinked: linking it supersedes that copy,
+ // so no subjectless duplicate is left whose forget would withdraw the claim from every entity.
+ const unlinked = input.entity_slug === null ? null : await activeUnlinkedCopy(e, row.source_id, input);
+ if (unlinked !== null) {
+ const linked = await replace(e, unlinked, lock).catch(() => null);
+ if (linked) return linked;
+ }
+ return 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);
@@ -134,6 +155,8 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
}
if (decision.status === 'superseded') await tx.executeRaw(`UPDATE facts SET expired_at=now(),superseded_by=$3
WHERE 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, decision.status === 'superseded' ? decision.candidate!.id : undefined), ...fencesNormalized };
+ const superseded = decision.status === 'superseded' ? decision.candidate! : undefined;
+ return { ...outcome(id, decision.status, input.entity_slug, validUntil, degraded, p, superseded?.id,
+ superseded !== undefined && superseded.entity_slug == null && input.entity_slug !== null), ...fencesNormalized };
} };
}
diff --git a/src/core/remember-batch.ts b/src/core/remember-batch.ts
index 0a1d56da3d..431db66efc 100644
--- a/src/core/remember-batch.ts
+++ b/src/core/remember-batch.ts
@@ -10,8 +10,9 @@
* deterministic child request_id derived from the caller's request_id and
* the item index, so replaying the same request_id replays each child
* (committed children return their receipt, nothing is written twice);
- * - each item's receipt is compact (status, fact id, entity, warnings, and
- * the write state only when it is not committed); repeated hints appear
+ * - each item's receipt is compact (status, fact id, entity, the fact it
+ * superseded, warnings, and the write state only when it is not
+ * committed); repeated hints appear
* once at the top level;
* - publication is per item: the response reports each item's status and
* `partial: true` when some failed. Replaying the same request_id returns
@@ -93,6 +94,7 @@ export async function runRememberBatch(ctx: OperationContext, p: Record<string,
index, request_id: child, status: String(out?.status ?? 'saved'),
...(out?.id !== undefined ? { id: out.id } : {}),
...(out?.entity_slug !== undefined ? { entity_slug: out.entity_slug } : {}),
+ ...(out?.superseded_fact_id !== undefined ? { superseded_fact_id: out.superseded_fact_id } : {}),
...(Array.isArray(out?.warnings) && out.warnings.length ? { warnings: out.warnings } : {}),
...(out?.valid_until ? { valid_until: out.valid_until } : {}),
...(typeof out?.state === 'string' && out.state !== 'committed' ? { state: out.state, retry_after_ms: out.retry_after_ms ?? null } : {}),
diff --git a/test/memory-sibling-facts.test.ts b/test/memory-sibling-facts.test.ts
index 97a3c7f7fb..9cbf233909 100644
--- a/test/memory-sibling-facts.test.ts
+++ b/test/memory-sibling-facts.test.ts
@@ -76,6 +76,21 @@ describe('facts about an entity with identity siblings', () => {
expect(r.json.warnings).toBeUndefined();
});
+ test('save without an entity, re-save with one, then forget the unlinked copy: the fact stays on both sibling cards (dev round 2)', async () => {
+ await siblings();
+ const claim = 'Correction: Ines Example is now the procurement lead at Widget Co; Lior Example moved to another role.';
+ const unlinked = (await call('remember', { items: [{ fact: claim }], provenance: 'team update', infer_entity: false })).json.items[0];
+ const linked = (await call('remember', { items: [{ fact: claim, entity: 'crm/widget-co' }], provenance: 'team update' })).json.items[0];
+ expect(linked).toMatchObject({ status: 'superseded', superseded_fact_id: unlinked.id });
+ const forgot = await dispatchToolCall(engine, 'forget', { id: unlinked.id, reason: 'duplicate without entity' }, local as never);
+ expect(forgot.isError).toBe(true);
+ expect(forgot.content[0].text).toContain('claim_linked:');
+ for (const name of ['WGCO', 'Widget Co', 'Copper Fox']) {
+ const card = (await call('entity', { name })).json.card;
+ expect(card.recent_facts.map((f: { id: string }) => String(f.id))).toEqual([String(linked.id)]);
+ }
+ });
+
test('search names the entity: its saved facts come first, then the facts of an entity they point to', async () => {
await siblings();
await put('crm/kite-co', 'crm', 'CRM record: Kite Co', 'Account code: KTCO.');
diff --git a/test/remember-withdrawn-claim.test.ts b/test/remember-withdrawn-claim.test.ts
index 373744656d..af175d555b 100644
--- a/test/remember-withdrawn-claim.test.ts
+++ b/test/remember-withdrawn-claim.test.ts
@@ -126,6 +126,61 @@ describe('remember after forget of the same claim', () => {
});
});
+describe('a claim saved without an entity, then with one', () => {
+ const active = async () => (await engine.executeRaw<{ id: number; entity_slug: string | null }>(
+ 'SELECT id,entity_slug FROM facts WHERE expired_at IS NULL ORDER BY id')).map(r => ({ id: String(r.id), entity_slug: r.entity_slug }));
+
+ test('re-saving it with the entity links the unlinked copy (superseded, not duplicated), so there is nothing to forget', async () => {
+ const unlinked = await call('remember', { items: [{ fact: CLAIM, provenance: 'team update' }], infer_entity: false });
+ const oldId = unlinked.body.items[0].id;
+ const linked = await call('remember', { items: [{ fact: CLAIM, provenance: 'team update', entity: 'crm/acme-example' }] });
+ expect(linked.body.items[0]).toMatchObject({ status: 'superseded', entity_slug: 'crm/acme-example', superseded_fact_id: oldId });
+ expect(linked.body.items[0].replaced_by_caller).toBeUndefined();
+ const single = await call('recall', { entity: 'crm/acme-example' });
+ expect(JSON.stringify(single.body.facts)).toContain(CLAIM);
+ expect(await active()).toEqual([{ id: linked.body.items[0].id, entity_slug: 'crm/acme-example' }]);
+ const [w] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM fact_withdrawals');
+ expect(Number(w!.n)).toBe(0);
+ });
+
+ test('the single-fact status text says the copy was linked', async () => {
+ const unlinked = await call('remember', { fact: CLAIM, provenance: 'team update', infer_entity: false });
+ const linked = await call('remember', { fact: CLAIM, provenance: 'team update', entity: 'crm/acme-example' });
+ expect(linked.body).toMatchObject({ status: 'superseded', superseded_fact_id: unlinked.body.id });
+ expect(linked.body.status_text).toBe(`linked — fact #${linked.body.id} replaces #${unlinked.body.id}, the same claim saved without an entity; nothing to forget`);
+ });
+
+ test('forgetting the unlinked copy refuses while the claim is active on a linked fact; the linked fact stays rememberable', async () => {
+ const unlinked = await call('remember', { fact: CLAIM, provenance: 'team update', infer_entity: false });
+ const linked = await call('remember', { fact: CLAIM, provenance: 'team update', entity: 'crm/acme-example' });
+ const forgot = await call('forget', { id: unlinked.body.id, reason: 'duplicate without entity' });
+ expect(forgot.isError).toBe(true);
+ expect(forgot.body.code).toBe('invalid_params');
+ expect(forgot.body.message).toBe(`claim_linked: fact #${unlinked.body.id} was saved without an entity, and the same claim is active as #${linked.body.id} (crm/acme-example). Forgetting #${unlinked.body.id} would withdraw those facts too, so nothing was forgotten.`);
+ expect(forgot.body.suggestion).toContain(`forget #${linked.body.id} first`);
+ expect(await active()).toEqual([{ id: linked.body.id, entity_slug: 'crm/acme-example' }]);
+ const [w] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM fact_withdrawals');
+ expect(Number(w!.n)).toBe(0);
+ });
+
+ test('an unlinked copy saved after the linked fact is refused the same way; forgetting the linked fact first withdraws the claim everywhere', async () => {
+ const linked = await call('remember', { fact: CLAIM, provenance: 'team update', entity: 'crm/acme-example' });
+ const unlinked = await call('remember', { fact: CLAIM, provenance: 'team update', infer_entity: false });
+ expect(unlinked.body).toMatchObject({ status: 'inserted', entity_slug: null });
+ expect((await call('forget', { id: unlinked.body.id })).body.message).toContain('claim_linked:');
+ expect((await call('forget', { id: linked.body.id })).body.expired).toBe(true);
+ expect((await call('forget', { id: unlinked.body.id })).body.expired).toBe(true);
+ expect(await active()).toEqual([]);
+ });
+
+ test('an unlinked fact whose claim is on no linked fact forgets as before', async () => {
+ const unlinked = await call('remember', { fact: CLAIM, provenance: 'team update', infer_entity: false });
+ const forgot = await call('forget', { id: unlinked.body.id });
+ expect(forgot.isError).toBe(false);
+ expect(forgot.body.expired).toBe(true);
+ });
+});
+
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',