Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(memory): remote forget refusals and entity cards respect visibility and withdrawal
garrytan3d6a05e23f5f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b4d2fdd457..a0c3df3a53 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,17 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased: visibility fix, version stamped at merge] - 2026-10-11++**Remote forget refusals and entity cards respect visibility and withdrawal.** A remote `forget` never withdraws, or names, an active fact on a page the caller cannot read; when one would be reached, it is refused with a `claim_linked:` message that names no fact. A remote `remember` refuses a withdrawn claim the caller cannot see the same way it refuses an unreadable page. The entity card's `identity_excerpt` no longer shows a forgotten fact row. Local callers keep their detailed refusals.++### Itemized changes++- `src/core/persistence/memory-mutations.ts`: the forget refusal splits the claim's other active copies by the caller's read visibility; local callers are unchanged.+- `src/core/facts/single-prepare.ts`, `src/core/persistence/memory-prepare.ts`, `src/core/persistence/page-visibility.ts`: the withdrawn-claim check takes the caller's visibility and reuses the existing not-visible refusal.+- `src/core/verbs/entity-card-identity.ts`: excerpt bodies come from page snapshots, which carry the withdrawal overlay `get_page` applies.+- Tests: `test/visibility-withdrawal.test.ts` (PGLite) and `test/e2e/visibility-withdrawal-postgres.test.ts` (Postgres) share `test/helpers/visibility-withdrawal-scenarios.ts`.+## [0.60.175.0] - 2026-10-11**CI test shards are balanced again, and the nightly run stops failing its shard-timing check.** CI splits each test lane across several machines using the recorded run time of every test file. A test file with no recorded time is packed blind, and 11.1% of E2E files had none, past the 10% bound the nightly enforces. This release re-measures every lane from green master runs. No product behaviour changes.diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex 20f70c9757..021cd6005e 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -569,6 +569,8 @@ 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.+A forget never withdraws an active fact the caller cannot read; when one+would be reached, the refusal keeps the `claim_linked:` prefix and names no fact.#### forget and purge (additive note)diff --git a/llms-full.txt b/llms-full.txtindex a5b7c3428f..07177622a9 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -8998,6 +8998,8 @@ 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.+A forget never withdraws an active fact the caller cannot read; when one+would be reached, the refusal keeps the `claim_linked:` prefix and names no fact.#### forget and purge (additive note)diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.tsindex 6d81577614..b4adc3d0dc 100644--- a/src/core/facts/single-prepare.ts+++ b/src/core/facts/single-prepare.ts@@ -8,6 +8,7 @@ import { cosineVerdict } from './capture-dedup.ts';import { interleaveFusion } from '../search/fusion-lists.ts';import { readSupersessionThreshold } from './supersession-threshold.ts';import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';+import { pageNotVisibleError } from '../persistence/page-visibility.ts';export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded'; candidate: FactCandidate | null; }@@ -27,11 +28,26 @@ export async function prepareFactEmbedding(fact: string, signal?: AbortSignal, d}return { embedding: null, embedding_model: null, degraded: true };}-export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: string, input: SingleFactIntent): Promise<void> {+/**+ * `excludePrivate`: the caller cannot read private pages. A withdrawal whose withdrawn rows all sit on pages it+ * cannot read is refused exactly as a page it may not see is, so the refusal never confirms a claim it cannot see.+ */+export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: string, input: SingleFactIntent, opts: { excludePrivate?: boolean } = {}): Promise<void> {await assertFactNotPurged(engine, sourceId, input);- if (await isFactWithdrawn(engine, sourceId, input.visibility, input.fact, input.entity_slug)) {- throw verbError('invalid_params', FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION);+ if (!await isFactWithdrawn(engine, sourceId, input.visibility, input.fact, input.entity_slug)) return;+ if (opts.excludePrivate) {+ const [backing] = await engine.executeRaw<{ visible: boolean; hidden: boolean }>(`SELECT+ COALESCE(bool_or(${privateProvenanceFilterFragment('f')}), false) AS visible,+ COALESCE(bool_or(NOT (${privateProvenanceFilterFragment('f')})), false) AS hidden+ FROM facts f JOIN fact_withdrawals w ON 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,'*'))+ WHERE f.source_id=$1 AND f.visibility=$2 AND f.expired_at IS NOT NULL+ AND gbrain_fact_fingerprint(f.fact)=gbrain_fact_fingerprint($3) AND (w.subject='*' OR w.subject=$4::text)`,+ [sourceId, input.visibility, input.fact, input.entity_slug]);+ if (backing?.hidden && !backing.visible) throw pageNotVisibleError();}+ throw verbError('invalid_params', FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION);}export const CANDIDATE_FUSION_KEY = 'facts.candidate_fusion';export type CandidateFusion = 'rrf_free' | 'interleave';diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 8e72e370a3..0a25221007 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -172,7 +172,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Recoawait decideReplacement(ctx.engine, sourceId, factIntent, Number(p.replaces),{ pageSlug: slug, remote: ctx.remote !== false, excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote) });}- await assertFactNotWithdrawn(ctx.engine, sourceId, factIntent);+ await assertFactNotWithdrawn(ctx.engine, sourceId, factIntent, { excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote) });const row = await admitWrite(ctx.engine, { principal, operation: 'remember', sourceId, sourceIncarnation: source.incarnation,slug, pageId: snapshot?.page.id ?? null, requestId, clientRequestId, callerIntent,// The transport's session (MCP `_meta.session_id`) is recorded on the fact, as extract_facts records@@ -193,19 +193,36 @@ interface WithdrawalTarget { id: number; entity_slug: string | null; source_mark* 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.+ * A caller that cannot read private pages never withdraws an active copy it+ * cannot see: the refusal is then one fixed text that names no fact.*/-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+async function refuseForgetReachingOtherCopies(tx: BrainEngine, sourceId: string, fact: WithdrawalTarget, remote: boolean, excludePrivate: boolean): Promise<void> {+ const id = fact.id;+ if (fact.entity_slug === null) {+ 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')${excludePrivate ? ` AND ${privateProvenanceFilterFragment('l')}` : ''}+ ORDER BY l.id LIMIT 5`, [id, sourceId, remote]);+ if (linked.length) {+ 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}.`);+ }+ }+ if (!excludePrivate) return;+ const hidden = await tx.executeRaw(`SELECT 1 FROM facts u+ JOIN facts l ON l.source_id=u.source_id AND l.visibility=u.visibility AND l.id<>u.id+ AND (u.entity_slug IS NULL OR l.entity_slug=u.entity_slug)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(', ');+ WHERE u.id=$1 AND u.source_id=$2 AND NOT (${privateProvenanceFilterFragment('l')}) LIMIT 1`, [id, sourceId]);+ if (!hidden.length) return;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}.`);+ `claim_linked: the same claim as fact #${id} is active elsewhere in this brain. Forgetting #${id} would withdraw it there too, so nothing was forgotten.`,+ 'Keep the fact. To withdraw the claim everywhere, ask the user to forget it on the brain host.');}/** Withdrawal commits independently of filesystem ownership and request FIFO. */@@ -246,7 +263,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'foif (!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 (ctx.remote !== false && supersessionGuarded('agent_written', fact.trust_tier)) throw remoteForgetRaced(id);- if (fact.entity_slug === null) await refuseUnlinkedForgetOfLinkedClaim(tx, sourceId, id, ctx.remote !== false);+ await refuseForgetReachingOtherCopies(tx, sourceId, fact, ctx.remote !== false, excludePrivate);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.tsindex 1c43b88d3f..b223b08a8c 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -83,7 +83,8 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeif ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted entity was deleted or recreated.');if (p.expected_revision !== undefined) assertPageRevision(snapshot, engineMutationPrecondition(parseMutationPrecondition(p)));const observedRevision = snapshot?.revision ?? null;- await assertFactNotWithdrawn(engine, row.source_id, input);+ const excludePrivate = await resolveExcludePrivatePages(engine, row.authority.remote === true);+ await assertFactNotWithdrawn(engine, row.source_id, input, { excludePrivate });signal?.throwIfAborted();const embeddingConfigSql = "SELECT key,value FROM config WHERE key IN ('embedding_model','embedding_dimensions') ORDER BY key";const observedEmbeddingConfig = JSON.stringify(await engine.executeRaw(embeddingConfigSql));@@ -93,7 +94,6 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst 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 excludePrivate = await resolveExcludePrivatePages(engine, row.authority.remote === true);const replace = (e: BrainEngine, target: number, lock: boolean) =>decideReplacement(e, row.source_id, input, target, { pageSlug: row.slug, remote: row.authority.remote === true, lock, excludePrivate });const decide = async (e: BrainEngine, lock = false) => {@@ -117,7 +117,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst lexicalOld = await lexical(engine);const contestedOld = contested ? decision.candidate! : lexicalOld;const validate = async (tx: BrainEngine) => {- await assertFactNotWithdrawn(tx, row.source_id, input);+ await assertFactNotWithdrawn(tx, row.source_id, input, { excludePrivate });if (embedding && JSON.stringify(await tx.executeRaw(`${embeddingConfigSql} FOR SHARE`)) !== observedEmbeddingConfig) conflict(row);const current = await decide(tx, true);if (candidateState(current) !== candidateState(decision)) conflict(row);diff --git a/src/core/persistence/page-visibility.ts b/src/core/persistence/page-visibility.tsindex 8de8361b68..e047af07ba 100644--- a/src/core/persistence/page-visibility.ts+++ b/src/core/persistence/page-visibility.ts@@ -15,5 +15,11 @@ export async function authorizePageVisibility(engine: SqlEngine, authority: Writif (!(authority.excludePrivate ?? true) && !await excludesPrivateWrites(engine, true)) return;const rows = await engine.executeRaw(`SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2AND NOT (${privatePagesFilterFragment('pages')}) LIMIT 1`, [authority.sourceId, slug]);- if (rows.length) throw opError('page_not_found', 'Page not found.', 'This page does not exist or is not visible to this connection, so nothing was written. Write to a different slug, or confirm the slug with a search first.');+ if (rows.length) throw pageNotVisibleError();}++/** The one refusal a remote writer gets for a target it may not see; other visibility refusals reuse it verbatim. */+export function pageNotVisibleError() {+ return opError('page_not_found', 'Page not found.', 'This page does not exist or is not visible to this connection, so nothing was written. Write to a different slug, or confirm the slug with a search first.');+}+diff --git a/src/core/verbs/entity-card-identity.ts b/src/core/verbs/entity-card-identity.tsindex cec5ade431..73eb56a12a 100644--- a/src/core/verbs/entity-card-identity.ts+++ b/src/core/verbs/entity-card-identity.ts@@ -17,6 +17,8 @@*/import type { BrainEngine } from '../engine.ts';+import { pageSnapshotKey } from '../page-snapshot-batch.ts';+import type { PageSnapshot } from '../page-state/types.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { ALIAS_ORIGIN_RANK, declarationsIn, titleName, type AliasOrigin } from '../mentions/aliases.ts';import { readIdentitySiblings, SIBLING_GROUP_CAP } from '../mentions/siblings.ts';@@ -127,12 +129,13 @@ export async function readCardIdentity(engine: BrainEngine, sourceId: string,capped: siblings.capped,};}- const bodies = new Map<string, { title: string; body: string }>([[row.slug, { title: row.title ?? row.slug, body: row.compiled_truth ?? '' }]]);- if (siblings.pages.length) {- const rows = await engine.executeRaw<{ slug: string; title: string | null; compiled_truth: string | null }>(- `SELECT slug, title, compiled_truth FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`,- [sourceId, siblings.pages.map(p => p.slug)]).catch(() => []);- for (const r of rows) bodies.set(r.slug, { title: r.title ?? r.slug, body: r.compiled_truth ?? '' });+ // Snapshot reads carry the withdrawal overlay get_page shows, so a forgotten fence row is struck and the sanitizer drops it.+ const { snapshots } = await engine.readPageSnapshotsBatch(slugs.map(slug => ({ slug, sourceId })))+ .catch(() => ({ snapshots: new Map<string, PageSnapshot>() }));+ const bodies = new Map<string, { title: string; body: string }>();+ for (const slug of slugs) {+ const snapshot = snapshots.get(pageSnapshotKey(sourceId, slug));+ if (snapshot) bodies.set(slug, { title: snapshot.page.title ?? slug, body: snapshot.page.compiled_truth ?? '' });}const excerpt: IdentityExcerptLine[] = [];const omitted: string[] = [];diff --git a/test/e2e/visibility-withdrawal-postgres.test.ts b/test/e2e/visibility-withdrawal-postgres.test.tsnew file mode 100644index 0000000000..0d57273b6f--- /dev/null+++ b/test/e2e/visibility-withdrawal-postgres.test.ts@@ -0,0 +1,29 @@+/**+ * Postgres twin of test/visibility-withdrawal.test.ts: remote forget refusals and+ * entity cards respect visibility and withdrawal. One isolated database per scenario.+ */+import { afterEach, beforeEach, describe, test } from 'bun:test';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { hasDatabase } from './helpers.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { cardExcerptHidesWithdrawnRows, hiddenWithdrawalRefusesGenerically, linkedForgetKeepsHiddenCopies,+ unlinkedForgetKeepsHiddenCopies } from '../helpers/visibility-withdrawal-scenarios.ts';++const d = hasDatabase() ? describe : describe.skip;+let engine: PostgresEngine;+let close: () => Promise<void>;++d('remote forget refusals and entity cards respect visibility and withdrawal (Postgres)', () => {+ beforeEach(async () => {+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ configureGateway({ env: {} } as never);+ }, 120_000);+ afterEach(async () => { resetGateway(); await disposePersistenceConsumer(engine); await close(); });++ test('an unlinked forget keeps copies the caller cannot read, with one fixed refusal', () => unlinkedForgetKeepsHiddenCopies(engine), 60_000);+ test('a linked forget keeps copies the caller cannot read', () => linkedForgetKeepsHiddenCopies(engine), 60_000);+ test('a withdrawal backed only by unreadable rows refuses as an unreadable page does', () => hiddenWithdrawalRefusesGenerically(engine), 60_000);+ test('the card excerpt carries the withdrawal overlay', () => cardExcerptHidesWithdrawnRows(engine), 60_000);+});diff --git a/test/helpers/visibility-withdrawal-scenarios.ts b/test/helpers/visibility-withdrawal-scenarios.tsnew file mode 100644index 0000000000..375b20a1e4--- /dev/null+++ b/test/helpers/visibility-withdrawal-scenarios.ts@@ -0,0 +1,127 @@+/**+ * Engine-parametrized scenarios: remote forget refusals and entity cards respect+ * visibility and withdrawal (test/visibility-withdrawal.test.ts on PGLite,+ * test/e2e/visibility-withdrawal-postgres.test.ts on Postgres). Each scenario+ * expects a fresh brain. Zero model calls.+ */+import { expect } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { FACT_WITHDRAWN_MESSAGE } from '../../src/core/facts/withdrawal.ts';++const CLAIM = 'Acme Example renewed for three years at 40 seats.';+const ACTIVE = 'Acme Example opened a second office in Lisbon.';+const GENERIC_CLAIM_LINKED = (id: number | string) =>+ `claim_linked: the same claim as fact #${id} is active elsewhere in this brain. Forgetting #${id} would withdraw it there too, so nothing was forgotten.`;++type Caller = 'remote' | 'local' | 'unset';+async function call(engine: BrainEngine, name: string, params: Record<string, unknown>, caller: Caller = 'remote') {+ const ctx = caller === 'remote' ? { remote: true, takesHoldersAllowList: ['world'], sourceId: 'default' }+ : caller === 'local' ? { remote: false } : { sourceId: 'default' };+ const res = await dispatchToolCall(engine as never, name, params, ctx as never);+ return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text!) as Record<string, any> };+}++async function seedPages(engine: BrainEngine): Promise<void> {+ for (const [slug, title, extra] of [['crm/acme-example', 'Acme Example', ''], ['crm/hidden-co', 'Hidden Co', 'visibility: private\n'],+ ['crm/hidden-two', 'Hidden Two', 'visibility: private\n']]) {+ await dispatchToolCall(engine as never, 'put_page', { slug, content: `---\ntitle: ${title}\ntype: company\n${extra}---\n# ${title}\n\nA company.\n` }, { remote: false });+ }+}++/** A fact about a visible entity whose provenance is a private page. */+async function insertHiddenSourced(engine: BrainEngine, entity: string, sourcePage: string): Promise<number> {+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,kind,visibility,entity_slug,source_markdown_slug,source,confidence,valid_from)+ VALUES ('default',$1,'fact','world',$2,$3,'meeting notes',1,now()) RETURNING id`, [CLAIM, entity, sourcePage]);+ return Number(row!.id);+}+const active = async (engine: BrainEngine, id: number) =>+ (await engine.executeRaw<{ a: boolean }>('SELECT expired_at IS NULL AS a FROM facts WHERE id=$1', [id]))[0]!.a;+const withdrawals = async (engine: BrainEngine) => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM fact_withdrawals'))[0]!.n);++/** 1a: a remote forget of an unlinked fact never names or withdraws a linked copy on a page the caller cannot read. */+export async function unlinkedForgetKeepsHiddenCopies(engine: BrainEngine): Promise<void> {+ await seedPages(engine);+ const hidden = await call(engine, 'remember', { fact: CLAIM, entity: 'crm/hidden-co', provenance: 'meeting notes' }, 'local');+ expect(hidden.body.status).toBe('inserted');+ const unlinked = await call(engine, 'remember', { fact: CLAIM, provenance: 'call notes', infer_entity: false });+ const id = unlinked.body.id;+ const one = await call(engine, 'forget', { id: String(id) });+ expect(one.isError).toBe(true);+ expect(one.body.code).toBe('invalid_params');+ expect(one.body.message).toBe(GENERIC_CLAIM_LINKED(id));+ expect(JSON.stringify(one.body)).not.toContain('hidden-co');+ expect(JSON.stringify(one.body)).not.toContain(`#${hidden.body.id}`);+ expect(await active(engine, Number(hidden.body.id))).toBe(true);+ expect(await withdrawals(engine)).toBe(0);+ // Fail closed: a call that does not say it is local is treated as remote.+ expect((await call(engine, 'forget', { id: String(id) }, 'unset')).body.message).toBe(GENERIC_CLAIM_LINKED(id));+ // One fixed text whatever the number of hidden copies.+ await call(engine, 'remember', { fact: CLAIM, entity: 'crm/hidden-two', provenance: 'meeting notes' }, 'local');+ const two = await call(engine, 'forget', { id: String(id) });+ expect(two.body.message).toBe(one.body.message);+ expect(two.body.suggestion).toBe(one.body.suggestion);+ // A local caller keeps the detailed refusal naming the linked facts.+ const local = await call(engine, 'forget', { id: String(id) }, 'local');+ expect(local.body.message).toStartWith(`claim_linked: fact #${id} was saved without an entity, and the same claim is active as #${hidden.body.id} (crm/hidden-co)`);+ expect(await active(engine, Number(hidden.body.id))).toBe(true);+}++/** 1a: a remote forget of a linked fact never withdraws a copy about the same entity filed from a page the caller cannot read. */+export async function linkedForgetKeepsHiddenCopies(engine: BrainEngine): Promise<void> {+ await seedPages(engine);+ const hiddenId = await insertHiddenSourced(engine, 'crm/acme-example', 'crm/hidden-co');+ const visible = await call(engine, 'remember', { fact: CLAIM, entity: 'crm/acme-example', provenance: 'call notes' });+ expect(visible.body.status).toBe('inserted');+ const refused = await call(engine, 'forget', { id: String(visible.body.id) });+ expect(refused.body.message).toBe(GENERIC_CLAIM_LINKED(visible.body.id));+ expect(await active(engine, hiddenId)).toBe(true);+ expect(await active(engine, Number(visible.body.id))).toBe(true);+ const local = await call(engine, 'forget', { id: String(visible.body.id) }, 'local');+ expect(local.isError).toBe(false);+ expect(local.body.expired).toBe(true);+}++/** 1b: a withdrawal backed only by rows the caller cannot read refuses exactly as a page the caller may not see does. */+export async function hiddenWithdrawalRefusesGenerically(engine: BrainEngine): Promise<void> {+ await seedPages(engine);+ const hiddenPage = await call(engine, 'remember', { fact: CLAIM, entity: 'crm/hidden-co', provenance: 'call notes' });+ expect(hiddenPage.isError).toBe(true);+ const hiddenId = await insertHiddenSourced(engine, 'crm/acme-example', 'crm/hidden-co');+ expect((await call(engine, 'forget_fact', { id: hiddenId }, 'local')).body.expired).toBe(true);+ const remote = await call(engine, 'remember', { fact: CLAIM, entity: 'crm/acme-example', provenance: 'call notes' });+ expect(remote.isError).toBe(true);+ for (const key of ['code', 'error', 'message', 'suggestion']) expect(remote.body[key]).toEqual(hiddenPage.body[key]);+ expect(JSON.stringify(remote.body)).not.toContain('withdrawn');+ const unset = await call(engine, 'remember', { fact: CLAIM, entity: 'crm/acme-example', provenance: 'call notes' }, 'unset');+ expect(unset.body.message).toBe(hiddenPage.body.message);+ const batch = await call(engine, 'remember', { items: [{ fact: CLAIM, entity: 'crm/acme-example', provenance: 'call notes' }] });+ expect(batch.body.items[0].error.message).toBe(hiddenPage.body.message);+ // The local caller keeps fact_withdrawn.+ const local = await call(engine, 'remember', { fact: CLAIM, entity: 'crm/acme-example', provenance: 'call notes' }, 'local');+ expect(local.body.message).toBe(FACT_WITHDRAWN_MESSAGE);+ // A withdrawal the caller can see keeps fact_withdrawn for remote callers too.+ const own = await call(engine, 'remember', { fact: ACTIVE, entity: 'crm/acme-example', provenance: 'call notes' });+ expect((await call(engine, 'forget', { id: String(own.body.id) })).body.expired).toBe(true);+ expect((await call(engine, 'remember', { fact: ACTIVE, entity: 'crm/acme-example', provenance: 'call notes' })).body.message).toBe(FACT_WITHDRAWN_MESSAGE);+}++/** 2: the card's identity_excerpt carries the withdrawal overlay; a private primary page is never carded for a remote caller. */+export async function cardExcerptHidesWithdrawnRows(engine: BrainEngine): Promise<void> {+ await seedPages(engine);+ const kept = await call(engine, 'remember', { fact: ACTIVE, entity: 'crm/acme-example', provenance: 'call notes' });+ const gone = await call(engine, 'remember', { fact: CLAIM, entity: 'crm/acme-example', provenance: 'call notes' });+ expect([kept.body.status, gone.body.status]).toEqual(['inserted', 'inserted']);+ const lines = async (caller: Caller) =>+ ((await call(engine, 'entity', { name: 'crm/acme-example' }, caller)).body.card?.identity_excerpt ?? []).map((l: { line: string }) => l.line).join('\n');+ expect(await lines('remote')).toContain('renewed for three years');+ expect((await call(engine, 'forget_fact', { id: Number(gone.body.id) })).body.expired).toBe(true);+ for (const caller of ['remote', 'local'] as const) {+ const text = await lines(caller);+ expect(text).not.toContain('renewed for three years');+ expect(text).toContain('second office in Lisbon');+ }+ // Upstream filter (src/core/verbs/entity-card.ts, the privatePredicate on the page lookup): no card for a private page.+ expect((await call(engine, 'entity', { name: 'crm/hidden-co' })).body.found).toBe(false);+ expect((await call(engine, 'entity', { name: 'crm/hidden-co' }, 'local')).body.found).not.toBe(false);+}diff --git a/test/visibility-withdrawal.test.ts b/test/visibility-withdrawal.test.tsnew file mode 100644index 0000000000..a5869733ed--- /dev/null+++ b/test/visibility-withdrawal.test.ts@@ -0,0 +1,34 @@+/**+ * Remote forget refusals and entity cards respect visibility and withdrawal (PGLite).+ * Scenarios: test/helpers/visibility-withdrawal-scenarios.ts; the Postgres twin is+ * test/e2e/visibility-withdrawal-postgres.test.ts.+ */+import { afterAll, beforeAll, beforeEach, describe, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { cardExcerptHidesWithdrawnRows, hiddenWithdrawalRefusesGenerically, linkedForgetKeepsHiddenCopies,+ unlinkedForgetKeepsHiddenCopies } from './helpers/visibility-withdrawal-scenarios.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => { resetGateway(); await disposePersistenceConsumer(engine); await engine.disconnect(); });+beforeEach(async () => {+ await disposePersistenceConsumer(engine);+ await resetPgliteState(engine);+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+});++describe('remote forget refusals and entity cards respect visibility and withdrawal', () => {+ test('an unlinked forget keeps copies the caller cannot read, with one fixed refusal', () => unlinkedForgetKeepsHiddenCopies(engine));+ test('a linked forget keeps copies the caller cannot read', () => linkedForgetKeepsHiddenCopies(engine));+ test('a withdrawal backed only by unreadable rows refuses as an unreadable page does', () => hiddenWithdrawalRefusesGenerically(engine));+ test('the card excerpt carries the withdrawal overlay', () => cardExcerptHidesWithdrawnRows(engine));+});