Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
belief ledger lane A: purge passes match carrying fields in JS keyset batches (#6, #11); receipt reports other subjects quoting the claim (#12)
garrytan840354ffae7c
diff --git a/src/core/belief/purge.ts b/src/core/belief/purge.tsindex 752a69510f..eae31ee86b 100644--- a/src/core/belief/purge.ts+++ b/src/core/belief/purge.ts@@ -52,22 +52,30 @@ export async function sourceHasBeliefEvents(tx: Pick<BrainEngine, 'executeRaw'>,return row?.present === true;}-/** A claim as it can appear in stored text: plain, fence-escaped, and each JSON-escaped (event values are matched as JSON text). */-export function purgeNeedles(claims: readonly string[]): string[] {+/**+ * The forms a claim takes in a stored field (plain and fence-escaped), lowercased in JS. Fields are matched+ * here, never with SQL `lower()`: both sides then fold case the same way, whatever the script (#11).+ */+export function claimForms(claims: readonly string[]): string[] {const out = new Set<string>();for (const claim of claims) {const lower = claim.trim().toLowerCase();- if (!lower) continue;- for (const form of [lower, escapeFenceCell(lower)]) { out.add(form); out.add(JSON.stringify(form).slice(1, -1)); }+ if (lower) { out.add(lower); out.add(escapeFenceCell(lower)); }}return [...out];}-const quotes = (text: string, claims: readonly string[]) => {+export const quotes = (text: string, forms: readonly string[]) => {const lower = text.toLowerCase();- return claims.some(c => { const l = c.trim().toLowerCase(); return !!l && (lower.includes(l) || lower.includes(escapeFenceCell(l))); });+ return forms.some(f => lower.includes(f));};+async function registerRedaction(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, key: string, field: string, request: string, hash: string): Promise<void> {+ await tx.executeRaw(`INSERT INTO belief_redactions (source_id, subject_key, field, purge_request, field_hash)+ SELECT $1, $2, $3, $4::uuid, $5 WHERE NOT EXISTS (SELECT 1 FROM belief_redactions WHERE source_id = $1 AND subject_key = $2 AND field = $3+ AND purge_request = $4::uuid AND field_hash = $5)`, [sourceId, key, field, request, hash]);+}+/** 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;@@ -79,38 +87,42 @@ export async function redactPurgedKeys(tx: Pick<BrainEngine, 'executeRaw'>, inpuexport interface RedactedField { subject_key: string; field: string; event_id: number }-/** Pass 2: carrying fields that quote a purged claim become the redaction marker and enter the redaction register. */+/**+ * Pass 2: carrying fields that quote a purged claim become the redaction marker and enter the redaction register.+ * Keyset batches read only the carrying fields of the source's events (no substring scan in SQL, so the cost is+ * one pass over the events whatever the number of claims, #6); the claims are matched in JS.+ */export async function redactCarryingFields(tx: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; request: string; claims: readonly string[] }): Promise<RedactedField[]> {- const needles = purgeNeedles(input.claims);- if (!needles.length || redactionFault === 'skip_carrying_fields') return [];+ const forms = claimForms(input.claims);+ if (!forms.length || redactionFault === 'skip_carrying_fields') return [];const out: RedactedField[] = [];const registered = new Set<string>();for (let after = 0; ;) {await faultPoint('purge:ledger_redaction', { sourceId: input.sourceId });- const rows = await tx.executeRaw<{ id: number; subject_kind: string; subject_key: string; value: unknown; redacted_fields: string[] | null }>(`SELECT e.id, e.subject_kind,- e.subject_key, e.value, e.redacted_fields FROM belief_events e- WHERE e.source_id = $1 AND e.id > $2 AND e.value IS NOT NULL AND e.subject_kind IN ('fact','take','link')- AND EXISTS (SELECT 1 FROM unnest($3::text[]) n WHERE strpos(lower(e.value::text), n) > 0)- ORDER BY e.id LIMIT ${SCAN_BATCH}`, [input.sourceId, after, needles]);+ const rows = await tx.executeRaw<{ id: number; subject_kind: string; subject_key: string; context: string | null; resolved_source: string | null }>(`SELECT e.id,+ e.subject_kind, e.subject_key, e.value->>'context' AS context, e.value->>'resolved_source' AS resolved_source FROM belief_events e+ WHERE e.source_id = $1 AND e.id > $2 AND e.subject_kind IN ('fact','take','link')+ AND (COALESCE(e.value->>'context', '') <> '' OR COALESCE(e.value->>'resolved_source', '') <> '')+ ORDER BY e.id LIMIT ${SCAN_BATCH}`, [input.sourceId, after]);if (!rows.length) break;after = Number(rows[rows.length - 1]!.id);for (const row of rows) {- const value = (typeof row.value === 'string' ? JSON.parse(row.value) : row.value) as Record<string, unknown>;- const fields = (CARRYING_FIELDS[row.subject_kind] ?? []).filter(f => typeof value[f] === 'string' && quotes(value[f] as string, input.claims));+ const fields = (CARRYING_FIELDS[row.subject_kind] ?? []).filter(f => {+ const text = (row as unknown as Record<string, string | null>)[f];+ 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 value = (typeof event!.value === 'string' ? JSON.parse(event!.value) : event!.value) as Record<string, unknown>;const next = { ...value };for (const field of fields) {- const tag = `${row.subject_key}\u0000${field}\u0000${fieldHash(value[field] as string)}`;- if (!registered.has(tag)) {- registered.add(tag);- await tx.executeRaw(`INSERT INTO belief_redactions (source_id, subject_key, field, purge_request, field_hash)- SELECT $1, $2, $3, $4::uuid, $5 WHERE NOT EXISTS (SELECT 1 FROM belief_redactions WHERE source_id = $1 AND subject_key = $2 AND field = $3- AND purge_request = $4::uuid AND field_hash = $5)`, [input.sourceId, row.subject_key, field, input.request, fieldHash(value[field] as string)]);- }+ const hash = fieldHash(value[field] as string);+ const tag = `${row.subject_key}\u0000${field}\u0000${hash}`;+ if (!registered.has(tag)) { registered.add(tag); await registerRedaction(tx, input.sourceId, row.subject_key, field, input.request, hash); }next[field] = REDACTION_MARKER(input.request);out.push({ subject_key: row.subject_key, field, event_id: Number(row.id) });}- const listed = [...new Set([...(row.redacted_fields ?? []), ...fields])];+ 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]);}@@ -119,23 +131,37 @@ export async function redactCarryingFields(tx: Pick<BrainEngine, 'executeRaw'>,return out;}+/** Keyset batches of `sql` (params: source, after-id; columns id, slug, text), returning the slugs whose text quotes a form. */+async function quotingSlugs(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, forms: readonly string[], sql: string, into: Set<string>): Promise<void> {+ for (let after = 0; ;) {+ const rows = await tx.executeRaw<{ id: number; slug: string | null; text: string }>(`${sql} ORDER BY 1 LIMIT ${SCAN_BATCH}`, [sourceId, after]);+ if (!rows.length) return;+ after = Number(rows[rows.length - 1]!.id);+ for (const r of rows) if (r.slug && quotes(r.text, forms)) into.add(r.slug);+ if (rows.length < SCAN_BATCH) return;+ }+}+/*** Pass 2, live half: a surviving row whose carrying field quotes a purged claim (a fence row's context, a take's* resolution evidence, a link's context) is left as it is by the purge, so its key enters the redaction register* with the field's current hash; its next event (a confidence edit, a reconcile, a backfill) then writes the marker- * until the owner releases it. Returns the registered keys, which the receipt names.+ * until the owner releases it. Returns the registered keys, which the receipt names. The candidate rows are read in+ * keyset batches and matched in JS, like the events.*/export async function registerLiveCarriers(tx: BrainEngine, input: { sourceId: string; request: string; claims: readonly string[] }): Promise<RedactedField[]> {- const needles = [...new Set(input.claims.map(c => c.trim().toLowerCase()).filter(Boolean).flatMap(c => [c, escapeFenceCell(c)]))];+ const forms = claimForms(input.claims);const source = await readLedgerSource(tx, input.sourceId);- if (!needles.length || !source || redactionFault === 'skip_live_carriers') return [];+ if (!forms.length || !source || redactionFault === 'skip_live_carriers') return [];await faultPoint('purge:ledger_redaction', { sourceId: input.sourceId });- const quoting = (column: string) => `EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(COALESCE(${column},'')), n) > 0)`;- const slugs = (await tx.executeRaw<{ slug: string }>(`SELECT DISTINCT slug FROM (- SELECT COALESCE(f.source_markdown_slug, f.entity_slug) AS slug FROM facts f WHERE f.source_id = $1 AND f.expired_at IS NULL AND ${quoting('f.context')}- UNION SELECT p.slug FROM takes k JOIN pages p ON p.id = k.page_id WHERE p.source_id = $1 AND ${quoting('k.resolved_source')}- UNION SELECT COALESCE(o.slug, f.slug) FROM links l JOIN pages f ON f.id = l.from_page_id LEFT JOIN pages o ON o.id = l.origin_page_id- WHERE COALESCE(o.source_id, f.source_id) = $1 AND ${quoting('l.context')}) s WHERE slug IS NOT NULL ORDER BY slug`, [input.sourceId, needles])).map(r => r.slug);+ const found = new Set<string>();+ await quotingSlugs(tx, input.sourceId, forms, `SELECT f.id, COALESCE(f.source_markdown_slug, f.entity_slug) AS slug, f.context AS text FROM facts f+ WHERE f.source_id = $1 AND f.id > $2 AND f.expired_at IS NULL AND COALESCE(f.context, '') <> ''`, found);+ await quotingSlugs(tx, input.sourceId, forms, `SELECT k.id, p.slug, k.resolved_source AS text FROM takes k JOIN pages p ON p.id = k.page_id+ WHERE p.source_id = $1 AND k.id > $2 AND COALESCE(k.resolved_source, '') <> ''`, found);+ await quotingSlugs(tx, input.sourceId, forms, `SELECT l.id, COALESCE(o.slug, f.slug) AS slug, l.context AS text FROM links l JOIN pages f ON f.id = l.from_page_id+ LEFT JOIN pages o ON o.id = l.origin_page_id WHERE COALESCE(o.source_id, f.source_id) = $1 AND l.id > $2 AND l.context <> ''`, found);+ const slugs = [...found].sort();const out: RedactedField[] = [];for (let at = 0; at < slugs.length; at += 200) {const state = await readBeliefState(tx, input.sourceId, slugs.slice(at, at + 200));@@ -144,10 +170,8 @@ export async function registerLiveCarriers(tx: BrainEngine, input: { sourceId: sid => state.pages.find(p => p.id === id)?.visible === false ? 'private' : 'world');for (const subject of subjects) for (const field of CARRYING_FIELDS[subject.kind] ?? []) {const text = subject.value[field];- if (typeof text !== 'string' || !quotes(text, input.claims)) continue;- await tx.executeRaw(`INSERT INTO belief_redactions (source_id, subject_key, field, purge_request, field_hash)- SELECT $1, $2, $3, $4::uuid, $5 WHERE NOT EXISTS (SELECT 1 FROM belief_redactions WHERE source_id = $1 AND subject_key = $2 AND field = $3- AND purge_request = $4::uuid AND field_hash = $5)`, [input.sourceId, subject.key, field, input.request, fieldHash(text)]);+ if (typeof text !== 'string' || !quotes(text, forms)) continue;+ await registerRedaction(tx, input.sourceId, subject.key, field, input.request, fieldHash(text));out.push({ subject_key: subject.key, field, event_id: 0 });}}diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex b1980ced46..d5cc49cf69 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -26,7 +26,8 @@ import type { WriteRequest } from '../persistence/model.ts';import { DELETION_INVENTORY, OUT_OF_REACH_RESIDUALS, type InventoryEntry } from '../deletion-inventory.ts';import type { PurgePlan, PurgeTarget } from './purge.ts';import { gitChildEnv } from '../git-env.ts';-import { purgeNeedles, type LedgerPurgeReport } from '../belief/purge.ts';+import { claimForms, quotes, type LedgerPurgeReport } from '../belief/purge.ts';+import { CARRYING_FIELDS } from '../belief/keys.ts';export type StoreCount = Record<string, number>;export type StoreStatus = 'deleted' | 'would_remove' | 'retained_inactive' | 'unverified' | 'out_of_reach' | 'out_of_scope' | 'not_present' | 'incomplete';@@ -172,24 +173,61 @@ async function effectPayloadReport(engine: BrainEngine, sourceId: string, needle* `incomplete`; the redacted fields are named; a live row whose own context quotes the claim survives the purge and is* named as `fact_context` (`out_of_scope: source_prose`) so the user can edit it.*/+/** Every string inside a recorded value, with the field it sits under. */+function valueStrings(value: unknown, field = ''): Array<[string, string]> {+ if (typeof value === 'string') return [[field, value]];+ if (Array.isArray(value)) return value.flatMap(v => valueStrings(v, field));+ if (value && typeof value === 'object') return Object.entries(value as Record<string, unknown>).flatMap(([k, v]) => valueStrings(v, field || k));+ return [];+}++/**+ * W1 (BELIEF_LEDGER.md 6.5): what recorded history still says about the claims. Every value is read in keyset+ * batches and matched in JS (case folded like the purge passes, #11). A carrying field still quoting a claim is a+ * redaction the purge missed (`incomplete`); any other field (another subject's longer claim, #12) is history the+ * purge does not rewrite, reported by key as `out_of_scope`.+ */async function ledgerReports(engine: BrainEngine, sourceId: string, claims: readonly string[], ledger: LedgerPurgeReport | null | undefined, deadline: number): Promise<StoreReport[]> {- const needles = purgeNeedles(claims);- if (!needles.length) return [];- const carrying = `EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(COALESCE(e.value->>'context','')), n) > 0 OR strpos(lower(COALESCE(e.value->>'resolved_source','')), n) > 0)`;- const left = await boundedCount(engine, `SELECT 1 FROM belief_events e WHERE e.source_id = $1 AND e.value IS NOT NULL AND e.subject_kind IN ('fact','take','link') AND ${carrying}`,- [sourceId, needles], deadline);+ const forms = claimForms(claims);+ if (!forms.length) return [];const redacted = ledger?.redacted_fields ?? [];const removed = (ledger?.purged_events ?? 0) + redacted.length;+ const missed: string[] = [], other: string[] = [];+ let unverified: string | null = null;+ for (let after = 0; ;) {+ if (performance.now() > deadline) { unverified = 'verification_deadline'; break; }+ const rows = await engine.executeRaw<{ id: number; subject_kind: string; subject_key: string; value: unknown }>(`SELECT id, subject_kind, subject_key, value+ FROM belief_events WHERE source_id = $1 AND id > $2 AND value IS NOT NULL ORDER BY id LIMIT 1000`, [sourceId, after]);+ if (!rows.length) break;+ after = Number(rows[rows.length - 1]!.id);+ for (const row of rows) {+ const value = typeof row.value === 'string' ? JSON.parse(row.value) : row.value;+ for (const [field, text] of valueStrings(value)) {+ if (!quotes(text, forms)) continue;+ ((CARRYING_FIELDS[row.subject_kind] ?? []).includes(field) ? missed : other).push(`${field}@${row.subject_key}`);+ }+ }+ if (rows.length < 1000) break;+ }const items = [...new Set(redacted.map(r => `${r.field}@${r.subject_key}`))].slice(0, 20);- const reports: StoreReport[] = ['unverified' in left ? { store: 'belief_events', status: 'unverified', reason: left.unverified, removed }- : left.count ? { store: 'belief_events', status: 'incomplete', remaining: left.count, removed }- : { store: 'belief_events', status: removed ? 'deleted' : 'not_present', removed, ...(items.length ? { items,- detail: 'Recorded history keeps each event\'s skeleton; the purged values and every carrying field that quoted them now read as the redaction marker.' } : {}) }];- const live = await engine.executeRaw<{ id: number }>(`SELECT f.id FROM facts f WHERE f.source_id = $1 AND f.expired_at IS NULL- AND EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(COALESCE(f.context,'')), n) > 0) ORDER BY f.id LIMIT 20`, [sourceId, needles]);+ const reports: StoreReport[] = [unverified ? { store: 'belief_events', status: 'unverified', reason: unverified, removed }+ : missed.length ? { store: 'belief_events', status: 'incomplete', remaining: missed.length, removed, items: [...new Set(missed)].slice(0, 20) }+ : other.length ? { store: 'belief_events', status: 'out_of_scope', reason: 'probed_reported', remaining: new Set(other).size, removed, items: [...new Set(other)].slice(0, 20),+ detail: 'These recorded events belong to other subjects whose own value quotes the purged claim (a longer claim, say); purge redacts only the purged keys and the fields that quote them. Purge those subjects too to remove them.' }+ : { store: 'belief_events', status: removed ? 'deleted' : 'not_present', removed, ...(items.length ? { items,+ detail: 'Recorded history keeps each event\'s skeleton; the purged values and every carrying field that quoted them now read as the redaction marker.' } : {}) }];+ const live: number[] = [];+ for (let after = 0; live.length < 20 && performance.now() <= deadline; ) {+ const rows = await engine.executeRaw<{ id: number; context: string }>(`SELECT id, context FROM facts WHERE source_id = $1 AND id > $2 AND expired_at IS NULL+ AND COALESCE(context, '') <> '' ORDER BY id LIMIT 1000`, [sourceId, after]);+ if (!rows.length) break;+ after = Number(rows[rows.length - 1]!.id);+ for (const r of rows) if (live.length < 20 && quotes(r.context, forms)) live.push(Number(r.id));+ if (rows.length < 1000) break;+ }if (live.length) {const keys = [...new Set([...(ledger?.live_carriers ?? []), ...redacted].filter(r => r.field === 'context').map(r => r.subject_key))].slice(0, 20);- reports.push({ store: 'fact_context', status: 'out_of_scope', reason: 'source_prose', remaining: live.length, items: [...live.map(r => `f${r.id}`), ...keys],+ reports.push({ store: 'fact_context', status: 'out_of_scope', reason: 'source_prose', remaining: live.length, items: [...live.map(id => `f${id}`), ...keys],detail: 'These live facts quote the purged claim in their context, which purge leaves as it is; their recorded history shows the redaction marker until the owner replaces the context. Edit them.' });}return reports;diff --git a/test/belief-ledger-purge-review.test.ts b/test/belief-ledger-purge-review.test.tsindex fec1d57203..c9e72ae522 100644--- a/test/belief-ledger-purge-review.test.ts+++ b/test/belief-ledger-purge-review.test.ts@@ -7,6 +7,7 @@ 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 { redactCarryingFields, registerLiveCarriers } from '../src/core/belief/purge.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';@@ -89,5 +90,52 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {expect(r.status).toBe('purged');expect(r.leaks).toEqual([]);}, 240_000);+ test('#6: the purge passes never substring-scan in SQL; 200 claims cost one keyset pass over the carrying fields', async () => {+ const r = await collect<Record<string, unknown>>(report => brain(async b => {+ await b.put('companies/acme-example', beliefPage({ prose: 'Acme.' }));+ await b.put('companies/acme-example', beliefPage({ facts: [{ claim: 'Acme sells widgets', context: `notes say ${X}` }, 'Acme has two offices'] }));+ const claims = [X, ...Array.from({ length: 199 }, (_, i) => `needle claim number ${i} about something`)];+ const statements: Array<{ sql: string; params: unknown[] }> = [];+ const out = await b.engine.transaction(async tx => withCoordinatedWrite(tx, [b.sourceId], async () => {+ const spy = new Proxy(tx, { get: (t, k) => k === 'executeRaw' ? (sql: string, params: unknown[] = []) => { statements.push({ sql, params }); return t.executeRaw(sql, params); }+ : (t as any)[k] });+ const request = randomUUID();+ return { redacted: (await redactCarryingFields(spy, { sourceId: b.sourceId, request, claims })).map(f => f.field),+ live: (await registerLiveCarriers(spy, { sourceId: b.sourceId, request, claims })).map(f => f.field) };+ }, TEST_WRITE_ATTRIBUTION));+ report({ ...out, substring: statements.filter(st => /strpos\(/i.test(st.sql)).length,+ claimParams: statements.filter(st => JSON.stringify(st.params).includes('needle claim')).length });+ }));+ expect(r).toEqual({ redacted: ['context'], live: ['context'], substring: 0, claimParams: 0 });+ }, 240_000);++ test('#11: a claim whose case folds differently in SQL and JS (Turkish dotted I, Greek sigma) is still redacted and registered', async () => {+ const r = await collect<Record<string, unknown>>(report => brain(async b => {+ const slug = 'companies/acme-example';+ const claims = ['İstanbul office code is 4417', 'ΟΔΟΣ ΣΟΦΙΑΣ door code 9921'];+ for (const [i, claim] of claims.entries()) await b.put(`vault/code-${i}-example`, beliefPage({ facts: [claim] }));+ await b.put(slug, beliefPage({ prose: 'Acme.' }));+ await b.put(slug, beliefPage({ facts: [{ claim: 'Acme sells widgets', context: `memo: ${claims[0]}` }, { claim: 'Acme has two offices', context: `memo: ${claims[1]}` }] }));+ for (const claim of claims) await purgeFact(b, claim);+ report({ leaks: quoting(await b.events(), claims[0]!).concat(quoting(await b.events(), claims[1]!)),+ register: (await b.engine.executeRaw<{ n: number }>('SELECT count(DISTINCT subject_key)::int AS n FROM belief_redactions WHERE source_id = $1', [b.sourceId]))[0]!.n });+ }));+ expect(r).toEqual({ leaks: [], register: 2 });+ }, 240_000);++ test('#12: the receipt reports another subject\'s recorded value that still quotes the claim, naming its key', async () => {+ const r = await collect<Record<string, unknown>>(report => brain(async b => {+ const slug = 'companies/acme-example';+ await b.put(slug, beliefPage({ facts: ['Acme sells widgets'] }));+ await b.put(slug, beliefPage({ facts: [`${X} for the back office`, 'Acme sells widgets'] }));+ await b.put(slug, beliefPage({ facts: [X, 'Acme sells widgets'] }));+ const result = await purgeFact(b, X);+ const store = (result.stores as Array<Record<string, any>>).find(st => st.store === 'belief_events')!;+ const carrier = (await b.events()).find(e => e.value?.fact === `${X} for the back office`)!;+ report({ status: store.status, items: store.items, key: carrier.subject_key });+ }));+ expect(r.status).toBe('out_of_scope');+ expect(r.items).toEqual([`fact@${r.key}`]);+ }, 240_000);});}