Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

WIP G4 wave 2: dated withdrawal markers only, streamed segmented strike, test triage for git-first forget

garrytanbc6f1dbc51c1
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index a4a29b9b0b..3e2bc3012b 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -167,15 +167,18 @@ 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
+ * marker (struck, a `valid_until` date and context `forgotten: ...`, as forget writes it) records its withdrawal at that
+ * date, so a brain rebuilt from Git keeps it and the import overlay leaves the row as the file holds it. A struck row
+ * without its date is an expired row with no ledger entry: deriving one would make the next import rewrite the row's
+ * `valid_until`, so the stored body would no longer match the file. 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() }));
+ rows: readonly ParsedFact[]): Promise<number> {
+ const marked = rows.filter(row => !row.active && row.forgotten === true && /^\d{4}-\d{2}-\d{2}$/.test(row.validUntil ?? ''))
+ .map(row => ({ fact: row.claim, visibility: row.visibility, at: `${row.validUntil}T00:00:00Z` }));
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)
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index b707adf643..69e9eb788e 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -622,7 +622,7 @@ export function compileCanonicalProjections(page: ParsedPage, slug: string, sour
const scan=scanCanonicalFences(page);
if(scan.defects.length) throw fenceOperationError(scan.defects[0]!, slug, sourceId);
const fields:Array<[FenceSection,string]>=[['body',page.compiled_truth],['timeline',page.timeline ?? '']];
- return { factRows: extractFactsFromFenceText(scan.facts,slug,sourceId,{ pageEffectiveDate: factDate }), takes: scan.takes, sections: scan.sections, quoted: scan.quoting ? quotedFenceRows(fields) : null };
+ return { fenceFacts: scan.facts, factRows: extractFactsFromFenceText(scan.facts,slug,sourceId,{ pageEffectiveDate: factDate }), takes: scan.takes, sections: scan.sections, quoted: scan.quoting ? quotedFenceRows(fields) : null };
}
/**
@@ -668,7 +668,7 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
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);
+ const { fenceFacts, factRows, takes, quoted, sections } = compileCanonicalProjections(page, slug, sourceId, factDate);
// #6259: a page the content-quality gate hid as junk projects no facts or takes. Rows projected before it
// was quarantined are left as they are (hiding them would need a new row state); only new projection stops.
const projectFences = !isQuarantined(page.frontmatter);
@@ -818,7 +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));
+ if (!factsHeld && ledger?.deriveWithdrawals) await step('withdrawals', () => deriveFenceWithdrawals(tx, sourceId, slug, fenceFacts));
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/forget-prepare.ts b/src/core/persistence/forget-prepare.ts
index 8eb019ca09..89509ad80b 100644
--- a/src/core/persistence/forget-prepare.ts
+++ b/src/core/persistence/forget-prepare.ts
@@ -18,13 +18,13 @@ 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 { isSegmentedPage } 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 { materializedPage } from './segmented-apply.ts';
+import { prepareFileTarget, snapshotLedger, unreadPageFile } from './page-prepare.ts';
import { pageIdentityError } from './page-identity.ts';
import type { CompanionPage, PageMutationFile, PreparedMutation } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
@@ -100,14 +100,21 @@ export async function prepareForgetMutation(engine: BrainEngine, row: WriteReque
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 target = { source_id: sourceId, worktree_id: row.worktree_id, slug, operation: row.operation };
+ if (isSegmentedPage(snapshot.page)) {
+ // A segmented page's file is streamed from its segments under the ledger plus this withdrawal (export's overlay),
+ // never rendered as one string, so a page of any size can be struck.
+ const struckFile = await unreadPageFile(engine, snapshot, undefined, { ...snapshotLedger(snapshot), withdrawals: [...snapshot.withdrawals, withdrawal] });
+ if (struckFile.hash === (await unreadPageFile(engine, snapshot)).hash) return undefined;
+ const file = await prepareFileTarget(engine, target, snapshot, struckFile, undefined, { allowMissing: true, remote });
+ return file && file.content !== null && existsSync(file.path) ? file : undefined;
+ }
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 });
+ const file = await prepareFileTarget(engine, target, 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;
};
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 456616c90e..68861aef8f 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -641,9 +641,8 @@ async function prepareUnreadRestore(engine: BrainEngine, row: WriteRequest, snap
* A withdrawal mirror of a segmented page (effects.ts, effect-recovery.ts) renders its file the same way, with
* `between` (its claim renewal) run after each piece each time the file is produced.
*/
-export async function unreadPageFile(engine: BrainEngine, snapshot: PageSnapshot, between?: () => Promise<void>): Promise<StreamedFileContent> {
+export async function unreadPageFile(engine: BrainEngine, snapshot: PageSnapshot, between?: () => Promise<void>, ledger: BodyLedger = snapshotLedger(snapshot)): Promise<StreamedFileContent> {
const head = serializePageToMarkdown({ ...withoutBody(snapshot.page), compiled_truth: '', timeline: '' }, snapshot.tags).slice(0, -1);
- const ledger = snapshotLedger(snapshot);
const produce = (exec: BrainEngine) => segmentedExportMarkdown(exec, snapshot.page, ledger, head);
return StreamedFileContent.measure(engine, !between ? produce : async function* (exec) { for await (const piece of produce(exec)) { yield piece; await between(); } });
}
diff --git a/test/agent-journey.serial.test.ts b/test/agent-journey.serial.test.ts
index 768ebf5d65..3b6f0945bf 100644
--- a/test/agent-journey.serial.test.ts
+++ b/test/agent-journey.serial.test.ts
@@ -250,7 +250,8 @@ describe('H1a keyless MCP journey (stdio)', () => {
expect(text0.startsWith(NOTICE_PREFIX)).toBe(false);
const result = body(recalled);
expect(JSON.stringify(result)).toContain(MARKER);
- expect(result.results.length).toBe(PAGES);
+ // The imported pages, plus memory/unattributed: a fact remembered without an entity is a row of its fence (GBRA-190 G4).
+ expect(result.results.length).toBe(PAGES + 1);
// The degraded notice is its own prefixed block (the model sees it) and mirrored in _meta.
// A recall that passes only `query` also carries the recall_hint (TC7) naming `question`.
const blocks = noticeBlocks(recalled);
diff --git a/test/ambient-recall.test.ts b/test/ambient-recall.test.ts
index 6bea0222ce..1d240b0b37 100644
--- a/test/ambient-recall.test.ts
+++ b/test/ambient-recall.test.ts
@@ -819,10 +819,11 @@ describe('budget packing + drop footer', () => {
expect(entityAfterRemember.revision).not.toBe(entityBeforeRemember.revision);
// Entity-bound remember publishes a canonical facts fence and advances the
// page revision. Pin this fixture's page clock before the cutoff so the
- // keyset assertions below isolate pages from newer fact/thread records.
+ // keyset assertions below isolate pages from newer fact/thread records. The
+ // facts remembered without an entity publish memory/unattributed (GBRA-190 G4); pin it too.
expect(entityBeforeRemember.page.updated_at.getTime()).toBeLessThan(Date.parse(since));
- await engine.executeRaw('UPDATE pages SET updated_at = $1::timestamptz WHERE source_id = $2 AND slug = $3',
- [entityBeforeRemember.page.updated_at.toISOString(), 'default', 'people/bob-example']);
+ await engine.executeRaw('UPDATE pages SET updated_at = $1::timestamptz WHERE source_id = $2 AND slug = ANY($3::text[])',
+ [entityBeforeRemember.page.updated_at.toISOString(), 'default', ['people/bob-example', 'memory/unattributed']]);
// delta never advances a cursor past now() - 2 s (commit-visibility lag),
// so age the whole fixture a minute to keep the keyset assertions exact.
await engine.executeRaw(`UPDATE pages SET updated_at = updated_at - interval '1 minute'`);
diff --git a/test/belief-ledger-page-at-time.test.ts b/test/belief-ledger-page-at-time.test.ts
index 4d52add74b..fdb7542746 100644
--- a/test/belief-ledger-page-at-time.test.ts
+++ b/test/belief-ledger-page-at-time.test.ts
@@ -22,7 +22,6 @@ import { preimageGaps } from '../src/core/belief/preimages.ts';
import { beliefLedgerEntry } from '../src/commands/doctor/checks/belief-ledger.ts';
import type { DoctorContext } from '../src/commands/doctor/context.ts';
import type { Check } from '../src/commands/doctor.ts';
-import { waitForValue } from './helpers/wait-for.ts';
import { beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain } from './helpers/belief-ledger.ts';
afterEach(() => __setBeliefEmitterFaultForTests(null));
@@ -150,23 +149,26 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
expect(JSON.stringify(history)).not.toContain('Back again.');
}), 120_000);
- test('create, forget, materialize, edit: the pre-forget body, the withdrawn view and the materialized body each answer their own instant', () => brain(async b => {
+ test('create, forget, edit: the pre-forget body and the struck body the withdrawal published each answer their own instant', () => brain(async b => {
await b.put(slug, beliefPage({ prose: 'Profile.', facts: ['Acme raised a seed round', 'Acme has ten staff'] }));
const created = await at(b);
const [fact] = await b.engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_id = $1 AND fact = 'Acme has ten staff' AND expired_at IS NULL`, [b.sourceId]);
const mark = await b.lastId();
await operationsByName.forget!.handler(b.ctx, { id: String(fact!.id), request_id: randomUUID() });
- const materialized = await waitForValue(async () => (await b.events(mark)).find(e => e.cause.op === 'withdrawal_materialize'), { timeoutMs: 30_000, label: 'withdrawal materialization' });
- const afterMaterialize = await at(b);
+ const afterForget = await at(b);
await b.put(slug, beliefPage({ prose: 'Profile, edited.', facts: ['Acme raised a seed round'] }));
const edited = await at(b);
const forget = (await b.events(mark)).find(e => e.cause.op === 'forget' && e.subject_kind === 'page')!;
expect((await read(b, { slug, known_as_of: created })).compiled_truth).toContain('Acme has ten staff');
const history = await versions(b, { slug, known_as_of: edited, include_body: true });
- expect(history.versions.map((v: any) => [v.event, v.body])).toEqual([['page.published', 'live'], ['page.view_changed', 'version'], ['page.view_changed', 'version'], ['page.published', 'version']]);
- expect(history.versions.map((v: any) => v.event_id).slice(1, 3)).toEqual([materialized!.id, forget.id]);
- expect(history.versions[3].compiled_truth).toContain('Acme has ten staff');
- expect((await read(b, { slug, known_as_of: afterMaterialize })).event_id).toBe(materialized!.id);
+ // GBRA-190 G4: the withdrawal publishes the struck file itself; no materialization follows it.
+ expect((await b.events(mark)).filter(e => e.cause.op === 'withdrawal_materialize')).toEqual([]);
+ expect(history.versions.map((v: any) => [v.event, v.body])).toEqual([['page.published', 'live'], ['page.view_changed', 'version'], ['page.published', 'version']]);
+ expect(history.versions[1].event_id).toBe(forget.id);
+ expect(history.versions[2].compiled_truth).toContain('| Acme has ten staff |');
+ const withdrawn = await read(b, { slug, known_as_of: afterForget });
+ expect(withdrawn.event_id).toBe(forget.id);
+ expect(withdrawn.compiled_truth).toContain('~~Acme has ten staff~~');
expect((await read(b, { slug, known_as_of: edited })).compiled_truth).toContain('Profile, edited.');
}), 180_000);
diff --git a/test/belief-ledger-trust.test.ts b/test/belief-ledger-trust.test.ts
index 80b6bdfd1b..4703d3ecab 100644
--- a/test/belief-ledger-trust.test.ts
+++ b/test/belief-ledger-trust.test.ts
@@ -36,7 +36,6 @@ import { lifetimeRef, pageKey } from '../src/core/belief/keys.ts';
import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
-import { waitForValue } from './helpers/wait-for.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { testBackends } from './helpers/test-backends.ts';
import { beliefBrain, beliefEngineCase, beliefPage, readEvents, shape, type BeliefEvent } from './helpers/belief-ledger.ts';
@@ -115,7 +114,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
}
const withHome = (fn: () => Promise<void>) => () => withEnv({ GBRAIN_HOME: home }, fn);
- test('forget: fact.withdrawn and page.view_changed with the pre-withdrawal body kept as a version; materialization is a second view change', withHome(async () => {
+ test('forget: fact.withdrawn and page.view_changed with the pre-withdrawal body kept as a version; the struck body publishes with them', withHome(async () => {
const b = await brain();
const slug = 'companies/acme-example';
await run(b.local, 'put_page', { slug, content: beliefPage({ facts: ['Acme raised a seed round', 'Acme has ten staff'] }) });
@@ -137,14 +136,16 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
const forget = check(await readEvents(b.engine, b.sourceId, mark), before);
const after = String(forget[0]!.value!.revision_after);
expect(after).not.toBe(before);
- // The effect worker materializes the body at the withdrawal's revision: one more view change, and its preimage version.
- const materialized = await waitForValue(async () => (await readEvents(b.engine, b.sourceId, mark)).find(e => e.cause.op === 'withdrawal_materialize'),
- { timeoutMs: 30_000, label: 'withdrawal materialization' });
- expect(materialized).toMatchObject({ event_type: 'page.view_changed', subject_key: pageKey(lifetime), value: { materialized: true, revision_before: after, revision_after: after } });
const versions = await b.engine.executeRaw<{ knowledge_revision: string; compiled_truth: string }>(
'SELECT knowledge_revision::text AS knowledge_revision, compiled_truth FROM page_versions WHERE page_id=$1 ORDER BY id', [await pageId(b, slug)]);
- expect(versions.map(v => v.knowledge_revision)).toEqual([before, after]);
- expect(versions[0]!.compiled_truth).toContain('Acme has ten staff');
+ // GBRA-190 G4: the withdrawal publishes the struck body itself, so the page at its revision is already struck and
+ // nothing materializes later; the pre-withdrawal body is the one version kept.
+ expect(versions.map(v => v.knowledge_revision)).toEqual([before]);
+ expect(versions[0]!.compiled_truth).toContain('| Acme has ten staff |');
+ const struck = await content(b, slug);
+ expect(String(struck.revision)).toBe(after);
+ expect(String(struck.compiled_truth)).toContain('~~Acme has ten staff~~');
+ expect((await readEvents(b.engine, b.sourceId, mark)).filter(e => e.cause.op === 'withdrawal_materialize')).toEqual([]);
// Forced probe: an emitter that records the withdrawal as a plain retraction is caught.
fault(retype('fact.withdrawn', 'fact.retracted'));
const seed = await factId(b, 'Acme raised a seed round');
@@ -153,15 +154,14 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
expect(() => check(forced, current)).toThrow();
}), 120_000);
- test('review #25: the withdrawal, its materialization and an unmanaged forget each leave a commit mark', withHome(async () => {
+ test('review #25: the withdrawal and an unmanaged forget each leave a commit mark', withHome(async () => {
const b = await brain();
const slug = 'companies/acme-example';
await run(b.local, 'put_page', { slug, content: beliefPage({ facts: ['Acme raised a seed round', 'Acme has ten staff'] }) });
const mark = await lastId(b);
await run(b.local, 'forget', { id: String(await factId(b, 'Acme has ten staff')) });
- await waitForValue(async () => (await readEvents(b.engine, b.sourceId, mark)).find(e => e.cause.op === 'withdrawal_materialize'), { timeoutMs: 30_000, label: 'withdrawal materialization' });
const ops = new Set((await readEvents(b.engine, b.sourceId, mark)).map(e => e.cause.op));
- expect([...ops].sort()).toEqual(['forget', 'withdrawal_materialize']);
+ expect([...ops].sort()).toEqual(['forget']);
expect(await unmarkedPublications(b.engine, b.sourceId)).toEqual([]);
await beliefBrain(async u => {
const remembered = await operationsByName.remember!.handler(u.ctx, { fact: 'Dana example likes tea', provenance: 'notes', entity: 'people/dana-example', request_id: randomUUID() }) as Record<string, any>;
diff --git a/test/decide/review-withdraw.serial.test.ts b/test/decide/review-withdraw.serial.test.ts
index 275dfb59ea..91b02f9bb3 100644
--- a/test/decide/review-withdraw.serial.test.ts
+++ b/test/decide/review-withdraw.serial.test.ts
@@ -21,7 +21,6 @@ import { join } from 'node:path';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { resetPgliteState } from '../helpers/reset-pglite.ts';
import { importFromContent } from '../../src/core/import-file.ts';
-import { writeSingleFact } from '../../src/core/facts/write-single.ts';
import { configureGateway, resetGateway, __setDecideTransportForTests, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
import { flushDecideWrites, insertCalibration, __resetDecideStoreForTests } from '../../src/core/ai/decide/store.ts';
import { packShape } from '../../src/core/ai/decide/pack.ts';
@@ -81,10 +80,12 @@ async function qualify(lb = 0.95) {
await engine.executeRaw('UPDATE decide_calibrations SET action_precision_lb = $2 WHERE id = $1', [id, lb]);
}
+/** Through the remember verb: forget claims the source's canonical worktree (GBRA-190 G4), so a legacy direct write would be refused after it. */
async function remember(fact: string, entity: string | null = SLUG, visibility: 'world' | 'private' = 'world'): Promise<number> {
- const r = await writeSingleFact(engine, 'default', { fact, provenance: 'test', entity, kind: 'fact', visibility });
- expect(r.status).toBe('inserted');
- return r.id;
+ const r = await operationsByName.remember!.handler({ engine, config: { engine: 'pglite' }, remote: false, dryRun: false, sourceId: 'default',
+ logger: { info: () => {}, warn: () => {}, error: () => {} } } as never, { fact, provenance: 'test', ...(entity ? { entity } : { infer_entity: false }), kind: 'fact', visibility }) as Record<string, any>;
+ expect(r.state).toBe('committed');
+ return Number(r.id);
}
async function forget(id: number, extra: Record<string, unknown> = {}): Promise<Record<string, any>> {
diff --git a/test/fixtures/agent-contract/v1/journey/recall-degraded.json b/test/fixtures/agent-contract/v1/journey/recall-degraded.json
index 91e4c8ab76..90a27740e0 100644
--- a/test/fixtures/agent-contract/v1/journey/recall-degraded.json
+++ b/test/fixtures/agent-contract/v1/journey/recall-degraded.json
@@ -44,7 +44,7 @@
"content": [
{
"type": "text",
- "text": "{\n \"facts\": [\n {\n \"id\": 1,\n \"fact\": \"quokka-journey-marker is the install-check fact\",\n \"kind\": \"fact\",\n \"entity_slug\": null,\n \"source_id\": \"default\",\n \"visibility\": \"world\",\n \"notability\": \"medium\",\n \"valid_from\": \"{{TIME}}\",\n \"valid_until\": null,\n \"expired_at\": null,\n \"superseded_by\": null,\n \"consolidated_at\": null,\n \"consolidated_into\": null,\n \"source\": \"install-check\",\n \"source_session\": null,\n \"context\": null,\n \"confidence\": 1,\n \"created_at\": \"{{TIME}}\",\n \"fact_id\": \"1\",\n \"provenance\": \"install-check\",\n \"trust_tier\": \"agent_written\",\n \"origin\": \"mcp:remember\"\n }\n ],\n \"total\": 1,\n \"facts_order\": \"newest\",\n \"protocol_version\": 1,\n \"results\": [\n {\n \"slug\": \"journey-note-3\",\n \"title\": \"Journey note 3\",\n \"chunk\": \"# Journey note 3\\n\\nThe quokka-journey-marker 3 lives in note 3.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-3\",\n \"source_id\": \"default\",\n \"trust_tier\": \"operator_curated\",\n \"origin\": \"managed_file_import\"\n },\n {\n \"slug\": \"journey-note-2\",\n \"title\": \"Journey note 2\",\n \"chunk\": \"# Journey note 2\\n\\nThe quokka-journey-marker 2 lives in note 2.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-2\",\n \"source_id\": \"default\",\n \"trust_tier\": \"operator_curated\",\n \"origin\": \"managed_file_import\"\n },\n {\n \"slug\": \"journey-note-1\",\n \"title\": \"Journey note 1\",\n \"chunk\": \"# Journey note 1\\n\\nThe quokka-journey-marker 1 lives in note 1.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-1\",\n \"source_id\": \"default\",\n \"trust_tier\": \"operator_curated\",\n \"origin\": \"managed_file_import\"\n }\n ],\n \"search_degraded\": \"keyword_only_embedding_disabled\"\n}"
+ "text": "{\n \"facts\": [\n {\n \"id\": 1,\n \"fact\": \"quokka-journey-marker is the install-check fact\",\n \"kind\": \"fact\",\n \"entity_slug\": null,\n \"source_id\": \"default\",\n \"visibility\": \"world\",\n \"notability\": \"medium\",\n \"valid_from\": \"{{TIME}}\",\n \"valid_until\": null,\n \"expired_at\": null,\n \"superseded_by\": null,\n \"consolidated_at\": null,\n \"consolidated_into\": null,\n \"source\": \"install-check\",\n \"source_session\": null,\n \"context\": null,\n \"confidence\": 1,\n \"created_at\": \"{{TIME}}\",\n \"fact_id\": \"1\",\n \"provenance\": \"install-check\",\n \"trust_tier\": \"agent_written\",\n \"origin\": \"mcp:remember\"\n }\n ],\n \"total\": 1,\n \"facts_order\": \"newest\",\n \"protocol_version\": 1,\n \"results\": [\n {\n \"slug\": \"journey-note-3\",\n \"title\": \"Journey note 3\",\n \"chunk\": \"# Journey note 3\\n\\nThe quokka-journey-marker 3 lives in note 3.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-3\",\n \"source_id\": \"default\",\n \"trust_tier\": \"operator_curated\",\n \"origin\": \"managed_file_import\"\n },\n {\n \"slug\": \"journey-note-2\",\n \"title\": \"Journey note 2\",\n \"chunk\": \"# Journey note 2\\n\\nThe quokka-journey-marker 2 lives in note 2.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-2\",\n \"source_id\": \"default\",\n \"trust_tier\": \"operator_curated\",\n \"origin\": \"managed_file_import\"\n },\n {\n \"slug\": \"journey-note-1\",\n \"title\": \"Journey note 1\",\n \"chunk\": \"# Journey note 1\\n\\nThe quokka-journey-marker 1 lives in note 1.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-1\",\n \"source_id\": \"default\",\n \"trust_tier\": \"operator_curated\",\n \"origin\": \"managed_file_import\"\n },\n {\n \"slug\": \"memory/unattributed\",\n \"title\": \"Unattributed memory\",\n \"chunk\": \"## Facts\\n\\n<!--- gbrain:facts:begin -->\\n\\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\\n|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\\n| 1 | quokka-journey-marker is the install-check fact | fact | 1.0 | world | medium | {{TIME}} | | install-check | |\\n<!--- gbrain:facts:end -->\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"memory/unattributed\",\n \"source_id\": \"default\",\n \"trust_tier\": \"agent_written\",\n \"origin\": \"mcp:remember\"\n }\n ],\n \"search_degraded\": \"keyword_only_embedding_disabled\"\n}"
},
{
"type": "text",
diff --git a/test/g4-forget-fence-edit.test.ts b/test/g4-forget-fence-edit.test.ts
new file mode 100644
index 0000000000..4c7579e77b
--- /dev/null
+++ b/test/g4-forget-fence-edit.test.ts
@@ -0,0 +1,202 @@
+/**
+ * GBRA-190 G4: forget is a fence edit, and the withdrawal ledger is derived from Git.
+ * - A withdrawal that strikes several pages is one coordinated publication: every struck file lands in one door commit
+ * on a strict source, before the ledger row and expiries commit, and no withdrawal-mirror effect is queued (D2).
+ * - Interrupted before its commit, recovery restores every file of its version 3 record and the replay commits once;
+ * interrupted after it, the committed files are kept and the replay completes against them.
+ * - Remember linking a fact saved without an entity strikes its memory/unattributed row in the same commit (D3).
+ * - A trusted local import of a withdrawal marker records its ledger row, so a brain rebuilt from Git keeps the
+ * withdrawal; subject '*' only for memory/unattributed rows, the page's slug otherwise. A remote page write carrying
+ * the marker records no ledger row and blocks no remember (D1).
+ * Runs on PGLite and, with DATABASE_URL, on Postgres.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { isFactWithdrawn } from '../src/core/facts/withdrawal.ts';
+import { durableGitRepo, git } from './helpers/git-publication.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const CLAIM = 'Keeps a rooftop beehive g4claim';
+const OTHER = 'Moved the hives indoors g4other';
+const today = new Date().toISOString().slice(0, 10);
+const fence = (rows: string[]) => ['<!--- gbrain:facts:begin -->',
+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|', ...rows, '<!--- gbrain:facts:end -->'].join('\n');
+const note = (title: string, rows: string[], type = 'note') => `---\ntype: ${type}\ntitle: ${title}\n---\n\nNotes.\n\n## Facts\n\n${fence(rows)}\n`;
+/** notes/a holds CLAIM as a row superseded by OTHER: no active entity-linked copy, so forgetting the unlinked copy is allowed. */
+const SUPERSEDED = [`| 1 | ~~${CLAIM}~~ | fact | 1.0 | world | medium | 2026-01-01 | 2026-02-01 | test | superseded by #2 |`,
+ `| 2 | ${OTHER} | fact | 1.0 | world | medium | 2026-02-01 | | test | |`];
+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };
+const strict = (engine: BrainEngine) => engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id='default'`);
+const call = (ctx: OperationContext, name: string, params: Record<string, unknown>) =>
+ operationsByName[name]!.handler(ctx, { request_id: randomUUID(), wait_ms: 30_000, ...params }) as Promise<Record<string, any>>;
+const interruption = (code: string) => Object.assign(new Error(`database interruption ${code}`), { code });
+const commitsTouching = (root: string, rel: string) => git(root, 'log', '--format=%H', '--', rel).split('\n').filter(Boolean);
+const ledger = async (engine: BrainEngine, claim: string) => (await engine.executeRaw<{ subject: string }>(
+ `SELECT subject FROM fact_withdrawals WHERE source_id='default' AND fact_hash=gbrain_fact_fingerprint($1) ORDER BY subject`, [claim])).map(row => row.subject);
+const unlinkedFactId = async (engine: BrainEngine) => (await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM facts WHERE source_id='default' AND entity_slug IS NULL AND fact=$1 AND expired_at IS NULL`, [CLAIM]))[0]?.id;
+
+/** notes/a (CLAIM superseded) and CLAIM remembered without an entity (a row of memory/unattributed). Returns that fact's id. */
+async function twoPagesCarryingTheClaim(ctx: OperationContext, engine: BrainEngine): Promise<number> {
+ expect(await call(ctx, 'put_page', { slug: 'notes/a', content: note('A', SUPERSEDED) })).toMatchObject({ state: 'committed' });
+ expect(await call(ctx, 'remember', { fact: CLAIM, provenance: 'test', visibility: 'world', infer_entity: false })).toMatchObject({ state: 'committed', entity_slug: null });
+ const id = await unlinkedFactId(engine);
+ expect(id).toBeDefined();
+ return Number(id);
+}
+
+for (const backend of testBackends()) describe(`[${backend}] G4: forget is a fence edit`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ test('a withdrawal that strikes two pages lands in one door commit, before its ledger row; no mirror is queued', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const id = await twoPagesCarryingTheClaim(ctx, engine);
+ const requestId = randomUUID();
+ const seen: { files?: string[]; ledger?: number } = {};
+ installFaultHook(async (point, detail) => {
+ if (point !== 'publication:before_commit' || detail.requestId !== requestId) return;
+ seen.files = git(root, 'show', '--name-only', '--format=', 'HEAD').split('\n').filter(Boolean).sort();
+ });
+ try {
+ const done = await call(ctx, 'forget', { id: String(id), request_id: requestId });
+ expect(done).toMatchObject({ state: 'committed', expired: true });
+ expect(done.persistence).toMatchObject({ git_state: 'committed' });
+ // The commit holding both struck files existed inside the publication transaction, before the row.
+ expect(seen.files).toEqual(['memory/unattributed.md', 'notes/a.md']);
+ expect(done.persistence.git_commit).toBe(git(root, 'rev-parse', 'HEAD').trim());
+ } finally { installFaultHook(undefined); }
+ for (const rel of ['memory/unattributed.md', 'notes/a.md']) {
+ const text = readFileSync(join(root, rel), 'utf8');
+ expect(text).toContain(`~~${CLAIM}~~`);
+ expect(text).toContain('forgotten:');
+ expect(git(root, 'status', '--porcelain', '--', rel)).toBe('');
+ }
+ expect(commitsTouching(root, 'notes/a.md')[0]).toBe(commitsTouching(root, 'memory/unattributed.md')[0]);
+ expect(await ledger(engine, CLAIM)).toEqual(['*']);
+ const [request] = await engine.executeRaw<{ id: string }>('SELECT id FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ expect(await engine.executeRaw(`SELECT kind FROM persistence_effects WHERE request_id=$1::uuid AND kind='withdrawal-mirror'`, [request!.id])).toHaveLength(0);
+ }, { databaseUrl, setup }), 180_000);
+
+ test('interrupted before its commit, recovery restores both files of its version 3 record and the replay commits once', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const id = await twoPagesCarryingTheClaim(ctx, engine);
+ const before = { a: commitsTouching(root, 'notes/a.md').length, m: commitsTouching(root, 'memory/unattributed.md').length };
+ const requestId = randomUUID();
+ const at: { record?: { version?: number; files?: unknown[] }; restored?: string[] } = {};
+ let thrown = 0;
+ installFaultHook(async (point, detail) => {
+ if (detail.requestId !== requestId) return;
+ // The record is durable before any file is written (read outside the publication transaction).
+ if (point === 'publication:prepared' && !thrown && !at.record) {
+ at.record = (await engine.executeRaw<{ recovery: { version: number; files: unknown[] } }>('SELECT recovery FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]!.recovery;
+ }
+ if (point === 'publication:after_publication' && !thrown) { thrown++; throw interruption('CONNECTION_CLOSED'); }
+ if (point === 'publication:prepared' && thrown && !at.restored) at.restored = ['notes/a.md', 'memory/unattributed.md'].map(rel => readFileSync(join(root, rel), 'utf8'));
+ });
+ try {
+ expect(await call(ctx, 'forget', { id: String(id), request_id: requestId })).toMatchObject({ state: 'committed' });
+ } finally { installFaultHook(undefined); }
+ expect(thrown).toBe(1);
+ expect(at.record).toMatchObject({ version: 3, target: 'pages' });
+ expect(at.record!.files).toHaveLength(2);
+ // The retry prepared against the restored prior bytes of both files.
+ for (const text of at.restored!) expect(text).not.toContain('forgotten:');
+ expect(commitsTouching(root, 'notes/a.md')).toHaveLength(before.a + 1);
+ expect(commitsTouching(root, 'memory/unattributed.md')).toHaveLength(before.m + 1);
+ expect(commitsTouching(root, 'notes/a.md')[0]).toBe(commitsTouching(root, 'memory/unattributed.md')[0]);
+ expect(git(root, 'show', 'HEAD:notes/a.md')).toContain('forgotten:');
+ expect(await ledger(engine, CLAIM)).toEqual(['*']);
+ }, { databaseUrl, setup }), 180_000);
+
+ test('interrupted after its commit, the committed files are kept and the replay completes against that one commit', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const id = await twoPagesCarryingTheClaim(ctx, engine);
+ const requestId = randomUUID();
+ let crash = '';
+ installFaultHook(async (point, detail) => {
+ if (point === 'publication:before_commit' && detail.requestId === requestId && !crash) { crash = git(root, 'rev-parse', 'HEAD').trim(); throw interruption('CONNECTION_CLOSED'); }
+ });
+ try {
+ expect(await call(ctx, 'forget', { id: String(id), request_id: requestId })).toMatchObject({ state: 'committed' });
+ } finally { installFaultHook(undefined); }
+ expect(crash).not.toBe('');
+ expect(commitsTouching(root, 'notes/a.md')[0]).toBe(crash);
+ expect(commitsTouching(root, 'memory/unattributed.md')[0]).toBe(crash);
+ const [receipt] = await engine.executeRaw<{ outcome: Record<string, any> }>('SELECT outcome FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ expect(receipt!.outcome.persistence).toMatchObject({ git_commit: crash });
+ expect(await ledger(engine, CLAIM)).toEqual(['*']);
+ }, { databaseUrl, setup }), 180_000);
+
+ test('remember linking a fact saved without an entity strikes its memory/unattributed row in the same commit', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ expect(await call(ctx, 'put_page', { slug: 'people/alice-example', content: '---\ntype: person\ntitle: Alice Example\n---\n\nFictional.\n' })).toMatchObject({ state: 'committed' });
+ const unlinked = await call(ctx, 'remember', { fact: CLAIM, provenance: 'test', visibility: 'world', infer_entity: false });
+ const linked = await call(ctx, 'remember', { fact: CLAIM, provenance: 'test', visibility: 'world', entity: 'people/alice-example' });
+ expect(linked).toMatchObject({ state: 'committed', status: 'superseded', superseded_fact_id: unlinked.id });
+ const head = git(root, 'show', '--name-only', '--format=', 'HEAD').split('\n').filter(Boolean).sort();
+ expect(head).toEqual(['memory/unattributed.md', 'people/alice-example.md']);
+ const unattributed = readFileSync(join(root, 'memory/unattributed.md'), 'utf8');
+ expect(unattributed).toContain(`~~${CLAIM}~~`);
+ expect(unattributed).toContain('linked to people/alice-example');
+ expect(readFileSync(join(root, 'people/alice-example.md'), 'utf8')).toContain(`| ${CLAIM} |`);
+ // A re-import of the struck row keeps the old fact retired and records no withdrawal.
+ expect((await engine.executeRaw<{ active: boolean }>('SELECT expired_at IS NULL AS active FROM facts WHERE id=$1', [Number(unlinked.id)]))[0]!.active).toBe(false);
+ expect(await ledger(engine, CLAIM)).toEqual([]);
+ }, { databaseUrl, setup }), 180_000);
+
+ test('a brain rebuilt from Git keeps the withdrawal: the local import derives the ledger from the markers', async () => {
+ const copy = mkdtempSync(join(tmpdir(), 'gbrain-g4-rebuild-'));
+ try {
+ await managedBrain(async ({ engine, ctx, root }) => {
+ const id = await twoPagesCarryingTheClaim(ctx, engine);
+ expect(await call(ctx, 'forget', { id: String(id) })).toMatchObject({ state: 'committed' });
+ const { settleManagedGitEffects } = await import('./helpers/managed-brain.ts');
+ await settleManagedGitEffects(engine);
+ expect(git(root, 'status', '--porcelain')).toBe('');
+ execFileSync('git', ['clone', '-q', root, join(copy, 'repo')]);
+ }, { databaseUrl, setup });
+ await managedBrain(async ({ engine, ctx }) => {
+ expect((await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
+ // memory/unattributed rows are withdrawn for every subject; a page's own marker for that page's subject.
+ expect(await ledger(engine, CLAIM)).toEqual(['*', 'notes/a']);
+ expect(await isFactWithdrawn(engine, 'default', 'world', CLAIM, null)).toBe(true);
+ const again = await call(ctx, 'remember', { fact: CLAIM, provenance: 'test', visibility: 'world', infer_entity: false }).catch((error: { code?: string; message?: string }) => error);
+ expect(String((again as { message?: string }).message)).toContain('fact_withdrawn');
+ }, { databaseUrl, setup: ({ root }) => { rmSync(root, { recursive: true, force: true }); execFileSync('git', ['clone', '-q', join(copy, 'repo'), root]); } });
+ } finally { rmSync(copy, { recursive: true, force: true }); }
+ }, 240_000);
+
+ test('a local page write of a withdrawal marker records it under the page; a remote one records nothing and blocks no remember', () => managedBrain(async ({ engine, ctx }) => {
+ const marked = (claim: string) => [`| 1 | ~~${claim}~~ | fact | 1.0 | world | medium | 2026-01-01 | ${today} | test | forgotten: no longer true |`];
+ const clientId = `client-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id) VALUES($1,'fixture-hash','example-client','read write','default')`, [clientId]);
+ const remote = { ...ctx, remote: true, transport: 'http', auth: { token: 'fixture', clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['read', 'write'], sourceId: 'default' } } as OperationContext;
+ const REMOTE = 'Remote marker claim g4remote', LOCAL = 'Local marker claim g4local';
+ expect(await call(remote, 'put_page', { slug: 'notes/remote', content: note('Remote', marked(REMOTE)) })).toMatchObject({ state: 'committed' });
+ expect(await ledger(engine, REMOTE)).toEqual([]);
+ expect((await engine.executeRaw<{ active: boolean }>(`SELECT expired_at IS NULL AS active FROM facts WHERE source_id='default' AND fact=$1`, [REMOTE]))[0]!.active).toBe(false);
+ expect(await call(ctx, 'remember', { fact: REMOTE, provenance: 'test', visibility: 'world', entity: 'notes/remote' })).toMatchObject({ state: 'committed' });
+ expect(await call(ctx, 'put_page', { slug: 'notes/local', content: note('Local', marked(LOCAL)) })).toMatchObject({ state: 'committed' });
+ expect(await ledger(engine, LOCAL)).toEqual(['notes/local']);
+ const refused = await call(ctx, 'remember', { fact: LOCAL, provenance: 'test', visibility: 'world', entity: 'notes/local' }).catch((error: { message?: string }) => error);
+ expect(String((refused as { message?: string }).message)).toContain('fact_withdrawn');
+ // A struck, forgotten row without its valid_until date is not the marker forget writes: no ledger row, so the next
+ // import's withdrawal overlay never dates the row and the stored body stays the file's.
+ const UNDATED = 'Undated marker claim g4undated';
+ const undated = note('Undated', [`| 1 | ~~${UNDATED}~~ | fact | 1.0 | world | medium | 2026-01-01 | | test | forgotten: no longer true |`]);
+ expect(await call(ctx, 'put_page', { slug: 'notes/undated', content: undated })).toMatchObject({ state: 'committed' });
+ expect(await ledger(engine, UNDATED)).toEqual([]);
+ expect((await engine.readPageSnapshot('notes/undated', { sourceId: 'default' }))!.page.compiled_truth).toContain(`| ~~${UNDATED}~~ | fact | 1.0 | world | medium | 2026-01-01 | |`);
+ }, { databaseUrl, setup }), 180_000);
+});
diff --git a/test/google-attachment-backfill.test.ts b/test/google-attachment-backfill.test.ts
index 562b8a00cd..96e1f8a0aa 100644
--- a/test/google-attachment-backfill.test.ts
+++ b/test/google-attachment-backfill.test.ts
@@ -12,6 +12,7 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
import { localHostId } from '../src/core/persistence/identity.ts';
import { submitForgetMutation } from '../src/core/persistence/memory-mutations.ts';
+import { legacyForget } from './helpers/legacy-forget.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { renderFactsTable } from '../src/core/facts-fence.ts';
import { sanitizeRemoteBody } from '../src/core/remote-body.ts';
@@ -193,7 +194,9 @@ test('withdrawal wins after receipt preparation but before real canonical public
expect(claimed.id).toBe(admitted.id);
const prepared = await prepareConnectorMutation(engine, claimed);
const [fact] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 ORDER BY id LIMIT 1', [f.id]);
- await submitForgetMutation(ctx(engine, f.id), 'forget_fact', { id: Number(fact.id) });
+ // A current forget queues behind the claimed request on its root; a gbrain before G4 sharing the brain still commits
+ // its withdrawal database-first, at any moment (test/helpers/legacy-forget.ts).
+ await legacyForget(ctx(engine, f.id), Number(fact.id));
const result = await publishMutation(engine, claimed, prepared);
expect(result.state).toBe('conflict');
const current = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
diff --git a/test/helpers/legacy-forget.ts b/test/helpers/legacy-forget.ts
new file mode 100644
index 0000000000..dbea8c4d37
--- /dev/null
+++ b/test/helpers/legacy-forget.ts
@@ -0,0 +1,35 @@
+/**
+ * What a gbrain before GBRA-190 G4 left for a `forget`: the withdrawal committed database-first in the request's own
+ * transaction (ledger row, expiries, chunk invalidation) with withdrawal-mirror, git and embedding effects queued to
+ * strike and commit the page files afterwards (recordFactWithdrawal with `requestId`). A current forget publishes the
+ * struck files first and queues no mirror; the effect only drains rows like these, so tests of that drain seed them here.
+ */
+import { randomUUID } from 'node:crypto';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { recordFactWithdrawal } from '../../src/core/facts/withdrawal.ts';
+import { requestAttribution } from '../../src/core/persistence/attribution.ts';
+import { submissionAuthority } from '../../src/core/persistence/authority.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { admitWriteInTransaction, completeWrite } from '../../src/core/persistence/journal.ts';
+import type { WriteRequest } from '../../src/core/persistence/model.ts';
+import { initializeLocalPersistence, requestPrincipalForContext } from '../../src/core/persistence/page-mutations.ts';
+
+export async function legacyForget(ctx: OperationContext, id: number): Promise<WriteRequest> {
+ const sourceId = ctx.sourceId ?? 'default';
+ await initializeLocalPersistence(ctx);
+ const principal = await requestPrincipalForContext(ctx);
+ const [fact] = await ctx.engine.executeRaw<{ slug: string }>(
+ "SELECT COALESCE(source_markdown_slug, entity_slug, 'memory/unattributed') AS slug FROM facts WHERE id=$1 AND source_id=$2", [id, sourceId]);
+ if (!fact) throw new Error(`legacyForget: no fact #${id} in source ${sourceId}`);
+ return ctx.engine.transaction(async tx => {
+ const [source] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);
+ const authority = await submissionAuthority({ ...ctx, engine: tx }, 'forget', sourceId, source!.incarnation, fact.slug);
+ const callerIntent = { id: String(id) };
+ const row = await admitWriteInTransaction(tx, { principal, operation: 'forget', sourceId, sourceIncarnation: source!.incarnation,
+ slug: fact.slug, requestId: randomUUID(), callerIntent, intent: { ...callerIntent, reason: null }, authority });
+ return withCoordinatedWrite(tx, [sourceId], async () => {
+ await recordFactWithdrawal(tx, id, sourceId, ctx.remote !== false, { requestId: row.id });
+ return completeWrite(tx, row, 'committed', { id: String(id), expired: true, reason: null, protocol_version: 1, persistence: { mode: 'database' } });
+ }, requestAttribution(row));
+ });
+}
diff --git a/test/large-pages/segmented-withdrawal-mirror.test.ts b/test/large-pages/segmented-withdrawal-mirror.test.ts
index f96969ae83..acf2d13c66 100644
--- a/test/large-pages/segmented-withdrawal-mirror.test.ts
+++ b/test/large-pages/segmented-withdrawal-mirror.test.ts
@@ -183,7 +183,7 @@ for (const kind of testBackends()) {
expect(work.largestPiece).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);
}, 600_000);
- test('forget_fact rewrites the segmented file with the row withdrawn, as the inline twin\'s, and commits it', async () => {
+ test('forget_fact publishes the segmented file with the row withdrawn, as the inline twin\'s, and commits it', async () => {
const before = { [INLINE]: readFileSync(fileOf(brain, INLINE), 'utf8'), [SEGMENTED]: readFileSync(fileOf(brain, SEGMENTED), 'utf8') };
const receipts: Record<string, string> = {};
const reads = watchWholeReads(fileOf(brain, SEGMENTED));
@@ -194,11 +194,14 @@ for (const kind of testBackends()) {
if (slug === INLINE) resetWork();
await settle(brain, kind);
} } finally { reads.restore(); }
- const wholeReads = reads.hits;
+ // The struck file is streamed from the segments; the one whole read is the prior file every page publication's
+ // recovery record embeds below PAGE_MAX_BYTES (coordinator.ts pageRecoveryRecord), as an append or edit of this page does.
+ const wholeReads = reads.hits.filter(hit => !hit.includes('at pageRecoveryRecord '));
const work = { ...largeFileWork };
expect(await effectsOf(brain, receipts[SEGMENTED]!)).toEqual(await effectsOf(brain, receipts[INLINE]!));
- expect(await effectsOf(brain, receipts[SEGMENTED]!)).toEqual(SETTLED);
+ // GBRA-190 G4: forget_fact strikes the file in its own publication; only purge_fact still mirrors.
+ expect(await effectsOf(brain, receipts[SEGMENTED]!)).toEqual(SETTLED.filter(effect => effect.kind !== 'withdrawal-mirror'));
const file = readFileSync(fileOf(brain, SEGMENTED));
expect(file.toString('utf8')).not.toBe(before[SEGMENTED]);
expect(readFileSync(fileOf(brain, INLINE), 'utf8')).not.toBe(before[INLINE]);
diff --git a/test/managed-maintenance.test.ts b/test/managed-maintenance.test.ts
index 75ca8f382c..fd43ad2181 100644
--- a/test/managed-maintenance.test.ts
+++ b/test/managed-maintenance.test.ts
@@ -16,7 +16,7 @@ import { disposePersistenceConsumer, startPersistenceConsumer } from '../src/cor
import { claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';
import { publishMutation } from '../src/core/persistence/coordinator.ts';
import { localHostId, revokeLocalWriter } from '../src/core/persistence/identity.ts';
-import { submitForgetMutation } from '../src/core/persistence/memory-mutations.ts';
+import { legacyForget } from './helpers/legacy-forget.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { readJournalLimits } from '../src/core/persistence/limits.ts';
@@ -420,8 +420,10 @@ for (const failure of ['commit', 'withdrawal'] as const) {
const prepared = await prepareMaintenanceMutation(engine, row, { engine: engine.kind, embedding_disabled: true });
if (failure === 'withdrawal') {
const [fact] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 ORDER BY id LIMIT 1', [sourceId]);
- await submitForgetMutation({ engine, sourceId, remote: false, config: { engine: engine.kind }, dryRun: false,
- logger: { info() {}, warn() {}, error() {} } }, 'forget', { id: Number(fact.id), request_id: randomUUID() });
+ // A current forget queues behind the claimed request on its root; a gbrain before G4 sharing the brain still commits
+ // its withdrawal database-first, at any moment (test/helpers/legacy-forget.ts).
+ await legacyForget({ engine, sourceId, remote: false, config: { engine: engine.kind }, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } }, Number(fact.id));
}
const outcome = await publishMutation(engine, row, prepared, localHostId(), { boundary: async name => {
if (failure === 'commit' && name === 'before_commit') throw new Error('Injected fixture commit failure');
diff --git a/test/pathological/c1-effect-stuck-recovery.test.ts b/test/pathological/c1-effect-stuck-recovery.test.ts
index 5774ba7ec0..98872795ef 100644
--- a/test/pathological/c1-effect-stuck-recovery.test.ts
+++ b/test/pathological/c1-effect-stuck-recovery.test.ts
@@ -1,7 +1,8 @@
/**
* GBRA-130 C-1 / A-16: a withdrawal-mirror effect stuck in recovery after a hand edit.
*
- * Protects: a `forget` whose mirror crashed after writing the file, followed by a hand edit of that file (it matches
+ * Protects: a `forget` queued by a gbrain before GBRA-190 G4 (test/helpers/legacy-forget.ts; a current forget publishes
+ * its files itself and the mirror only drains such rows) whose mirror crashed after writing the file, followed by a hand edit of that file (it matches
* neither the pre-withdrawal nor the withdrawn bytes), blocks every write on the worktree. `gbrain repair
* stuck-recovery` resolves it with `--keep withdrawn` only: the preview lists the file, both fingerprints and the
* request; the apply is bound to the preview hash, backs the edited bytes up first, writes the recorded withdrawn
@@ -21,7 +22,7 @@ import { execFileSync } from 'node:child_process';
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { BrainEngine } from '../../src/core/engine.ts';
-import { operations } from '../../src/core/operations.ts';
+import { legacyForget } from '../helpers/legacy-forget.ts';
import { performSync } from '../../src/commands/sync/perform.ts';
import { parseFactsFence } from '../../src/core/facts-fence.ts';
import { sha256 } from '../../src/core/persistence/digest.ts';
@@ -79,7 +80,7 @@ async function stuckEffect(databaseUrl: string | undefined, run: (s: StuckEffect
const [fact] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL', [SOURCE, CLAIM]);
let killed = 0;
installFaultHook(async point => { if (point === 'effect_recovery:before_clear' && killed++ === 0) throw new Error('process ended before the mirror commit'); });
- await operations.find(o => o.name === 'forget')!.handler(ctx, { id: Number(fact!.id) });
+ await legacyForget(ctx, Number(fact!.id));
await waitFor(async () => killed > 0, { timeoutMs: 30_000, intervalMs: 50, label: 'mirror killed before commit' });
installFaultHook(undefined);
const file = join(root, 'affected.md');
@@ -197,7 +198,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) {
test('C-1 stale: a later withdrawal on the same page makes the stuck record stale; no interruption of --keep withdrawn publishes a withdrawn fact, and the same apply resumes to resolved', () => stuckEffect(databaseUrl, async s => {
const [second] = await s.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL', [SOURCE, CLAIM_B]);
- await operations.find(o => o.name === 'forget')!.handler(s.b.ctx, { id: Number(second!.id) });
+ await legacyForget(s.b.ctx, Number(second!.id));
const active = async () => (await s.engine.executeRaw<{ fact: string }>('SELECT fact FROM facts WHERE source_id=$1 AND fact = ANY($2::text[]) AND expired_at IS NULL',
[SOURCE, [CLAIM, CLAIM_B]])).map(row => row.fact);
expect(await active()).toEqual([]);
diff --git a/test/pathological/lp-d-recovery-version.test.ts b/test/pathological/lp-d-recovery-version.test.ts
index 3b820fba97..48fadcf83c 100644
--- a/test/pathological/lp-d-recovery-version.test.ts
+++ b/test/pathological/lp-d-recovery-version.test.ts
@@ -2,8 +2,8 @@
* LPH (d) part 1: a recovery record of a version this gbrain does not know is refused, never misread.
*
* 1. Protects: a withdrawal-mirror effect recovery record (persistence_effects.recovery) or a write request recovery
- * record (persistence_requests.recovery) whose `version` this binary does not know (a synthetic version 3, as a
- * future release could write) is refused `recovery_version_unsupported` with fix.next `tell_user_to_run`
+ * record (persistence_requests.recovery) whose `version` this binary does not know (a synthetic effect version 3 or
+ * request version 4, as a future release could write) is refused `recovery_version_unsupported` with fix.next `tell_user_to_run`
* `gbrain upgrade`, before anything reads it: the record stays byte for byte, its streamed stage stays on disk with
* its bytes, the canonical file keeps its bytes, nothing is cleared and the effect keeps retrying (never parks). The
* head blocker names it as needing intervention with the same upgrade fix.
@@ -144,11 +144,11 @@ for (const kind of testBackends()) {
} finally { installFaultHook(undefined); }
}, 600_000);
- test('a version 3 write request recovery record is refused by staging upgrade, file listing and clearing, and left as it is', async () => {
+ test('a version 4 write request recovery record is refused by staging upgrade, file listing and clearing, and left as it is', async () => {
const [request] = await brain.engine.executeRaw<{ id: string; request_id: string; worktree_id: string }>(
`SELECT id::text AS id, request_id::text AS request_id, worktree_id::text AS worktree_id FROM persistence_requests WHERE source_id=$1 AND state='committed' AND worktree_id IS NOT NULL ORDER BY sequence DESC LIMIT 1`, [brain.sourceId]);
// No staging: a version 1 reader's upgradeRecoveryStaging would allocate a restoration stage from `before` and rewrite the record.
- const record = { version: 3, path: fileOf(brain, SEGMENTED), root: brain.root, before: Buffer.from('prior bytes').toString('base64'), beforeHash: sha(Buffer.from('prior bytes')),
+ const record = { version: 4, path: fileOf(brain, SEGMENTED), root: brain.root, before: Buffer.from('prior bytes').toString('base64'), beforeHash: sha(Buffer.from('prior bytes')),
afterHash: sha(readFileSync(fileOf(brain, SEGMENTED))), mode: null, ownerEpoch: '1', attempt: randomUUID(), next: { layout: 'future' } };
// The request protocol trigger admits only the record shapes this schema knows; a newer gbrain's would come with its
// own schema, so the trigger is set aside for this one write (replica role) to model that brain.
diff --git a/test/persistence-memory-mutations.test.ts b/test/persistence-memory-mutations.test.ts
index bcb5aa3ce8..dd12548813 100644
--- a/test/persistence-memory-mutations.test.ts
+++ b/test/persistence-memory-mutations.test.ts
@@ -14,6 +14,8 @@ import { submissionAuthority } from '../src/core/persistence/authority.ts';
import { admitWrite, claimNextWrite, getWriteRequest, getWriteRequestById, receiptFor } from '../src/core/persistence/journal.ts';
import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';
import { waitFor } from './helpers/wait-for.ts';
+import { legacyForget } from './helpers/legacy-forget.ts';
+import { cancelWriteRequest } from '../src/core/persistence/control.ts';
import { publishMutation } from '../src/core/persistence/coordinator.ts';
import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
@@ -354,7 +356,7 @@ describe('journaled memory publication, both engines', () => {
}
});
- test('forget commits offline, withdraws before sealing reads and replays after fact removal', async () => {
+ test('forget waits for an offline owner like every page write, withdraws nothing until it publishes, and replays after fact removal', async () => {
for (const engine of engines) {
const slug = 'people/withdraw-example';
await setupPage(engine, slug);
@@ -364,6 +366,20 @@ describe('journaled memory publication, both engines', () => {
await engine.executeRaw('INSERT INTO persistence_worktrees(id,owner_host_id) VALUES($1::uuid,$2::uuid)', [worktreeId, offlineHost]);
await engine.executeRaw(`INSERT INTO persistence_source_bindings(source_id,source_incarnation,worktree_id)
VALUES($1,$2::uuid,$3::uuid)`, [sourceId, before.sourceIncarnation, worktreeId]);
+ // GBRA-190 G4: a withdrawal is a page publication (Git is the parent), so it waits for the source's owner as
+ // remember does; until it publishes nothing is withdrawn.
+ const local = await registerLocalWriter(engine, 'cli');
+ const principal = { kind: 'local_cli' as const, id: local.id };
+ const offline = randomUUID();
+ const pending = await submitForgetMutation(context(engine), 'forget', { id: remembered.id, request_id: offline }, 200).catch((error: unknown) => error);
+ expect(pending).toMatchObject({ code: 'write_pending' });
+ expect((await getWriteRequest(engine, principal, offline))!.worktree_id).toBe(worktreeId);
+ expect(await engine.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1', [sourceId])).toEqual([]);
+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE id=$1 AND expired_at IS NULL', [Number(remembered.id)])).toHaveLength(1);
+ expect((await engine.readPageSnapshot(slug, { sourceId }))!.revision).toBe(before.revision);
+ expect((await cancelWriteRequest(engine, principal, offline))?.state).toBe('cancelled');
+ // The source is database-only again (its synthetic offline owner unbound): the withdrawal publishes at once.
+ await engine.executeRaw('DELETE FROM persistence_source_bindings WHERE source_id=$1', [sourceId]);
const requestId = randomUUID();
const params = { id: remembered.id, reason: 'User correction', request_id: requestId };
const forgotten = await submitForgetMutation(context(engine), 'forget', params);
@@ -375,17 +391,11 @@ describe('journaled memory publication, both engines', () => {
const chunks = (await engine.getChunks(slug, { sourceId })).map(chunk => chunk.chunk_text).join('\n');
expect(chunks).toContain('Existing biography');
expect(chunks).not.toContain('Withdraw this unique memory');
- const local = await registerLocalWriter(engine, 'cli');
- const request = (await getWriteRequest(engine, { kind: 'local_cli', id: local.id }, requestId))!;
+ const request = (await getWriteRequest(engine, principal, requestId))!;
expect(request.worktree_id).toBeNull();
- expect(await engine.executeRaw('SELECT kind FROM persistence_effects WHERE request_id=$1::uuid', [request.id])).not.toHaveLength(0);
+ expect(await engine.executeRaw("SELECT kind FROM persistence_effects WHERE request_id=$1::uuid AND kind='withdrawal-mirror'", [request.id])).toEqual([]);
await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw('DELETE FROM facts WHERE id=$1', [Number(remembered.id)]), TEST_WRITE_ATTRIBUTION));
expect(await submitForgetMutation(context(engine), 'forget', params)).toEqual(forgotten);
- // The fixture's offline owner is synthetic. Durable effects otherwise
- // deliberately retain their worktree identity until reconciliation.
- await engine.executeRaw('DELETE FROM persistence_effects WHERE worktree_id=$1::uuid', [worktreeId]);
- await engine.executeRaw('DELETE FROM persistence_source_bindings WHERE source_id=$1', [sourceId]);
- await engine.executeRaw('DELETE FROM persistence_worktrees WHERE id=$1::uuid', [worktreeId]);
}
});
@@ -404,7 +414,9 @@ describe('journaled memory publication, both engines', () => {
slug, pageId: snapshot.page.id, callerIntent: p, intent: p, authority, requestId: randomUUID() });
const row = (await claimNextWrite(engine, randomUUID()))!;
const prepared = await prepareMemoryMutation(engine, row, context(engine).config);
- await submitForgetMutation(context(engine), 'forget', { id: String(old.id), request_id: randomUUID() });
+ // A current forget queues behind the claimed remember on its root; a gbrain before G4 sharing the brain still commits
+ // its withdrawal database-first, at any moment. The publication must refuse the withdrawn claim either way.
+ await legacyForget(context(engine), Number(old.id));
const result = await publishMutation(engine, row, prepared);
expect(result.state).not.toBe('committed');
const live = await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL', [sourceId, p.fact]);
diff --git a/test/readiness-embedding-enablement.serial.test.ts b/test/readiness-embedding-enablement.serial.test.ts
index e910158fa5..407a00688b 100644
--- a/test/readiness-embedding-enablement.serial.test.ts
+++ b/test/readiness-embedding-enablement.serial.test.ts
@@ -57,7 +57,7 @@ async function cli(args: string[], home: string, extra: Record<string, string> =
}
}
-/** A keyless brain at `home` (or `--path`), with two imported pages and one DB-only remembered fact. */
+/** A keyless brain at `home` (or `--path`), with two imported pages and one fact remembered without an entity (a row of memory/unattributed). */
async function seed(home: string, initArgs: string[], extra: Record<string, string> = {}): Promise<void> {
const notes = join(home, 'notes');
mkdirSync(notes, { recursive: true });
@@ -106,7 +106,7 @@ async function enableAndVerify(home: string, dbPath: string, keys: Record<string
const model = fix.argv![fix.argv!.indexOf('--embedding-model') + 1];
const dims = Number(fix.argv![fix.argv!.indexOf('--embedding-dimensions') + 1]);
const before = await inspect(dbPath, model, dims);
- expect(before.pages).toBe(2);
+ expect(before.pages).toBe(3);
expect(before.facts).toContain(FACT);
const run = await cli(fix.argv!.slice(1), home, keys);
expect(run.exitCode).toBe(0);
diff --git a/test/receipt-coverage.test.ts b/test/receipt-coverage.test.ts
index 694ce35dd1..e490ced2dd 100644
--- a/test/receipt-coverage.test.ts
+++ b/test/receipt-coverage.test.ts
@@ -28,9 +28,8 @@ type Coverage =
| { sites: number; tables: GuardedTable[]; other: string };
const RECEIPT_COVERAGE: Record<string, Coverage> = {
- 'src/core/persistence/coordinator.ts': { sites: 2, receipted: 'the publication of an admitted request: every maintenance intent (conversation facts, fence reconcile, deleted-page expiry, takes reextract, take reprojection) applies here; a writeback import\'s folded pass stamp (afterEffects, #6712 PR 4b) runs inside that same receipted publication' },
+ 'src/core/persistence/coordinator.ts': { sites: 2, receipted: 'the publication of an admitted request: every maintenance intent and forget/forget_fact (one door commit across every page carrying the fact; conversation facts, fence reconcile, deleted-page expiry, takes reextract, take reprojection) applies here; a writeback import\'s folded pass stamp (afterEffects, #6712 PR 4b) runs inside that same receipted publication' },
'src/core/persistence/group-publish.ts': { sites: 1, receipted: 'the grouped publication of admitted requests; each member is the attributed actor' },
- 'src/core/persistence/memory-mutations.ts': { sites: 1, receipted: 'forget/withdraw: admitWriteInTransaction admits the request in the same transaction' },
'src/core/repair/segmented-mirror.ts': { sites: 1, receipted: 'repair segmented-mirror: admitWriteInTransaction admits each page\'s repair request and completeWrite records its terminal receipt in the same transaction' },
'src/core/facts/purge.ts': { sites: 1, receipted: 'purge_fact: admitWriteInTransaction admits the request and completeWrite records its terminal receipt in the same transaction' },
'src/core/shared-skills/publication.ts': { sites: 1, receipted: 'shared-skill revision pruning inside an admitted skill publication' },
diff --git a/test/sources-mirror-read-only.test.ts b/test/sources-mirror-read-only.test.ts
index 4c86c87aa3..c430ef0da0 100644
--- a/test/sources-mirror-read-only.test.ts
+++ b/test/sources-mirror-read-only.test.ts
@@ -180,22 +180,20 @@ for (const backend of testBackends()) {
expect(existsSync(join(m.root, 'notes/brain-only.md'))).toBe(false);
}), 120_000);
- test('a fact withdrawal in a read-only mirror settles its Git effect as skipped, never failed (Codex review)', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ test('a fact withdrawal in a read-only mirror commits database-only with no Git or mirror effect, never failed (Codex review)', () => withEnv({ GBRAIN_HOME: home }, async () => {
const m = await mirror(true);
await submitPageMutation(ctx(m.id), { operation: 'put_page', params: { slug: 'people/alice-example', request_id: randomUUID(),
content: '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n' } });
const [{ id }] = await engine.transaction(tx => withCoordinatedWrite(tx, [m.id], () => tx.executeRaw<{ id: number }>(
`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source) VALUES ($1, 'people/alice-example', 'Alice prefers mornings', 'preference', 'private', 'test')
RETURNING id::int AS id`, [m.id]), TEST_WRITE_ATTRIBUTION));
- const forgot = await submitForgetMutation(ctx(m.id), 'forget', { id: Number(id), request_id: randomUUID() }) as { request_id: string };
- let effects: Array<{ kind: string; state: string; outcome: Record<string, unknown> | null }> = [];
- for (let i = 0; i < 100; i++) {
- effects = await engine.executeRaw(`SELECT e.kind, e.state, e.outcome FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
- WHERE r.request_id=$1::uuid AND e.kind='git'`, [forgot.request_id]);
- if (effects.length && effects.every(e => e.state !== 'queued' && e.state !== 'running')) break;
- await new Promise(resolve => setTimeout(resolve, 100));
- }
- expect(effects).toEqual([expect.objectContaining({ kind: 'git', state: 'committed', outcome: expect.objectContaining({ git: 'skipped', reason: 'mirror_read_only' }) })]);
+ const forgot = await submitForgetMutation(ctx(m.id), 'forget', { id: Number(id), request_id: randomUUID() }) as { request_id: string; state: string; persistence: unknown };
+ // GBRA-190 G4: a withdrawal is a page publication; a read-only mirror publishes its writes database-only, so nothing
+ // is left for a Git or withdrawal-mirror effect to do.
+ expect(forgot).toMatchObject({ state: 'committed', persistence: { mode: 'database' } });
+ const effects = await engine.executeRaw<{ kind: string }>(`SELECT e.kind FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
+ WHERE r.request_id=$1::uuid AND e.kind IN ('git','withdrawal-mirror')`, [forgot.request_id]);
+ expect(effects).toEqual([]);
expect(tracked(m.root)).toBe('');
}), 120_000);
});
diff --git a/test/write-attribution.test.ts b/test/write-attribution.test.ts
index b1f7f77e3e..970d6a3ebf 100644
--- a/test/write-attribution.test.ts
+++ b/test/write-attribution.test.ts
@@ -242,8 +242,10 @@ describe('write attribution on a managed brain', () => {
expect(row.expired_at).not.toBeNull();
expect(created(row)).toEqual(actor(await requestRow(brain, brain.oauth, remembered), brain.principals.oauth));
expect(last(row)).toEqual(forgetRequest);
- const effects = await engine.executeRaw<{ request_id: string | null }>("SELECT request_id::text FROM persistence_effects WHERE kind='withdrawal-mirror' AND source_id=$1", [brain.sourceId]);
- expect(effects.map(effect => effect.request_id)).toEqual([forgetRequest.request]);
+ // GBRA-190 G4: the withdrawal is the forget request's own page publication (the struck fence row), never a later mirror.
+ const revision = await pageRevisionActor(brain, 'people/alice-example');
+ expect({ request: revision.request, kind: revision.kind, id: revision.id }).toEqual(forgetRequest);
+ expect(await engine.executeRaw("SELECT 1 FROM persistence_effects WHERE kind='withdrawal-mirror' AND source_id=$1", [brain.sourceId])).toEqual([]);
}
}, 120_000);