Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(remember): replaces finds a private fenced fact when visibility is unset (#7248)

garrytan64c04ec801c0
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 992a2d2b51..a64e696b60 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -331,13 +331,16 @@ suggestion are unchanged.
old fact is no longer current (the texts need not 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. A target saved without an entity may be
+entity, on the same entity page. A local call that leaves `visibility` unset
+takes a private target's visibility, so the replacement stays private. 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`,
-`replaces_cross_page` (forget the old fact, then remember), and
+`replaces_cross_page` (forget the old fact, then remember),
+`replaces_visibility_mismatch` (an explicit `visibility` that differs from the
+target's; pass the target's visibility), 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
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 91e52533e4..7fb1de92d2 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1047,7 +1047,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.330.0', text: '`gbrain entity <name>` now resolves one unambiguous name variant when no exact name matches (a nickname, an initial, a title in front, reversed order, a one-letter surname typo, a surname only one page has), across every source you can read, and says so in `card.match`; a variant two pages share is a miss with `ambiguous: true`. Cards list `possible_duplicates` (title-prefixed person pages, never merged), and a miss or a card with no backlinks or facts while mention coverage is incomplete lists the pages whose text names it (`text_mentions`). The human miss line is now just "No entity found."; timing and mention coverage print on their own lines. `gbrain config set entity.name_variants false` (or `variants: false`) keeps exact names only. Doctor adds `person_title_duplicates`, which lists such pairs with the merge to review and changes nothing.' },
{ since: '0.60.330.0', text: '`gbrain recall <entity>` on a local brain now reads every slug the entity\'s facts may be saved under, as the recall operation already did (identity siblings, the title subject, and the bare basename when no other page claims it), so facts saved before the page existed show up. `gbrain recall "<name> <topic words>"` that matched nothing as one entity or text now recalls the leading or trailing name\'s facts with the topic matches first, with a note naming the entity. `recall --entity <x>` is accepted (never split or widened to a text match). With `GBRAIN_FAIL_ON_EMPTY=1`, a recall or entity lookup that matches nothing exits 12 (`no_results`); by default it still exits 0, and recall\'s list `--json` adds `status: "no_results"`.' },
{ since: '0.60.330.0', text: 'A search for an identifier (an email, a URL, a phone number in any common format, a long number, a hex id or a code such as an invoice number) now puts the pages that contain it verbatim first (`exact_lookup: identifier`) before the ranked results; dates and ordinary words are unchanged.' },
- { since: '0.60.330.0', text: '`remember` with a folder-less `entity` (`alex-example`, `Alice`) now saves only when it names exactly one readable entity page (by slug, a unique basename, an alias or the same name). When it could mean several pages, only begins a page name, or only resembles pages, the call is refused `invalid_params` with `reason` `entity_ambiguous`, `entity_unverified`, `entity_not_entity` or `entity_no_page` and up to five candidate slugs, and nothing is saved; before, the fact was keyed under a bare slug no page carries. A name nothing resembles still saves under its slug, and a slug with a folder saves as before. A pending reply\'s `write_request.target` names the page and entity the fact goes to, and a `remember` batch reports an item still publishing as `pending`, not `failed` (#7248).' },
+ { since: '0.60.330.0', text: '`remember` with a folder-less `entity` (`alex-example`, `Alice`) now saves only when it names exactly one readable entity page (by slug, a unique basename, an alias or the same name). When it could mean several pages, only begins a page name, or only resembles pages, the call is refused `invalid_params` with `reason` `entity_ambiguous`, `entity_unverified`, `entity_not_entity` or `entity_no_page` and up to five candidate slugs, and nothing is saved; before, the fact was keyed under a bare slug no page carries. A name nothing resembles still saves under its slug, and a slug with a folder saves as before. A pending reply\'s `write_request.target` names the page and entity the fact goes to, and a `remember` batch reports an item still publishing as `pending`, not `failed`. `remember` with `replaces` on a private fact and no `visibility` now replaces it and keeps the new fact private (it answered `not_found` to a local caller); an explicit `visibility` that differs from the fact\'s is refused `invalid_params` with the prefix `replaces_visibility_mismatch`. A remote caller still gets `not_found` for a private fact (#7248).' },
// GBRA-150 (synced-but-not-searchable landing checks). `since` is restamped at the merge slot.
{ since: '0.60.337.0', id: 'sync_status_blocked_means_source_stopped', text: '`gbrain sync status` now reads `blocked` only when the source cannot advance without a person or an operator, the meaning a sync run\'s drain outcome and a sync job\'s `blocked` progress already had. A file hold that waits on a person while the rest of the source keeps syncing now reads `synced` with the new reason `held_needs_human` (it read `blocked` before); `needs_human`, `next` and the hold rows are unchanged, so a client acting on `needs_human` sees no difference.' },
{ since: '0.60.337.0', id: 'sources_resolve_path', text: 'New read-only `gbrain sources resolve-path <id> <path...> [--stdin] [--json]` (MCP `sources_resolve_path`, read scope, at most 200 paths) says what gbrain did with each file path of a source by its own rules: the slug sync gives it, whether it is skipped, held, not synced yet, deleted, or a live page, and whether search can find it (`searchable` true, `keyword` or false), with a `why` and a `fix`. Landing checks should call it instead of copying gbrain\'s path-to-slug rules. `gbrain sync status --detail` adds a `landing` block, and the new cheap doctor check `sync_landing_gaps` warns when pages a managed sync committed more than the freshness target ago still cannot be fully searched.' },
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index 6ed91d981e..a532991e8c 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -140,6 +140,19 @@ function replacesDerivedSuggestion(sourceId: string, slug: string): string {
return `Re-extract the conversation page to change its facts: preview with ${base} --dry-run, then run ${base} --max-cost-usd <n> (paid).`;
}
+/**
+ * #7248: a replacement whose visibility the caller did not set keeps a
+ * private target private, so replacing a private fact needs no flag. Only a
+ * local caller qualifies (a remote caller never sees a private fact), and a
+ * world target never widens a default.
+ */
+export async function replacementVisibility(engine: BrainEngine, sourceId: string, targetId: number,
+ defaulted: 'world' | 'private', opts: { remote: boolean }): Promise<'world' | 'private'> {
+ if (defaulted === 'private' || opts.remote || !Number.isSafeInteger(targetId)) return defaulted;
+ const [target] = await engine.executeRaw<{ visibility: string }>('SELECT visibility FROM facts WHERE id=$1 AND source_id=$2', [targetId, sourceId]);
+ return target?.visibility === 'private' ? 'private' : defaulted;
+}
+
/**
* `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
@@ -156,9 +169,12 @@ export async function decideReplacement(engine: BrainEngine, sourceId: string, i
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.excludePrivate ? ` AND ${privateProvenanceFilterFragment('f')}` : ''}${opts.lock ? ' FOR UPDATE OF f' : ''}`, [targetId, sourceId]);
if (!target || (opts.remote && target.visibility !== 'world')) throw notFound();
- if (target.visibility !== input.visibility) throw notFound();
// #5913 [R2]: a slug-bound writer learns nothing about a fact outside its prefixes; the answer is the missing-id one.
if (opts.slugPrefixes && [target.entity_slug, target.source_markdown_slug].some(slug => slug && !slugUnderBoundPrefixes(opts.slugPrefixes!, slug))) throw notFound();
+ if (target.visibility !== input.visibility) {
+ throw verbError('invalid_params', `replaces_visibility_mismatch: fact #${targetId} is ${target.visibility}, and the new fact would be ${input.visibility}.`,
+ `Pass visibility: "${target.visibility}" to replace it, or forget fact #${targetId} and remember the new claim separately.`);
+ }
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.`,
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index fbe4446131..6aa956c3f3 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -196,8 +196,11 @@ 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, call);
- const { assertFactNotWithdrawn, decideReplacement } = await import('../facts/single-prepare.ts');
- const visibility = await rememberVisibility(ctx, call, snapshot?.page);
+ const { assertFactNotWithdrawn, decideReplacement, replacementVisibility } = await import('../facts/single-prepare.ts');
+ const defaultedVisibility = await rememberVisibility(ctx, call, snapshot?.page);
+ const visibility = call.visibilityDefaulted && p.replaces !== undefined && p.replaces !== null
+ ? await replacementVisibility(ctx.engine, sourceId, Number(p.replaces), defaultedVisibility, { remote: ctx.remote !== false })
+ : defaultedVisibility;
const factIntent = { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as never, visibility, 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) {
diff --git a/test/remember-replaces-fenced-7248.test.ts b/test/remember-replaces-fenced-7248.test.ts
new file mode 100644
index 0000000000..f5608b6cc7
--- /dev/null
+++ b/test/remember-replaces-fenced-7248.test.ts
@@ -0,0 +1,101 @@
+/**
+ * #7248 follow-up: `remember --replaces` on a fact that lives in an owner
+ * page's `## Facts` fence (imported from the page, not written by remember).
+ * A private fenced fact answered not_found to a local caller that left
+ * visibility unset, because the default (world) never matched it. The
+ * replacement now keeps a private target private; an explicit mismatch names
+ * itself instead of claiming the fact is missing; a remote caller still gets
+ * not_found for a private 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;
+const SLUG = 'people/alice-example';
+const HEADER = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n';
+const PAGE = '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n\nA person.\n\n## Facts\n\n<!--- gbrain:facts:begin -->\n\n' + HEADER
+ + '| 1 | Alice Example works at acme-example. | fact | 1.0 | world | medium | 2026-10-01T00:00:00Z | | test | |\n'
+ + '| 2 | Alice Example likes tea. | preference | 1.0 | private | medium | 2026-10-01T00:00:00Z | | test | |\n'
+ + '<!--- gbrain:facts:end -->\n';
+
+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 fenced(claim: string) {
+ const [row] = await engine.executeRaw<{ id: number; row_num: number; visibility: string }>(
+ 'SELECT id, row_num, visibility FROM facts WHERE source_markdown_slug = $1 AND fact = $2', [SLUG, claim]);
+ return row!;
+}
+async function factRow(id: number | string) {
+ const [r] = await engine.executeRaw<{ visibility: string; expired: boolean; superseded_by: number | null }>(
+ 'SELECT visibility, 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 () => { await disposePersistenceConsumer(engine); resetGateway(); __setEmbedTransportForTests(null); await engine.disconnect(); });
+beforeEach(async () => {
+ await disposePersistenceConsumer(engine);
+ await resetPgliteState(engine);
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ const put = await call('put_page', { slug: SLUG, content: PAGE });
+ expect(put.isError).toBe(false);
+});
+
+describe('remember replaces a fenced fact (#7248)', () => {
+ test('the imported fence rows are active facts with row numbers', async () => {
+ expect(await fenced('Alice Example works at acme-example.')).toMatchObject({ row_num: 1, visibility: 'world' });
+ expect(await fenced('Alice Example likes tea.')).toMatchObject({ row_num: 2, visibility: 'private' });
+ });
+
+ test('a world fenced fact is replaced', async () => {
+ const old = await fenced('Alice Example works at acme-example.');
+ const res = await call('remember', { fact: 'Alice Example left acme-example.', provenance: 'test', entity: SLUG, replaces: String(old.id) });
+ expect(res.isError).toBe(false);
+ expect(res.body).toMatchObject({ status: 'superseded', superseded_fact_id: String(old.id), replaced_by_caller: true });
+ expect(await factRow(old.id)).toEqual({ visibility: 'world', expired: true, superseded_by: Number(res.body.id) });
+ });
+
+ test('a private fenced fact is replaced without passing visibility, and the replacement stays private', async () => {
+ const old = await fenced('Alice Example likes tea.');
+ const res = await call('remember', { fact: 'Alice Example likes coffee.', provenance: 'test', entity: SLUG, replaces: String(old.id) });
+ expect(res.isError).toBe(false);
+ expect(res.body).toMatchObject({ status: 'superseded', superseded_fact_id: String(old.id) });
+ expect(await factRow(res.body.id)).toMatchObject({ visibility: 'private', expired: false });
+ expect(await factRow(old.id)).toEqual({ visibility: 'private', expired: true, superseded_by: Number(res.body.id) });
+ const page = await call('get_page', { slug: SLUG, include_content: true });
+ const content = String(page.body.content ?? page.body.compiled_truth);
+ expect(content).toContain('superseded by #' + res.body.id);
+ expect(content).toMatch(/\| Alice Example likes coffee\. \| [a-z]+ \| [0-9.]+ \| private \|/);
+ });
+
+ test('an explicit visibility that differs names the mismatch instead of claiming the fact is missing', async () => {
+ const old = await fenced('Alice Example likes tea.');
+ const res = await call('remember', { fact: 'Alice Example likes coffee.', provenance: 'test', entity: SLUG, replaces: String(old.id), visibility: 'world' });
+ expect(res.isError).toBe(true);
+ expect(res.body.code).toBe('invalid_params');
+ expect(res.body.message).toContain('replaces_visibility_mismatch');
+ expect(res.body.suggestion).toContain('visibility: "private"');
+ expect(await factRow(old.id)).toMatchObject({ expired: false, superseded_by: null });
+ });
+
+ test('a remote caller still gets not_found for a private fenced fact', async () => {
+ const old = await fenced('Alice Example likes tea.');
+ const res = await call('remember', { fact: 'Alice Example likes coffee.', provenance: 'test', entity: SLUG, replaces: String(old.id) }, true);
+ expect(res.isError).toBe(true);
+ expect(res.body.code).toBe('not_found');
+ expect(JSON.stringify(res.body)).not.toContain('private');
+ expect(await factRow(old.id)).toMatchObject({ expired: false, superseded_by: null });
+ });
+});