Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(persistence): preview-approval helper for preview-bound applies (ENG-O1)
garrytanb2b1607c1b58
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjsindex 09fa913cd5..88f8e6d678 100644--- a/scripts/check-orphan-modules.mjs+++ b/scripts/check-orphan-modules.mjs@@ -71,6 +71,7 @@ const PERMITTED_TEST_ONLY = [{ path: 'src/core/archive-crawler-config.ts', reason: "held: skills/archive-crawler/SKILL.md describes the scan_paths safety fence as code-enforced; wire-or-retract is a product decision" },{ path: 'src/core/chronicle/backstop.ts', reason: 'held: the put_page chronicle backstop was dropped in v0.51.0.0, so the documented auto_chronicle setting does nothing; restore-or-retract is a product decision' },{ path: 'src/core/onboard/impact-capture.ts', reason: 'held: sole writer of migration_impact_log, which the shipped `gbrain onboard --history` reads; wire-or-retract is a product decision' },+ { path: 'src/core/persistence/preview-approval.ts', reason: 'held: fix wave 5 shared commit (ENG-O1); its callers (jobs authorize-legacy/cancel --select, repair stale-atoms/extractor-facts) land in the wave 5 lanes, which remove this entry' },{ path: 'src/core/progressive-batch/orchestrator.ts', reason: 'held: TODOS.md keeps an open item to re-compose progressive-batch with --workers on the 3 reindex sites (callers dropped in the v0.41.17.0 merge)' },{ path: 'src/core/progressive-batch/retrofit-wrap.ts', reason: 'held: progressive-batch re-compose item still open in TODOS.md' },{ path: 'src/core/progressive-batch/stage-report.ts', reason: 'held: progressive-batch re-compose item still open in TODOS.md' },diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsnew file mode 100644index 0000000000..582278a2e2--- /dev/null+++ b/src/core/persistence/preview-approval.ts@@ -0,0 +1,104 @@+/**+ * Preview-bound approval (fix wave 5, ENG-O1), shared by every command whose+ * apply must touch exactly the set its preview showed: `gbrain jobs+ * authorize-legacy --select`, `gbrain jobs cancel --select`, `gbrain repair+ * stale-atoms` and `gbrain repair extractor-facts`.+ *+ * The flow is the same for all four:+ *+ * 1. The preview computes `previewHash(parts)` over everything the operator+ * reviewed (brain and source identity, the listed items with their+ * revisions or evidence, the selection options) and saves the items with+ * `saveApprovedSet`. It prints the hash and the filled apply command.+ * 2. The apply passes the hash back (`--expect <hash>`). `loadApprovedSet`+ * returns the saved items, or refuses with `preview_changed` when no set+ * was saved under that hash or the set is older than the checkpoint purge+ * window. A refused load never returns a partial set, so an apply either+ * starts from the whole approved set or not at all.+ * 3. The apply replays the approved items (each with its own request id, so+ * a resumed apply after a crash replays the same requests and reconciles+ * their receipts before advancing), rechecking each item against the+ * live state, and calls `clearApprovedSet` when it finishes.+ *+ * Sets live in `op_checkpoints` (`op='repair-approval'`, keyed by command and+ * hash), so no migration is needed. `purgeStaleCheckpoints` deletes rows older+ * than its TTL (7 days by default); `APPROVAL_MAX_AGE_DAYS` matches it, so a+ * set the purge may already have taken is never trusted.+ *+ * `previewHash` is SHA-256 over the same key-sorted JSON as+ * `authorityDigest` (`minions/submission-authority.ts`), so the existing+ * `authorizeLegacyJobs --ids` snapshot digest is byte-identical when computed+ * through this helper.+ */+import type { BrainEngine } from '../engine.ts';+import type { OperationError } from '../ops/contract.ts';+import { catalogueError } from '../error-catalogue.ts';+import { digest } from './digest.ts';++export const PREVIEW_APPROVAL_OP = 'repair-approval';++/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */+export const APPROVAL_MAX_AGE_DAYS = 7;++export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts';++export interface ApprovedSetKey {+ command: PreviewApprovalCommand;+ /** The preview hash the operator passed with `--expect`. */+ hash: string;+ /** The read-only command that prints a fresh preview, filled with the caller's real flags. */+ previewCommand: string;+}++export interface ApprovedSet<T> {+ command: PreviewApprovalCommand;+ hash: string;+ items: T[];+ /** When the preview last saved this set (database clock, ISO 8601). */+ approved_at: string;+}++/** SHA-256 hex over key-sorted JSON of everything the preview showed. */+export function previewHash(parts: unknown): string {+ return digest(parts);+}++/** `preview_changed`: the hash no longer names a saved, fresh approved set. */+export function previewChangedError(hash: string, previewCommand: string): OperationError {+ return catalogueError('preview_changed', `The preview changed since ${hash}; re-run ${previewCommand} and use the new hash.`,+ `Re-run the preview: ${previewCommand}`);+}++function fingerprint(command: PreviewApprovalCommand, hash: string): string {+ return `${command}:${hash}`;+}++/** Saves (or re-confirms, restarting its age) the approved set a preview printed. */+export async function saveApprovedSet<T>(engine: BrainEngine, key: Omit<ApprovedSetKey, 'previewCommand'>, items: readonly T[]): Promise<void> {+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,+ [PREVIEW_APPROVAL_OP, fingerprint(key.command, key.hash), JSON.stringify([{ command: key.command, hash: key.hash, items }])]);+}++/**+ * The whole approved set saved under `hash`, or `preview_changed` when it is+ * missing, malformed or older than `APPROVAL_MAX_AGE_DAYS`. Age is measured on+ * the database clock, the same clock the purge uses.+ */+export async function loadApprovedSet<T>(engine: BrainEngine, key: ApprovedSetKey): Promise<ApprovedSet<T>> {+ const [row] = await engine.executeRaw<{ completed_keys: Array<{ command?: string; hash?: string; items?: T[] }>; fresh: boolean; approved_at: string }>(+ `SELECT completed_keys, updated_at >= now() - ($3 || ' days')::interval AS fresh,+ to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS approved_at+ FROM op_checkpoints WHERE op=$1 AND fingerprint=$2`,+ [PREVIEW_APPROVAL_OP, fingerprint(key.command, key.hash), String(APPROVAL_MAX_AGE_DAYS)]);+ const saved = row?.completed_keys?.[0];+ if (!row || row.fresh !== true || saved?.command !== key.command || saved.hash !== key.hash || !Array.isArray(saved.items)) {+ throw previewChangedError(key.hash, key.previewCommand);+ }+ return { command: key.command, hash: key.hash, items: saved.items, approved_at: row.approved_at };+}++/** Drops an approved set once its apply finished. */+export async function clearApprovedSet(engine: BrainEngine, key: Omit<ApprovedSetKey, 'previewCommand'>): Promise<void> {+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [PREVIEW_APPROVAL_OP, fingerprint(key.command, key.hash)]);+}diff --git a/test/e2e/preview-approval-postgres.test.ts b/test/e2e/preview-approval-postgres.test.tsnew file mode 100644index 0000000000..cb2957075e--- /dev/null+++ b/test/e2e/preview-approval-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../preview-approval.test.ts'));diff --git a/test/preview-approval.test.ts b/test/preview-approval.test.tsnew file mode 100644index 0000000000..27c54f3691--- /dev/null+++ b/test/preview-approval.test.ts@@ -0,0 +1,143 @@+/**+ * Preview-approval helper contract (fix wave 5, ENG-O1 / ENG-O14), on PGLite+ * and, with a safe DATABASE_URL, Postgres (test/e2e/preview-approval-postgres.test.ts).+ *+ * One contract across the four preview-bound commands: the saved set round-+ * trips whole under its hash, sets of different commands never satisfy each+ * other, a missing, foreign or expired set refuses with `preview_changed`+ * (never a partial set), a purge-eligible set is never trusted, and+ * `previewHash` is byte-identical to the `authorizeLegacyJobs --ids` digest.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';+import { authorityDigest } from '../src/core/minions/submission-authority.ts';+import { APPROVAL_MAX_AGE_DAYS, PREVIEW_APPROVAL_OP, clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet,+ type PreviewApprovalCommand } from '../src/core/persistence/preview-approval.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const COMMANDS: Array<{ command: PreviewApprovalCommand; preview: string }> = [+ { command: 'authorize-legacy', preview: 'gbrain jobs authorize-legacy --select "status=waiting"' },+ { command: 'jobs-cancel', preview: 'gbrain jobs cancel --select "status=waiting|delayed"' },+ { command: 'stale-atoms', preview: 'gbrain repair stale-atoms --source default' },+ { command: 'extractor-facts', preview: 'gbrain repair extractor-facts --include-ambiguous' },+];++async function refusal(run: () => Promise<unknown>): Promise<OperationError> {+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a preview_changed refusal');+}++describe('previewHash', () => {+ // The shape authorizeLegacyJobs --ids hashes: raw rows with Dates, bigints, JSONB, nulls and unsorted keys.+ const legacySnapshot = {+ preview_version: 1, authority_version: 1, version: '0.60.26.0',+ jobs: [{ id: 7, name: 'sync', status: 'waiting', data: { sourceId: 'default', z: [1, null, { b: 2, a: 1 }] }, submission_authority: null,+ created_at: new Date('2026-09-01T00:00:00.000Z'), claim_generation: 3n, legacy_authority_is_null: true, absent: undefined }],+ dependencies: [], sources: [{ id: 'default', local_path: null, config: {}, archived: false, created_at: new Date('2026-01-01T00:00:00.000Z') }],+ };++ test('is byte-identical to the authorize-legacy --ids digest (authorityDigest) and pinned', () => {+ expect(previewHash(legacySnapshot)).toBe(authorityDigest(legacySnapshot));+ expect(previewHash(legacySnapshot)).toBe('8a78b9ac1ca4ea11a4a0dadeab4e2733f318d8c0730766f8f62e88ff47c74351');+ expect(previewHash(['stale-atoms', { b: 1, a: 2 }])).toBe(authorityDigest(['stale-atoms', { a: 2, b: 1 }]));+ });++ test('changes when any listed item or option changes', () => {+ const base = previewHash({ command: 'stale-atoms', items: [{ id: 1, revision: 'r1' }], options: { limit: 10 } });+ expect(previewHash({ command: 'stale-atoms', items: [{ id: 1, revision: 'r2' }], options: { limit: 10 } })).not.toBe(base);+ expect(previewHash({ command: 'stale-atoms', items: [{ id: 1, revision: 'r1' }], options: { limit: 11 } })).not.toBe(base);+ expect(base).toMatch(/^[a-f0-9]{64}$/);+ });++ test('preview_changed carries the DX-O2 message, the filled preview command and the anchor', () => {+ const error = previewChangedError('abc123', 'gbrain repair stale-atoms');+ expect(error.toJSON()).toMatchObject({ error: 'preview_changed',+ message: 'The preview changed since abc123; re-run gbrain repair stale-atoms and use the new hash.',+ suggestion: 'Re-run the preview: gbrain repair stale-atoms', docs: 'docs/guides/repair.md#preview-changed' });+ });+});++for (const kind of testBackends()) {+ describe(`approved sets in op_checkpoints (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }+ }, 120_000);+ afterAll(async () => { await close?.(); });+ beforeEach(async () => { await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1', [PREVIEW_APPROVAL_OP]); });++ const age = (command: PreviewApprovalCommand, hash: string, days: number) => engine.executeRaw(+ `UPDATE op_checkpoints SET updated_at=now()-($3 || ' days')::interval WHERE op=$1 AND fingerprint=$2`, [PREVIEW_APPROVAL_OP, `${command}:${hash}`, String(days)]);++ test('every command round-trips its whole set under its hash, and never satisfies another command', async () => {+ for (const { command, preview } of COMMANDS) {+ const items = Array.from({ length: 500 }, (_, i) => ({ id: i, request_id: `00000000-0000-4000-a000-${String(i).padStart(12, '0')}`, note: `it's "${command}"` }));+ const hash = previewHash({ command, items });+ await saveApprovedSet(engine, { command, hash }, items);+ const loaded = await loadApprovedSet<typeof items[number]>(engine, { command, hash, previewCommand: preview });+ expect(loaded).toMatchObject({ command, hash });+ expect(loaded.items).toEqual(items);+ expect(Number.isNaN(Date.parse(loaded.approved_at))).toBe(false);+ for (const other of COMMANDS.filter(c => c.command !== command)) {+ const error = await refusal(() => loadApprovedSet(engine, { command: other.command, hash, previewCommand: other.preview }));+ expect(error.code).toBe('preview_changed');+ expect(error.message).toContain(other.preview);+ }+ }+ });++ test('an unknown hash refuses with preview_changed naming the hash and the filled preview command', async () => {+ const error = await refusal(() => loadApprovedSet(engine, { command: 'extractor-facts', hash: 'f'.repeat(64), previewCommand: COMMANDS[3]!.preview }));+ expect(error.toJSON()).toMatchObject({ error: 'preview_changed', docs: 'docs/guides/repair.md#preview-changed',+ message: `The preview changed since ${'f'.repeat(64)}; re-run ${COMMANDS[3]!.preview} and use the new hash.` });+ });++ test('a set older than the purge window refuses whole; a younger one loads; a re-preview restarts its age', async () => {+ const items = [{ id: 1 }, { id: 2 }];+ const hash = previewHash(['stale-atoms', items]);+ const key = { command: 'stale-atoms' as const, hash, previewCommand: COMMANDS[2]!.preview };+ await saveApprovedSet(engine, key, items);+ await age('stale-atoms', hash, APPROVAL_MAX_AGE_DAYS - 1);+ expect((await loadApprovedSet(engine, key)).items).toEqual(items);+ await age('stale-atoms', hash, APPROVAL_MAX_AGE_DAYS + 1);+ expect((await refusal(() => loadApprovedSet(engine, key))).code).toBe('preview_changed');+ await saveApprovedSet(engine, key, items);+ expect((await loadApprovedSet(engine, key)).items).toEqual(items);+ });++ test('the purge window matches purgeStaleCheckpoints: an expired set is purged, a fresh one survives', async () => {+ const fresh = previewHash(['jobs-cancel', 'fresh']);+ const stale = previewHash(['jobs-cancel', 'stale']);+ await saveApprovedSet(engine, { command: 'jobs-cancel', hash: fresh }, [{ id: 1 }]);+ await saveApprovedSet(engine, { command: 'jobs-cancel', hash: stale }, [{ id: 2 }]);+ await age('jobs-cancel', stale, APPROVAL_MAX_AGE_DAYS + 1);+ await purgeStaleCheckpoints(engine);+ const rows = await engine.executeRaw<{ fingerprint: string }>('SELECT fingerprint FROM op_checkpoints WHERE op=$1', [PREVIEW_APPROVAL_OP]);+ expect(rows.map(row => row.fingerprint)).toEqual([`jobs-cancel:${fresh}`]);+ expect((await loadApprovedSet(engine, { command: 'jobs-cancel', hash: fresh, previewCommand: COMMANDS[1]!.preview })).items).toEqual([{ id: 1 }]);+ });++ test('a malformed saved row refuses instead of returning a partial set', async () => {+ const hash = previewHash(['authorize-legacy', 'malformed']);+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)`,+ [PREVIEW_APPROVAL_OP, `authorize-legacy:${hash}`, JSON.stringify([{ command: 'authorize-legacy', hash }])]);+ expect((await refusal(() => loadApprovedSet(engine, { command: 'authorize-legacy', hash, previewCommand: COMMANDS[0]!.preview }))).code).toBe('preview_changed');+ });++ test('clearApprovedSet removes only that set', async () => {+ const a = previewHash(['extractor-facts', 'a']);+ const b = previewHash(['extractor-facts', 'b']);+ await saveApprovedSet(engine, { command: 'extractor-facts', hash: a }, [1]);+ await saveApprovedSet(engine, { command: 'extractor-facts', hash: b }, [2]);+ await clearApprovedSet(engine, { command: 'extractor-facts', hash: a });+ expect((await refusal(() => loadApprovedSet(engine, { command: 'extractor-facts', hash: a, previewCommand: 'p' }))).code).toBe('preview_changed');+ expect((await loadApprovedSet(engine, { command: 'extractor-facts', hash: b, previewCommand: 'p' })).items).toEqual([2]);+ });+ });+}