Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence-gate): history fixture mode and the op-descriptor protocol

garrytan7cafaf781448
diff --git a/scripts/persistence/history-fixture.ts b/scripts/persistence/history-fixture.ts
new file mode 100644
index 0000000000..5fe45ce60a
--- /dev/null
+++ b/scripts/persistence/history-fixture.ts
@@ -0,0 +1,253 @@
+/**
+ * History fixture mode of the crash robot: builds a managed brain with real
+ * persistence history at a requested size (up to 10k pages), for engine
+ * graduation and the attribution-backfill check.
+ *
+ * Frozen signature: `buildHistoryFixture(engine, { pages, seed, sources, worktrees })`.
+ *
+ * The engine must be connected, `initSchema()`d, not yet activated, and the
+ * process must run under an isolated `GBRAIN_HOME` (the persistence host
+ * identity and worktree locks live there). The fixture registers its sources
+ * in fresh durability-hardened Git checkouts under `root` (a new temporary
+ * directory unless given), activates managed persistence, and writes history
+ * through the real operation handlers (see `ops.ts`). On return the in-process
+ * persistence consumer is stopped, so the queued request and the delayed
+ * effect stay exactly as recorded until the caller starts an owner.
+ *
+ * Reached through real operations: pages, revisions and `page_versions`
+ * (put_page, edit_page), timeline, takes with supersession and attribution,
+ * remembered facts and their withdrawals (remember, forget), delete/restore,
+ * `chronicle_page_state` (the publication-time chronicle decision on
+ * meeting pages), local writer registrations, remote writes by an OAuth
+ * client and a legacy token (verified through the production token verifier).
+ * Seeded through the narrowest real API instead:
+ * - sources rows: `INSERT INTO sources` (as the gate's fixtures), then the real
+ * `claimWorktree` and `activatePersistence` (worktrees, host bindings);
+ * - the OAuth client and its token: `GBrainOAuthProvider.registerClientManual`
+ * and `exchangeClientCredentials`;
+ * - the access token with unified grant columns: `mintLegacyToken`;
+ * - the delayed effect: a real Git effect that failed on a stale `index.lock`
+ * and was rescheduled with `next_attempt_at` in the future (the lock is then
+ * removed);
+ * - the queued request: `admitWrite`, the journal call every page mutation
+ * makes, with no owner running: the state a crash right after admission leaves.
+ */
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { GBrainConfig } from '../../src/core/config.ts';
+import { claimWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';
+import { activatePersistence } from '../../src/core/persistence/activation.ts';
+import { admitWrite } from '../../src/core/persistence/journal.ts';
+import { submissionAuthority } from '../../src/core/persistence/authority.ts';
+import { requestPrincipalForContext } from '../../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../../src/core/sql-query.ts';
+import { mintLegacyToken } from '../../src/core/token-mint.ts';
+import { random } from './harness.ts';
+import { authenticateRemotes, contextFor, descriptor, executeOp, type OpDescriptor,
+ type OpObservation, type RemoteActor, type World } from './ops.ts';
+
+export interface HistoryFixtureOptions {
+ /** Pages written through put_page (1..10,000). */
+ pages: number;
+ /** Unsigned 32-bit seed; the same seed yields the same logical history. */
+ seed: number;
+ /** Registered sources (>= worktrees). */
+ sources: number;
+ /** Git checkouts the sources are spread across (>= 1). */
+ worktrees: number;
+ /** Scratch directory for the checkouts; a fresh temporary directory by default. */
+ root?: string;
+}
+export interface HistoryFixtureSource { id: string; root: string; worktree: number }
+export interface HistoryFixture {
+ root: string;
+ seed: number;
+ sources: HistoryFixtureSource[];
+ /** Remote principals with their synthetic bearer tokens (valid only in this scratch brain). */
+ remotes: RemoteActor[];
+ /** The access token row minted with unified grant columns. */
+ accessTokenId: string;
+ oauthClientId: string;
+ /** Every op the fixture ran, in order, with what its caller observed. */
+ observations: OpObservation[];
+ queuedRequestId: string;
+ delayedEffectId: string;
+ /** Row counts of the tables the fixture is required to populate. */
+ counts: Record<string, number>;
+ /** sha256 over the logical history (slugs, contents, takes, facts, withdrawals): equal for equal seeds. */
+ digest: string;
+}
+
+export const HISTORY_FIXTURE_TABLES = ['persistence_requests', 'persistence_effects', 'fact_withdrawals', 'persistence_worktrees',
+ 'persistence_host_bindings', 'persistence_local_writers', 'access_tokens', 'oauth_clients', 'oauth_tokens', 'takes',
+ 'page_versions', 'chronicle_page_state', 'pages', 'facts', 'timeline_entries'] as const;
+
+function durableGitRepo(root: string): void {
+ const git = (...args: string[]) => {
+ const result = Bun.spawnSync(['git', '-C', root, ...args], { stdout: 'pipe', stderr: 'pipe' });
+ if (result.exitCode) throw new Error(`git ${args[0]}: ${result.stderr.toString()}`);
+ };
+ git('init', '-q', '-b', 'main');
+ git('config', 'user.name', 'History Fixture');
+ git('config', 'user.email', '[email protected]');
+ writeFileSync(join(root, 'README.md'), '# History fixture\n');
+ git('add', 'README.md'); git('commit', '-q', '-m', 'Initial');
+ // The durability banner makes Git effects run real commits; with no remote the hook does nothing.
+ const hook = join(root, '.git', 'hooks', 'post-commit');
+ writeFileSync(hook, '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n');
+ chmodSync(hook, 0o755);
+}
+
+const words = ['alpha', 'harbor', 'ledger', 'quartz', 'meadow', 'signal', 'copper', 'lantern', 'orbit', 'thistle', 'cobalt', 'drift'];
+function phrase(rand: () => number, n: number): string {
+ return Array.from({ length: n }, () => words[Math.floor(rand() * words.length)]).join(' ');
+}
+function pageContent(type: string, title: string, body: string, extra = ''): string {
+ return `---\ntype: ${type}\ntitle: ${title}\n${extra}---\n\n${body}\n`;
+}
+
+/**
+ * The logical plan: deterministic descriptors for a seed. Request ids derive
+ * from the seed too, so two builds with one seed submit identical requests.
+ */
+export function historyPlan(opts: HistoryFixtureOptions, sourceIds: string[], remotes: Pick<RemoteActor, 'name' | 'sourceId'>[]): OpDescriptor[] {
+ const rand = random(opts.seed);
+ const uuid = (n: number) => {
+ const h = createHash('sha256').update(`${opts.seed}:${n}`).digest('hex');
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`;
+ };
+ const plan: OpDescriptor[] = [];
+ let n = 0;
+ const add = (kind: OpDescriptor['kind'], actor: string, source: string, args: OpDescriptor['args'], deps?: string[]) => {
+ const id = `op-${n}`; plan.push(descriptor(id, kind, actor, source, args, { requestId: uuid(n), deps })); n++; return id;
+ };
+ const meetingDate = new Date(Date.now() - 2 * 86_400_000).toISOString().slice(0, 10);
+ for (let i = 0; i < opts.pages; i++) {
+ const source = sourceIds[i % sourceIds.length];
+ const remote = remotes.find(r => r.sourceId === source && i % 7 === 3);
+ const actor = remote?.name ?? 'local';
+ const meeting = i % 25 === 5;
+ const slug = meeting ? `meetings/m-${i}` : `notes/p-${i}`;
+ const body = meeting
+ ? `Weekly sync on ${meetingDate} about ${phrase(rand, 6)}. Decided to ${phrase(rand, 8)} and follow up next week with ${phrase(rand, 4)}.`
+ : `Page ${i}: ${phrase(rand, 10)}.\n\nMarker line ${i}.`;
+ const put = add('put_page', actor, source, { slug, content: pageContent(meeting ? 'meeting' : 'note', slug, body, meeting ? `date: ${meetingDate}\n` : '') });
+ if (i % 5 === 1) add('edit_page', actor, source, { slug, expected_revision: { $ref: put, field: 'revision' },
+ edits: [{ old_text: `Marker line ${i}.`, new_text: `Marker line ${i}, revised.` }] }, [put]);
+ if (i % 6 === 2) add('add_timeline_entry', actor, source, { slug, date: '2026-09-1' + (i % 10), summary: `Event ${i}: ${phrase(rand, 3)}` }, [put]);
+ if (i % 8 === 4) {
+ const take = add('takes_add', 'local', source, { slug, claim: `Claim ${i}: ${phrase(rand, 5)}`, kind: 'take', holder: 'world', weight: 0.6 }, [put]);
+ if (i % 16 === 4) add('takes_supersede', 'local', source, { slug, row_num: { $ref: take, field: 'row_num' }, claim: `Revised claim ${i}: ${phrase(rand, 5)}` }, [put, take]);
+ }
+ if (i % 10 === 6) {
+ const fact = add('remember', actor, source, { fact: `Fact ${i}: ${phrase(rand, 6)}`, entity: slug }, [put]);
+ if (i % 20 === 6) add('forget', actor, source, { fact_id: { $ref: fact, field: 'fact_id' }, reason: 'history fixture withdrawal' }, [fact]);
+ }
+ if (i % 50 === 9) {
+ add('delete_page', 'local', source, { slug, expected_revision: '$current' }, [put]);
+ if (i % 100 === 9) add('restore_page', 'local', source, { slug, expected_revision: '$current' }, [put]);
+ }
+ }
+ return plan;
+}
+
+function digestOf(plan: OpDescriptor[], observations: OpObservation[]): string {
+ const h = createHash('sha256');
+ for (const d of plan) h.update(JSON.stringify([d.id, d.kind, d.actor, d.source, d.requestId, d.args]));
+ for (const o of observations) h.update(JSON.stringify([o.id, o.status, o.code ?? null]));
+ return h.digest('hex');
+}
+
+/** Build a brain with real persistence history. See the module comment for preconditions. */
+export async function buildHistoryFixture(engine: BrainEngine,
+ { pages, seed, sources, worktrees, root: requestedRoot }: HistoryFixtureOptions): Promise<HistoryFixture> {
+ assert(Number.isSafeInteger(pages) && pages >= 1 && pages <= 10_000, 'history fixture: pages must be 1..10000');
+ assert(Number.isSafeInteger(seed) && seed >= 0 && seed <= 0xFFFFFFFF, 'history fixture: seed must be an unsigned 32-bit integer');
+ assert(Number.isSafeInteger(worktrees) && worktrees >= 1, 'history fixture: worktrees must be >= 1');
+ assert(Number.isSafeInteger(sources) && sources >= worktrees, 'history fixture: sources must be >= worktrees');
+ assert(process.env.GBRAIN_HOME, 'history fixture: run under an isolated GBRAIN_HOME');
+ const root = requestedRoot ?? mkdtempSync(join(tmpdir(), 'gbrain-history-fixture-'));
+ const checkouts = Array.from({ length: worktrees }, (_, k) => { const dir = join(root, `worktree-${k}`); mkdirSync(dir, { recursive: true }); durableGitRepo(dir); return dir; });
+ const fixtureSources: HistoryFixtureSource[] = Array.from({ length: sources }, (_, i) => {
+ const worktree = i % worktrees; const dir = join(checkouts[worktree], `source-${i}`); mkdirSync(dir, { recursive: true });
+ return { id: `history-${i}`, root: dir, worktree };
+ });
+ for (const source of fixtureSources) {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source.id, source.root]);
+ await claimWorktree(engine, source.id, source.root);
+ }
+ assert.equal((await activatePersistence(engine, { confirmQuiesced: true })).enabled, true);
+
+ const sql = sqlQueryForEngine(engine);
+ const provider = new GBrainOAuthProvider({ sql, transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const client = await provider.registerClientManual('history fixture agent', ['client_credentials'], 'read write', [], fixtureSources[0].id);
+ const oauth = await provider.exchangeClientCredentials(client.clientId, client.clientSecret!, 'read write');
+ const tokenSource = fixtureSources[Math.min(1, sources - 1)].id;
+ const minted = await mintLegacyToken(engine, { name: 'history-fixture-token', scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: [tokenSource] });
+ const remotes: RemoteActor[] = [{ name: 'agent-oauth', kind: 'oauth_client', sourceId: fixtureSources[0].id, token: oauth.access_token },
+ { name: 'agent-token', kind: 'legacy_token', sourceId: tokenSource, token: minted.token }];
+ const config = { engine: engine.kind, embedding_disabled: true } as GBrainConfig;
+ const world: World = { engine, config, remotes, auth: new Map(), observations: new Map() };
+ await authenticateRemotes(world);
+
+ const plan = historyPlan({ pages, seed, sources, worktrees }, fixtureSources.map(s => s.id), remotes);
+ // Sources publish independently; ops within one source run in plan order.
+ const lanes = new Map<string, OpDescriptor[]>();
+ for (const d of plan) lanes.set(d.source, [...(lanes.get(d.source) ?? []), d]);
+ await Promise.all([...lanes.values()].map(async lane => { for (const d of lane) await executeOp(world, d); }));
+ const observations = plan.map(d => world.observations.get(d.id)!);
+ const failed = observations.filter(o => o.status !== 'committed');
+ assert.deepEqual(failed.map(o => `${o.id} ${o.kind} ${o.code}`), [], 'every history op must commit');
+
+ // A Git effect that fails on a stale index.lock reschedules into the future.
+ const delayedSource = fixtureSources[0];
+ const lock = join(checkouts[delayedSource.worktree], '.git', 'index.lock');
+ writeFileSync(lock, '');
+ let delayedEffectId: string;
+ try {
+ const delayed = descriptor('delayed-effect', 'put_page', 'local', delayedSource.id,
+ { slug: 'notes/delayed-effect', content: pageContent('note', 'Delayed effect', 'Its Git effect waits on a stale index.lock.') });
+ assert.equal((await executeOp(world, delayed)).status, 'committed');
+ observations.push(world.observations.get('delayed-effect')!);
+ const deadline = Date.now() + 60_000;
+ for (;;) {
+ const [effect] = await engine.executeRaw<{ id: string }>(`SELECT e.id::text AS id FROM persistence_effects e
+ JOIN persistence_requests r ON r.id=e.request_id WHERE r.request_id=$1::uuid AND e.kind='git'
+ AND e.state='queued' AND e.attempts>0 AND e.next_attempt_at>now()`, [delayed.requestId]);
+ if (effect) { delayedEffectId = effect.id; break; }
+ assert(Date.now() < deadline, 'history fixture: the Git effect never rescheduled after the stale index.lock');
+ await Bun.sleep(100);
+ }
+ } finally {
+ await disposePersistenceConsumer(engine);
+ if (existsSync(lock)) rmSync(lock);
+ }
+
+ // A request accepted with no owner running, exactly as admission records it.
+ const queuedSlug = 'notes/queued-request';
+ const ctx = contextFor(world, 'local', delayedSource.id);
+ const principal = await requestPrincipalForContext(ctx);
+ const [sourceRow] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [delayedSource.id]);
+ const binding = (await getWorktreeBinding(engine, delayedSource.id))!;
+ const callerIntent = { source_id: delayedSource.id, slug: queuedSlug, content: pageContent('note', 'Queued request', 'Accepted while no owner ran.') };
+ const queuedRequestId = historyPlan({ pages: 1, seed: seed ^ 0x5eed, sources, worktrees }, [delayedSource.id], [])[0].requestId;
+ const queued = await admitWrite(engine, { principal, operation: 'put_page', sourceId: delayedSource.id, sourceIncarnation: sourceRow.incarnation,
+ slug: queuedSlug, pageId: null, requestId: queuedRequestId, callerIntent, intent: { ...callerIntent },
+ authority: await submissionAuthority(ctx, 'put_page', delayedSource.id, sourceRow.incarnation, queuedSlug),
+ worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });
+ assert.equal(queued.state, 'queued');
+
+ const counts: Record<string, number> = {};
+ for (const table of HISTORY_FIXTURE_TABLES) {
+ counts[table] = Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM ${table}`))[0].n);
+ }
+ return { root, seed, sources: fixtureSources, remotes, accessTokenId: minted.id, oauthClientId: client.clientId,
+ observations, queuedRequestId, delayedEffectId: delayedEffectId!, counts, digest: digestOf(plan, observations) };
+}
+
diff --git a/scripts/persistence/ops.ts b/scripts/persistence/ops.ts
new file mode 100644
index 0000000000..284a824139
--- /dev/null
+++ b/scripts/persistence/ops.ts
@@ -0,0 +1,208 @@
+/**
+ * The op-descriptor protocol between the crash-robot driver (`validate.ts`)
+ * and its workers (`worker.ts`). A descriptor is plain JSON: it names one
+ * logical operation, the actor that submits it, the source it targets, a
+ * fixed request id and op-specific arguments. Values only known after an
+ * earlier op ran (a fact id, a take row, a page revision) are `{ $ref }`
+ * pointers into earlier observations, so a recorded schedule replays exactly.
+ *
+ * Every op runs through its real admission wrapper: the registered operation
+ * handler with a real OperationContext, a local CLI principal or an
+ * authenticated remote principal whose grant lives in `oauth_clients`.
+ * Nothing here calls a preparer or `tx.*` directly.
+ */
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { GBrainConfig } from '../../src/core/config.ts';
+import type { AuthInfo, OperationContext } from '../../src/core/ops/contract.ts';
+import { operationsByName } from '../../src/core/operations.ts';
+import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../../src/core/sql-query.ts';
+
+export const OP_KINDS = ['put_page', 'edit_page', 'remember', 'forget', 'takes_add', 'takes_supersede',
+ 'add_timeline_entry', 'delete_page', 'restore_page'] as const;
+export type OpKind = typeof OP_KINDS[number];
+/** Read surfaces the oracle checks; they never mutate. */
+export const READ_KINDS = ['get_page', 'recall', 'takes_list'] as const;
+
+/**
+ * A value produced by an earlier op: `{ $ref: 'op-3', field: 'fact_id' }`.
+ * The string `'$current'` as `expected_revision` reads the page's revision
+ * (tombstones included) right before submission, as an agent reads first.
+ */
+export interface OpRef { $ref: string; field: 'fact_id' | 'row_num' | 'revision' }
+export type OpArg = string | number | boolean | null | OpRef | OpArg[] | { [key: string]: OpArg };
+
+export interface OpDescriptor {
+ v: 1;
+ /** Logical id, unique within a schedule ("op-17"). */
+ id: string;
+ kind: OpKind;
+ /** 'local' (trusted CLI) or a remote agent name declared in the world ("agent-0"). */
+ actor: string;
+ source: string;
+ /** Fixed per descriptor so a replayed schedule resubmits the same request. */
+ requestId: string;
+ args: Record<string, OpArg>;
+ /** Ops whose observations this one reads through `$ref`; shrinking keeps them. */
+ deps?: string[];
+ /** Replay of an earlier descriptor's request id (same or different actor/intent). */
+ replayOf?: string;
+}
+
+export type OpStatus = 'committed' | 'pending' | 'refused';
+export interface OpObservation {
+ id: string;
+ kind: OpKind;
+ actor: string;
+ source: string;
+ requestId: string;
+ status: OpStatus;
+ /** Typed error code for a refusal or a non-committed receipt. */
+ code?: string;
+ /** The durable receipt the caller saw, when one was returned. */
+ receipt?: { request_id: string; state: string; revision?: string | null; principal_kind?: string; principal_id?: string; source_id?: string };
+ /** Values later ops can `$ref`. */
+ values: { fact_id?: string; row_num?: number; revision?: string };
+ /** The raw handler result or error fields, JSON-safe. */
+ raw?: unknown;
+}
+
+/**
+ * One authenticated remote agent: an OAuth client or legacy access token whose
+ * bearer token the real verifier (`GBrainOAuthProvider.verifyAccessToken`)
+ * turns into the AuthInfo every remote op runs under. Tokens are synthetic,
+ * minted into the fixture's own scratch database.
+ */
+export interface RemoteActor { name: string; kind: 'oauth_client' | 'legacy_token'; sourceId: string; token: string }
+export interface World {
+ engine: BrainEngine;
+ config: GBrainConfig;
+ remotes: RemoteActor[];
+ /** AuthInfo per remote actor, from the real token verifier. */
+ auth: Map<string, AuthInfo>;
+ observations: Map<string, OpObservation>;
+}
+
+export function descriptor(id: string, kind: OpKind, actor: string, source: string, args: Record<string, OpArg>,
+ extra: Partial<Pick<OpDescriptor, 'deps' | 'replayOf' | 'requestId'>> = {}): OpDescriptor {
+ return { v: 1, id, kind, actor, source, requestId: extra.requestId ?? randomUUID(), args,
+ ...(extra.deps?.length ? { deps: extra.deps } : {}), ...(extra.replayOf ? { replayOf: extra.replayOf } : {}) };
+}
+
+/** Rejects anything that is not a well-formed descriptor; the worker trusts nothing it reads from the driver. */
+export function parseDescriptor(value: unknown): OpDescriptor {
+ const d = value as OpDescriptor;
+ if (!d || typeof d !== 'object' || d.v !== 1) throw new Error('op descriptor: unsupported version');
+ if (typeof d.id !== 'string' || !d.id) throw new Error('op descriptor: id required');
+ if (!(OP_KINDS as readonly string[]).includes(d.kind)) throw new Error(`op descriptor ${d.id}: unknown kind ${String(d.kind)}`);
+ for (const key of ['actor', 'source', 'requestId'] as const) if (typeof d[key] !== 'string' || !d[key]) throw new Error(`op descriptor ${d.id}: ${key} required`);
+ if (!d.args || typeof d.args !== 'object' || Array.isArray(d.args)) throw new Error(`op descriptor ${d.id}: args must be an object`);
+ if (d.deps !== undefined && (!Array.isArray(d.deps) || d.deps.some(dep => typeof dep !== 'string'))) throw new Error(`op descriptor ${d.id}: deps must be ids`);
+ return d;
+}
+
+/** Verify every remote actor's bearer token through the production verifier. */
+export async function authenticateRemotes(world: World): Promise<void> {
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(world.engine) });
+ for (const remote of world.remotes) world.auth.set(remote.name, await provider.verifyAccessToken(remote.token) as unknown as AuthInfo);
+}
+
+export function contextFor(world: World, actor: string, sourceId: string): OperationContext {
+ const base = { engine: world.engine, config: world.config, dryRun: false, sourceId,
+ logger: { info() {}, warn() {}, error() {} } };
+ if (actor === 'local') return { ...base, remote: false };
+ const auth = world.auth.get(actor);
+ if (!auth) throw new Error(`op descriptor: actor ${actor} is not an authenticated remote`);
+ return { ...base, remote: true, transport: 'http', auth };
+}
+
+function resolveArg(world: World, value: OpArg): unknown {
+ if (Array.isArray(value)) return value.map(v => resolveArg(world, v));
+ if (value && typeof value === 'object') {
+ if ('$ref' in value && typeof value.$ref === 'string') {
+ const ref = value as unknown as OpRef;
+ const seen = world.observations.get(ref.$ref);
+ const resolved = seen?.values[ref.field];
+ // An unresolvable reference is still submitted (as a value the real op refuses),
+ // so a shrunk sequence that drops the producer stays executable.
+ return resolved ?? (ref.field === 'row_num' ? 999_999 : ref.field === 'fact_id' ? '999999999' : 'unresolved-revision');
+ }
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolveArg(world, v as OpArg)]));
+ }
+ return value;
+}
+
+/** Map a descriptor to the operation's own parameter shape. */
+export async function paramsFor(world: World, d: OpDescriptor): Promise<{ op: string; params: Record<string, unknown> }> {
+ const a = resolveArg(world, d.args as OpArg) as Record<string, unknown>;
+ if (a.expected_revision === '$current') {
+ const snapshot = await world.engine.readPageSnapshot(String(a.slug), { sourceId: d.source, includeDeleted: true });
+ a.expected_revision = snapshot?.revision ?? 'missing-page';
+ }
+ const revision = a.expected_revision === undefined ? {} : { expected_revision: a.expected_revision };
+ const base = { request_id: d.requestId, ...(d.actor === 'local' ? { source_id: d.source } : {}) };
+ switch (d.kind) {
+ case 'put_page': return { op: 'put_page', params: { ...base, ...revision, slug: a.slug, content: a.content } };
+ case 'edit_page': return { op: 'edit_page', params: { ...base, ...revision, slug: a.slug, edits: a.edits } };
+ case 'remember': return { op: 'remember', params: { ...base, fact: a.fact, provenance: a.provenance ?? 'crash-robot fixture',
+ ...(a.entity ? { entity: a.entity } : {}), infer_entity: false, ...(a.visibility ? { visibility: a.visibility } : {}) } };
+ case 'forget': return { op: 'forget', params: { request_id: d.requestId, id: a.fact_id, ...(a.reason ? { reason: a.reason } : {}) } };
+ case 'takes_add': return { op: 'takes_add', params: { ...base, slug: a.slug, claim: a.claim, kind: a.kind ?? 'take', holder: a.holder ?? 'world', weight: a.weight ?? 0.5 } };
+ case 'takes_supersede': return { op: 'takes_supersede', params: { ...base, slug: a.slug, row_num: a.row_num, claim: a.claim } };
+ case 'add_timeline_entry': return { op: 'add_timeline_entry', params: { ...base, slug: a.slug, date: a.date, summary: a.summary } };
+ case 'delete_page': return { op: 'delete_page', params: { ...base, ...revision, slug: a.slug } };
+ case 'restore_page': return { op: 'restore_page', params: { ...base, ...revision, slug: a.slug } };
+ }
+}
+
+function jsonSafe(value: unknown): unknown {
+ try { return JSON.parse(JSON.stringify(value ?? null)); } catch { return String(value); }
+}
+
+function receiptOf(value: Record<string, unknown> | undefined): OpObservation['receipt'] {
+ const r = (value?.write_request ?? value?.writeRequest ?? value) as Record<string, unknown> | undefined;
+ if (!r || typeof r.request_id !== 'string') return undefined;
+ const outcome = r.outcome as Record<string, unknown> | undefined;
+ return { request_id: r.request_id, state: String(r.state),
+ revision: (r.revision ?? outcome?.revision ?? null) as string | null,
+ principal_kind: r.principal_kind as string | undefined, principal_id: r.principal_id as string | undefined,
+ source_id: r.source_id as string | undefined };
+}
+
+/** Run one descriptor through its real handler and record what the caller observed. */
+export async function executeOp(world: World, d: OpDescriptor): Promise<OpObservation> {
+ const { op, params } = await paramsFor(world, d);
+ const handler = operationsByName[op]?.handler;
+ if (!handler) throw new Error(`op descriptor ${d.id}: operation ${op} is not registered`);
+ const ctx = contextFor(world, d.actor, d.source);
+ const base = { id: d.id, kind: d.kind, actor: d.actor, source: d.source, requestId: d.requestId };
+ let observation: OpObservation;
+ try {
+ const result = await handler(ctx, params) as Record<string, unknown>;
+ const receipt = receiptOf(result);
+ const state = receipt?.state ?? 'committed';
+ observation = { ...base, status: state === 'committed' ? 'committed' : 'pending', receipt, values: {}, raw: jsonSafe(result) };
+ if (result?.fact_id !== undefined) observation.values.fact_id = String(result.fact_id);
+ else if (result?.id !== undefined && d.kind === 'remember') observation.values.fact_id = String(result.id);
+ const row = (result?.row_num ?? result?.new_row ?? result?.row) as number | undefined;
+ if (typeof row === 'number') observation.values.row_num = row;
+ if (receipt?.revision) observation.values.revision = receipt.revision;
+ } catch (error) {
+ const e = error as { code?: string; writeRequest?: Record<string, unknown>; message?: string };
+ const receipt = receiptOf(e.writeRequest);
+ observation = { ...base, status: e.code === 'write_pending' ? 'pending' : 'refused', code: e.code ?? 'uncoded_error',
+ receipt, values: {}, raw: { code: e.code, message: e.message?.slice(0, 400) } };
+ }
+ world.observations.set(d.id, observation);
+ return observation;
+}
+
+/** Read the current revision of a page the way an agent does (get_page with content). */
+export async function currentRevision(world: World, actor: string, sourceId: string, slug: string): Promise<string | null> {
+ try {
+ const page = await operationsByName.get_page.handler(contextFor(world, actor, sourceId),
+ { slug, include_content: true, ...(actor === 'local' ? { source_id: sourceId } : {}) }) as Record<string, unknown>;
+ return typeof page?.revision === 'string' ? page.revision : null;
+ } catch { return null; }
+}
diff --git a/scripts/persistence/would-have-caught.json b/scripts/persistence/would-have-caught.json
new file mode 100644
index 0000000000..a8579d0628
--- /dev/null
+++ b/scripts/persistence/would-have-caught.json
@@ -0,0 +1,110 @@
+{
+ "version": 1,
+ "frozen_at": "2026-10-04",
+ "base": "5bd9e84978126689b11cf65107c0a9aa0e91e11b",
+ "selection": "Merged non-merge fix commits from the last 60 days touching persistence, sync, refresh, connectors or managed facts/atoms, whose src/ hunks reverse-apply cleanly (git apply -R -3) on the wave base. Tests in the fix commit are not reverted, so the gate alone decides caught/missed.",
+ "candidates_checked": 30,
+ "clean": 12,
+ "fixes": [
+ {
+ "sha": "382fa73f68a7dca9095e753192375fd92a8558f1",
+ "date": "2026-10-04",
+ "subject": "fix(refresh): recheck recovery under the worktree lock so a publisher finishing mid-probe is not refused; harden 13c",
+ "src_files": [
+ "src/core/persistence/worktree-refresh.ts"
+ ]
+ },
+ {
+ "sha": "08ddd72b717fc5f1d715a0716f5c2dfa8597ff0a",
+ "date": "2026-10-04",
+ "subject": "fix(sync): a drain keeps retrying admission that gave up on counter contention; document group lock order (#5984)",
+ "src_files": [
+ "src/core/persistence/admission-retry.ts",
+ "src/core/persistence/group-publish.ts",
+ "src/core/persistence/sync-drain.ts"
+ ]
+ },
+ {
+ "sha": "f4cdff892cb800500fab92de7305b8f7028de2b4",
+ "date": "2026-10-04",
+ "subject": "fix(sync): no bulk group forms while a foreground write is queued; default group budget 15 s (#5984)",
+ "src_files": [
+ "src/core/persistence/sync-group.ts",
+ "src/core/persistence/sync-run.ts"
+ ]
+ },
+ {
+ "sha": "6e60d6ed081a988c055c6ac2ad081b24b9c3841e",
+ "date": "2026-10-04",
+ "subject": "fix(sync): managed sources drain one at a time under sync --all (#5984)",
+ "src_files": [
+ "src/commands/sync/run.ts"
+ ]
+ },
+ {
+ "sha": "7ffda48ead8163f3662da344e800e46d8f43d654",
+ "date": "2026-10-04",
+ "subject": "fix(sync): hold rows never store a declared slug; fail-closed fixtures pin sync.holds=fail (#5988)",
+ "src_files": [
+ "src/core/persistence/sync-screen.ts"
+ ]
+ },
+ {
+ "sha": "5a5505335109fb6dba7d9964be3830a0b55a7800",
+ "date": "2026-10-01",
+ "subject": "fix(persistence): a concurrent CLI call waits for the PGLite lock instead of owner_unavailable (N5-2)",
+ "src_files": [
+ "src/core/persistence/local-client.ts"
+ ]
+ },
+ {
+ "sha": "6fe43935ebe63c44e33f329913ead3b9222ed8a0",
+ "date": "2026-09-30",
+ "subject": "v0.60.21.0 fix(persistence): SIGTERM a stopped git child before SIGKILL so it can release index.lock (#5793)",
+ "src_files": [
+ "src/core/brain-repo-durability.ts"
+ ]
+ },
+ {
+ "sha": "cc7c9956ae173100c3ddf5306cb120ed9f9aa9fd",
+ "date": "2026-10-02",
+ "subject": "fix(persistence): a write reaching a row that awaits its revision backfill settles as revision_backfill_pending, not storage_error (#5216)",
+ "src_files": [
+ "src/core/persistence/coordinator.ts"
+ ]
+ },
+ {
+ "sha": "33ab99d659c21717915fda45934c43edd0d8928a",
+ "date": "2026-10-03",
+ "subject": "fix(persistence): startup refresh recovery scans only interrupted rows; test admission's lazy completion",
+ "src_files": [
+ "src/core/persistence/worktree-refresh.ts"
+ ]
+ },
+ {
+ "sha": "3b2320e1fe9c54421194f7fb164a96014c72a233",
+ "date": "2026-10-02",
+ "subject": "fix(connectors): retained-publication recovery waits the configured write wait instead of a fixed 5 s (#5232)",
+ "src_files": [
+ "src/core/persistence/connector-sync.ts",
+ "src/core/persistence/write-wait.ts"
+ ]
+ },
+ {
+ "sha": "05d5fe6a28fbe0c1f468d3f5509c7baed4f04564",
+ "date": "2026-10-01",
+ "subject": "fix(atoms): invalidate earlier extractions as each retirement commits; retry identity ignores the generation",
+ "src_files": [
+ "src/core/persistence/atom-maintenance.ts"
+ ]
+ },
+ {
+ "sha": "e01e9824dc645d02331e28d5703a22a774745814",
+ "date": "2026-10-01",
+ "subject": "fix(repair): extractor-facts restores only onto the previewed page id",
+ "src_files": [
+ "src/core/repair/extractor-facts.ts"
+ ]
+ }
+ ]
+}
diff --git a/test/persistence-history-fixture.test.ts b/test/persistence-history-fixture.test.ts
new file mode 100644
index 0000000000..af84c85065
--- /dev/null
+++ b/test/persistence-history-fixture.test.ts
@@ -0,0 +1,74 @@
+/**
+ * The crash robot's history fixture (`scripts/persistence/history-fixture.ts`).
+ *
+ * Protects: `buildHistoryFixture(engine, { pages, seed, sources, worktrees })`,
+ * the frozen contract engine graduation and the attribution-backfill check
+ * build on: every required table holds rows written through real operations
+ * (terminal and one queued request, a delayed effect, withdrawals, worktrees,
+ * local writers, a unified-grant access token, an OAuth client and token,
+ * superseded takes, page versions, chronicle ledger rows), and one seed always
+ * yields one logical history.
+ * Fails when: an op the fixture drives stops committing, a required table
+ * stays empty, the queued request is claimed or the delayed effect runs before
+ * the caller starts an owner, or the plan stops being a function of the seed.
+ * Seams: none; PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { buildHistoryFixture, HISTORY_FIXTURE_TABLES, historyPlan, type HistoryFixture } from '../scripts/persistence/history-fixture.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+async function build(databaseUrl: string | undefined, seed: number): Promise<{ fixture: HistoryFixture; rows: Record<string, unknown> }> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-history-fixture-test-'));
+ try {
+ return await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ const fixture = await buildHistoryFixture(engine, { pages: 30, seed, sources: 3, worktrees: 2, root: join(home, 'checkouts') });
+ const [queued] = await engine.executeRaw('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [fixture.queuedRequestId]);
+ const [delayed] = await engine.executeRaw<{ state: string; future: boolean }>(
+ 'SELECT state,next_attempt_at>now() AS future FROM persistence_effects WHERE id=$1', [fixture.delayedEffectId]);
+ const [token] = await engine.executeRaw<{ revision: number; source: unknown }>(
+ 'SELECT grant_revision AS revision,source_grant AS source FROM access_tokens WHERE id=$1::uuid', [fixture.accessTokenId]);
+ const superseded = await engine.executeRaw('SELECT 1 FROM takes WHERE superseded_by IS NOT NULL');
+ const terminal = await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE state='committed'");
+ const remoteWriters = await engine.executeRaw<{ kind: string }>("SELECT DISTINCT principal_kind AS kind FROM persistence_requests ORDER BY 1");
+ return { fixture, rows: { queued, delayed, token, superseded: superseded.length, terminal: terminal.length,
+ principals: remoteWriters.map(r => r.kind) } };
+ } finally { await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ describe(`${backend}: buildHistoryFixture`, () => {
+ test('populates every required table through real operations', async () => {
+ const { fixture, rows } = await build(databaseUrl, 11);
+ for (const table of HISTORY_FIXTURE_TABLES) expect({ table, rows: fixture.counts[table] > 0 }).toEqual({ table, rows: true });
+ expect(fixture.observations.every(o => o.status === 'committed')).toBe(true);
+ expect(rows.queued).toEqual({ state: 'queued' });
+ expect(rows.delayed).toEqual({ state: 'queued', future: true });
+ expect(rows.token).toMatchObject({ revision: 1 });
+ expect(rows.superseded).toBeGreaterThan(0);
+ expect(rows.terminal).toBeGreaterThan(30);
+ expect(rows.principals).toEqual(expect.arrayContaining(['legacy_token', 'local_cli', 'oauth_client']));
+ }, 240_000);
+ });
+}
+
+test('one seed is one logical history; another seed differs', () => {
+ const sources = ['history-0', 'history-1', 'history-2'];
+ const remotes = [{ name: 'agent-oauth', sourceId: 'history-0' }, { name: 'agent-token', sourceId: 'history-1' }];
+ const shape = (seed: number) => historyPlan({ pages: 200, seed, sources: 3, worktrees: 2 }, sources, remotes)
+ .map(d => [d.kind, d.actor, d.source, d.requestId, JSON.stringify(d.args).replace(/\d{4}-\d{2}-\d{2}/g, 'DATE')]);
+ expect(shape(42)).toEqual(shape(42));
+ expect(shape(43)).not.toEqual(shape(42));
+ const kinds = new Set(shape(42).map(([kind]) => kind));
+ expect([...kinds].sort()).toEqual(['add_timeline_entry', 'delete_page', 'edit_page', 'forget', 'put_page', 'remember',
+ 'restore_page', 'takes_add', 'takes_supersede']);
+});