Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
belief ledger lane A: no prior_hash of a purged or redacted value survives the purge or a later append (#36)
garrytan7bd1f6b91d9d
diff --git a/src/core/belief/append.ts b/src/core/belief/append.tsindex 5aeaa711b1..0a7dfd6741 100644--- a/src/core/belief/append.ts+++ b/src/core/belief/append.ts@@ -142,7 +142,7 @@ export async function appendBeliefEvents(tx: BrainEngine, input: BeliefEventDraftrust_tier: d.trustTier, writer_tier: d.writerTier && d.writerTier !== d.trustTier ? d.writerTier : null, tier_basis: d.tierBasis ?? 'row',visibility: d.visibility, publication_id: ctx.publicationId, ord, source_time: d.sourceTime ?? null, valid_from: d.validFrom ?? null,valid_until: d.validUntil ?? null, value: value == null ? null : canonicalJson(value), value_hash: value == null ? null : valueHash(value),- prior_hash: d.priorHash ?? null, state_hash: d.stateHash, cause: canonicalJson(d.cause), claim_fp: d.claimFp ?? null, purged,+ prior_hash: purged || d.eventType.endsWith('.purged') || redactions.has(d) ? null : d.priorHash ?? null, state_hash: d.stateHash, cause: canonicalJson(d.cause), claim_fp: d.claimFp ?? null, purged,redacted_fields: redactions.get(d) ?? null,};});diff --git a/src/core/belief/purge.ts b/src/core/belief/purge.tsindex f9fbf0a2a7..9ee4ce7e2f 100644--- a/src/core/belief/purge.ts+++ b/src/core/belief/purge.ts@@ -5,12 +5,15 @@* 1. purged keys: every event of a purged claim fingerprint (fact and take* events carry the claim-only fingerprint in `claim_fp`, so kind, holder,* subject and the rename chain cannot evade it) and every event of the purged- * page's lifetimes loses its value and is marked `purged`;+ * page's lifetimes loses its value and its prior_hash and is marked `purged`;* 2. carrying fields: every event in the source whose value contains a purge* needle has each carrying field that quotes a claim replaced by the* redaction marker, its value_hash recomputed and the field listed in* `redacted_fields`; each replacement is registered in `belief_redactions`- * so later appends keep the marker until an owner release (append.ts);+ * so later appends keep the marker until an owner release (append.ts). A+ * later event of the key that named the old hash as its prior_hash names the+ * new one, and the redacted event keeps its own prior_hash only when it names+ * an earlier recorded value, so no hash of the quoted text stays readable;* 3. derived keys: each row the derivation walk hides gets one `derived.hidden`* event naming the purge request; `readBeliefHistory` hides the key's events* up to it (and its backfill events at any id).@@ -81,9 +84,9 @@ async function registerRedaction(tx: Pick<BrainEngine, 'executeRaw'>, sourceId:/** Pass 1: purged keys lose their values. Returns the events marked. */export async function redactPurgedKeys(tx: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; claimFps: readonly string[]; lifetimes: readonly string[] }): Promise<number> {if ((!input.claimFps.length && !input.lifetimes.length) || redactionFault === 'skip_purged_keys') return 0;- const rows = await tx.executeRaw(`UPDATE belief_events SET value = NULL, value_hash = NULL, purged = true+ const rows = await tx.executeRaw(`UPDATE belief_events SET value = NULL, value_hash = NULL, prior_hash = NULL, purged = trueWHERE source_id = $1 AND ((subject_kind IN ('fact','take') AND claim_fp = ANY($2::text[])) OR page_lifetime = ANY($3::uuid[]))- AND (purged = false OR value IS NOT NULL) RETURNING id`, [input.sourceId, [...input.claimFps], [...input.lifetimes]]);+ AND (purged = false OR value IS NOT NULL OR prior_hash IS NOT NULL) RETURNING id`, [input.sourceId, [...input.claimFps], [...input.lifetimes]]);return rows.length;}@@ -114,7 +117,7 @@ export async function redactCarryingFields(tx: Pick<BrainEngine, 'executeRaw'>,return typeof text === 'string' && quotes(text, forms);});if (!fields.length) continue;- const [event] = await tx.executeRaw<{ value: unknown; redacted_fields: string[] | null }>('SELECT value, redacted_fields FROM belief_events WHERE id = $1', [row.id]);+ const [event] = await tx.executeRaw<{ value: unknown; value_hash: string | null; redacted_fields: string[] | null }>('SELECT value, value_hash, redacted_fields FROM belief_events WHERE id = $1', [row.id]);const value = (typeof event!.value === 'string' ? JSON.parse(event!.value) : event!.value) as Record<string, unknown>;const next = { ...value };for (const field of fields) {@@ -125,8 +128,11 @@ export async function redactCarryingFields(tx: Pick<BrainEngine, 'executeRaw'>,out.push({ subject_key: row.subject_key, field, event_id: Number(row.id) });}const listed = [...new Set([...(event!.redacted_fields ?? []), ...fields])];- await tx.executeRaw('UPDATE belief_events SET value = $2::text::jsonb, value_hash = $3, redacted_fields = $4::text[] WHERE id = $1',- [row.id, canonicalJson(next), valueHash(next), listed]);+ await tx.executeRaw(`UPDATE belief_events e SET value = $2::text::jsonb, value_hash = $3, redacted_fields = $4::text[],+ prior_hash = CASE WHEN EXISTS (SELECT 1 FROM belief_events o WHERE o.source_id = e.source_id AND o.subject_key = e.subject_key AND o.id < e.id+ AND o.value_hash = e.prior_hash) THEN e.prior_hash END WHERE e.id = $1`, [row.id, canonicalJson(next), valueHash(next), listed]);+ if (event!.value_hash) await tx.executeRaw(`UPDATE belief_events SET prior_hash = $4 WHERE source_id = $1 AND subject_key = $2 AND id > $5 AND prior_hash = $3`,+ [input.sourceId, row.subject_key, event!.value_hash, valueHash(next), row.id]);}if (rows.length < SCAN_BATCH) break;}diff --git a/test/belief-ledger-purge-review.test.ts b/test/belief-ledger-purge-review.test.tsindex b9b4185382..849dcb40d6 100644--- a/test/belief-ledger-purge-review.test.ts+++ b/test/belief-ledger-purge-review.test.ts@@ -173,6 +173,20 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {expect(r).toEqual([['page.published', 'private'], ['take.asserted', 'private'], ['page.published', 'world'], ['take.asserted', 'world']]);}, 240_000);+ test('#36: no recorded hash of a purged or redacted value survives as a prior_hash', async () => {+ const r = await collect<Record<string, unknown>>(report => brain(async b => {+ const slug = 'companies/acme-example';+ await b.put(slug, beliefPage({ facts: [X, { claim: 'Acme sells widgets', context: `notes say ${X}` }] }));+ await b.put(slug, beliefPage({ facts: [{ claim: X, confidence: '0.9' }, { claim: 'Acme sells widgets', context: `notes say ${X}`, confidence: '0.8' }] }));+ const quoted = new Set((await b.events()).filter(e => JSON.stringify(e.value ?? {}).includes(X)).flatMap(e => [e.value_hash, e.prior_hash]).filter((h): h is string => !!h));+ await purgeFact(b, X);+ const events = await b.events();+ report({ quoted: quoted.size >= 4, prior: events.filter(e => e.prior_hash && quoted.has(e.prior_hash)).map(e => [e.event_type, e.purged]),+ value: events.filter(e => e.value_hash && quoted.has(e.value_hash)).length });+ }));+ expect(r).toEqual({ quoted: true, prior: [], value: 0 });+ }, 240_000);+test('#14: a hard delete (purge, managed and unmanaged retention) records every cascaded inbound link as link.retracted in its own stream', async () => {const run = (managed: boolean, remove: (b: BeliefBrain, slug: string) => Promise<unknown>) => collect<string[]>(report => brain(async b => {await b.put('people/target-example', beliefPage({ type: 'person', title: 'Target Example' }));