Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

WIP G4 wave 2: forget through the coordinator, companion pages, import-derived ledger

garrytan412ca9bde74a
diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.ts
index 0c48d0f9c5..5e09128257 100644
--- a/src/core/belief/ledger.ts
+++ b/src/core/belief/ledger.ts
@@ -537,5 +537,6 @@ export function publicationBeliefOptions(row: { id: string; source_id: string; s
publicationId: row.id, op: row.operation, remote: row.authority.remote !== false,
...(row.authority.remote === false && (allowlistDropped || OWNER_EDIT_OPERATIONS.has(row.operation) && row.intent?.kind == null) ? { ownerEdit: true } : {}),
...(row.operation === 'revert_version' ? { pageEventType: 'page.reverted' as const } : {}),
+ ...(row.operation === 'forget' || row.operation === 'forget_fact' ? { pageEventType: 'page.view_changed' as const } : {}),
...(row.operation === 'delete_page' && row.intent?.retention === true ? { hardDeleteEvent: 'page.expired' as const } : {}), ...(report ? { report } : {}) };
}
diff --git a/src/core/facts/fence-fact-append.ts b/src/core/facts/fence-fact-append.ts
index f5a6bdabed..e9d892f058 100644
--- a/src/core/facts/fence-fact-append.ts
+++ b/src/core/facts/fence-fact-append.ts
@@ -29,12 +29,12 @@ import type { PageSnapshot } from '../page-state/types.ts';
import type { Page } from '../types.ts';
import { opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
-import { factsFenceSection, fenceCellReadBackProblem, formatFenceDate, parseFactsFence, strikeFactRowInPage, upsertFactRow } from '../facts-fence.ts';
+import { factsFenceSection, fenceCellReadBackProblem, formatFenceDate, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, strikeFactRowInPage, upsertFactRow } from '../facts-fence.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { pageBodyOverCeilingError } from '../page-body/page-shape.ts';
import { materializedPage, segmentedOverCeiling } from '../persistence/segmented-apply.ts';
import { preparePageMutation } from '../persistence/page-prepare.ts';
-import type { PreparedMutation } from '../persistence/coordinator.ts';
+import type { CompanionPage, PreparedMutation } from '../persistence/coordinator.ts';
import type { WriteRequest } from '../persistence/model.ts';
import { normalizeTargetFences } from '../fence-repair/import-step.ts';
import { refuseUnparsedRewrite } from '../fence-repair/refusal.ts';
@@ -148,3 +148,30 @@ export async function prepareFenceFactAppend(engine: BrainEngine, row: WriteRequ
return { id: await insert(tx, rowNum, fact), pageReceipt };
} };
}
+
+
+/**
+ * GBRA-190 G4: the fence row `rowNum` of another page, struck in the same publication as the request's own page (a
+ * CompanionPage): remember linking a fact saved without an entity strikes its memory/unattributed row, noting the
+ * entity it now lives under, so the file never keeps a row whose facts row the link retired. Null when that page or
+ * row is gone (nothing in a file to strike). The page write is prepared unprojected, as remember's own is.
+ */
+export async function prepareFenceRowRetirement(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, slug: string,
+ retire: { rowNum: number; note: string; validUntil: Date | null }, signal?: AbortSignal): Promise<CompanionPage | null> {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: row.source_id, includeDeleted: true });
+ if (!snapshot || snapshot.page.deleted_at) return null;
+ if (segmentedOverCeiling(snapshot.page)) throw pageBodyOverCeilingError(snapshot.page, `${row.operation} facts fence write`);
+ const base = await materializedPage(engine, snapshot.page);
+ const fenced = { compiled_truth: base.compiled_truth, timeline: base.timeline ?? '' };
+ const section = (['compiled_truth', 'timeline'] as const).find(key => parseFactsFence(fenced[key]).facts.some(f => f.rowNum === retire.rowNum && f.active));
+ if (!section) return null;
+ const until = retire.validUntil ? formatFenceDate(retire.validUntil) : undefined;
+ const rows = parseFactsFence(fenced[section]).facts.map(f => f.rowNum === retire.rowNum
+ ? { ...f, active: false, context: [retire.note, f.context?.trim()].filter(Boolean).join(' | '), ...(until ? { validUntil: until } : {}) } : f);
+ const content = serializePageToMarkdown({ ...base, ...fenced, [section]: replaceOrInsertFactsFence(fenced[section], renderFactsTable(rows)) }, snapshot.tags);
+ const prepared = await preparePageMutation(engine, { ...row, slug, page_id: snapshot.page.id,
+ intent: { ...row.intent, content, expected_revision: snapshot.revision, force: false } }, config, undefined, signal, { unprojected: true });
+ return { slug, pageId: snapshot.page.id, observedRevision: prepared.observedRevision, ...(prepared.file ? { file: prepared.file } : {}),
+ ...(prepared.validate ? { validate: (tx: BrainEngine) => prepared.validate!(tx) } : {}), apply: (tx, preimage) => prepared.apply(tx, preimage) };
+}
+
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index a532991e8c..039c3ab254 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -10,6 +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 { UNATTRIBUTED_MEMORY_SLUG } from './extract-from-fence.ts';
export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };
export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded'; candidate: FactCandidate | null; }
@@ -193,7 +194,9 @@ export async function decideReplacement(engine: BrainEngine, sourceId: string, i
throw verbError('invalid_params', `replaces_entity_mismatch: fact #${targetId} is about ${target.entity_slug ?? 'no entity'}, not ${input.entity_slug ?? 'no entity'}.`,
'Pass the same entity as the fact being replaced, or forget the old fact and remember the new one separately.');
}
- if (candidate.source_markdown_slug && candidate.source_markdown_slug !== opts.pageSlug) {
+ // GBRA-190 G4: a fact saved without an entity is a row of memory/unattributed; linking it strikes that row in the same write.
+ const linking = target.entity_slug == null && input.entity_slug != null && candidate.source_markdown_slug === UNATTRIBUTED_MEMORY_SLUG;
+ if (candidate.source_markdown_slug && candidate.source_markdown_slug !== opts.pageSlug && !linking) {
const derived = String(candidate.source ?? '').startsWith('cli:extract-conversation-facts');
throw verbError('invalid_params', `replaces_cross_page: fact #${targetId} lives on page ${candidate.source_markdown_slug}${derived ? ', extracted from that conversation page' : ''}.`,
derived ? replacesDerivedSuggestion(sourceId, candidate.source_markdown_slug) : 'Forget the old fact, then remember the new one.');
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index 075e8378fc..a4a29b9b0b 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 { UNATTRIBUTED_MEMORY_SLUG } from './extract-from-fence.ts';
export interface WithdrawalCommit {
withdrawn: boolean;
@@ -49,33 +50,58 @@ export function reviewWithdrawOn(raw: string | null | undefined): boolean {
return v === '' || ['true', 'on', '1', 'yes'].includes(v);
}
+/**
+ * What withdrawing fact `id` changes: its claim (visibility, fingerprint, subject), whether a withdrawal already
+ * covers it, the pages discovery finds carrying the claim for that subject (`affected`), and every page key the
+ * withdrawal holds (`slugs`: those pages and the belief streams of the facts it expires). Null when the fact is not
+ * visible to the caller. Read-only; forget's preparation (persistence/forget-prepare.ts) and the withdrawal share it.
+ */
+export async function planFactWithdrawal(engine: BrainEngine, id: number, sourceId: string, worldOnly: boolean, excludePrivate?: boolean) {
+ const visible = await engine.executeRaw<{ visibility: 'private' | 'world'; fact: string; fact_hash: string; subject: string; expired: boolean }>(
+ `SELECT visibility,fact,gbrain_fact_fingerprint(fact) AS fact_hash,COALESCE(entity_slug,'*') AS subject,expired_at IS NOT NULL AS expired FROM facts WHERE id=$1 AND source_id=$2
+ AND ($3::boolean=false OR visibility='world')${excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`, [id, sourceId, worldOnly]);
+ if (!visible.length) return null;
+ const { visibility, fact, fact_hash, subject, expired } = visible[0];
+ // Discovery is keyed on the claim and its subject: a subject-scoped
+ // withdrawal changes only that entity's pages and its facts' provenance.
+ // Only an existing withdrawal covering this subject makes it a no-op.
+ const existing = (await engine.executeRaw(`SELECT 1 FROM fact_withdrawals
+ WHERE source_id=$1 AND visibility=$2 AND fact_hash IN ($3,gbrain_fact_fingerprint_v1($5)) AND (subject='*' OR subject=$4) LIMIT 1`,
+ [sourceId, visibility, fact_hash, subject, fact])).length > 0;
+ const affected = existing ? [] : await discoverWithdrawalTargets(engine, 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 engine.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
+ 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])].sort();
+ return { visibility, fact, fact_hash, subject, expired: expired === true, existing, affected, slugs };
+}
+
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 };
+ /**
+ * GBRA-190 G4: the withdrawal is the database half of a coordinated publication (forget-prepare.ts) whose page
+ * files the coordinator already published and committed, under page keys and a belief batch the publication holds.
+ * Nothing is locked, batched or queued here; the ledger row carries the timestamp the files were struck with, and
+ * a discovery that no longer finds exactly `expectedSlugs` refuses `revision_conflict` so the request prepares again.
+ */
+ publication?: { withdrawnAt: string; expectedSlugs: readonly string[] } } = {},
): Promise<WithdrawalCommit> {
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]);
- 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
- // withdrawal changes only that entity's pages and its facts' provenance.
- // Only an existing withdrawal covering this subject makes it a no-op.
- const existing = await tx.executeRaw(`SELECT 1 FROM fact_withdrawals
- WHERE source_id=$1 AND visibility=$2 AND fact_hash IN ($3,gbrain_fact_fingerprint_v1($5)) AND (subject='*' OR subject=$4) LIMIT 1`,
- [sourceId, visibility, fact_hash, subject, fact]);
- 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
- 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 })));
+ if (!opts.publication) await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);
+ const plan = await planFactWithdrawal(tx, id, sourceId, worldOnly, opts.excludePrivate);
+ if (!plan) return { withdrawn: false, pages: [] };
+ const { affected, slugs } = plan;
+ if (opts.publication) {
+ if (JSON.stringify(slugs) !== JSON.stringify([...opts.publication.expectedSlugs].sort())) {
+ throw new OperationError('revision_conflict', 'The pages this withdrawal changes moved during preparation.',
+ 'Read the fact again and submit the forget with a new request_id; nothing was withdrawn.');
+ }
+ } else 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]);
@@ -89,13 +115,15 @@ export async function recordFactWithdrawal(
if (preimage) await createPageVersion(tx, page.slug, sourceId, preimage);
}
}
- return withBeliefBatch(tx, { sourceId, slugs, publicationId: opts.requestId ?? opts.publicationId ?? null, op: 'forget', pageEventType: 'page.view_changed',
- remote: worldOnly, ...(opts.beliefReport ? { report: opts.beliefReport } : {}) }, async () => {
+ const batch = async (fn: () => Promise<WithdrawalCommit>) => opts.publication ? fn()
+ : withBeliefBatch(tx, { sourceId, slugs, publicationId: opts.requestId ?? opts.publicationId ?? null, op: 'forget', pageEventType: 'page.view_changed',
+ remote: worldOnly, ...(opts.beliefReport ? { report: opts.beliefReport } : {}) }, fn);
+ return batch(async () => {
// Scoped to the forgotten row's entity: the same claim about another
// entity stays active and rememberable. A subjectless fact withdraws
// source-wide ('*').
- const inserted = await tx.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash)
- VALUES ($1,$2,$4,gbrain_fact_fingerprint($3)) ON CONFLICT DO NOTHING RETURNING fact_hash`, [sourceId,row.visibility,row.fact,row.subject]);
+ const inserted = await tx.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash,withdrawn_at)
+ VALUES ($1,$2,$4,gbrain_fact_fingerprint($3),COALESCE($5::timestamptz,now())) ON CONFLICT DO NOTHING RETURNING fact_hash`, [sourceId,row.visibility,row.fact,row.subject,opts.publication?.withdrawnAt ?? null]);
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]);
@@ -122,7 +150,7 @@ export async function recordFactWithdrawal(
if (inline.length) await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=ANY($1::integer[])', [inline.map(page => page.id)]);
const pages = [...inline, ...segmented.length ? await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(
'SELECT id,slug,knowledge_revision FROM pages WHERE id=ANY($1::int[])', [segmented.map(page => page.id)]) : []];
- if (opts.requestId) {
+ if (opts.requestId && !opts.publication) {
await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,data,source_id,source_incarnation,worktree_id)
SELECT $1::uuid,k.kind,$3::text::jsonb,s.id,s.incarnation,b.worktree_id
FROM sources s LEFT JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation
@@ -136,6 +164,30 @@ export async function recordFactWithdrawal(
});
}
+/**
+ * GBRA-190 G4 (D1): the ledger is derived from Git. A trusted local import (the owner's sync or import, a local page
+ * write; never a remote one, prepareCanonicalProjections' `ledger`) of a fence row carrying the explicit withdrawal
+ * marker (struck, context `forgotten: ...`) records its withdrawal, so a brain rebuilt from Git keeps it. The subject is
+ * the page's slug, and '*' only for a row of memory/unattributed (a fact saved without an entity). A '*' row is not
+ * derived while the same claim is active on a fact with an entity: it would withdraw that fact too, which forget
+ * refuses (`claim_linked`). Existing ledger rows are kept as they are. Returns the rows added.
+ */
+export async function deriveFenceWithdrawals(tx: BrainEngine, sourceId: string, slug: string,
+ rows: readonly { fact: string; visibility?: string | null; context?: string | null; expired_at?: Date | null }[]): Promise<number> {
+ const marked = rows.filter(row => row.expired_at && /^forgotten\s*:/i.test((row.context ?? '').trim()))
+ .map(row => ({ fact: row.fact, visibility: row.visibility ?? 'private', at: row.expired_at!.toISOString() }));
+ if (!marked.length) return 0;
+ const inserted = await tx.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash,withdrawn_at)
+ SELECT $1,m.visibility,$2,gbrain_fact_fingerprint(m.fact),min(m.at::timestamptz)
+ FROM jsonb_to_recordset($3::text::jsonb) AS m(fact text,visibility text,at text)
+ WHERE m.visibility IN ('private','world')
+ AND ($2<>'*' OR NOT EXISTS (SELECT 1 FROM facts l WHERE l.source_id=$1 AND l.visibility=m.visibility AND l.entity_slug IS NOT NULL
+ 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(m.fact)))
+ GROUP BY m.visibility,gbrain_fact_fingerprint(m.fact)
+ ON CONFLICT DO NOTHING RETURNING fact_hash`, [sourceId, slug === UNATTRIBUTED_MEMORY_SLUG ? '*' : slug, JSON.stringify(marked)]);
+ return inserted.length;
+}
+
// Fingerprint each incoming claim once. Inside the join condition the planner
// re-evaluates both fingerprint functions for every (claim, withdrawal) pair,
// so a 28-row fence against 400 withdrawals spent 4 s in this query.
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 6e7f50dff2..b707adf643 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -6,6 +6,7 @@ import { pipelined } from '../page-state/transactions.ts';
import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fence.ts';
import { extractFactsFromFenceText, pageFactDate } from '../facts/extract-from-fence.ts';
+import { deriveFenceWithdrawals } from '../facts/withdrawal.ts';
import { takesPreparation } from '../takes-write.ts';
import { LINK_EXTRACTOR_VERSION_TS, parseTimelineEntries } from '../link-extraction.ts';
import { eachStoredTimelineRow, extractTimelineFromContent, hasExtractorDetail, supersededCitationTimeline, TimelineKeySet,
@@ -662,7 +663,9 @@ function takeCollision(rows: number[], sections: Map<number, FenceSection>, slug
* over the single-string ceiling) is read block by block (segmentedPriorView).
*/
export async function prepareCanonicalProjections(engine: BrainEngine, page: ParsedPage, slug: string, sourceId: string,
- prior: PageSnapshot | null, writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<(tx: BrainEngine, pageId?: number) => Promise<CanonicalProjectionResult>> {
+ prior: PageSnapshot | null, writer: ProjectionWriter, policy?: TimelineWritePolicy,
+ /** GBRA-190 G4 (D1): a trusted local writer's body (the owner's sync or import, a local page write) records the ledger rows of its explicit withdrawal markers. */
+ ledger?: { deriveWithdrawals: boolean }): Promise<(tx: BrainEngine, pageId?: number) => Promise<CanonicalProjectionResult>> {
// #7247: a fence row without a valid_from takes the page's stated date, as extract_facts does, never the import time.
const factDate = pageFactDate({ slug, frontmatter: page.frontmatter, timeZone: await engine.getConfig('brain.timezone') });
const { factRows, takes, quoted, sections } = compileCanonicalProjections(page, slug, sourceId, factDate);
@@ -815,6 +818,7 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
() => pipelined(tx, factGeneration.retiring ? [expireFacts, ...timelineRows] : timelineRows)));
if (factsHeld) await step('timeline', () => pipelined(tx, timelineRows));
if (guard.rows.length) await step('facts', () => tx.insertFacts(guard.rows, { source_id: sourceId })); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction
+ if (!factsHeld && ledger?.deriveWithdrawals) await step('withdrawals', () => deriveFenceWithdrawals(tx, sourceId, slug, factRows));
const contested = await step('fact_trust', () => guard.finish(tx));
// W1 #6783 §12 (b): a fence row's field rewrite can lower a more trusted fact (the tier trigger); what was derived from it follows.
const above = factRows.length ? await factsAboveWriter(tx, sourceId, slug) : [];
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 80f7ceefa8..68b9cb77d2 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -105,17 +105,18 @@ interface PreparedMutationBase {
export type PageMutationFile = MutationFile & { publishMode?: number; commit?: GitCommitNote };
/**
* GBRA-190 G4 (D2): another page a page publication writes in the same transaction, under the same recovery record and
- * in the same Git commit as the request's own page (a withdrawal's other pages). Its key is locked with the request's,
- * its revision and identity are checked under that lock, its file (when the source has one) is published with the
- * request's, and `apply` runs in the publication transaction after the request's own apply. Only a protocol 2 page
- * request carries companions; the single-page path is unchanged.
+ * in the same Git commit as the request's own page (a withdrawal's other pages, or the memory/unattributed row a
+ * remember links). Its key is locked with the request's, its revision and identity are checked under that lock, its
+ * file (when the source has one) is published with the request's, and `validate` and `apply` run in the publication
+ * transaction after the request's own. A request without companions publishes exactly as before.
*/
export interface CompanionPage {
slug: string;
pageId: number | null;
observedRevision: string | null;
file?: PageMutationFile;
- apply(tx: BrainEngine, preimage: PageSnapshot | null): Promise<void>;
+ validate?(tx: BrainEngine): Promise<void>;
+ apply(tx: BrainEngine, preimage: PageSnapshot | null): Promise<unknown>;
}
export type PreparedMutation = PreparedMutationBase & (
| { target?: 'page'; file?: PageMutationFile; files?: never; companions?: readonly CompanionPage[] }
@@ -482,7 +483,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
try {
assertMutationProtocol(row);
if ((row.target_kind ?? 'page') !== (prepared.target ?? 'page') || (skill ? !!prepared.file || !files.length : prepared.files !== undefined)
- || (companions.length > 0 && row.protocol_version !== 2)) {
+ || companions.some(companion => companion.slug === row.slug) || new Set(companions.map(companion => companion.slug)).size !== companions.length) {
throw opError('unsupported_mutation_protocol', 'Prepared mutation does not match its accepted target.',
`Request ${row.request_id} in source ${row.source_id} was prepared for a different target than it was accepted for, so nothing was published. This is an internal mismatch, not a caller error: inspect the request and report it to the user; do not resubmit it unchanged.`,
{ fix: requestFix(row) });
@@ -618,6 +619,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
}
}
await prepared.validate?.(tx);
+ for (const companion of companions) await companion.validate?.(tx);
// #5409: a file target prepared before the source became a read-only mirror is never published.
if (!skill && prepared.file && await sourceMirrorReadOnly(tx, row.source_id, true)) {
throw new OperationError('source_changed', 'The source became a read-only mirror after this write was prepared; nothing was written to its checkout.',
diff --git a/src/core/persistence/forget-prepare.ts b/src/core/persistence/forget-prepare.ts
new file mode 100644
index 0000000000..8eb019ca09
--- /dev/null
+++ b/src/core/persistence/forget-prepare.ts
@@ -0,0 +1,152 @@
+/**
+ * GBRA-190 G4: forget and forget_fact are fence edits. Git is the parent, so a withdrawal is one coordinated
+ * publication: its preparation strikes the claim (`withdrawnFact`: `~~claim~~` and `forgotten: ...`, the overlay's
+ * rendering) in the file of every page that carries it, the coordinator publishes those files under one recovery
+ * record and one Git commit (the request's page plus a CompanionPage per other page, coordinator.ts), and the
+ * publication transaction then writes the ledger row, the expiries and the chunk invalidation (recordFactWithdrawal's
+ * `publication` mode). No withdrawal-mirror effect is queued for it; that effect only drains rows queued before.
+ *
+ * A page's file is struck when the withdrawal applies to it (its subject is '*' or the page's slug, as the read overlay
+ * applies it) and the page has a canonical file; a deleted page, or one whose file is missing, gets no file, as the
+ * mirror never resurrected one. A file that differs from the database refuses the forget (the uncoordinated-edit
+ * refusal every coordinated page write gives) instead of leaving it unstruck.
+ */
+import { existsSync } from 'node:fs';
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import type { PageSnapshot, PageWithdrawal } from '../page-state/types.ts';
+import { opError, verbError } from '../ops/contract.ts';
+import { overlayCanonicalBodies } from '../page-state/snapshot.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import { pageBodyOverCeilingError } from '../page-body/page-shape.ts';
+import { planFactWithdrawal, recordFactWithdrawal } from '../facts/withdrawal.ts';
+import { rebuildPendingPageProjections } from '../page-state/projections.ts';
+import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
+import { remoteForgetRaced, supersessionGuarded } from '../trust/supersede-handlers.ts';
+import { materializedPage, segmentedOverCeiling } from './segmented-apply.ts';
+import { prepareFileTarget } from './page-prepare.ts';
+import { pageIdentityError } from './page-identity.ts';
+import type { CompanionPage, PageMutationFile, PreparedMutation } from './coordinator.ts';
+import type { WriteRequest } from './model.ts';
+
+interface ForgetTarget { id: number; entity_slug: string | null; trust_tier?: string | 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.
+ * 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.
+ */
+export async function refuseForgetReachingOtherCopies(tx: BrainEngine, sourceId: string, fact: ForgetTarget, 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 NOT (${privateProvenanceFilterFragment('l')}) LIMIT 1`, [id, sourceId]);
+ if (!hidden.length) return;
+ throw verbError('invalid_params',
+ `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.');
+}
+
+/** The fact a forget names, under the caller's visibility (locked inside a transaction when `lock`); null when it is not visible. */
+export async function readForgetTarget(engine: BrainEngine, id: number, sourceId: string, remote: boolean, excludePrivate: boolean, lock = false) {
+ const [fact] = await engine.executeRaw<ForgetTarget & { source_markdown_slug: string | null; expired_at: Date | null }>(`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')}` : ''}${lock ? ' FOR UPDATE' : ''}`, [id, sourceId, remote]);
+ return fact ?? null;
+}
+
+export async function prepareForgetMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig, signal?: AbortSignal): Promise<PreparedMutation> {
+ signal?.throwIfAborted();
+ const p = row.intent ?? {};
+ const id = Number(p.id);
+ const rawId = String(p.id ?? '').trim();
+ const sourceId = row.source_id;
+ const remote = row.authority.remote !== false;
+ const reason = typeof p.reason === 'string' && p.reason.trim() ? p.reason.trim() : null;
+ const excludePrivate = await resolveExcludePrivatePages(engine, remote);
+ const missing = () => verbError(row.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 (!Number.isSafeInteger(id) || id <= 0) throw missing();
+ const fact = await readForgetTarget(engine, id, sourceId, remote, excludePrivate);
+ if (!fact) throw missing();
+ if (row.operation === 'forget_fact' && fact.expired_at !== null) {
+ throw opError('fact_already_expired', `Fact id ${id} already expired.`, 'Recall the entity to read its current facts; nothing was changed.');
+ }
+ const plan = await planFactWithdrawal(engine, id, sourceId, remote, excludePrivate);
+ if (!plan) throw missing();
+ // The files are struck with this timestamp, and the ledger row records it, so the file and the read overlay agree.
+ const withdrawnAt = new Date().toISOString();
+ const withdrawal: PageWithdrawal = { visibility: plan.visibility, fact_hash: plan.fact_hash, withdrawn_at: withdrawnAt };
+ const struck = new Set(plan.affected.map(page => page.slug));
+ const strike = async (slug: string, snapshot: PageSnapshot | null): Promise<PageMutationFile | undefined> => {
+ if (!snapshot || snapshot.page.deleted_at || !row.worktree_id || !struck.has(slug) || (plan.subject !== '*' && plan.subject !== slug)) return undefined;
+ if (segmentedOverCeiling(snapshot.page)) throw pageBodyOverCeilingError(snapshot.page, `${row.operation} facts fence write`);
+ const page = await materializedPage(engine, snapshot.page);
+ const query = <T,>(sql: string, params?: unknown[]) => engine.executeRaw<T & Record<string, unknown>>(sql, params) as Promise<T[]>;
+ const bodies = await overlayCanonicalBodies(query, page.compiled_truth, page.timeline ?? '', [...snapshot.withdrawals, withdrawal],
+ { sourceId, marker: snapshot.globalPurges });
+ if (bodies.compiled_truth === page.compiled_truth && bodies.timeline === (page.timeline ?? '')) return undefined;
+ const file = await prepareFileTarget(engine, { source_id: sourceId, worktree_id: row.worktree_id, slug, operation: row.operation }, snapshot,
+ serializePageToMarkdown({ ...page, ...bodies }, snapshot.tags), undefined, { allowMissing: true, remote });
+ // A removal (a strict page turning private, git-declared.ts) is that transition's own write, never a withdrawal's.
+ return file && file.content !== null && existsSync(file.path) ? file : undefined;
+ };
+ const own = await engine.readPageSnapshot(row.slug, { sourceId, includeDeleted: true });
+ if ((own?.page.id ?? null) !== row.page_id) throw pageIdentityError(own != null || row.page_id === null, 'The page of the forgotten fact was deleted or recreated.');
+ const file = await strike(row.slug, own);
+ const companions: CompanionPage[] = [];
+ for (const slug of plan.slugs) {
+ if (slug === row.slug) continue;
+ signal?.throwIfAborted();
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ const companionFile = await strike(slug, snapshot);
+ companions.push({ slug, pageId: snapshot?.page.id ?? null, observedRevision: snapshot?.revision ?? null,
+ ...(companionFile ? { file: companionFile } : {}), apply: async () => undefined });
+ }
+ let pages: string[] = [];
+ return { observedRevision: own?.revision ?? null, ...(file ? { file } : {}), ...(companions.length ? { companions } : {}),
+ validate: async tx => {
+ // Under the publication's locks: the fact is still visible, no more trusted than a remote caller, and reaches no other copy.
+ const current = await readForgetTarget(tx, id, sourceId, remote, excludePrivate, true);
+ if (!current) throw missing();
+ if (remote && supersessionGuarded('agent_written', current.trust_tier)) throw remoteForgetRaced(id);
+ await refuseForgetReachingOtherCopies(tx, sourceId, current, remote, excludePrivate);
+ },
+ apply: async tx => {
+ // Even an expired legacy fact acquires a ledger row, so a stale import cannot reactivate it.
+ pages = (await recordFactWithdrawal(tx, id, sourceId, remote, { requestId: row.id, semanticReview: p.semantic_review !== false, excludePrivate,
+ publication: { withdrawnAt, expectedSlugs: plan.slugs } })).pages.map(page => page.slug);
+ 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}`]);
+ return row.operation === 'forget'
+ ? { id: rawId, expired: fact.expired_at === null, reason, protocol_version: 1 }
+ : { id, expired: true, path: 'legacy_db', reason: reason ?? 'forgotten' };
+ },
+ // The publication removed the withdrawn pages' chunks; rebuild them now, as a CLI process exits without a
+ // resident projection worker. A failed rebuild stays queued as durable projection work.
+ afterCommit: async committed => {
+ for (let start = 0; start < pages.length; start += 100) {
+ await rebuildPendingPageProjections(committed, 100, { pages: { sourceId, slugs: pages.slice(start, start + 100) } }).catch(() => undefined);
+ }
+ } };
+}
diff --git a/src/core/persistence/git-declared.ts b/src/core/persistence/git-declared.ts
index 8d52154c2c..accaefc637 100644
--- a/src/core/persistence/git-declared.ts
+++ b/src/core/persistence/git-declared.ts
@@ -218,6 +218,8 @@ export async function declareStrictPublication(tx: BrainEngine, row: WriteReques
before: PageSnapshot | null, final: PageSnapshot | null, binding: Pick<WorktreeBinding, 'canonical_git' | 'local_path' | 'relative_path'> | null | undefined): Promise<void> {
if (binding?.canonical_git !== true || !binding.local_path || !row.worktree_id || prepared.noop || !final || final.page.deleted_at) return;
if (syncRow(row)) return;
+ // GBRA-190 G4: a withdrawal writes no page content of its own; the files it strikes are its Git home (forget-prepare.ts).
+ if ((row.operation === 'forget' || row.operation === 'forget_fact') && !prepared.file) return;
const [stored] = await tx.executeRaw<{ reason: string | null }>('SELECT database_only_reason AS reason FROM pages WHERE id=$1', [final.page.id]);
const reason = stored?.reason ?? null;
const root = join(binding.local_path, binding.relative_path ?? '');
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index fc37cebf9b..3c65c9face 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -98,7 +98,7 @@ export function singleWrite(row: Pick<WriteRequest, 'operation' | 'intent'>): bo
/** Whether a prepared member can share a group transaction. */
export function groupable(row: WriteRequest, prepared: PreparedMutation): boolean {
if ((row.target_kind ?? 'page') !== 'page' || prepared.target === 'skill_bundle' || prepared.sourceExclusive || prepared.exclusiveSources?.length || prepared.afterEffects
- || prepared.companions?.length || (row.protocol_version ?? 1) !== 1) return false;
+ || prepared.companions?.length) return false;
if (syncMember(row)) return !prepared.file && typeof prepared.validate === 'function';
// A streamed file (large-file.ts) is staged before its publication transaction, which only publishMutation does.
if (isStreamedContent(prepared.file?.content)) return false;
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index 8e1ca77007..e03579e6a3 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -271,7 +271,8 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
const rendered = imageBytes ?? (code ? content : serializePageToMarkdown({
...(snapshot ? withoutBody(snapshot.page) : { id: 0, slug: row.slug, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage,
} as Page, tags));
- const project = code || image ? undefined : await prepareCanonicalProjections(engine, ready.parsedPage!, row.slug, row.source_id, snapshot, 'file');
+ const project = code || image ? undefined : await prepareCanonicalProjections(engine, ready.parsedPage!, row.slug, row.source_id, snapshot, 'file', undefined,
+ { deriveWithdrawals: true });
const mutation: PreparedMutation = { observedRevision: ready.observedRevision, noop: ready.noop && p.targetHash === sha256(rendered),
trust: await ownerImportTrust(engine, row, ready.parsedPage?.frontmatter, p.sourcePath), deferEmbedding: image || p.noEmbed, validate: async tx => { await checkPaths(tx); await ready.validate(tx); },
...(ready.afterCommit ? { afterCommit: ready.afterCommit } : {}),
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index bfb3c1a935..aeb0842922 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -2,13 +2,11 @@ import { throwIfHeld } from '../trust/gate-outcomes.ts';
import { guardRemoteForget, remoteForgetRaced, supersessionGuarded } from '../trust/supersede-handlers.ts';
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';
import { isNullLikeEntity } from '../facts/write-single.ts';
-import { isFactWithdrawn, recordFactWithdrawal, type WithdrawalCommit } from '../facts/withdrawal.ts';
-import { rebuildPendingPageProjections } from '../page-state/projections.ts';
+import { isFactWithdrawn } from '../facts/withdrawal.ts';
import { inferFactSubject, isEntityInferenceEnabled, type InferredVia } from '../facts/subject-infer.ts';
import { parseFactsFence } from '../facts-fence.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
@@ -17,19 +15,16 @@ import { materializedPage, segmentedOverCeiling } from './segmented-apply.ts';
import { excludesPrivateWrites } from './page-visibility.ts';
import { emitFenceNotice, initializeLocalPersistence, requestPrincipalForContext } from './page-mutations.ts';
import { authorizeStoredRequest, submissionAuthority } from './authority.ts';
-import { admitWrite, admitWriteInTransaction, assertPageRequestIdentity, assertReplayIntent, completeWrite, getWriteRequest, intentDigest } from './journal.ts';
+import { admitWrite, assertPageRequestIdentity, assertReplayIntent, getWriteRequest, intentDigest } from './journal.ts';
import { assertPersistenceAccepting, registerMutationPreparer, waitForWrite, writeResponse } from './service.ts';
import { claimWorktree } from './ownership.ts';
-import { declareDurablePersistence } from './protocol.ts';
import { resolveFactWriteTarget } from './fact-write-target.ts';
import { clientRequestIdOf, parseMutationPrecondition } from './preconditions.ts';
-import { withCoordinatedWrite } from './context.ts';
-import { requestAttribution } from './attribution.ts';
-import { isTerminal, type WriteRequest } from './model.ts';
+import type { WriteRequest } from './model.ts';
import { prepareMemoryMutation } from './memory-prepare.ts';
-import { retryWriteAdmission } from './admission-retry.ts';
-import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
-import { markBeliefCommits } from '../belief/append.ts';
+import { readForgetTarget, refuseForgetReachingOtherCopies } from './forget-prepare.ts';
+import { UNATTRIBUTED_MEMORY_SLUG } from '../facts/extract-from-fence.ts';
+import { resolveExcludePrivatePages } from '../search/private-visibility.ts';
export { prepareMemoryMutation } from './memory-prepare.ts';
/** Only semantic appends without an explicit caller revision can be recomputed. */
@@ -279,116 +274,51 @@ async function resolveRememberEntity(ctx: OperationContext, sourceId: string, en
throw error;
}
-interface WithdrawalTarget { id: number; entity_slug: string | null; source_markdown_slug: string | null; expired_at: Date | null; trust_tier?: string | 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.
- * 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.
+ * GBRA-190 G4: a withdrawal is a coordinated page publication (forget-prepare.ts): the files that carry the claim are
+ * struck and committed first, then the ledger row, expiries and chunk invalidation commit in its transaction. The
+ * checks here fail fast before admission; preparation and publication repeat them under their locks.
*/
-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 NOT (${privateProvenanceFilterFragment('l')}) LIMIT 1`, [id, sourceId]);
- if (!hidden.length) return;
- throw verbError('invalid_params',
- `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. */
-export async function submitForgetMutation(ctx: OperationContext, operation: 'forget' | 'forget_fact', params: Record<string, unknown>): Promise<Record<string, unknown>> {
+export async function submitForgetMutation(ctx: OperationContext, operation: 'forget' | 'forget_fact', params: Record<string, unknown>, waitMs?: number): Promise<Record<string, unknown>> {
const sub = await submission(ctx, operation, params);
- if (sub.prior) return withSimilarActive(ctx, operation, sub.sourceId, sub.p, writeResponse(sub.prior));
+ if (sub.prior) return withSimilarActive(ctx, operation, sub.sourceId, sub.p, writeResponse(await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs ?? ctx.writeWaitMs)));
const { p, sourceId, principal, callerIntent, requestId, clientRequestId } = sub;
- const semanticReview = p.semantic_review !== false;
const id = Number(p.id);
const rawId = String(p.id).trim();
const reason = typeof p.reason === 'string' && p.reason.trim() ? p.reason.trim() : null;
+ const missing = () => 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 (!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 remote = ctx.remote !== false;
const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
// #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
- // are released before backoff. Admission must not retry a nested savepoint.
- let withdrawn: WithdrawalCommit['pages'] = [];
- const beliefReport = { appended: 0 };
- const done = await retryWriteAdmission(requestId, remaining => ctx.engine.transaction(async tx => {
- withdrawn = [];
- beliefReport.appended = 0;
- await declareDurablePersistence(tx, `${Math.min(1000, remaining)}ms`, `${remaining}ms`);
- // Brain row -> source -> current grant -> counters/request -> sorted page keys -> facts.
- // Do not acquire a shared source lock first and upgrade it after admission.
- const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>(
- 'SELECT incarnation,archived FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);
- if (!source || source.archived) throw sourceInactive(sourceId);
- // Another same-ID caller may have completed while we waited for the source.
- const prior = await getWriteRequest(tx, principal, requestId);
- if (prior) {
- await submissionAuthority({ ...ctx, engine: tx }, operation, sourceId, source.incarnation, prior.slug);
- await authorizeStoredRequest(tx, prior, true);
- assertReplayIntent(prior, intentDigest({ operation, sourceId, slug: prior.slug, callerIntent }));
- 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]);
- 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);
- 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);
- const row = await admitWriteInTransaction(tx, { origin: ctx.admissionOrigin, principal, operation, sourceId, sourceIncarnation: source.incarnation,
- slug, requestId, clientRequestId, callerIntent, intent: { ...callerIntent, reason }, authority });
- if (isTerminal(row)) return row;
- 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;
- 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) {
- return completeWrite(tx, row, 'failed', {}, { code: 'fact_already_expired', message: `Fact id ${id} already expired.` });
- }
- const outcome = operation === 'forget'
- ? { id: rawId, expired: fact.expired_at === null, reason, protocol_version: 1 }
- : { id, expired: true, path: 'legacy_db', reason: reason ?? 'forgotten' };
- return completeWrite(tx, row, 'committed', { ...outcome, persistence: { mode: 'database' } });
- }, requestAttribution(row));
- }), undefined, error => ctx.engine.reconnect({ error }));
- if (beliefReport.appended && done.state === 'committed') await markBeliefCommits(ctx.engine, [done.id]).catch(() => undefined);
- // The commit removed the withdrawn pages' chunks. Rebuild them before
- // acknowledging: a CLI process exits without a resident projection worker.
- // A failed rebuild stays queued as durable projection work.
- const slugs = withdrawn.map(page => page.slug);
- for (let start = 0; start < slugs.length; start += 100) {
- await rebuildPendingPageProjections(ctx.engine, 100, { pages: { sourceId, slugs: slugs.slice(start, start + 100) } }).catch(() => undefined);
- }
- return withSimilarActive(ctx, operation, sourceId, p, writeResponse(done));
+ if (remote) await guardRemoteForget(ctx.engine, { sourceId, factId: id, principal, reason, excludePrivate });
+ const [source] = await ctx.engine.executeRaw<RememberSource>(
+ "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);
+ if (!source || source.archived) throw sourceInactive(sourceId);
+ const fact = await readForgetTarget(ctx.engine, id, sourceId, remote, excludePrivate);
+ if (!fact) throw missing();
+ if (remote && supersessionGuarded('agent_written', fact.trust_tier)) throw remoteForgetRaced(id);
+ await refuseForgetReachingOtherCopies(ctx.engine, sourceId, fact, remote, excludePrivate);
+ const slug = fact.source_markdown_slug ?? fact.entity_slug ?? UNATTRIBUTED_MEMORY_SLUG;
+ enforceClientSlugFence(ctx, slug, operation); enforceSubagentSlugFence(ctx, slug, operation);
+ const authority = await submissionAuthority(ctx, operation, sourceId, source.incarnation, slug);
+ const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ const sandbox = ctx.viaSubagent === true && !(ctx.allowedSlugPrefixes?.length);
+ // The pages a withdrawal strikes publish through the source's canonical worktree, as remember's do; a source whose
+ // root has no owner and refuses a claim publishes database-only, as its writes do.
+ const target = await resolveFactWriteTarget(ctx.engine, sourceId, source, { sandbox, fileBacked: true, remote })
+ .catch((error: unknown) => { if (error instanceof OperationError) return null; throw error; });
+ if (target?.kind === 'publish' && target.databaseOnlyReason) authority.databaseOnlyReason = target.databaseOnlyReason;
+ const binding = target?.kind === 'unbound' ? await claimWorktree(ctx.engine, sourceId, target.root, undefined, undefined, { automatic: true })
+ : target?.binding ?? null;
+ const row = await admitWrite(ctx.engine, { origin: ctx.admissionOrigin, principal, operation, sourceId, sourceIncarnation: source.incarnation,
+ slug, pageId: snapshot?.page.id ?? null, requestId, clientRequestId, callerIntent,
+ intent: { ...callerIntent, reason, semantic_review: p.semantic_review !== false }, authority,
+ worktreeId: binding?.worktree_id ?? null, topologyGeneration: binding?.topology_generation ?? null });
+ const written = await waitForWrite(ctx.engine, row, ctx.config, waitMs ?? ctx.writeWaitMs);
+ return withSimilarActive(ctx, operation, sourceId, p, writeResponse(written));
}
/** `forget` responses carry `similar_active` (ids and scores only, zero model calls); best-effort, never fails the forget. */
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index c20f0bc27f..e402970f01 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -18,7 +18,7 @@ import { writeGateRejectedError } from '../write-gate.ts';
import { lexicalContestCandidate, recordContestedFact, supersessionGuarded } from '../trust/supersede-handlers.ts';
import { storedTrustTier } from '../trust/tier.ts';
import { fenceAppendPendingTier } from '../eligibility/fence-overlay.ts';
-import { prepareFenceFactAppend, requestReceiptFix, type FenceFactAppend } from '../facts/fence-fact-append.ts';
+import { prepareFenceFactAppend, prepareFenceRowRetirement, requestReceiptFix, type FenceFactAppend } from '../facts/fence-fact-append.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { tightenToPage } from '../facts/visibility.ts';
import { UNATTRIBUTED_MEMORY_SLUG } from '../facts/extract-from-fence.ts';
@@ -141,11 +141,16 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
fence = await prepareFenceFactAppend(engine, row, config, snapshot, { fact, pendingTier: fenceAppendPendingTier(writerTier),
supersede: status === 'superseded' && old?.source_markdown_slug === row.slug && old.row_num != null ? { rowNum: Number(old.row_num), validUntil: retiredUntil } : undefined }, signal);
}
+ // GBRA-190 G4: linking a fact saved without an entity retires its memory/unattributed row in the same publication.
+ const old = status === 'superseded' ? decision.candidate! : null;
+ const linkedRow = old && old.source_markdown_slug === UNATTRIBUTED_MEMORY_SLUG && row.slug !== UNATTRIBUTED_MEMORY_SLUG && old.row_num != null
+ ? await prepareFenceRowRetirement(engine, row, config, UNATTRIBUTED_MEMORY_SLUG, { rowNum: Number(old.row_num), note: `linked to ${input.entity_slug}`, validUntil: retiredUntil }, signal) : null;
// The belief ledger records the superseded fact in its own stream, so that stream's page key is held too.
const supersededStream = status === 'superseded' ? decision.candidate!.source_markdown_slug ?? decision.candidate!.entity_slug ?? null : null;
- const additionalPageKeys = supersededStream && supersededStream !== row.slug ? [{ sourceId: row.source_id, slug: supersededStream }] : undefined;
+ const additionalPageKeys = supersededStream && supersededStream !== row.slug && !linkedRow ? [{ sourceId: row.source_id, slug: supersededStream }] : undefined;
const page = fence?.prepared ?? undefined;
- return { observedRevision, file: page?.file, ...(page?.exclusiveSources ? { exclusiveSources: page.exclusiveSources } : {}), ...(additionalPageKeys ? { additionalPageKeys } : {}), validate: async tx => { await validate(tx); await page?.validate?.(tx); }, apply: async tx => {
+ return { observedRevision, file: page?.file, ...(page?.exclusiveSources ? { exclusiveSources: page.exclusiveSources } : {}), ...(additionalPageKeys ? { additionalPageKeys } : {}),
+ ...(linkedRow ? { companions: [linkedRow] } : {}), validate: async tx => { await validate(tx); await page?.validate?.(tx); }, apply: async tx => {
let id: number;
let pageReceipt: { size_state?: unknown } | undefined;
if (fence) {
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 6e8525f8fe..456616c90e 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -926,7 +926,8 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
// Projections, advisories, link resolution (links-preparation.ts), the file target and the core guard go out together.
enterClaimStep(clock, 'link_resolution', undefined, 'db');
const [project, advisories, links, target, core] = await pipelined(together, [
- async () => projected ? prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer,timelinePolicy) : undefined,
+ async () => projected ? prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer,timelinePolicy,
+ { deriveWithdrawals: row.authority.remote === false }) : undefined,
async () => noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : preparePageAdvisories(engine,row,ready.parsedPage,snapshot),
async () => !noop && !targetDeleted && autoLinkedPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)
? prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id,options.coordinated === true) : undefined,
diff --git a/src/core/persistence/preparation-budget.ts b/src/core/persistence/preparation-budget.ts
index 2c80ee5187..2eb0ad2b61 100644
--- a/src/core/persistence/preparation-budget.ts
+++ b/src/core/persistence/preparation-budget.ts
@@ -125,7 +125,7 @@ export type PreparationKind = 'foreground' | 'sync' | 'maintenance';
/** Which budget a request takes: the foreground 30 s, the sync member budget, or the maintenance budget for everything else. */
export function preparationKind(row: Pick<WriteRequest, 'operation' | 'intent'>): PreparationKind {
const kind = row.intent?.kind;
- if (row.operation === 'remember' || (row.operation === 'put_page' || row.operation === 'edit_page') && !kind) return 'foreground';
+ if (row.operation === 'remember' || row.operation === 'forget' || row.operation === 'forget_fact' || (row.operation === 'put_page' || row.operation === 'edit_page') && !kind) return 'foreground';
return String(kind ?? '').startsWith('managed_sync_') ? 'sync' : 'maintenance';
}
export function preparationBudgetMs(row: Pick<WriteRequest, 'operation' | 'intent'>, policy: PreparationPolicy, foregroundMs: number): number {
diff --git a/src/core/persistence/protocol.ts b/src/core/persistence/protocol.ts
index 184a38b331..61e857aad2 100644
--- a/src/core/persistence/protocol.ts
+++ b/src/core/persistence/protocol.ts
@@ -61,8 +61,7 @@ export function isPersistenceDeclaration(statement: string): boolean {
export const PERSISTENCE_PROTOCOL_PREDICATE = "set_config('gbrain.persistence_protocol','2',true)='2'";
export function assertMutationProtocol(row: Pick<WriteRequest, 'target_kind' | 'protocol_version'>): void {
- // GBRA-190 G4 (D2): a page request at protocol 2 may publish several pages together (a withdrawal).
- if (((row.target_kind ?? 'page') === 'page' && [1, 2].includes(row.protocol_version ?? 1))
+ if (((row.target_kind ?? 'page') === 'page' && (row.protocol_version ?? 1) === 1)
|| (row.target_kind === 'skill_bundle' && row.protocol_version === 2)) return;
throw opError('unsupported_mutation_protocol', 'This consumer does not support the request target and protocol version.',
`This gbrain process cannot apply ${row.target_kind ?? 'page'} requests at protocol ${row.protocol_version ?? 1}, so it left the request untouched. A newer gbrain wrote it: upgrading gbrain on this host (the user's call) lets it be applied.`);
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index 848937fd6d..3168020f0b 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -114,7 +114,7 @@ export async function prepareReconcileResult(engine: BrainEngine, state: Reconci
{ fix: pageFix(state.pins.source_id, state.pins.slug) });
if (ready.observedRevision !== state.snapshot.revision) staleReconcile('revision changed during policy assessment');
const resolved = reconcileCanonical(ready.parsedPage, [...new Set([...state.snapshot.tags, ...ready.parsedPage.tags])]);
- const project = await prepareCanonicalProjections(engine, resolved, state.pins.slug, state.pins.source_id, state.snapshot, writer);
+ const project = await prepareCanonicalProjections(engine, resolved, state.pins.slug, state.pins.source_id, state.snapshot, writer, undefined, { deriveWithdrawals: true });
return { ...merged, result: resolved, ready, project };
}
diff --git a/src/core/persistence/semantic.ts b/src/core/persistence/semantic.ts
index 44f5fa6199..4b73163981 100644
--- a/src/core/persistence/semantic.ts
+++ b/src/core/persistence/semantic.ts
@@ -1,6 +1,6 @@
import type { WriteRequest } from './model.ts';
export const SEMANTIC_PAGE_OPERATIONS: ReadonlySet<string> = new Set([
- 'add_tag', 'remove_tag', 'add_timeline_entry', 'add_link', 'remove_link', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove', 'remember',
+ 'add_tag', 'remove_tag', 'add_timeline_entry', 'add_link', 'remove_link', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove', 'remember', 'forget', 'forget_fact',
]);
/**
* Recompute only supported merges; caller-supplied stale replacements remain conflicts. #5385 [R13]: a merge submitted
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 4414619fa5..c59ab5f928 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -101,6 +101,7 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest
if (row.operation === 'put_page' && row.intent?.kind === 'managed_file_import') return (await import('./import-prepare.ts')).prepareManagedImportMutation(e, row, cfg);
if (row.operation === 'put_page' && row.intent?.kind === 'managed_file_repair') return (await import('./file-repair.ts')).prepareManagedFileRepairMutation(e, row, cfg);
if (row.operation === 'remember') return (await import('./memory-mutations.ts')).prepareMemoryMutation(e, row, cfg, signal);
+ if (row.operation === 'forget' || row.operation === 'forget_fact') return (await import('./forget-prepare.ts')).prepareForgetMutation(e, row, cfg, signal);
if (row.operation === 'loops_close' && row.intent?.kind === 'retire_loop_fact') return (await import('./loop-fact-retirement.ts')).prepareLoopFactRetirement(e, row, cfg);
if (row.operation === 'decide_proposal') return (await import('../facts/proposal-supersede.ts')).prepareProposalMutation(e, row, cfg);
if (row.operation === 'trust_owner_page') return (await import('../trust/page-handlers.ts')).prepareTrustOwnerPageMutation(e, row, cfg);
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 1e307ead4f..bea1f12db5 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -898,7 +898,8 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c
const writeback = canonicalWritebackNeeded(row, p, p.content, canonicalFile);
// A rename projects against the moved page (same id), so its pinned timeline rows carry over.
enterClaimStep(clock, 'canonical_projections', undefined, 'db');
- const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');
+ const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file', undefined,
+ { deriveWithdrawals: row.authority.remote !== true });
const importProvenance: SyncImportProvenanceBase = { source_id: row.source_id, incarnation: row.source_incarnation, origin: p.sourcePath!, raw_sha256: sha256(p.content!),
...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}), parser: syncImportParser(pack?.identity ?? null),
...(p.fullEpisode ? { full_episode: p.fullEpisode } : {}) };
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index afb9251e6b..526b4f54c7 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -2039,7 +2039,7 @@ CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer)
RAISE EXCEPTION 'writer_upgrade_required: this mutation requires persistence protocol 2' USING ERRCODE='42501';
END IF;
END \$\$;
-CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$
+CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
DECLARE target text; version integer; floor integer; active boolean; record jsonb;
BEGIN
IF TG_OP='DELETE' THEN target:=OLD.target_kind; version:=OLD.protocol_version;
@@ -2076,7 +2076,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGU
RAISE EXCEPTION 'unsupported_mutation_protocol: recovery target mismatch' USING ERRCODE='42501';
END IF;
RETURN NEW;
- END \$;
+ END \$\$;
DROP TRIGGER IF EXISTS gbrain_request_protocol ON persistence_requests;
CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_requests
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol();
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 6b6aa49b1b..1edc3b8691 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -2798,7 +2798,7 @@ CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer)
RAISE EXCEPTION 'writer_upgrade_required: this mutation requires persistence protocol 2' USING ERRCODE='42501';
END IF;
END \$\$;
-CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$
+CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
DECLARE target text; version integer; floor integer; active boolean; record jsonb;
BEGIN
IF TG_OP='DELETE' THEN target:=OLD.target_kind; version:=OLD.protocol_version;
@@ -2835,7 +2835,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGU
RAISE EXCEPTION 'unsupported_mutation_protocol: recovery target mismatch' USING ERRCODE='42501';
END IF;
RETURN NEW;
- END \$;
+ END \$\$;
DROP TRIGGER IF EXISTS gbrain_request_protocol ON persistence_requests;
CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_requests
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol();
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index c0729630d1..999c6b658f 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -275,7 +275,7 @@ import { v271 } from './v271-facts-superseded-by-index.ts';
import { v272 } from './v272-git-canonical-declared.ts';
import { v273 } from './v273-segment-derivations.ts';
import { v274 } from './v274-pages-withheld-source-path.ts';
-import { v275 } from './v275-multi-page-publication-protocol.ts';
+import { v275 } from './v275-multi-page-recovery-record.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
diff --git a/src/core/schema-migrations/v275-multi-page-publication-protocol.ts b/src/core/schema-migrations/v275-multi-page-publication-protocol.ts
deleted file mode 100644
index 03af5b53f2..0000000000
--- a/src/core/schema-migrations/v275-multi-page-publication-protocol.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { Migration } from './types.ts';
-import { REQUEST_PROTOCOL_GUARD_SQL } from '../shared-skills/persistence-schema.ts';
-
-export const v275: Migration = {
- // GBRA-190 G4 (D2): one publication may write several pages (a withdrawal strikes its claim on every page that
- // carries it) and commit them in one Git commit. Such a request is a page target at protocol 2, so a binary that
- // predates it leaves it untouched, and its recovery record is version 3 (several page files), which those binaries
- // refuse unread (recovery-version.ts). Only the trigger function is replaced: no table, column or row changes.
- version: 275,
- name: 'multi_page_publication_protocol',
- idempotent: true,
- sql: REQUEST_PROTOCOL_GUARD_SQL + ';',
-};
diff --git a/src/core/schema-migrations/v275-multi-page-recovery-record.ts b/src/core/schema-migrations/v275-multi-page-recovery-record.ts
new file mode 100644
index 0000000000..afcfe2e213
--- /dev/null
+++ b/src/core/schema-migrations/v275-multi-page-recovery-record.ts
@@ -0,0 +1,14 @@
+import type { Migration } from './types.ts';
+import { REQUEST_PROTOCOL_GUARD_SQL } from '../shared-skills/persistence-schema.ts';
+
+export const v275: Migration = {
+ // GBRA-190 G4 (D2): one publication may write several pages (a withdrawal strikes its claim on every page that
+ // carries it; remember linking a fact saved without an entity strikes its memory/unattributed row) and commit them in
+ // one Git commit. Its recovery record is version 3 (several page files, model.ts PagesRecoveryRecord), which binaries
+ // that predate it refuse unread (recovery-version.ts). Only the request guard's trigger function is replaced so it
+ // accepts that record on a page target: no table, column or row changes.
+ version: 275,
+ name: 'multi_page_recovery_record',
+ idempotent: true,
+ sql: REQUEST_PROTOCOL_GUARD_SQL + ';',
+};
diff --git a/src/core/shared-skills/persistence-schema.ts b/src/core/shared-skills/persistence-schema.ts
index 09c0a55197..7d24fe9006 100644
--- a/src/core/shared-skills/persistence-schema.ts
+++ b/src/core/shared-skills/persistence-schema.ts
@@ -1,9 +1,9 @@
/**
- * The request protocol guard. GBRA-190 G4 (D2): a page target is protocol 1, or 2 for a request whose publication
- * writes several pages (a withdrawal), and its recovery record is version 1 (one file) or version 3 (several page
- * files, model.ts PagesRecoveryRecord); a binary that predates protocol 2 page requests leaves them untouched.
+ * The request protocol guard. GBRA-190 G4 (D2): a page target's recovery record is version 1 (one file) or version 3
+ * (the page files one publication writes together, model.ts PagesRecoveryRecord), which binaries that predate it
+ * refuse unread (recovery-version.ts).
*/
-export const REQUEST_PROTOCOL_GUARD_SQL = `CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $
+export const REQUEST_PROTOCOL_GUARD_SQL = `CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
DECLARE target text; version integer; floor integer; active boolean; record jsonb;
BEGIN
IF TG_OP='DELETE' THEN target:=OLD.target_kind; version:=OLD.protocol_version;
@@ -29,7 +29,7 @@ export const REQUEST_PROTOCOL_GUARD_SQL = `CREATE OR REPLACE FUNCTION gbrain_gua
WHERE w.id=NEW.worktree_id AND w.state='active') THEN
RAISE EXCEPTION 'writer_not_quiesced: canonical owner capability must be revalidated' USING ERRCODE='42501';
END IF;
- ELSIF version NOT IN (1,2) THEN
+ ELSIF version<>1 THEN
RAISE EXCEPTION 'unsupported_mutation_protocol: invalid page target' USING ERRCODE='42501';
END IF;
record:=NEW.recovery;
@@ -40,7 +40,7 @@ export const REQUEST_PROTOCOL_GUARD_SQL = `CREATE OR REPLACE FUNCTION gbrain_gua
RAISE EXCEPTION 'unsupported_mutation_protocol: recovery target mismatch' USING ERRCODE='42501';
END IF;
RETURN NEW;
- END $`;
+ END $$`;
export const SHARED_SKILLS_PERSISTENCE_SCHEMA_STATEMENTS: readonly string[] = [
`ALTER TABLE persistence_brain ADD COLUMN IF NOT EXISTS writer_protocol_floor integer NOT NULL DEFAULT 1 CHECK (writer_protocol_floor IN (1,2))`,
diff --git a/src/schema.sql b/src/schema.sql
index 93d142cb34..d5c44cdad4 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -2794,7 +2794,7 @@ CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer)
RAISE EXCEPTION 'writer_upgrade_required: this mutation requires persistence protocol 2' USING ERRCODE='42501';
END IF;
END $$;
-CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $
+CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
DECLARE target text; version integer; floor integer; active boolean; record jsonb;
BEGIN
IF TG_OP='DELETE' THEN target:=OLD.target_kind; version:=OLD.protocol_version;
@@ -2831,7 +2831,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGU
RAISE EXCEPTION 'unsupported_mutation_protocol: recovery target mismatch' USING ERRCODE='42501';
END IF;
RETURN NEW;
- END $;
+ END $$;
DROP TRIGGER IF EXISTS gbrain_request_protocol ON persistence_requests;
CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_requests
FOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol();
diff --git a/test/persistence-withdrawal-retry.test.ts b/test/persistence-withdrawal-retry.test.ts
index 8e860a3118..c5e538dc2b 100644
--- a/test/persistence-withdrawal-retry.test.ts
+++ b/test/persistence-withdrawal-retry.test.ts
@@ -11,6 +11,7 @@ import { submitForgetMutation } from '../src/core/persistence/memory-mutations.t
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { getWriteRequest } from '../src/core/persistence/journal.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -51,39 +52,40 @@ for (const boundary of ['admission-counter', 'completed-withdrawal'] as const) {
const principal = { kind: 'local_cli' as const, id: local.id };
const params = { id: String(fact.id), reason: 'Explicit correction', request_id: randomUUID() };
const [before] = await engine.executeRaw<{ lifetime_ids: string }>("SELECT lifetime_ids::text FROM persistence_counters WHERE key='brain'");
- let injected = false, sourceTransactions = 0, rollbacks = 0;
+ let injected = false, rollbacks = 0;
const proxy = new Proxy(engine, { get(target, property) {
- if (property === 'transaction') return (run: (tx: BrainEngine) => Promise<any>) => {
- let withdrawal = false;
+ if (property === 'transaction') return (run: (tx: BrainEngine) => Promise<any>, ...rest: unknown[]) => {
+ let aborted = false;
const wrap = (tx: BrainEngine): BrainEngine => new Proxy(tx, { get(nested, key) {
- if (key === 'transaction') return (fn: (tx: BrainEngine) => Promise<any>) => nested.transaction(child => fn(wrap(child)));
+ if (key === 'transaction') return (fn: (tx: BrainEngine) => Promise<any>, ...more: unknown[]) => (nested.transaction as any)((child: BrainEngine) => fn(wrap(child)), ...more);
if (key === 'executeRaw') return async (sql: string, args?: unknown[]) => {
- if (sql === 'SELECT incarnation,archived FROM sources WHERE id=$1 FOR UPDATE') { withdrawal = true; sourceTransactions++; }
+ // GBRA-190 G4: the forget is admitted like every write, then published by the coordinator.
if (!injected && boundary === 'admission-counter' && sql.startsWith('SELECT * FROM persistence_counters WHERE key')) {
- injected = true;
+ injected = aborted = true;
throw Object.assign(new Error('confirmed counter statement abort'), { code: '55P03' });
}
return nested.executeRaw(sql, args);
};
const value = Reflect.get(nested, key); return typeof value === 'function' ? value.bind(nested) : value;
} });
- return target.transaction(async tx => {
+ return (target.transaction as any)(async (tx: BrainEngine) => {
const result = await run(wrap(tx));
- if (!injected && boundary === 'completed-withdrawal' && result?.operation === 'forget') {
- injected = true;
- throw Object.assign(new Error('confirmed abort after withdrawal and receipt writes'), { code: '40001' });
+ if (!injected && boundary === 'completed-withdrawal' && result?.operation === 'forget' && result?.state === 'committed') {
+ injected = aborted = true;
+ // A statement cancel, the interruption the coordinator charges and retries (transient-retry.ts).
+ throw Object.assign(new Error('confirmed abort after withdrawal and receipt writes'), { code: '57014' });
}
return result;
- }).catch(async error => {
- if (withdrawal && ['55P03', '40001'].includes(error.code)) {
+ }, ...rest).catch(async (error: { code?: string }) => {
+ if (aborted && ['55P03', '57014'].includes(error.code ?? '')) {
rollbacks++;
- // This new transaction cannot acquire the source NOWAIT if a
- // failed attempt retained its source guard through retry backoff.
+ // The aborted attempt kept nothing: no withdrawal, no expiry, no committed receipt.
await target.transaction(async tx => {
await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE NOWAIT', [sourceId]);
expect((await tx.readPageSnapshot(page.slug, { sourceId }))!.revision).toBe(page.knowledge_revision!);
expect((await tx.executeRaw<{ expired_at: Date | null }>('SELECT expired_at FROM facts WHERE id=$1', [fact.id]))[0].expired_at).toBeNull();
- expect(await getWriteRequest(tx, principal, params.request_id)).toBeNull();
+ expect(await tx.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1 AND fact_hash=gbrain_fact_fingerprint($2)', [sourceId, `Withdraw ${page.slug}`])).toHaveLength(0);
+ expect((await getWriteRequest(tx, principal, params.request_id))?.state ?? null).not.toBe('committed');
});
}
throw error;
@@ -92,13 +94,16 @@ for (const boundary of ['admission-counter', 'completed-withdrawal'] as const) {
const value = Reflect.get(target, property); return typeof value === 'function' ? value.bind(target) : value;
} });
const result = await submitForgetMutation(context(proxy), 'forget', params);
+ // The consumer this forget started publishes through the proxy; the next case starts its own.
+ await disposePersistenceConsumer(proxy);
expect(result).toMatchObject({ state: 'committed', expired: true, request_id: params.request_id });
- expect(sourceTransactions).toBe(2); expect(rollbacks).toBe(1);
+ expect(rollbacks).toBe(1);
const after = (await engine.readPageSnapshot(page.slug, { sourceId }))!;
expect(after.revision).not.toBe(page.knowledge_revision!);
expect(await engine.executeRaw('SELECT fact_hash FROM fact_withdrawals WHERE source_id=$1 AND fact_hash=gbrain_fact_fingerprint($2)', [sourceId, `Withdraw ${page.slug}`])).toHaveLength(1);
const row = (await getWriteRequest(engine, principal, params.request_id))!;
- expect(await engine.executeRaw('SELECT id FROM persistence_effects WHERE request_id=$1::uuid', [row.id])).toHaveLength(3);
+ // No withdrawal mirror: the publication itself is the withdrawal (a source with no checkout queues its embedding only).
+ expect((await engine.executeRaw<{ kind: string }>('SELECT kind FROM persistence_effects WHERE request_id=$1::uuid ORDER BY kind', [row.id])).map(e => e.kind)).toEqual(['embedding']);
const [counter] = await engine.executeRaw<{ lifetime_ids: string; outstanding_count: string }>("SELECT lifetime_ids::text,outstanding_count::text FROM persistence_counters WHERE key='brain'");
expect(Number(counter.lifetime_ids)).toBe(Number(before?.lifetime_ids ?? 0) + 1);
expect(Number(counter.outstanding_count)).toBe(0);
diff --git a/test/withdrawal-followup-writes.test.ts b/test/withdrawal-followup-writes.test.ts
index df899c1b3c..61ca769505 100644
--- a/test/withdrawal-followup-writes.test.ts
+++ b/test/withdrawal-followup-writes.test.ts
@@ -1,16 +1,17 @@
/**
- * A forget queues its file mirror and rebuild work after it commits; the CLI
- * process that committed it exits without running any of it. These pin what
+ * GBRA-190 G4: a forget is a coordinated publication that strikes the page's
+ * file before it commits (no withdrawal mirror runs after it); the CLI process
+ * that committed it exits without running its queued effects. These pin what
* the next caller sees:
- * - a write to the withdrawn page is not prepared while its mirror is queued,
- * so the mirror cannot change the file under an accepted request (N5-3);
- * - a withdrawal that commits while a write is preparing makes that write
- * reprepare instead of failing as an uncoordinated file edit;
+ * - the file already holds the struck row, so a write to the withdrawn page
+ * commits first time and nothing rewrites the file under it (N5-3);
+ * - a forget submitted while a write to the page is in flight queues behind it,
+ * and both commit first time, neither failing as an uncoordinated file edit;
* - the acknowledged forget leaves the page's retained text searchable (N5-2).
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -24,7 +25,6 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { submissionAuthority } from '../src/core/persistence/authority.ts';
import { admitWrite, claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';
import { publishMutation } from '../src/core/persistence/coordinator.ts';
-import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
import { prepareMemoryMutation, submitForgetMutation, submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
@@ -73,7 +73,7 @@ async function entity(engine: BrainEngine) {
expect([forgotten.state, retained.state]).toEqual(['committed', 'committed']);
// The committing process exits: nothing drains queued effects in-process.
await disposePersistenceConsumer(engine);
- return { ctx, sourceId, slug, binding, forgottenId: String(forgotten.id) };
+ return { ctx, sourceId, slug, binding, forgottenId: String(forgotten.id), file };
}
async function admitCorrection(engine: BrainEngine, f: Awaited<ReturnType<typeof entity>>) {
@@ -93,29 +93,38 @@ async function claimAndPublish(engine: BrainEngine, f: Awaited<ReturnType<typeof
}
describe('writes after a forget whose effects stay queued, both engines', () => {
- test('a write to the withdrawn page waits for its queued mirror, then commits first time', async () => {
+ test('a forget strikes the file before it commits, so a write to the withdrawn page commits first time', async () => {
for (const engine of engines) {
const f = await entity(engine);
expect(await submitForgetMutation(f.ctx, 'forget', { id: f.forgottenId, reason: 'test' })).toMatchObject({ state: 'committed' });
+ await disposePersistenceConsumer(engine);
+ const struck = readFileSync(f.file, 'utf8');
+ expect(struck).toContain('~~Keeps bees followupaaaa~~');
+ expect(struck).toContain('forgotten:');
+ expect(await engine.executeRaw(`SELECT 1 FROM persistence_effects WHERE source_id=$1 AND kind='withdrawal-mirror'`, [f.sourceId])).toHaveLength(0);
const admitted = await admitCorrection(engine, f);
- expect(await claimNextWrite(engine, hostId)).toBeNull();
- await runPersistenceEffects(engine, f.ctx.config, { hostId, limit: 20 });
expect((await claimAndPublish(engine, f, admitted.id)).state).toBe('committed');
+ expect(readFileSync(f.file, 'utf8')).toContain('~~Keeps bees followupaaaa~~');
}
});
- test('a withdrawal committed during preparation makes the write reprepare, not fail as a file edit', async () => {
+ test('a forget submitted while a write to the page is in flight queues behind it, and both commit first time', async () => {
for (const engine of engines) {
const f = await entity(engine);
const admitted = await admitCorrection(engine, f);
const row = (await claimNextWrite(engine, hostId))!;
expect(row.id).toBe(admitted.id);
const prepared = await prepareMemoryMutation(engine, row, f.ctx.config);
- expect(await submitForgetMutation(f.ctx, 'forget', { id: f.forgottenId, reason: 'test' })).toMatchObject({ state: 'committed' });
- await runPersistenceEffects(engine, f.ctx.config, { hostId, limit: 20 });
+ const forget = { id: f.forgottenId, reason: 'test', request_id: randomUUID() };
+ const pending = await submitForgetMutation(f.ctx, 'forget', forget, 200).catch((error: { writeRequest?: { state?: string } }) => error);
+ expect((pending as { writeRequest?: { state?: string } }).writeRequest?.state).toBe('queued');
const first = await publishMutation(engine, row, prepared, hostId);
- expect({ state: first.state, error: first.error_code }).toEqual({ state: 'queued', error: null });
- expect((await claimAndPublish(engine, f, admitted.id)).state).toBe('committed');
+ expect({ state: first.state, error: first.error_code }).toEqual({ state: 'committed', error: null });
+ expect(await submitForgetMutation(f.ctx, 'forget', forget, 30_000)).toMatchObject({ state: 'committed' });
+ await disposePersistenceConsumer(engine);
+ const text = readFileSync(f.file, 'utf8');
+ expect(text).toContain('Gave up beekeeping followupcccc');
+ expect(text).toContain('~~Keeps bees followupaaaa~~');
expect((await getWriteRequestById(engine, admitted.id))!.state).toBe('committed');
}
});