Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief ledger lane A: a truncated purge derivation walk withholds certification of its coverage interval (#21)

garrytan0de67aa51ada
diff --git a/src/core/belief/coverage-report.ts b/src/core/belief/coverage-report.ts
index a3fe61f24d..ba7aa437c9 100644
--- a/src/core/belief/coverage-report.ts
+++ b/src/core/belief/coverage-report.ts
@@ -38,6 +38,8 @@ export interface CoverageInterval {
restores: RestoreMark[];
/** Slug intervals a drift finding uncertified: (from, to], permanently. */
drift: DriftMark[];
+ /** Purge requests whose derivation walk hit its bound in this interval: the interval is not certified (design 6.5). */
+ truncated_walks: string[];
}
interface CoverageRow { id: number; event_type: string; recorded_at: string; value: unknown; cause: unknown; incarnation: string }
@@ -56,7 +58,7 @@ export async function coverageIntervals(engine: BrainEngine, sourceId: string):
const current = intervals.at(-1);
if (row.event_type === 'coverage.started') {
intervals.push({ run: (obj(row.cause).run as string | undefined) ?? null, incarnation: row.incarnation, started_id: id, started_at: iso(row.recorded_at),
- watermark: null, stopped_at: null, certified: false, links_certified: false, baseline: { pages_done: 0, pending: null, complete: false }, restores: [], drift: [] });
+ watermark: null, stopped_at: null, certified: false, links_certified: false, baseline: { pages_done: 0, pending: null, complete: false }, restores: [], drift: [], truncated_walks: [] });
continue;
}
if (!current || current.stopped_at) continue;
@@ -84,6 +86,11 @@ export async function coverageIntervals(engine: BrainEngine, sourceId: string):
AND ($4::timestamptz IS NULL OR recorded_at <= $4::timestamptz) ORDER BY id`,
[sourceId, interval.incarnation, interval.started_id, interval.stopped_at]);
interval.drift = drift.map(d => ({ slug: d.slug, event_id: Number(d.id), from: d.from ? iso(d.from) : null, to: iso(d.recorded_at) }));
+ const walks = await engine.executeRaw<{ request: string }>(`SELECT DISTINCT cause->>'purge_request' AS request FROM belief_events
+ WHERE source_id = $1 AND event_type = 'derived.hidden' AND cause->>'derived_walk' = 'truncated' AND source_incarnation = $2::uuid AND id > $3
+ AND ($4::timestamptz IS NULL OR recorded_at <= $4::timestamptz) ORDER BY 1`, [sourceId, interval.incarnation, interval.started_id, interval.stopped_at]);
+ interval.truncated_walks = walks.map(w => w.request);
+ if (walks.length) { interval.certified = false; interval.links_certified = false; }
}
const open = intervals.at(-1);
if (open && !open.stopped_at && !open.baseline.complete) {
@@ -98,7 +105,7 @@ export async function coverageIntervals(engine: BrainEngine, sourceId: string):
}
export type CoverageAt =
- | { ok: true; certified: boolean; uncertified_reason: 'unmanaged' | 'drift' | null; cut: string; interval: CoverageInterval }
+ | { ok: true; certified: boolean; uncertified_reason: 'unmanaged' | 'truncated_walk' | 'drift' | null; cut: string; interval: CoverageInterval }
| { ok: false; code: 'coverage_from'; from: string | null; message: string }
| { ok: false; code: 'coverage_gap'; reason: 'not_covered' | 'restore'; from: string | null; until: string | null; message: string };
@@ -117,7 +124,8 @@ async function slugCut(engine: BrainEngine, sourceId: string, interval: Coverage
* (`slug`), from its own cut; for the source, from the watermark. Before the
* cut: `coverage_from`. Between intervals or inside a restore gap
* ([archive time, restore]): `coverage_gap`. A covered answer says whether it
- * is certified (managed source, no drift mark over `at`).
+ * is certified (managed source, no truncated purge walk in the interval, no
+ * drift mark over `at`).
*/
export async function coverageAt(engine: BrainEngine, sourceId: string, at: Date | string, slug?: string): Promise<CoverageAt> {
const t = new Date(at).getTime();
@@ -144,7 +152,8 @@ export async function coverageAt(engine: BrainEngine, sourceId: string, at: Date
message: cut ? `The belief ledger covers ${slug ?? sourceId} only from ${cut}.` : `The baseline of ${slug ?? sourceId} has not run yet.` };
}
const drifted = slug ? interval.drift.some(d => d.slug === slug && (d.from == null || t > Date.parse(d.from)) && t <= Date.parse(d.to)) : false;
- return { ok: true, certified: interval.certified && !drifted, uncertified_reason: !interval.certified ? 'unmanaged' : drifted ? 'drift' : null, cut, interval };
+ return { ok: true, certified: interval.certified && !drifted, cut, interval,
+ uncertified_reason: interval.truncated_walks.length ? 'truncated_walk' : !interval.certified ? 'unmanaged' : drifted ? 'drift' : null };
}
/**
diff --git a/src/core/belief/purge.ts b/src/core/belief/purge.ts
index 800a69ff3b..f9fbf0a2a7 100644
--- a/src/core/belief/purge.ts
+++ b/src/core/belief/purge.ts
@@ -318,13 +318,6 @@ export async function appendDerivedHidden(tx: BrainEngine, input: { sourceId: st
export interface LedgerPurgeReport { purged_events: number; redacted_fields: RedactedField[]; live_carriers: RedactedField[]; version_carriers?: RedactedField[]; derived_hidden: number; derived_walk: 'complete' | 'truncated' }
-/** Purge requests whose derivation walk was truncated: the coverage check withholds certification of their source until a complete walk runs. */
-export async function truncatedPurgeWalks(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<string[]> {
- const rows = await engine.executeRaw<{ request: string }>(`SELECT DISTINCT cause->>'purge_request' AS request FROM belief_events
- WHERE source_id = $1 AND cause->>'derived_walk' = 'truncated' AND cause->>'purge_request' IS NOT NULL ORDER BY 1`, [sourceId]);
- return rows.map(r => r.request);
-}
-
/** The logical key of one live fact or take row and its carrying-field values, for an owner release. */
async function rowSubject(engine: BrainEngine, table: 'facts' | 'takes', id: number): Promise<{ sourceId: string; key: string; value: Record<string, unknown> } | null> {
const [row] = await engine.executeRaw<{ source_id: string; slug: string | null }>(table === 'facts'
diff --git a/test/belief-ledger-purge-review.test.ts b/test/belief-ledger-purge-review.test.ts
index 87a925137a..b9b4185382 100644
--- a/test/belief-ledger-purge-review.test.ts
+++ b/test/belief-ledger-purge-review.test.ts
@@ -11,6 +11,8 @@ import { CODES } from '../src/core/error-registry.ts';
import { __setBeliefEmitterFaultForTests } from '../src/core/belief/append.ts';
import { withBeliefBatch } from '../src/core/belief/ledger.ts';
import { backfillBeliefHistory } from '../src/core/belief/backfill.ts';
+import { coverageAt, coverageIntervals } from '../src/core/belief/coverage-report.ts';
+import { recordDerivationInputs } from '../src/core/facts/derivation-inputs.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';
@@ -213,6 +215,25 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
}));
expect(r).toEqual({ retention: 0, purge: 1 });
}, 240_000);
+ test('#21: a truncated derivation walk withholds certification of the interval it ran in', async () => {
+ const r = await collect<Record<string, unknown>>(report => brain(async b => {
+ const derived = Array.from({ length: 9 }, (_, i) => `Acme derived note ${i + 1}`);
+ await b.put('companies/acme-example', beliefPage({ facts: [X] }));
+ await b.put('notes/derived-example', beliefPage({ title: 'Derived Example', facts: derived }));
+ const ids = async (claims: string[]) => Promise.all(claims.map(async c => Number((await b.engine.executeRaw<{ id: number }>(
+ 'SELECT id FROM facts WHERE source_id = $1 AND fact = $2 AND expired_at IS NULL', [b.sourceId, c]))[0]!.id)));
+ const chain = await ids([X, ...derived]);
+ for (let i = 1; i < chain.length; i++) await recordDerivationInputs(b.engine, { table: 'facts', id: chain[i]!, sourceId: b.sourceId }, [{ table: 'facts', id: chain[i - 1]! }]);
+ const before = await coverageAt(b.engine, b.sourceId, new Date());
+ const result = await purgeFact(b, X);
+ const after = await coverageAt(b.engine, b.sourceId, new Date());
+ const [interval] = await coverageIntervals(b.engine, b.sourceId);
+ report({ truncated: result.purge.derived.truncated, before: before.ok && before.certified, after: after.ok && [after.certified, after.uncertified_reason],
+ walks: interval!.truncated_walks.length });
+ }));
+ expect(r).toEqual({ truncated: true, before: true, after: [false, 'truncated_walk'], walks: 1 });
+ }, 240_000);
+
test('#22: an unwritable purge mirror refuses the purge with a typed error, with or without a ledger', async () => {
const run = (enable: boolean) => collect<Record<string, unknown>>(report => beliefBrain(async b => {
await b.put('companies/acme-example', beliefPage({ facts: [X, 'Acme sells widgets'] }));