Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: a remote write cannot plant a forget marker that a rebuild from Git turns into a withdrawal

garrytan8e94793ca455
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index dfe58485ae..c66bdda848 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -1,5 +1,5 @@
import type { BrainEngine } from '../engine.ts';
-import { renderFactsTable, type ParsedFact } from '../facts-fence.ts';
+import { normalizeClaimWhitespace, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, type ParsedFact } from '../facts-fence.ts';
import { OperationError, opError, type WithdrawnDetail } from '../ops/contract.ts';
import { fenceOperationError } from '../fence-repair/refusal.ts';
import { withdrawnFact, withdrawalFenceBlocks } from './withdrawal-overlay.ts';
@@ -204,6 +204,27 @@ export async function deriveFenceWithdrawals(tx: BrainEngine, sourceId: string,
return inserted.length;
}
+/**
+ * A remote write never records a withdrawal, but Git keeps no record of who wrote a row: a forget marker a remote caller
+ * adds would become a withdrawal on the next trusted re-derivation of the file (a rebuild from Git, a reconcile, an
+ * import). So before a remote write is admitted, each marker row the stored page does not already carry (same claim,
+ * visibility and date) loses its `forgotten:` context. The row stays struck: an expired row with no ledger entry, as
+ * the live brain already treats it. A marker the owner wrote survives a remote edit that keeps it.
+ */
+export function remoteWithdrawalMarkersDropped(body: string, stored: readonly string[]): string {
+ const marker = (row: ParsedFact) => !row.active && row.forgotten === true;
+ const key = (row: ParsedFact) => [row.visibility, row.validUntil ?? '', normalizeClaimWhitespace(row.claim)].join('\n');
+ const parsed = parseFactsFence(body);
+ const owned = new Set(stored.flatMap(text => parseFactsFence(text).facts.filter(marker).map(key)));
+ const planted = (row: ParsedFact) => marker(row) && !owned.has(key(row));
+ if (!parsed.facts.some(planted)) return body;
+ if (parsed.warnings.length) throw opError('invalid_params',
+ 'A remote write cannot add a forget marker (a struck Facts row with context "forgotten: ..."), and this Facts table does not parse cleanly enough to drop it.',
+ 'Remove the marker (call forget_fact to forget a claim), fix the Facts table, then submit the content with a new request_id.');
+ return replaceOrInsertFactsFence(body, renderFactsTable(parsed.facts.map(row => planted(row)
+ ? { ...row, forgotten: false, context: row.context?.replace(/^\s*forgotten\s*:\s*/i, '') || undefined } : row)));
+}
+
// 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/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 70eb4b841d..d4671873a5 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -69,6 +69,7 @@ import { DEFAULT_WRITE_GATE_CONFIG, writeGateApplies } from '../write-gate.ts';
import { materializeTimeline, prepareCanonicalProjections, type TimelineRowsRemoved } from './canonical-projections.ts';
import { assertTimelineNotOmitted, timelineWritePolicy } from './timeline-omission.ts';
import { preserveProtectedTakes } from './protected-takes.ts';
+import { remoteWithdrawalMarkersDropped } from '../facts/withdrawal.ts';
import { assertPrivateRequestKept, privateRequestGuarded, readPrivateRequest } from './visibility-request.ts';
import { isAutoLinkEnabled } from '../link-extraction.ts';
import { prepareAutomaticLinks } from './links-preparation.ts';
@@ -860,7 +861,8 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
if (row.authority.remote && row.operation !== 'remember' && !row.operation.startsWith('takes_') && typeof content==='string') {
const parsed=parseMarkdown(content,row.slug,{ activePack });
assertRetirementStampUnchanged(row.slug, parsed.frontmatter, snapshot?.page.frontmatter);
- const compiled_truth=preserveProtectedTakes(parsed.compiled_truth,snapshot?.page.compiled_truth??''), timeline=preserveProtectedTakes(parsed.timeline??'',snapshot?.page.timeline??'');
+ const stored=[snapshot?.page.compiled_truth??'',snapshot?.page.timeline??''];
+ const compiled_truth=remoteWithdrawalMarkersDropped(preserveProtectedTakes(parsed.compiled_truth,stored[0]),stored), timeline=remoteWithdrawalMarkersDropped(preserveProtectedTakes(parsed.timeline??'',stored[1]),stored);
if (compiled_truth!==parsed.compiled_truth || timeline!==(parsed.timeline??'')) content=serializePageToMarkdown({
...(snapshot?.page??{id:0,source_id:row.source_id,created_at:new Date(),updated_at:new Date()}),...parsed,compiled_truth,timeline},parsed.tags);
}
diff --git a/test/g4-forget-fence-edit.test.ts b/test/g4-forget-fence-edit.test.ts
index a5eb685f75..cbd215a5bd 100644
--- a/test/g4-forget-fence-edit.test.ts
+++ b/test/g4-forget-fence-edit.test.ts
@@ -7,7 +7,7 @@
* - 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).
+ * the marker records no ledger row and blocks no remember (D1), and the marker never reaches Git, so a rebuild derives none.
* Runs on PGLite and, with DATABASE_URL, on Postgres.
*/
import { describe, expect, test } from 'bun:test';
@@ -230,4 +230,34 @@ for (const backend of testBackends()) describe(`[${backend}] G4: forget is a fen
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);
+
+ test('a remote write of a withdrawal marker plants nothing a rebuild derives; a remote edit keeps the owner\'s marker', async () => {
+ const copy = mkdtempSync(join(tmpdir(), 'gbrain-g4-remote-rebuild-'));
+ const marked = (claim: string) => `| 1 | ~~${claim}~~ | fact | 1.0 | world | medium | 2026-01-01 | ${today} | test | forgotten: no longer true |`;
+ const REMOTE = 'Remote planted claim g4plant', KEPT = 'Owner forgotten claim g4kept';
+ try {
+ await managedBrain(async ({ engine, ctx, root }) => {
+ 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;
+ expect(await call(ctx, 'put_page', { slug: 'notes/kept', content: note('Kept', [marked(KEPT)]) })).toMatchObject({ state: 'committed' });
+ expect(await ledger(engine, KEPT)).toEqual(['notes/kept']);
+ expect(await call(remote, 'put_page', { slug: 'notes/remote', content: note('Remote', [marked(REMOTE)]) })).toMatchObject({ state: 'committed' });
+ const kept = await engine.readPageSnapshot('notes/kept', { sourceId: 'default' });
+ expect(await call(remote, 'put_page', { slug: 'notes/kept', expected_revision: kept!.revision,
+ content: note('Kept', [marked(KEPT), `| 2 | ${OTHER} | fact | 1.0 | world | medium | 2026-02-01 | | test | |`]) })).toMatchObject({ state: 'committed' });
+ const { settleManagedGitEffects } = await import('./helpers/managed-brain.ts');
+ await settleManagedGitEffects(engine);
+ expect(readFileSync(join(root, 'notes/remote.md'), 'utf8')).not.toContain('forgotten:');
+ expect(readFileSync(join(root, 'notes/kept.md'), 'utf8')).toContain(`| ~~${KEPT}~~ |`);
+ 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');
+ expect(await ledger(engine, REMOTE)).toEqual([]);
+ expect(await ledger(engine, KEPT)).toEqual(['notes/kept']);
+ expect(await call(ctx, 'remember', { fact: REMOTE, provenance: 'test', visibility: 'world', entity: 'notes/remote' })).toMatchObject({ state: 'committed' });
+ }, { 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);
});