Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief ledger lane A: owner release only on an explicit owner edit of a different value (#1); first page purge redacts (#2)

garrytan90bdeb125867
diff --git a/src/core/belief/append.ts b/src/core/belief/append.ts
index 1abf00d7b6..5aeaa711b1 100644
--- a/src/core/belief/append.ts
+++ b/src/core/belief/append.ts
@@ -27,6 +27,11 @@ export interface AppendContext {
publicationId: string; origin: BeliefOrigin;
/** Writer of this transaction: an owner release needs a trusted local write at or above OWNER_TIER_FLOOR. */
writerTier?: string | null; remote?: boolean;
+ /**
+ * The batch is an explicit owner edit of the subjects' fields (section 6.5). Only such a write can release a
+ * redaction; sync, import, reconcile, file repair, gate release and held accept never set it, whatever their tier.
+ */
+ ownerEdit?: boolean;
/** Skip the tombstone and register reads when the source never had a purge (begin's probe). */
purgesPossible?: boolean;
/**
@@ -44,7 +49,7 @@ export function orderDrafts(drafts: BeliefEventDraft[]): BeliefEventDraft[] {
|| (a.subjectKey < b.subjectKey ? -1 : a.subjectKey > b.subjectKey ? 1 : 0) || a.eventType.localeCompare(b.eventType));
}
-const isOwnerWrite = (ctx: AppendContext) => ctx.remote === false && isTrustTier(ctx.writerTier)
+const isOwnerWrite = (ctx: AppendContext) => ctx.ownerEdit === true && ctx.remote === false && isTrustTier(ctx.writerTier)
&& TRUST_TIER_RANK[ctx.writerTier] >= TRUST_TIER_RANK[OWNER_TIER_FLOOR];
/** Tombstoned fingerprints among the drafts' asserting events (fact_purges/take_purges match rules, subject '*' included). */
@@ -92,7 +97,7 @@ async function applyRedactions(tx: BrainEngine, sourceId: string, drafts: Belief
}
if (!own.length) continue;
if (own.every(s => s.released_hash === hash)) continue;
- if (owner) {
+ if (owner && own.every(s => s.field_hash !== hash)) {
await tx.executeRaw('UPDATE belief_redactions SET released_by = $2::uuid, released_hash = $3 WHERE id = ANY($1::bigint[])',
[own.map(s => Number(s.id)), ctx.publicationId, hash]);
continue;
diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.ts
index 33da404c48..53ade60a3b 100644
--- a/src/core/belief/ledger.ts
+++ b/src/core/belief/ledger.ts
@@ -45,6 +45,8 @@ export interface BeliefBatchOptions {
hardDeleteEvent?: 'page.purged' | 'page.expired';
/** Request authority: an owner release of a redaction needs a trusted local (remote = false) write. */
remote?: boolean;
+ /** An explicit owner edit of the batch's fields: the only write that can release a purge redaction (append.ts). */
+ ownerEdit?: boolean;
cause?: Record<string, unknown>;
/** Filled by the batch: how many events it appended, so the caller marks the commit only when there is one. */
report?: { appended: number };
@@ -363,7 +365,7 @@ export async function finalizeBeliefEvents(tx: BrainEngine, batch: Batch): Promi
}
}
return appendBeliefEvents(tx, drafts, { publicationId: batch.publicationId, origin: opts.origin ?? (batch.managed ? 'live' : 'unmanaged'),
- writerTier, remote: opts.remote, purgesPossible: batch.purgesPossible });
+ writerTier, remote: opts.remote, ownerEdit: opts.ownerEdit, purgesPossible: batch.purgesPossible || batch.notes.some(n => n.kind === 'purged') });
}
/** `trust.contested` on the held row's key: its tier as trust_tier, the challenger's as writer_tier (section 6.1). */
diff --git a/src/core/belief/purge.ts b/src/core/belief/purge.ts
index 7647b269d2..752a69510f 100644
--- a/src/core/belief/purge.ts
+++ b/src/core/belief/purge.ts
@@ -284,18 +284,20 @@ async function rowSubject(engine: BrainEngine, table: 'facts' | 'takes', id: num
return subject ? { sourceId: row.source_id, key: subject.key, value: subject.value } : null;
}
-/** Carrying fields of a row still under a purge redaction its current value has not been released for. */
+/** Carrying fields of a row under a purge redaction that a confirm would release: the current value is not released yet and is not the redacted value itself. */
export async function suppressedFields(engine: BrainEngine, table: 'facts' | 'takes', id: number): Promise<string[]> {
const subject = await rowSubject(engine, table, id);
if (!subject) return [];
- const rows = await engine.executeRaw<{ field: string; released_hash: string | null }>(`SELECT field, released_hash FROM belief_redactions
+ const rows = await engine.executeRaw<{ field: string; field_hash: string; released_hash: string | null }>(`SELECT field, field_hash, released_hash FROM belief_redactions
WHERE source_id = $1 AND subject_key = $2`, [subject.sourceId, subject.key]);
- return [...new Set(rows.filter(r => typeof subject.value[r.field] === 'string' && r.released_hash !== fieldHash(subject.value[r.field] as string)).map(r => r.field))];
+ return [...new Set(rows.filter(r => typeof subject.value[r.field] === 'string' && r.released_hash !== fieldHash(subject.value[r.field] as string)
+ && r.field_hash !== fieldHash(subject.value[r.field] as string)).map(r => r.field))];
}
/**
* The owner release (section 6.5): the confirm action on a key binds each suppressed field to its current value
* (`released_hash`), so the next append that writes exactly that value records it; any later change is redacted again.
+ * A field still holding the value the purge redacted (`field_hash`) is never released.
*/
export async function releaseSuppressedFields(engine: BrainEngine, table: 'facts' | 'takes', id: number, releasedBy: string): Promise<string[]> {
const subject = await rowSubject(engine, table, id);
@@ -305,7 +307,7 @@ export async function releaseSuppressedFields(engine: BrainEngine, table: 'facts
const text = subject.value[field];
if (typeof text !== 'string') continue;
const rows = await engine.executeRaw(`UPDATE belief_redactions SET released_by = $4::uuid, released_hash = $5 WHERE source_id = $1 AND subject_key = $2 AND field = $3
- AND released_hash IS DISTINCT FROM $5 RETURNING id`, [subject.sourceId, subject.key, field, releasedBy, fieldHash(text)]);
+ AND released_hash IS DISTINCT FROM $5 AND field_hash <> $5 RETURNING id`, [subject.sourceId, subject.key, field, releasedBy, fieldHash(text)]);
if (rows.length) released.push(field);
}
return released;
diff --git a/test/belief-ledger-purge-review.test.ts b/test/belief-ledger-purge-review.test.ts
new file mode 100644
index 0000000000..fec1d57203
--- /dev/null
+++ b/test/belief-ledger-purge-review.test.ts
@@ -0,0 +1,93 @@
+/**
+ * Regression probes for the lane A findings of the #6806 review (purge,
+ * redaction, mirror). Each was reproduced failing on the reviewed code; each
+ * runs on PGLite and on Postgres when DATABASE_URL is set.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { __setBeliefEmitterFaultForTests } from '../src/core/belief/append.ts';
+import { withBeliefBatch } from '../src/core/belief/ledger.ts';
+import { REDACTION_MARKER } from '../src/core/belief/keys.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';
+import { operations } from '../src/core/operations.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain, type BeliefEvent } from './helpers/belief-ledger.ts';
+
+afterEach(() => { __setBeliefEmitterFaultForTests(null); });
+
+const X = 'Door code is 4417';
+const purgeOp = operations.find(o => o.name === 'purge_fact')!;
+const deleteOp = operations.find(o => o.name === 'delete_page')!;
+
+async function purgeFact(b: BeliefBrain, claim: string): Promise<Record<string, any>> {
+ const [row] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id = $1 AND fact = $2 AND expired_at IS NULL ORDER BY id LIMIT 1', [b.sourceId, claim]);
+ const dry = await purgeOp.handler(b.ctx, { id: Number(row!.id), dry_run: true }) as Record<string, any>;
+ return await purgeOp.handler(b.ctx, { id: Number(row!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() }) as Record<string, any>;
+}
+
+async function purgePage(b: BeliefBrain, slug: string): Promise<Record<string, any>> {
+ const snapshot = await b.engine.readPageSnapshot(slug, { sourceId: b.sourceId, includeDeleted: true });
+ return await deleteOp.handler(b.ctx, { slug, purge: true, expected_revision: snapshot!.revision, request_id: randomUUID() }) as Record<string, any>;
+}
+
+const requestOf = async (b: BeliefBrain, clientRequestId: string) =>
+ (await b.engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_requests WHERE request_id = $1::uuid', [clientRequestId]))[0]!.id;
+
+const quoting = (events: BeliefEvent[], claim: string) => events.filter(e => JSON.stringify(e.value ?? {}).toLowerCase().includes(claim.toLowerCase())).map(e => [e.id, e.event_type, e.origin]);
+
+/** Runs a brain scenario to completion (teardown included) and returns what it reported. */
+async function collect<T>(run: (report: (value: T) => void) => Promise<void>): Promise<T> {
+ let out: T | undefined;
+ await run(value => { out = value; });
+ return out as T;
+}
+
+/** An owner-tier, trusted local write in its own batch: the shape of sync, reconcile and file repair (or, with ownerEdit, an explicit owner edit). */
+const ownerTierWrite = (b: BeliefBrain, slug: string, op: string, sql: string, ownerEdit = false) => b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], async () => {
+ await tx.lockPageKeys([{ sourceId: b.sourceId, slug }]);
+ await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: [slug], op, remote: false, ...(ownerEdit ? { ownerEdit } : {}) }, () => tx.executeRaw(sql, [b.sourceId]));
+}, { ...TEST_WRITE_ATTRIBUTION, trust: { tier: 'operator_curated', origin: { channel: op } } }));
+
+for (const engineCase of testBackends().map(beliefEngineCase)) {
+ describe(`belief ledger purge review (${engineCase.name})`, () => {
+ const brain = (run: (b: BeliefBrain) => Promise<void>, managed = true) => beliefBrain(run, { managed, databaseUrl: engineCase.databaseUrl });
+
+ test('#1: sync, reconcile and file repair at owner tier never release a redaction; an explicit owner edit releases only a different value', 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}` }] }));
+ const request = await requestOf(b, String((await purgeFact(b, X)).request_id));
+ const ctx = async (fn: () => Promise<unknown>) => { const mark = await b.lastId(); await fn(); return (await b.events(mark)).filter(e => e.event_type.startsWith('fact.')).map(e => e.value?.context); };
+ const fact = `source_id = $1 AND fact = 'Acme sells widgets' AND expired_at IS NULL`;
+ const out: Record<string, unknown> = { request };
+ for (const op of ['canonical_reconcile', 'managed_file_import', 'managed_file_repair', 'trust_release', 'trust_accept'])
+ out[op] = await ctx(() => ownerTierWrite(b, slug, op, `UPDATE facts SET confidence = confidence * 0.9 WHERE ${fact}`));
+ out.unchangedOwnerEdit = await ctx(() => ownerTierWrite(b, slug, 'owner_edit', `UPDATE facts SET confidence = 0.4 WHERE ${fact}`, true));
+ out.syncSetsField = await ctx(() => ownerTierWrite(b, slug, 'managed_file_import', `UPDATE facts SET context = 'sync rewrote it' WHERE ${fact}`));
+ out.ownerEdit = await ctx(() => ownerTierWrite(b, slug, 'owner_edit', `UPDATE facts SET context = 'owner rewrote it' WHERE ${fact}`, true));
+ out.released = (await b.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM belief_redactions WHERE source_id = $1 AND released_hash IS NOT NULL', [b.sourceId]))[0]!.n;
+ report(out);
+ }));
+ const m = REDACTION_MARKER(r.request as string);
+ expect(r).toEqual({ request: r.request, canonical_reconcile: [m], managed_file_import: [m], managed_file_repair: [m], trust_release: [m], trust_accept: [m],
+ unchangedOwnerEdit: [m], syncSetsField: [m], ownerEdit: ['owner rewrote it'], released: 1 });
+ }, 240_000);
+
+ test('#2: the first page purge in a source writes no purged text into the ledger', async () => {
+ const r = await collect<Record<string, unknown>>(report => brain(async b => {
+ const claim = 'Vault code is 7731';
+ await submitRememberMutation(b.ctx, { fact: 'Secret example owns a vault', entity: 'people/secret-example', provenance: 'probe' });
+ await b.put('people/secret-example', beliefPage({ type: 'person', title: 'Secret Example', facts: [claim] }));
+ await b.engine.executeRaw(`UPDATE facts SET context = $2 WHERE source_id = $1 AND source_markdown_slug IS NULL AND entity_slug = 'people/secret-example'`,
+ [b.sourceId, `per memo: ${claim.toLowerCase()}`]);
+ const mark = await b.lastId();
+ const result = await purgePage(b, 'people/secret-example');
+ report({ status: result.status, leaks: quoting(await b.events(), claim), published: (await b.events(mark)).filter(e => e.subject_kind === 'fact').map(e => [e.event_type, e.redacted_fields]) });
+ }, false));
+ expect(r.status).toBe('purged');
+ expect(r.leaks).toEqual([]);
+ }, 240_000);
+ });
+}
diff --git a/test/belief-ledger-purge.test.ts b/test/belief-ledger-purge.test.ts
index 58a2d5d535..8f91f7d955 100644
--- a/test/belief-ledger-purge.test.ts
+++ b/test/belief-ledger-purge.test.ts
@@ -169,7 +169,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
const agentEdit = await step(() => b.put(slug, page(`notes say ${X} and more`, '0.5')));
const owner = await step(() => b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], async () => {
await tx.lockPageKeys([{ sourceId: b.sourceId, slug }]);
- await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: [slug], op: 'owner_edit', remote: false },
+ await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: [slug], op: 'owner_edit', remote: false, ownerEdit: true },
() => tx.executeRaw(`UPDATE facts SET context = 'owner rewrote this' WHERE source_id = $1 AND fact = 'Acme sells widgets' AND expired_at IS NULL`, [b.sourceId]));
}, { ...TEST_WRITE_ATTRIBUTION, trust: { tier: 'operator_curated', origin: { channel: 'cli:owner_edit' } } })));
const later = await step(() => b.put(slug, page('agent rewrote this', '0.5')));