Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W1: belief ledger probe harness and forced-probe emitter seam
garrytand70c3e092b1a
diff --git a/src/core/belief/append.ts b/src/core/belief/append.tsindex e8d314d2ce..ff0076c948 100644--- a/src/core/belief/append.ts+++ b/src/core/belief/append.ts@@ -99,7 +99,18 @@ async function applyRedactions(tx: BrainEngine, sourceId: string, drafts: Beliefreturn redacted;}-export async function appendBeliefEvents(tx: BrainEngine, drafts: BeliefEventDraft[], ctx: AppendContext): Promise<number> {+let emitterFault: ((drafts: BeliefEventDraft[]) => BeliefEventDraft[]) | null = null;+/**+ * Test seam for the forced probes (section 11): a deliberately broken emitter+ * rewrites the drafts before the insert (drop a type, corrupt a value), and the+ * probe that must catch it is asserted to fail. Null restores the real emitter.+ */+export function __setBeliefEmitterFaultForTests(fault: ((drafts: BeliefEventDraft[]) => BeliefEventDraft[]) | null): void {+ emitterFault = fault;+}++export async function appendBeliefEvents(tx: BrainEngine, input: BeliefEventDraft[], ctx: AppendContext): Promise<number> {+ const drafts = emitterFault ? emitterFault(input) : input;if (!drafts.length) return 0;const ordered = orderDrafts(drafts);const sourceId = ordered[0]!.sourceId;diff --git a/test/helpers/belief-ledger.ts b/test/helpers/belief-ledger.tsnew file mode 100644index 0000000000..b553228cf9--- /dev/null+++ b/test/helpers/belief-ledger.ts@@ -0,0 +1,123 @@+/**+ * Shared harness for the belief ledger probes (docs/designs/BELIEF_LEDGER.md+ * section 11): a brain whose source has active coverage, page writes through+ * the shared write path, and readers for the events it appended. Runs on+ * PGLite, and on Postgres when DATABASE_URL names a test database+ * (`beliefEngineCases`), so every probe asserts the same values on both.+ */+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { enableBeliefLedger } from '../../src/core/belief/coverage.ts';+import { managedBrain } from './managed-brain.ts';+import { isolatedPersistencePostgres } from './persistence-postgres.ts';+import { withEnv } from './with-env.ts';++export interface BeliefEvent {+ id: number; source_id: string; source_incarnation: string; page_lifetime: string | null; slug: string; subject_kind: string; subject_key: string;+ event_type: string; origin: string; trust_tier: string; writer_tier: string | null; tier_basis: string; visibility: string; publication_id: string;+ ord: number; recorded_at: string; value: Record<string, unknown> | null; value_hash: string | null; prior_hash: string | null; state_hash: string;+ cause: Record<string, unknown>; claim_fp: string | null; purged: boolean; redacted_fields: string[] | null; event_key: string;+}++export interface BeliefBrain {+ engine: BrainEngine; ctx: OperationContext; root: string; sourceId: string;+ put(slug: string, content: string, extra?: Record<string, unknown>): Promise<Record<string, unknown>>;+ op(operation: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;+ enable(): Promise<void>;+ /** Events after `afterId` (default all), in id order. */+ events(afterId?: number): Promise<BeliefEvent[]>;+ lastId(): Promise<number>;+}++export const beliefEngineCases = (): Array<{ name: 'pglite' | 'postgres'; databaseUrl?: string }> => [+ { name: 'pglite' }, ...(process.env.DATABASE_URL ? [{ name: 'postgres' as const, databaseUrl: process.env.DATABASE_URL }] : []),+];++async function readEvents(engine: BrainEngine, sourceId: string, afterId = 0): Promise<BeliefEvent[]> {+ const rows = await engine.executeRaw<BeliefEvent>(`SELECT id, source_id, source_incarnation::text AS source_incarnation, page_lifetime::text AS page_lifetime,+ slug, subject_kind, subject_key, event_type, origin, trust_tier, writer_tier, tier_basis, visibility, publication_id::text AS publication_id, ord,+ recorded_at, value, value_hash, prior_hash, state_hash, cause, claim_fp, purged, redacted_fields, encode(event_key, 'hex') AS event_key+ FROM belief_events WHERE source_id = $1 AND id > $2 ORDER BY id`, [sourceId, afterId]);+ const json = (v: unknown) => typeof v === 'string' ? JSON.parse(v) : v;+ return rows.map(r => ({ ...r, id: Number(r.id), ord: Number(r.ord), value: json(r.value) as BeliefEvent['value'], cause: json(r.cause) as BeliefEvent['cause'] }));+}++function brainApi(engine: BrainEngine, ctx: OperationContext, root: string, sourceId: string): BeliefBrain {+ const op = async (operation: string, params: Record<string, unknown>) =>+ await submitPageMutation(ctx as never, { operation: operation as never, params: { request_id: randomUUID(), ...params } as never }) as Record<string, unknown>;+ return {+ engine, ctx, root, sourceId, op,+ put: (slug, content, extra = {}) => op('put_page', { slug, content, force: true, ...extra }),+ enable: async () => { await enableBeliefLedger(engine, sourceId); },+ events: afterId => readEvents(engine, sourceId, afterId),+ lastId: async () => Number((await engine.executeRaw<{ id: number | null }>('SELECT max(id) AS id FROM belief_events WHERE source_id = $1', [sourceId]))[0]?.id ?? 0),+ };+}++/**+ * A brain with one source. `managed: true` runs the activated managed brain+ * (certified coverage); otherwise an unmanaged brain whose source owns a+ * claimed worktree. Coverage is enabled unless `enable: false`.+ */+export async function beliefBrain(run: (brain: BeliefBrain) => Promise<void>,+ opts: { managed?: boolean; databaseUrl?: string; enable?: boolean; setup?: (brain: BeliefBrain) => Promise<void> } = {}): Promise<void> {+ if (opts.managed) {+ await managedBrain(async ({ engine, ctx, root }) => {+ const brain = brainApi(engine, ctx, root, 'default');+ await opts.setup?.(brain);+ if (opts.enable !== false) await brain.enable();+ await run(brain);+ }, { databaseUrl: opts.databaseUrl });+ return;+ }+ const home = mkdtempSync(join(tmpdir(), 'gbrain-belief-'));+ let engine: BrainEngine | undefined;+ let close: (() => Promise<void>) | undefined;+ try {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ if (opts.databaseUrl) ({ engine, close } = await isolatedPersistencePostgres(opts.databaseUrl));+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }+ const root = join(home, 'brain'); mkdirSync(root);+ const sourceId = `belief-${randomUUID().slice(0, 8)}`;+ await engine!.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await claimWorktree(engine!, sourceId, root);+ const ctx: OperationContext = { engine: engine!, sourceId, remote: false, dryRun: false,+ config: { engine: engine!.kind, embedding_disabled: true } as never, logger: { info() {}, warn() {}, error() {} } as never };+ const brain = brainApi(engine!, ctx, root, sourceId);+ await opts.setup?.(brain);+ if (opts.enable !== false) await brain.enable();+ await run(brain);+ });+ } finally {+ if (engine) { await disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); }+ rmSync(home, { recursive: true, force: true });+ }+}++/** A page body with a facts fence, a takes fence, prose and wikilinks. */+export function beliefPage(o: { title?: string; type?: string; prose?: string; facts?: Array<string | { claim: string; context?: string; confidence?: string; visibility?: string }>;+ takes?: Array<string | { claim: string; weight?: string; since?: string }>; links?: string[]; frontmatter?: Record<string, string> } = {}): string {+ const fm = { type: o.type ?? 'company', title: o.title ?? 'Acme Example', ...o.frontmatter };+ const facts = (o.facts ?? []).map(f => typeof f === 'string' ? { claim: f } : f);+ const takes = (o.takes ?? []).map(t => typeof t === 'string' ? { claim: t } : t);+ const parts = [`---\n${Object.entries(fm).map(([k, v]) => `${k}: ${v}`).join('\n')}\n---`,+ `${o.prose ?? 'Draft.'}${(o.links ?? []).map(l => ` See [[${l}]].`).join('')}`];+ if (facts.length) parts.push(['<!--- gbrain:facts:begin -->', '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',+ ...facts.map((f, i) => `| ${i + 1} | ${f.claim} | fact | ${f.confidence ?? '1.0'} | ${f.visibility ?? 'world'} | medium | 2026-01-01 | | remember | ${f.context ?? ''} |`),+ '<!--- gbrain:facts:end -->'].join('\n'));+ if (takes.length) parts.push(['<!--- gbrain:takes:begin -->', '| # | claim | kind | who | weight | since | source |', '|---|-------|------|-----|--------|-------|--------|',+ ...takes.map((t, i) => `| ${i + 1} | ${t.claim} | take | brain | ${t.weight ?? '0.5'} | ${t.since ?? '2026-07'} | notes |`), '<!--- gbrain:takes:end -->'].join('\n'));+ return `${parts.join('\n\n')}\n`;+}++/** Events reduced to what probes assert exactly: type, kind and the subject key's readable parts. */+export const shape = (events: BeliefEvent[]) => events.map(e => `${e.subject_kind}:${e.event_type}`);