Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(purge): purge mode of the withdrawal overlay drops purged fence rows

garrytan7190c4545a65
diff --git a/src/core/export-snapshot.ts b/src/core/export-snapshot.ts
index b1e11afa1c..729a06b3be 100644
--- a/src/core/export-snapshot.ts
+++ b/src/core/export-snapshot.ts
@@ -12,8 +12,11 @@ export async function readExportWithdrawals(tx: BrainEngine, sourceId: string):
jsonb_build_object('visibility',visibility,'fact_hash',fact_hash,'withdrawn_at',withdrawn_at,'subject',subject)::text)+1),0)+2 AS bytes
FROM fact_withdrawals WHERE source_id=$1`, [sourceId]);
if (Number(size.bytes) > EXPORT_PAYLOAD_LIMIT) throw new Error('Export withdrawal ledger capacity exceeded. No destination output was published.');
- return tx.executeRaw<ExportWithdrawal>(`SELECT visibility,fact_hash,withdrawn_at,subject
- FROM fact_withdrawals WHERE source_id=$1 ORDER BY visibility,fact_hash,subject`, [sourceId]);
+ // Purge tombstones ride the same overlay and drop their rows from the export.
+ return tx.executeRaw<ExportWithdrawal>(`SELECT visibility,fact_hash,withdrawn_at,subject,false AS purged
+ FROM fact_withdrawals WHERE source_id=$1
+ UNION ALL SELECT visibility,fact_hash,purged_at,subject,true FROM fact_purges WHERE source_id=$1
+ ORDER BY visibility,fact_hash,subject`, [sourceId]);
}
export async function readExportPage(tx: BrainEngine, key: { id: string; source_id: string; slug: string }, withdrawals: ExportWithdrawal[]) {
@@ -27,7 +30,7 @@ export async function readExportPage(tx: BrainEngine, key: { id: string; source_
const page = rowToPage(row);
if (page.compiled_truth.includes('gbrain:facts:') || page.timeline.includes('gbrain:facts:')) {
const applicable = withdrawals.filter(w => w.subject === '*' || w.subject === page.slug)
- .map(({ visibility, fact_hash, withdrawn_at }) => ({ visibility, fact_hash, withdrawn_at }));
+ .map(({ visibility, fact_hash, withdrawn_at, purged }) => ({ visibility, fact_hash, withdrawn_at, ...(purged ? { purged: true } : {}) }));
Object.assign(page, await overlayCanonicalBodies(tx.executeRaw.bind(tx), page.compiled_truth, page.timeline, applicable));
}
return { page, tags: row.export_tags as string[] };
diff --git a/src/core/facts/purge-overlay.ts b/src/core/facts/purge-overlay.ts
new file mode 100644
index 0000000000..575f62bfe9
--- /dev/null
+++ b/src/core/facts/purge-overlay.ts
@@ -0,0 +1,70 @@
+/**
+ * Purge mode of the import overlay: fence rows whose claim matches a purge
+ * tombstone (fact_purges, take_purges) are dropped from incoming Markdown,
+ * not struck, before hashing, chunking and projection. A stale file, a
+ * re-sync or a revert to an older body therefore cannot bring a purged claim
+ * back into canonical text, chunks, facts or takes. Malformed fences are left
+ * for the withdrawal path's diagnostics (it refuses a purged claim inside one).
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { renderFactsTable } from '../facts-fence.ts';
+import { locateOutsideCode } from '../fence-scan.ts';
+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence, renderTakesFence } from '../takes-fence.ts';
+import { withdrawalFenceBlocks } from './withdrawal-overlay.ts';
+
+/** True when the source has any fact or take purge tombstone (one indexed probe). */
+async function sourceHasPurges(engine: BrainEngine, sourceId: string): Promise<{ facts: boolean; takes: boolean }> {
+ const [row] = await engine.executeRaw<{ facts: boolean; takes: boolean }>(`SELECT
+ EXISTS (SELECT 1 FROM fact_purges WHERE source_id=$1) AS facts,
+ EXISTS (SELECT 1 FROM take_purges WHERE source_id=$1) AS takes`, [sourceId]);
+ return { facts: row?.facts === true, takes: row?.takes === true };
+}
+
+/** Drop every fence row naming a purged claim. `subject` is the page slug; without it every subject's tombstone applies. */
+export async function dropPurgedFenceRows(engine: BrainEngine, sourceId: string, body: string, subject?: string): Promise<string> {
+ const hasFacts = body.includes('gbrain:facts:begin'), hasTakes = body.includes(TAKES_FENCE_BEGIN);
+ if (!hasFacts && !hasTakes) return body;
+ const purges = await sourceHasPurges(engine, sourceId);
+ if (hasFacts && purges.facts) {
+ for (const block of withdrawalFenceBlocks(body).reverse()) {
+ if (block.parsed.warnings.length || !block.parsed.facts.length) continue;
+ const rows = await engine.executeRaw<{ row_num: number }>(`WITH incoming AS MATERIALIZED (
+ SELECT i.row_num, i.visibility, gbrain_fact_fingerprint(i.claim) AS fp
+ FROM jsonb_to_recordset($2::text::jsonb) AS i(row_num integer, claim text, visibility text))
+ SELECT DISTINCT incoming.row_num FROM incoming JOIN fact_purges p ON p.source_id=$1
+ AND p.visibility=incoming.visibility AND p.fact_hash=incoming.fp
+ AND ($3::text IS NULL OR p.subject='*' OR p.subject=$3::text)`,
+ [sourceId, JSON.stringify(block.parsed.facts.map(f => ({ row_num: f.rowNum, claim: f.claim, visibility: f.visibility }))), subject ?? null]);
+ if (!rows.length) continue;
+ const drop = new Set(rows.map(r => Number(r.row_num)));
+ body = body.slice(0, block.start) + renderFactsTable(block.parsed.facts.filter(f => !drop.has(f.rowNum))) + body.slice(block.end);
+ }
+ }
+ if (hasTakes && purges.takes) {
+ const parsed = parseTakesFence(body);
+ if (parsed.warnings.length || !parsed.takes.length) return body;
+ const rows = await engine.executeRaw<{ row_num: number }>(`SELECT DISTINCT i.row_num
+ FROM jsonb_to_recordset($2::text::jsonb) AS i(row_num integer, claim text)
+ JOIN take_purges p ON p.source_id=$1 AND p.claim_hash=gbrain_fact_fingerprint(i.claim)
+ AND ($3::text IS NULL OR p.subject='*' OR p.subject=$3::text)`,
+ [sourceId, JSON.stringify(parsed.takes.map(t => ({ row_num: t.rowNum, claim: t.claim }))), subject ?? null]);
+ if (!rows.length) return body;
+ const drop = new Set(rows.map(r => Number(r.row_num)));
+ const { beginIdx, endIdx } = locateOutsideCode(body, TAKES_FENCE_BEGIN, TAKES_FENCE_END);
+ if (beginIdx === -1 || endIdx === -1) return body;
+ body = body.slice(0, beginIdx) + renderTakesFence(parsed.takes.filter(t => !drop.has(t.rowNum))) + body.slice(endIdx + TAKES_FENCE_END.length);
+ }
+ return body;
+}
+
+/** Pure: drop fact fence rows by row number in every complete fence block (used by purge on stored bodies). */
+export function dropFactFenceRowsByNumber(body: string, keep: (row: { rowNum: number; claim: string; visibility: string }) => boolean): string {
+ if (!body.includes('gbrain:facts:begin')) return body;
+ for (const block of withdrawalFenceBlocks(body).reverse()) {
+ if (block.parsed.warnings.length) continue;
+ const kept = block.parsed.facts.filter(f => keep({ rowNum: f.rowNum, claim: f.claim, visibility: f.visibility }));
+ if (kept.length !== block.parsed.facts.length) body = body.slice(0, block.start) + renderFactsTable(kept) + body.slice(block.end);
+ }
+ return body;
+}
diff --git a/src/core/facts/withdrawal-overlay.ts b/src/core/facts/withdrawal-overlay.ts
index 0de7a9b7a5..a76f9405ea 100644
--- a/src/core/facts/withdrawal-overlay.ts
+++ b/src/core/facts/withdrawal-overlay.ts
@@ -113,21 +113,26 @@ export function hasAmbiguousWithdrawalFence(body: string): boolean {
/** Apply hashes from DB-normalized companion text to the original Markdown. */
export function overlayWithdrawalBody(body: string, normalizedBody: string, withdrawals: PageWithdrawal[]): string {
if (!withdrawals.length || !body.includes('gbrain:facts:begin')) return body;
- const ledger = new Map(withdrawals.map(w => [`${w.visibility}:${w.fact_hash}`, w.withdrawn_at]));
+ const ledger = new Map<string, PageWithdrawal>();
+ for (const w of withdrawals) {
+ const key = `${w.visibility}:${w.fact_hash}`;
+ if (!ledger.get(key)?.purged) ledger.set(key, w);
+ }
const blocks = withdrawalFenceBlocks(body), normalized = withdrawalFenceBlocks(normalizedBody);
for (let i = blocks.length - 1; i >= 0; i--) {
const block = blocks[i], norm = normalized[i];
if (!norm || block.parsed.warnings.length || norm.parsed.warnings.length) continue;
const claims = new Map(norm.parsed.facts.map(f => [f.rowNum, f.claim]));
let changed = false;
- const facts = block.parsed.facts.map(f => {
+ // A purge tombstone drops the row (the claim leaves the canonical text); a withdrawal strikes it.
+ const facts = block.parsed.facts.flatMap(f => {
const claim = claims.get(f.rowNum);
- if (claim === undefined) return f;
- const at = ledger.get(`${f.visibility}:${createHash('sha256').update(normalizeLoweredClaim(claim)).digest('hex')}`)
+ if (claim === undefined) return [f];
+ const entry = ledger.get(`${f.visibility}:${createHash('sha256').update(normalizeLoweredClaim(claim)).digest('hex')}`)
?? ledger.get(`${f.visibility}:${createHash('sha256').update(claim).digest('hex')}`);
- if (!at) return f;
+ if (!entry) return [f];
changed = true;
- return withdrawnFact(f, new Date(at).toISOString().slice(0, 10));
+ return entry.purged ? [] : [withdrawnFact(f, new Date(entry.withdrawn_at).toISOString().slice(0, 10))];
});
if (changed) body = body.slice(0, block.start) + renderFactsTable(facts) + body.slice(block.end);
}
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index 79152161d0..a5fda431df 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -4,6 +4,7 @@ import { OperationError } from '../ops/contract.ts';
import { fenceOperationError } from '../fence-repair/refusal.ts';
import { withdrawnFact, withdrawalFenceBlocks } from './withdrawal-overlay.ts';
import { ambiguousFenceClaims, discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';
+import { dropPurgedFenceRows } from './purge-overlay.ts';
export interface WithdrawalCommit {
withdrawn: boolean;
@@ -105,7 +106,9 @@ async function ambiguousFenceMatchesWithdrawal(engine: BrainEngine, sourceId: st
const rows = await engine.executeRaw(`WITH incoming AS MATERIALIZED (${FINGERPRINTED_CLAIMS}
FROM jsonb_to_recordset($2::text::jsonb) i(claim text,visibility text))
SELECT 1 FROM incoming
- JOIN fact_withdrawals w ON w.source_id=$1 AND w.fact_hash IN (incoming.fp,incoming.fp_v1)
+ JOIN (SELECT source_id,visibility,subject,fact_hash FROM fact_withdrawals WHERE source_id=$1
+ UNION ALL SELECT source_id,visibility,subject,fact_hash FROM fact_purges WHERE source_id=$1) w
+ ON w.source_id=$1 AND w.fact_hash IN (incoming.fp,incoming.fp_v1)
AND (incoming.visibility IS NULL OR w.visibility=incoming.visibility)
AND ($3::text IS NULL OR w.subject = '*' OR w.subject = $3::text) LIMIT 1`,
[sourceId, JSON.stringify(claims), subject]);
@@ -133,6 +136,7 @@ async function withdrawalDates(engine: BrainEngine, sourceId: string, facts: rea
* as `subject`; without it every subject's withdrawal applies (conservative).
*/
export async function preserveWithdrawnFenceRows(engine: BrainEngine, sourceId: string, body: string, subject?: string): Promise<string> {
+ body = await dropPurgedFenceRows(engine, sourceId, body, subject);
if (!body.includes('gbrain:facts:begin')) return body;
const blocks = withdrawalFenceBlocks(body);
for (const block of blocks.reverse()) {
diff --git a/src/core/page-state/snapshot.ts b/src/core/page-state/snapshot.ts
index f552219feb..27f382afd7 100644
--- a/src/core/page-state/snapshot.ts
+++ b/src/core/page-state/snapshot.ts
@@ -47,7 +47,11 @@ export async function readPageSnapshot(query: ReadQuery, slug: string, opts?: Pa
COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at)
ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at
FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug)
- ${opts?.excludePrivate ? "AND visibility='world'" : ''} GROUP BY visibility,fact_hash) w), '[]'::jsonb) AS snapshot_withdrawals,
+ ${opts?.excludePrivate ? "AND visibility='world'" : ''} GROUP BY visibility,fact_hash) w), '[]'::jsonb)
+ || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true)
+ ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at
+ FROM fact_purges WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug)
+ ${opts?.excludePrivate ? "AND visibility='world'" : ''} GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals,
(SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)
FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body,
(SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)
diff --git a/src/core/page-state/types.ts b/src/core/page-state/types.ts
index 36f6e731c1..1b9a89de6d 100644
--- a/src/core/page-state/types.ts
+++ b/src/core/page-state/types.ts
@@ -29,6 +29,8 @@ export interface PageWithdrawal {
visibility: 'private' | 'world';
fact_hash: string;
withdrawn_at: string;
+ /** A purge tombstone (fact_purges): the overlay drops the row instead of striking it. */
+ purged?: boolean;
}
export interface PageSnapshot {
page: Page;
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index 807e1f9ce0..bf7a43140f 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -244,6 +244,6 @@ export function validateReconcileArtifact(value: unknown): ReconcileArtifact {
}
}
for (const conflict of value.conflicts as unknown[]) strictReconcileKeys(conflict, ['path', 'file', 'database']);
- for (const withdrawal of value.preimages.database.withdrawals as unknown[]) strictReconcileKeys(withdrawal, ['visibility', 'fact_hash', 'withdrawn_at']);
+ for (const withdrawal of value.preimages.database.withdrawals as unknown[]) strictReconcileKeys(withdrawal, ['visibility', 'fact_hash', 'withdrawn_at', 'purged'], ['visibility', 'fact_hash', 'withdrawn_at']);
return JSON.parse(stableJson(value)) as ReconcileArtifact;
}