Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GST-359 D: key forget and forget_fact to the attested person's own member page

garrytan7c636ff08a9a
diff --git a/src/core/access/actor-model.ts b/src/core/access/actor-model.ts
index 84a96bdf14..a590816fe6 100644
--- a/src/core/access/actor-model.ts
+++ b/src/core/access/actor-model.ts
@@ -11,13 +11,14 @@ export const ATTEST_SYSTEMS: readonly string[] = ['qm'];
export const DEFAULT_ATTEST_OPS: readonly string[] = ['memory_recall', 'memory_write'];
/**
* Operations no attested call may run yet: what they read or write is not keyed to the person, so one person could
- * change or see another's (a fact withdrawn by id, a conflict list across writers) or write facts and takes every
- * reader sees. GST-359 C2 keyed remember (the member page), delta cursors, write receipts and agent jobs to the person
- * and removed them. Refused at `--attest-ops`, at every call and when a stored write or job tool call is re-resolved.
+ * change or see another's (a conflict list across writers) or write facts and takes every reader sees. GST-359 C2
+ * keyed remember (the member page), delta cursors, write receipts and agent jobs to the person and removed them; D keyed
+ * forget and forget_fact (the person's own member-page facts, withdrawn there alone). Refused at `--attest-ops`, at
+ * every call and when a stored write or job tool call is re-resolved.
*/
export const ACTOR_DEFERRED_OPS: ReadonlySet<string> = new Set([
'list_write_conflicts',
- 'capture', 'extract_facts', 'forget', 'forget_fact',
+ 'capture', 'extract_facts',
'takes_add', 'takes_update', 'takes_resolve', 'takes_supersede',
]);
diff --git a/src/core/access/member-facts.ts b/src/core/access/member-facts.ts
index 43e155460f..f416ad7804 100644
--- a/src/core/access/member-facts.ts
+++ b/src/core/access/member-facts.ts
@@ -68,6 +68,25 @@ export function onMemberPageSql(alias: string): string {
return `starts_with(COALESCE(${alias}.source_markdown_slug, ''), '${MEMBER_PAGE_PREFIX}')`;
}
+/**
+ * GST-359 D: the withdrawal-ledger subject of a fact, as SQL. A fact on a member page is withdrawn for that page alone
+ * (its slug), so forgetting it never reaches another member's copy of the same claim; any other fact keeps its entity
+ * ('*' without one).
+ */
+export function factWithdrawalSubjectSql(alias: string): string {
+ return `CASE WHEN ${onMemberPageSql(alias)} THEN ${alias}.source_markdown_slug ELSE COALESCE(${alias}.entity_slug, '*') END`;
+}
+
+/** Whether withdrawal row `w` covers fact `f`, as SQL: every subject ('*'), the fact's entity, or the member page it sits on. */
+export function withdrawalCoversFactSql(w: string, f: string): string {
+ return `(${w}.subject = '*' OR ${w}.subject = COALESCE(${f}.entity_slug, '*') OR (${onMemberPageSql(f)} AND ${w}.subject = ${f}.source_markdown_slug))`;
+}
+
+/** The member page a claim is checked on for withdrawals, or null: `slug` when it is one, so a page-scoped withdrawal applies there alone. */
+export function memberWithdrawalSubject(slug: string | null | undefined): string | null {
+ return slug && slug.startsWith(MEMBER_PAGE_PREFIX) ? slug : null;
+}
+
/**
* Facts whose source page names readers or sits under a folder rule, as SQL. Derivations that write their output onto
* another page (consolidation into takes, relinking onto an entity page) skip them: the output would lose the readers.
diff --git a/src/core/ai/decide/review-lane.ts b/src/core/ai/decide/review-lane.ts
index d2cb4c23b7..dc67c81af6 100644
--- a/src/core/ai/decide/review-lane.ts
+++ b/src/core/ai/decide/review-lane.ts
@@ -30,6 +30,7 @@ import { packShape } from './pack.ts';
import { resolveSlotPolicy, type SlotPolicy } from './policy.ts';
import { writeReceipts } from './receipts.ts';
import { reviewWithdrawOn } from '../../facts/withdrawal.ts';
+import { withdrawalCoversFactSql } from '../../access/member-facts.ts';
import { flushDecideWrites, hmacRef, listCalibrations, receiptSalt, recentResolvedModels } from './store.ts';
import { DecideError, partialOf, type ChoiceAnswer, type DecideQuestion, type EvidenceItem } from './types.ts';
@@ -215,7 +216,7 @@ async function withdrawAnchor(engine: BrainEngine, row: QueueRow, cfg: DecideCon
`SELECT f.id, f.fact, f.entity_slug, f.visibility, f.embedding IS NOT NULL AS has_embedding,
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
+ AND ${withdrawalCoversFactSql('w', 'f')}) AS withdrawn
FROM facts f WHERE f.id = $1 AND f.source_id = $2`, [anchorId, row.source_id]);
if (!anchor || !anchor.withdrawn) return { skip: 'no_candidates' };
if (!anchor.has_embedding) return { skip: 'no_embedding' };
diff --git a/src/core/facts/proposal-review.ts b/src/core/facts/proposal-review.ts
index 3a34c905ca..9f67107aba 100644
--- a/src/core/facts/proposal-review.ts
+++ b/src/core/facts/proposal-review.ts
@@ -16,6 +16,7 @@
import { createHash } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import { loadConfig } from '../config.ts';
+import { withdrawalCoversFactSql } from '../access/member-facts.ts';
import {
getReviewProposal, reviewAcceptHandler, transitionReviewProposal, type ReviewProposalRow,
} from '../ai/decide/review-lane.ts';
@@ -39,7 +40,7 @@ async function staleReason(engine: BrainEngine, p: ReviewProposalRow): Promise<s
const [anchor] = await engine.executeRaw<{ withdrawn: boolean }>(
`SELECT 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
+ AND ${withdrawalCoversFactSql('w', 'f')}) AS withdrawn
FROM facts f WHERE f.id = $1 AND f.source_id = $2`, [Number(p.a_ref), p.source_id]);
if (!anchor?.withdrawn) return 'the withdrawn claim is no longer withdrawn';
const [candidate] = await engine.executeRaw<{ active: boolean; text_hash: string }>(
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index 6520977d2d..36fd992c79 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -10,7 +10,7 @@ import { readSupersessionThreshold } from './supersession-threshold.ts';
import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';
import { pageNotVisibleError } from '../persistence/page-visibility.ts';
import { slugUnderBoundPrefixes } from '../ops/context.ts';
-import { onMemberPageSql } from '../access/member-facts.ts';
+import { memberWithdrawalSubject, onMemberPageSql, withdrawalCoversFactSql } from '../access/member-facts.ts';
export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };
export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded'; candidate: FactCandidate | null; }
@@ -42,7 +42,7 @@ export async function prepareFactEmbedding(fact: string, signal?: AbortSignal, d
*/
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 await factWithdrawnRefusal(engine, sourceId, input, opts);
+ if (await isFactWithdrawn(engine, sourceId, input.visibility, input.fact, input.entity_slug, memberWithdrawalSubject(input.page_slug))) throw await factWithdrawnRefusal(engine, sourceId, input, opts);
}
/**
@@ -51,27 +51,29 @@ export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: stri
* (or that no row backs). It covers the exact normalized claim only.
*/
export async function factWithdrawnRefusal(engine: BrainEngine, sourceId: string, input: SingleFactIntent, opts: { excludePrivate?: boolean } = {}): Promise<OperationError> {
+ // GST-359 D: a member writing to its own member page sees that page's withdrawn rows.
+ const seen = (param: number) => `(${privateProvenanceFilterFragment('f')} OR COALESCE(f.source_markdown_slug = $${param}::text, false))`;
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
+ COALESCE(bool_or(${seen(5)}), false) AS visible,
+ COALESCE(bool_or(NOT ${seen(5)}), 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,'*'))
+ AND ${withdrawalCoversFactSql('w', 'f')}
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]);
+ AND gbrain_fact_fingerprint(f.fact)=gbrain_fact_fingerprint($3) AND (w.subject='*' OR w.subject=$4::text OR w.subject=$5::text)`,
+ [sourceId, input.visibility, input.fact, input.entity_slug, memberWithdrawalSubject(input.page_slug)]);
if (backing?.hidden && !backing.visible) return pageNotVisibleError();
}
const [row] = await engine.executeRaw<{ subject: string; withdrawn_at: string; visibility: 'world' | 'private' }>(`SELECT w.subject,w.visibility,w.withdrawn_at::text AS withdrawn_at
FROM fact_withdrawals w LEFT JOIN facts f ON f.source_id=w.source_id AND f.visibility=w.visibility AND f.expired_at IS NOT NULL
- 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,'*'))
+ AND w.fact_hash IN (gbrain_fact_fingerprint(f.fact),gbrain_fact_fingerprint_v1(f.fact)) AND ${withdrawalCoversFactSql('w', 'f')}
WHERE w.source_id=$1 AND w.visibility=$2 AND w.fact_hash IN (gbrain_fact_fingerprint($3),gbrain_fact_fingerprint_v1($3))
- AND (w.subject='*' OR w.subject=$4::text)
+ AND (w.subject='*' OR w.subject=$4::text OR w.subject=$6::text)
GROUP BY w.subject,w.visibility,w.withdrawn_at
- HAVING $5::boolean=false OR COALESCE(bool_or(${privateProvenanceFilterFragment('f')}), false) OR NOT COALESCE(bool_or(f.id IS NOT NULL), false)
+ HAVING $5::boolean=false OR COALESCE(bool_or(${seen(6)}), false) OR NOT COALESCE(bool_or(f.id IS NOT NULL), false)
ORDER BY (w.subject<>'*') DESC, w.withdrawn_at DESC LIMIT 1`,
- [sourceId, input.visibility, input.fact, input.entity_slug, opts.excludePrivate === true]);
+ [sourceId, input.visibility, input.fact, input.entity_slug, opts.excludePrivate === true, memberWithdrawalSubject(input.page_slug)]);
const error = verbError('invalid_params', FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION);
if (row) error.withdrawn = { at: new Date(row.withdrawn_at).toISOString(), subject: row.subject === '*' ? 'all_entities' : row.subject, visibility: row.visibility };
return error;
@@ -174,7 +176,7 @@ export async function decideReplacement(engine: BrainEngine, sourceId: string, i
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
+ AND ${withdrawalCoversFactSql('w', 'f')}) 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();
// #5913 [R2]: a slug-bound writer learns nothing about a fact outside its prefixes; the answer is the missing-id one.
diff --git a/src/core/facts/withdrawal-discovery.ts b/src/core/facts/withdrawal-discovery.ts
index 71efaaefc6..8cb5209722 100644
--- a/src/core/facts/withdrawal-discovery.ts
+++ b/src/core/facts/withdrawal-discovery.ts
@@ -7,6 +7,7 @@ import { fenceTooLargeError, readStoredFence } from '../page-body/read-range.ts'
import { FENCE_MAX_BYTES } from '../page-body/limits.ts';
import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';
import type { BodyRegion } from '../page-body/types.ts';
+import { onMemberPageSql } from '../access/member-facts.ts';
export const WITHDRAWAL_LIMITS = { targets: 256, targetBytes: 1024 * 1024, scanMs: 10_000, batch: 128, matchRows: 16_384, matchBytes: 8 * 1024 * 1024 } as const;
export interface WithdrawalTarget { slug: string; page_id: number; revision: string }
@@ -129,7 +130,7 @@ export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: s
FROM jsonb_to_recordset($2::text::jsonb) k(visibility text,fact_hash text,subject text,norm text)
JOIN facts f ON f.source_id=$1 AND f.visibility=k.visibility
AND gbrain_fact_fingerprint(f.fact)=COALESCE(encode(sha256(convert_to(k.norm,'UTF8')),'hex'),k.fact_hash)
- AND (k.subject='*' OR f.entity_slug=k.subject)
+ AND (k.subject='*' OR f.entity_slug=k.subject OR (${onMemberPageSql('f')} AND f.source_markdown_slug=k.subject))
JOIN pages p ON p.source_id=f.source_id AND p.slug=COALESCE(f.source_markdown_slug,f.entity_slug)`, [sourceId, keys]);
for (const row of provenance) affected.add(row.id);
if (affected.size > WITHDRAWAL_LIMITS.targets) await refuseAffected(engine, sourceId, affected);
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index 075e8378fc..c138bf5d1b 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -9,6 +9,7 @@ import { privateProvenanceFilterFragment } from '../search/private-visibility.ts
import { coverageActive, noteBelief, readLedgerSource, withBeliefBatch } from '../belief/ledger.ts';
import { createPageVersion } from '../page-state/versions.ts';
import { validateSlug } from '../utils.ts';
+import { factWithdrawalSubjectSql, onMemberPageSql } from '../access/member-facts.ts';
export interface WithdrawalCommit {
withdrawn: boolean;
@@ -51,15 +52,18 @@ export function reviewWithdrawOn(raw: string | null | undefined): boolean {
export async function recordFactWithdrawal(
engine: BrainEngine, id: number, sourceId: string, worldOnly = false,
- opts: { requestId?: string; publicationId?: string; semanticReview?: boolean; excludePrivate?: boolean; beliefReport?: { appended: number } } = {},
+ opts: { requestId?: string; publicationId?: string; semanticReview?: boolean; excludePrivate?: boolean; beliefReport?: { appended: number }; memberPage?: string } = {},
): Promise<WithdrawalCommit> {
+ // GST-359 D: an attested person's own member-page fact (memberPage) is admitted besides world facts; the caller checked it.
+ const admit = `AND ($3::boolean=false OR visibility='world' OR (visibility='private' AND source_markdown_slug=$4::text))${opts.excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`;
+ const pageScoped = `(${onMemberPageSql('facts')} AND source_markdown_slug=$4)`;
return engine.transaction(async tx => {
// A managed caller takes this EXCLUSIVE source lock before authority,
// counters and request rows. Repeating an already-held lock is safe.
await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);
const visible = await tx.executeRaw<{ visibility: 'private' | 'world'; fact: string; fact_hash: string; subject: string }>(
- `SELECT visibility,fact,gbrain_fact_fingerprint(fact) AS fact_hash,COALESCE(entity_slug,'*') AS subject FROM facts WHERE id=$1 AND source_id=$2
- AND ($3::boolean=false OR visibility='world')${opts.excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`, [id, sourceId, worldOnly]);
+ `SELECT visibility,fact,gbrain_fact_fingerprint(fact) AS fact_hash,${factWithdrawalSubjectSql('facts')} AS subject FROM facts WHERE id=$1 AND source_id=$2
+ ${admit}`, [id, sourceId, worldOnly, opts.memberPage ?? null]);
if (!visible.length) return { withdrawn: false, pages: [] };
const { visibility, fact, fact_hash, subject } = visible[0];
// Discovery is keyed on the claim and its subject: a subject-scoped
@@ -71,14 +75,14 @@ export async function recordFactWithdrawal(
const affected = existing.length ? [] : await discoverWithdrawalTargets(tx, sourceId, [{ visibility, fact_hash, subject, claim: fact }]).catch(withdrawalDiscoveryFailure);
// The belief ledger's streams of the facts this withdrawal expires (fence pages and database-only subjects), locked with the pages.
const streams = (await tx.executeRaw<{ slug: string }>(`SELECT DISTINCT COALESCE(source_markdown_slug, entity_slug) AS slug FROM facts
- WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4) AND expired_at IS NULL
+ WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4 OR ${pageScoped}) AND expired_at IS NULL
AND COALESCE(source_markdown_slug, entity_slug) IS NOT NULL`, [sourceId, visibility, fact_hash, subject]))
.map(r => r.slug).filter(slug => { try { validateSlug(slug); return true; } catch { return false; } });
const slugs = [...new Set([...affected.map(page => page.slug), ...streams])];
await tx.lockPageKeys(slugs.map(slug => ({ sourceId, slug })));
const rows = await tx.executeRaw<{ visibility: string; fact: string; subject: string }>(
- `SELECT visibility,fact,COALESCE(entity_slug,'*') AS subject FROM facts WHERE id=$1 AND source_id=$2
- AND ($3::boolean=false OR visibility='world')${opts.excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''} FOR UPDATE`, [id, sourceId, worldOnly]);
+ `SELECT visibility,fact,${factWithdrawalSubjectSql('facts')} AS subject FROM facts WHERE id=$1 AND source_id=$2
+ ${admit} FOR UPDATE`, [id, sourceId, worldOnly, opts.memberPage ?? null]);
if (!rows.length) return { withdrawn: false, pages: [] };
const row = rows[0];
const ledger = affected.length ? await readLedgerSource(tx, sourceId) : null;
@@ -98,7 +102,7 @@ export async function recordFactWithdrawal(
VALUES ($1,$2,$4,gbrain_fact_fingerprint($3)) ON CONFLICT DO NOTHING RETURNING fact_hash`, [sourceId,row.visibility,row.fact,row.subject]);
const expired = await tx.executeRaw<{ id: number }>(`UPDATE facts SET expired_at=now(),valid_until=LEAST(COALESCE(valid_until,now()),now())
WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3)
- AND ($4='*' OR entity_slug=$4) AND expired_at IS NULL RETURNING id`, [sourceId,row.visibility,row.fact,row.subject]);
+ AND ($4='*' OR entity_slug=$4 OR ${pageScoped}) AND expired_at IS NULL RETURNING id`, [sourceId,row.visibility,row.fact,row.subject]);
noteBelief({ kind: 'withdrawn', factIds: expired.map(r => Number(r.id)) });
if (!inserted.length) return { withdrawn: false, pages: [] };
// Overnight semantic review (decide review lane): queued with the ledger row so a late commit is never skipped.
@@ -216,13 +220,14 @@ export async function assertPreparedFactWithdrawals(engine: BrainEngine, sourceI
/** Explicit remember is not an implicit restore operation for that entity. A purged claim counts as withdrawn for every writer. */
export async function isFactWithdrawn(
- engine: BrainEngine, sourceId: string, visibility: string, claim: string, entitySlug: string | null,
+ engine: BrainEngine, sourceId: string, visibility: string, claim: string, entitySlug: string | null, memberPage: string | null = null,
): Promise<boolean> {
+ // GST-359 D: `memberPage` (a claim saved on a member page) also matches that page's own withdrawals.
const rows = await engine.executeRaw(`SELECT 1 FROM fact_withdrawals
WHERE source_id=$1 AND visibility=$2 AND fact_hash IN (gbrain_fact_fingerprint($3),gbrain_fact_fingerprint_v1($3))
- AND (subject = '*' OR subject = $4::text)
+ AND (subject = '*' OR subject = $4::text OR subject = $5::text)
UNION ALL SELECT 1 FROM fact_purges WHERE source_id=$1 AND visibility=$2 AND fact_hash=gbrain_fact_fingerprint($3)
- AND (subject = '*' OR subject = $4::text) LIMIT 1`, [sourceId,visibility,claim,entitySlug]);
+ AND (subject = '*' OR subject = $4::text) LIMIT 1`, [sourceId,visibility,claim,entitySlug,memberPage]);
return rows.length > 0;
}
diff --git a/src/core/persistence/effect-targets.ts b/src/core/persistence/effect-targets.ts
index aae9002184..90b44a2c92 100644
--- a/src/core/persistence/effect-targets.ts
+++ b/src/core/persistence/effect-targets.ts
@@ -5,6 +5,7 @@ import { discoverWithdrawalTargets, withdrawalDiscoveryFailure, WITHDRAWAL_LIMIT
import type { PersistenceEffect } from './effect-model.ts';
import { guardEffectSource } from './effect-recovery.ts';
import { declarePersistenceProtocol } from './protocol.ts';
+import { withdrawalCoversFactSql } from '../access/member-facts.ts';
export function targetedWithdrawalEffect(effect: PersistenceEffect): boolean {
if (effect.data.version === undefined) return false;
@@ -37,7 +38,7 @@ export async function upgradeWithdrawalEffect(engine: BrainEngine, effect: Persi
FROM persistence_requests r JOIN facts f ON r.intent->>'id' ~ '^[0-9]+$' AND f.id=(r.intent->>'id')::bigint AND f.source_id=$1
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,'*'))
+ AND ${withdrawalCoversFactSql('w', 'f')}
WHERE r.id=$2::uuid ORDER BY w.visibility,w.fact_hash,w.subject`, [effect.source_id, effect.request_id]);
const claims = requested.length ? requested : await tx.executeRaw<WithdrawalClaim>(`SELECT visibility,fact_hash,subject FROM fact_withdrawals
WHERE source_id=$1 ORDER BY visibility,fact_hash,subject LIMIT $2`, [effect.source_id, WITHDRAWAL_LIMITS.targets + 1]);
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index 1a8d4a7875..ec8f063da3 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -28,9 +28,9 @@ import { requestAttribution } from './attribution.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { prepareMemoryMutation } from './memory-prepare.ts';
import { retryWriteAdmission } from './admission-retry.ts';
-import { privateProvenanceFilterFragment, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';
+import { currentCallerAccess, privateProvenanceFilterFragment, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';
import { markBeliefCommits } from '../belief/append.ts';
-import { memberFactPage } from '../access/member-facts.ts';
+import { memberFactAdmitSql, memberFactPage, memberPageSlug } from '../access/member-facts.ts';
export { prepareMemoryMutation } from './memory-prepare.ts';
/** Only semantic appends without an explicit caller revision can be recomputed. */
@@ -330,6 +330,10 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
if (!Number.isSafeInteger(id) || id <= 0) throw verbError(operation === 'forget' ? 'not_found' : 'fact_not_found',
`No fact with id "${rawId}".`, 'Pass the fact id returned by remember or recall.');
const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
+ // GST-359 D: an attested person withdraws only facts on their own member page, and only there (the page is the
+ // withdrawal's subject), so another member's copy of the same claim stays active and rememberable.
+ const actor = ctx.remote !== false ? currentCallerAccess().actor : undefined;
+ const ownPage = actor ? memberPageSlug(actor.member) : null;
// #5575 I3: a remote caller cannot forget a fact more trusted than its own writes; the owner is asked instead.
if (ctx.remote !== false && Number.isSafeInteger(id) && id > 0) await guardRemoteForget(ctx.engine, { sourceId, factId: id, principal, reason, excludePrivate });
// Retry the whole withdrawal, so source/principal guards and the connection
@@ -354,11 +358,13 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
return prior;
}
const [fact] = await tx.executeRaw<WithdrawalTarget>(`SELECT id,entity_slug,source_markdown_slug,expired_at,trust_tier FROM facts
- WHERE id=$1 AND source_id=$2 AND ($3::boolean=false OR visibility='world')${excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''} FOR UPDATE`, [id, sourceId, ctx.remote !== false]);
+ WHERE id=$1 AND source_id=$2 AND ${ownPage ? memberFactAdmitSql('facts')
+ : `($3::boolean=false OR visibility='world')${excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`} FOR UPDATE`,
+ ownPage ? [id, sourceId] : [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 (ctx.remote !== false && supersessionGuarded('agent_written', fact.trust_tier)) throw remoteForgetRaced(id);
- await refuseForgetReachingOtherCopies(tx, sourceId, fact, ctx.remote !== false, excludePrivate);
+ if (!ownPage) 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);
@@ -368,7 +374,9 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
return withCoordinatedWrite(tx, [sourceId], async () => {
// Even an expired legacy fact acquires a ledger so a stale import cannot
// reactivate it. Internal affected-page identities never enter the receipt.
- withdrawn = (await recordFactWithdrawal(tx, id, sourceId, ctx.remote !== false, { requestId: row.id, semanticReview, excludePrivate, beliefReport })).pages;
+ withdrawn = (await recordFactWithdrawal(tx, id, sourceId, ctx.remote !== false, ownPage
+ ? { requestId: row.id, semanticReview: false, memberPage: ownPage, beliefReport }
+ : { requestId: row.id, semanticReview, excludePrivate, beliefReport })).pages;
if (reason) await tx.executeRaw(`UPDATE facts SET context=concat_ws(' | ',NULLIF(context,''),$3::text)
WHERE id=$1 AND source_id=$2`, [id, sourceId, `forgotten: ${reason}`]);
if (operation === 'forget_fact' && fact.expired_at !== null) {
diff --git a/test/access-qm-actor.test.ts b/test/access-qm-actor.test.ts
index 34c0b634d8..dd58088d71 100644
--- a/test/access-qm-actor.test.ts
+++ b/test/access-qm-actor.test.ts
@@ -401,11 +401,12 @@ for (const kind of testBackends()) {
expect(() => parseAttestOps('get_page,' + op, lookup)).toThrow(/cannot run yet/);
await expect(bindCredential(engine, { kind: 'client', id: clients.qm!.id }, { attestActor: 'qm', attestOps: ['get_page', op] })).rejects.toMatchObject({ code: 'invalid_params' });
}
- // GST-359 C2 keyed remember, delta, the write receipts and agent jobs to the person (test/access-member-facts.test.ts).
- for (const op of ['capture', 'extract_facts', 'forget', 'forget_fact', 'takes_add', 'list_write_conflicts']) {
+ // GST-359 C2 keyed remember, delta, the write receipts and agent jobs to the person (test/access-member-facts.test.ts);
+ // D keyed forget and forget_fact to the person's own member page (test/qm-memory-tools.test.ts).
+ for (const op of ['capture', 'extract_facts', 'takes_add', 'list_write_conflicts']) {
expect(ACTOR_DEFERRED_OPS.has(op)).toBe(true);
}
- for (const op of ['get_agent_job', 'submit_agent', 'get_write_request', 'list_write_requests', 'cancel_write_request', 'delta', 'remember']) {
+ for (const op of ['get_agent_job', 'submit_agent', 'get_write_request', 'list_write_requests', 'cancel_write_request', 'delta', 'remember', 'forget', 'forget_fact']) {
expect(ACTOR_DEFERRED_OPS.has(op)).toBe(false);
}
const { clientId, clientSecret } = await provider().registerClientManual('qm-jobs-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);
@@ -415,7 +416,7 @@ for (const kind of testBackends()) {
const bearer = (await provider().exchangeClientCredentials(clientId, clientSecret!)).access_token;
const deferredCalls: Array<[string, Record<string, unknown>]> = [
['list_write_conflicts', {}], ['capture', { content: 'note' }], ['extract_facts', { text: 'x' }],
- ['forget_fact', { id: '1' }], ['takes_add', { page_slug: PAGES.alice.slug, claim: 'x' }],
+ ['takes_add', { page_slug: PAGES.alice.slug, claim: 'x' }],
];
for (const [op, params] of deferredCalls) {
const out = await refused(call(bearer, op, params, { actor: ALICE_ID }), 'actor_not_attested', 'op_not_attested');
diff --git a/test/qm-memory-tools.test.ts b/test/qm-memory-tools.test.ts
index 8e27ce30bf..27ab087e63 100644
--- a/test/qm-memory-tools.test.ts
+++ b/test/qm-memory-tools.test.ts
@@ -96,7 +96,7 @@ const ALICE_ID = 'U0ALICE';
const BOB_ID = 'oidc:3f2a:bob-example';
const CAROL_ID = '[email protected]';
const ACME = 'companies/acme-example';
-const ATTEST_OPS = ['get_write_request', 'memory_recall', 'memory_write'];
+const ATTEST_OPS = ['forget', 'forget_fact', 'get_write_request', 'memory_recall', 'memory_write', 'remember'];
for (const kind of testBackends()) {
describe('memory_recall and memory_write (' + kind + ', repo-less)', () => {
@@ -122,7 +122,7 @@ for (const kind of testBackends()) {
return { out, isError: out.isError === true, text, json, structured: out.structuredContent as Record<string, any> | undefined,
all: text + JSON.stringify(out._meta ?? {}) + JSON.stringify(out.structuredContent ?? {}) };
}
- const write = (as: Who, facts: Array<Record<string, unknown>>, key: string = randomUUID(), extra: { writeWaitMs?: number } = {}) =>
+ const write = (as: Who, facts: Array<Record<string, unknown>>, key: string = randomUUID(), extra: { writeWaitMs?: number } = { writeWaitMs: 30_000 }) =>
call(as, 'memory_write', { facts, idempotency_key: key }, extra);
const recall = (as: Who, query: string, args: Record<string, unknown> = {}) => call(as, 'memory_recall', { query, ...args });
const factRows = (needle: string) => engine.executeRaw<Record<string, any>>(
@@ -324,6 +324,40 @@ for (const kind of testBackends()) {
expect(line).toMatch(/^- Harbor rules keep the ledger canaryfence \(\d{4}-\d{2}-\d{2}; fact\)$/);
}, 60_000);
+ test('forget and forget_fact withdraw the person\'s own member-page fact there alone, never another member\'s or a world fact', async () => {
+ const claim = 'Shared standup moved to Thursdays canaryforget';
+ const a = await write(alice, [{ fact: claim, provenance: 'turn 11' }]);
+ const b = await write(bob, [{ fact: claim, provenance: 'turn 11' }]);
+ const [aliceId] = a.structured!.fact_ids;
+ const [bobId] = b.structured!.fact_ids;
+ const [worldRow] = await factRows('canaryworld');
+ const active = async (id: string) => (await engine.executeRaw<{ expired_at: unknown }>('SELECT expired_at FROM facts WHERE id = $1', [Number(id)]))[0]?.expired_at === null;
+ for (const [op, id] of [['forget', bobId], ['forget_fact', bobId], ['forget', String(worldRow!.id)], ['forget_fact', String(worldRow!.id)]] as const) {
+ const out = await call(alice, op, { id: op === 'forget' ? id : Number(id) });
+ expect(out.isError).toBe(true);
+ expect(['not_found', 'fact_not_found']).toContain(out.json.code);
+ }
+ expect(await active(bobId!)).toBe(true);
+ expect(await active(String(worldRow!.id))).toBe(true);
+ const forgot = await call(alice, 'forget', { id: aliceId, reason: 'moved back' });
+ expect(forgot.isError).toBe(false);
+ expect(await active(aliceId!)).toBe(false);
+ expect(await active(bobId!)).toBe(true);
+ const [ledger] = await engine.executeRaw<{ subject: string }>('SELECT subject FROM fact_withdrawals WHERE source_id = $1 AND fact_hash = gbrain_fact_fingerprint($2)', [SRC, claim]);
+ expect(ledger!.subject).toBe('memory/members/alice-example');
+ expect((await recall(alice, 'standup Thursdays')).all).not.toContain('canaryforget');
+ expect((await recall(bob, 'standup Thursdays')).text).toContain(claim);
+ const again = await write(alice, [{ fact: claim, provenance: 'turn 12' }]);
+ expect(again.isError).toBe(true);
+ expect(again.text).toContain('fact_withdrawn');
+ const carolCopy = await write(carol, [{ fact: claim, provenance: 'turn 12' }]);
+ expect(carolCopy.structured!.status).toBe('committed');
+ const second = await write(alice, [{ fact: 'Alice drafts the harbor memo canaryforgetfact', provenance: 'turn 13' }]);
+ const viaFactOp = await call(alice, 'forget_fact', { id: Number(second.structured!.fact_ids[0]) });
+ expect(viaFactOp.isError).toBe(false);
+ expect(await active(second.structured!.fact_ids[0])).toBe(false);
+ }, 120_000);
+
test('a keyless brain ranks by keyword and makes no embedding call', async () => {
let embedCalls = 0;
try {