Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(persistence-gate): crash robot over the real operations
garrytanf3527204d373
diff --git a/scripts/persistence/crash-robot.ts b/scripts/persistence/crash-robot.tsnew file mode 100644index 0000000000..b33ea273c6--- /dev/null+++ b/scripts/persistence/crash-robot.ts@@ -0,0 +1,279 @@+/**+ * Crash robot: runs generated op schedules through the real operation+ * handlers on a managed brain and checks the reference model after every step,+ * after every injected crash and recovery, and after the final drain.+ *+ * `runSchedule` executes one schedule inside the current process (the owner+ * consumer runs here too). The process-separated crash mode in `worker.ts`+ * reuses it: a worker installs a fault hook, the driver SIGKILLs it at the+ * chosen point, and a fresh worker recovers and resumes the schedule.+ */+import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, utimesSync, writeFileSync, writeSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { GBrainConfig } from '../../src/core/config.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { disposePersistenceConsumer, startPersistenceConsumer } from '../../src/core/persistence/service.ts';+import { installFaultHook, type FaultPoint } from '../../src/core/persistence/fault-points.ts';+import { assertSafeE2eDatabaseUrl } from '../../test/helpers/db-guard.ts';+import { prepareTopology } from './history-fixture.ts';+import { executeOp, type OpDescriptor, type OpObservation, type World } from './ops.ts';+import { ReferenceModel, SAFETY_CLASSES, type Violation } from './model.ts';+import type { Schedule } from './generator.ts';+import { pageBody } from './generator.ts';+import { descriptor } from './ops.ts';+import { randomUUID } from 'node:crypto';++export interface ScheduleResult { label: string; seed: number; steps: number; violations: Violation[]; safety: Violation[]; observations: OpObservation[] }++/**+ * How long a drain may take before the robot calls it a wedge. Every claim a+ * dead owner left behind must be resumable well inside this bound; a lease+ * that only expires later (requests 30 s, effects 2 min) is reported.+ */+export const DRAIN_BOUND_MS = 20_000;++/** Wait until no request is pending and no effect is runnable; false when the bound passes (a wedge). */+export async function drain(engine: BrainEngine, world: World, timeoutMs = 60_000): Promise<boolean> {+ startPersistenceConsumer(engine, world.config).wake();+ const deadline = Date.now() + timeoutMs;+ for (;;) {+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT+ (SELECT count(*) FROM persistence_requests WHERE state IN ('queued','running','recovering'))+ + (SELECT count(*) FROM persistence_effects WHERE (state IN ('queued','running') AND next_attempt_at <= now() + interval '30 seconds') OR recovery IS NOT NULL) AS n`);+ if (Number(row.n) === 0) return true;+ if (Date.now() > deadline) return false;+ await Bun.sleep(100);+ }+}++/** Run `ops` from `start`, honoring concurrent groups; every observation is folded into `model`. */+export async function runSteps(world: World, model: ReferenceModel, schedule: Schedule, start = 0,+ onStep?: (next: number, batch: OpDescriptor[]) => void): Promise<number> {+ const groupOf = new Map<string, string[]>();+ for (const group of schedule.groups) for (const id of group) groupOf.set(id, group);+ let i = start;+ while (i < schedule.ops.length) {+ const d = schedule.ops[i];+ const group = groupOf.get(d.id);+ const batch = group ? schedule.ops.slice(i).filter(op => group.includes(op.id)) : [d];+ onStep?.(i, batch);+ const observed = await Promise.all(batch.map(op => executeOp(world, op)));+ model.beginStep(batch.length > 1);+ for (let k = 0; k < batch.length; k++) {+ const op = batch[k];+ await model.observe(op, observed[k], op.replayOf ? world.observations.get(op.replayOf) : undefined);+ }+ if (batch.length > 1) await model.settleGroup(batch, observed);+ await model.checkGlobal(`after ${batch.map(op => op.id).join('+')}`);+ i += batch.length;+ }+ return i;+}++/** Resubmit every request whose caller stopped waiting while it was pending; its final receipt is folded like a first observation. */+export async function settlePending(world: World, model: ReferenceModel): Promise<void> {+ const pending = [...model.pending.values()];+ if (!pending.length) return;+ model.beginStep(false);+ for (const d of pending) {+ const seen = await executeOp(world, d);+ await model.observe({ ...d, replayOf: undefined }, seen);+ if (seen.status === 'pending') model.violate({ class: 'wedge', op: d.id, detail: `request ${d.requestId} still pending after the drain` });+ }+}++/** Finish a schedule: drain, check drained invariants, prove a fresh write still admits. */+export async function finish(world: World, model: ReferenceModel, label: string, drainMs = DRAIN_BOUND_MS): Promise<void> {+ const drained = await drain(world.engine, world, drainMs);+ if (!drained) model.violate({ class: 'wedge', detail: `${label}: requests or effects did not drain within ${drainMs / 1000} s` });+ await settlePending(world, model);+ await model.checkDrained(`${label}: drained`);+ await model.checkGlobal(`${label}: drained`);+ const source = world.remotes[0].sourceId;+ const probe = descriptor(`probe-${randomUUID().slice(0, 8)}`, 'put_page', 'local', source,+ { slug: `notes/probe-${randomUUID().slice(0, 8)}`, content: pageBody('notes/probe', 'mk-probe0') });+ const seen = await executeOp(world, probe);+ if (seen.status !== 'committed') model.violate({ class: 'wedge', detail: `${label}: a fresh write after the schedule ended ${seen.status}/${seen.code}` });+}++export async function runSchedule(world: World, schedule: Schedule): Promise<ScheduleResult> {+ const model = new ReferenceModel(world);+ world.descriptors = new Map(schedule.ops.map(d => [d.id, d]));+ await runSteps(world, model, schedule);+ await finish(world, model, schedule.label);+ return { label: schedule.label, seed: schedule.seed, steps: schedule.ops.length, violations: model.violations,+ safety: model.violations.filter(v => SAFETY_CLASSES.has(v.class)), observations: schedule.ops.map(d => world.observations.get(d.id)!) };+}++/* ------------------------------------------------------------------------ */+/* Process-separated crash mode: the worker side. */+/* ------------------------------------------------------------------------ */++export type ProcessFault = 'stale_index_lock' | 'hung_git';+export interface RobotConfig {+ kind: 'pglite' | 'postgres'; root: string; dataDir: string; databaseUrl?: string;+ schedule: Schedule; worktrees: number; statePath: string;+ /** SIGKILL at the nth time this seam is reached (1-based). */+ fault?: { point: FaultPoint; nth: number };+ process?: ProcessFault;+}+interface RobotState {+ remotes: World['remotes']; checkouts: string[]; next: number; inFlight: string[];+ model: Record<string, unknown>; observations: [string, OpObservation][]; submitted: [string, Record<string, unknown>][];+}+export interface RobotOutcome extends Omit<ScheduleResult, 'observations'> {+ crashed: boolean; fault?: RobotConfig['fault']; process?: ProcessFault; counts?: Record<string, number>; inFlight?: string[];+}++function writeState(config: RobotConfig, world: World, model: ReferenceModel, checkouts: string[], next: number, inFlight: string[]): void {+ const state: RobotState = { remotes: world.remotes, checkouts, next, inFlight, model: model.toJSON(),+ observations: [...world.observations], submitted: [...(world.submitted ?? [])] };+ const staged = `${config.statePath}.tmp`;+ writeFileSync(staged, JSON.stringify(state), { mode: 0o600 }); renameSync(staged, config.statePath);+}++async function openRobotEngine(config: RobotConfig, initialize: boolean): Promise<BrainEngine> {+ const engine: BrainEngine = config.kind === 'pglite' ? new PGLiteEngine() : new PostgresEngine();+ if (engine instanceof PostgresEngine) {+ assertSafeE2eDatabaseUrl(config.databaseUrl!);+ await engine.connect({ database_url: config.databaseUrl!, poolSize: 4 });+ } else await engine.connect({ database_path: config.dataDir });+ if (initialize) await engine.initSchema();+ return engine;+}++/** Freeze the whole process at a seam until the driver's SIGKILL arrives; nothing after this point runs. */+function freeze(event: Record<string, unknown>): never {+ const bytes = Buffer.from(`${JSON.stringify(event)}\n`);+ for (let offset = 0; offset < bytes.length;) offset += writeSync(1, bytes, offset, bytes.length - offset);+ const blocked = new Int32Array(new SharedArrayBuffer(4));+ for (;;) Atomics.wait(blocked, 0, 0);+}++function finalize(config: RobotConfig, model: ReferenceModel, extra: Partial<RobotOutcome>): RobotOutcome {+ return { label: config.schedule.label, seed: config.schedule.seed, steps: config.schedule.ops.length, crashed: false,+ violations: model.violations, safety: model.violations.filter(v => SAFETY_CLASSES.has(v.class)), ...extra };+}++/** A git shim that hangs `git commit` while the marker file exists (a stuck child, never answering). */+function installHungGit(root: string): { marker: string; release(): void } {+ const dir = join(root, 'hung-git-bin'); mkdirSync(dir, { recursive: true });+ const real = Bun.which('git')!; const marker = join(root, 'hung-git.marker');+ writeFileSync(join(dir, 'git'), `#!/bin/sh\nfor a in "$@"; do if [ "$a" = commit ] && [ -e '${marker}' ]; then echo $$ >> '${marker}.pids'; exec sleep 600; fi; done\nexec '${real}' "$@"\n`);+ chmodSync(join(dir, 'git'), 0o755); writeFileSync(marker, '');+ process.env.PATH = `${dir}:${process.env.PATH}`;+ return { marker, release: () => rmSync(marker, { force: true }) };+}++/**+ * Process faults SIGKILL cannot model. Each must end in a terminal state or a+ * typed, agent-facing error, never a wedge, and must clear once the fault does.+ */+async function processFault(config: RobotConfig, world: World, model: ReferenceModel, checkouts: string[]): Promise<void> {+ const engine = world.engine;+ const typedGitErrors = new Set(['git_index_locked', 'git_index_stale', 'git_failed', 'git_timeout', 'targets_parked', 'storage_error']);+ const gitEffects = () => engine.executeRaw<{ id: string; state: string; error_code: string | null }>(+ "SELECT id::text,state,error_code FROM persistence_effects WHERE kind='git' AND state<>'committed'");+ if (config.process === 'stale_index_lock') {+ const lock = join(checkouts[0], '.git', 'index.lock'); writeFileSync(lock, '');+ const old = new Date(Date.now() - 3_600_000); utimesSync(lock, old, old);+ await runSteps(world, model, config.schedule);+ const deadline = Date.now() + 30_000;+ let stuck = await gitEffects();+ while (Date.now() < deadline && stuck.some(e => e.state === 'running' || !e.error_code)) { await Bun.sleep(250); stuck = await gitEffects(); }+ for (const e of stuck) if (!e.error_code || !typedGitErrors.has(e.error_code)) {+ model.violate({ class: 'wedge', detail: `stale index.lock: git effect ${e.id} is ${e.state} without a typed error (${e.error_code})` });+ }+ rmSync(lock, { force: true });+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git' AND state='queued'");+ } else if (config.process === 'hung_git') {+ const shim = installHungGit(config.root);+ await runSteps(world, model, config.schedule);+ const deadline = Date.now() + 15_000;+ while (Date.now() < deadline && !existsSync(`${shim.marker}.pids`)) await Bun.sleep(100);+ if (existsSync(`${shim.marker}.pids`)) {+ const started = Date.now();+ const stopped = await Promise.race([disposePersistenceConsumer(engine).then(() => true), Bun.sleep(45_000).then(() => false)]);+ if (!stopped) model.violate({ class: 'wedge', detail: 'hung git child: consumer shutdown did not finish within 45 s' });+ else if (Date.now() - started > 30_000) model.violate({ class: 'wedge', detail: `hung git child: consumer shutdown took ${Date.now() - started} ms` });+ }+ shim.release();+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git' AND state='queued'");+ }+ await finish(world, model, `${config.schedule.label}+${config.process}`);+}++/**+ * Worker entry for one crash-robot role. `count` runs the schedule with a+ * counting hook; `run` starts a fresh brain and freezes at `config.fault`;+ * `recover` reopens the brain after the driver's SIGKILL, checks the+ * pre-recovery state, drains, resubmits the in-flight requests and finishes.+ */+export async function robotWorker(role: 'count' | 'run' | 'recover', config: RobotConfig): Promise<RobotOutcome> {+ const fresh = role !== 'recover';+ const engine = await openRobotEngine(config, fresh);+ try {+ let world: World; let model: ReferenceModel; let checkouts: string[]; let state: RobotState | undefined;+ if (fresh) {+ const topology = await prepareTopology(engine, { sources: 2, worktrees: config.worktrees, root: join(config.root, 'checkouts'), prefix: 'robot' });+ world = topology.world; checkouts = topology.checkouts; model = new ReferenceModel(world);+ } else {+ state = JSON.parse(readFileSync(config.statePath, 'utf8')) as RobotState;+ world = { engine, config: { engine: engine.kind, embedding_disabled: true } as GBrainConfig, remotes: state.remotes, auth: new Map(),+ observations: new Map(state.observations), submitted: new Map(state.submitted) };+ checkouts = state.checkouts; model = ReferenceModel.fromJSON(world, state.model);+ }+ world.descriptors = new Map(config.schedule.ops.map(d => [d.id, d]));+ const counts: Record<string, number> = {};+ if (role === 'count') installFaultHook(point => { counts[point] = (counts[point] ?? 0) + 1; });+ if (role === 'run' && config.fault) {+ let seen = 0; const fault = config.fault;+ installFaultHook((point, detail) => {+ if (point !== fault.point || ++seen !== fault.nth) return;+ freeze({ event: 'fault', point, nth: seen, detail });+ });+ }+ if (role === 'run') {+ let next = 0; let inFlight: string[] = [];+ world.onSubmit = () => writeState(config, world, model, checkouts, next, inFlight);+ writeState(config, world, model, checkouts, 0, []);+ if (config.process) { await processFault(config, world, model, checkouts); return finalize(config, model, { process: config.process }); }+ await runSteps(world, model, config.schedule, 0, (i, batch) => { next = i; inFlight = batch.map(d => d.id); writeState(config, world, model, checkouts, next, inFlight); });+ await finish(world, model, config.schedule.label);+ return finalize(config, model, { fault: config.fault });+ }+ if (role === 'count') {+ await runSteps(world, model, config.schedule);+ await finish(world, model, config.schedule.label);+ return finalize(config, model, { counts });+ }+ // recover+ const inFlight = state!.inFlight.map(id => world.descriptors!.get(id)!);+ model.beginStep(inFlight.length > 1);+ model.allowInFlight(inFlight); model.relaxInFlight(inFlight);+ await model.checkGlobal('after SIGKILL, before recovery');+ const drained = await drain(engine, world, DRAIN_BOUND_MS);+ if (!drained) model.violate({ class: 'wedge', detail: `recovery: requests or effects did not drain within ${DRAIN_BOUND_MS / 1000} s after restart` });+ await model.checkDrained('recovered');+ await settlePending(world, model);+ model.allowInFlight(inFlight);+ await model.checkGlobal('recovered');+ // The interrupted callers resubmit with their original request ids.+ if (inFlight.length) {+ const observed = await Promise.all(inFlight.map(d => executeOp(world, d)));+ model.beginStep(inFlight.length > 1);+ for (let k = 0; k < inFlight.length; k++) await model.observe(inFlight[k], observed[k], inFlight[k].replayOf ? world.observations.get(inFlight[k].replayOf!) : undefined);+ if (inFlight.length > 1) await model.settleGroup(inFlight, observed);+ await model.checkGlobal('after resubmission');+ }+ await runSteps(world, model, config.schedule, state!.next + inFlight.length);+ await finish(world, model, config.schedule.label);+ return finalize(config, model, { crashed: true, fault: config.fault, inFlight: state!.inFlight });+ } finally {+ installFaultHook(undefined);+ await disposePersistenceConsumer(engine).catch(() => {});+ await engine.disconnect();+ }+}diff --git a/scripts/persistence/generator.ts b/scripts/persistence/generator.tsnew file mode 100644index 0000000000..4d985375b3--- /dev/null+++ b/scripts/persistence/generator.ts@@ -0,0 +1,161 @@+/**+ * Seeded generator of op-descriptor sequences for the crash robot. A+ * sequence mixes the real write ops across two sources whose slugs overlap,+ * a local CLI principal and one authenticated remote agent per source, stale+ * revisions (competing writers), caller-bound replays and concurrent groups.+ * The five irreducible cross-boundary sequences are always present+ * (`crossBoundarySequences`); random sequences add breadth around them.+ */+import { createHash } from 'node:crypto';+import { random } from './harness.ts';+import { descriptor, type OpArg, type OpDescriptor, type OpKind } from './ops.ts';++export interface GeneratorTopology { sources: string[]; remotes: { name: string; sourceId: string }[] }+/** A schedule: descriptors plus the concurrent groups among them (ids that run together). */+export interface Schedule { seed: number; ops: OpDescriptor[]; groups: string[][]; label: string }++export const SLUGS = ['notes/alpha', 'notes/beta', 'people/pat-example', 'meetings/standup'] as const;++export function requestUuid(seed: number, n: number, salt = ''): string {+ const h = createHash('sha256').update(`${salt}:${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)}`;+}+export function pageBody(slug: string, marker: string): string {+ const type = slug.startsWith('people/') ? 'person' : slug.startsWith('meetings/') ? 'meeting' : 'note';+ return `---\ntype: ${type}\ntitle: ${slug}\n---\n\nPage ${slug}.\n\nMarker: ${marker}\n`;+}++class Builder {+ ops: OpDescriptor[] = [];+ groups: string[][] = [];+ private n = 0;+ constructor(readonly seed: number, readonly salt: string) {}+ next(kind: OpKind, actor: string, source: string, args: Record<string, OpArg>, deps: string[] = [], requestId?: string, replayOf?: string): OpDescriptor {+ const id = `${this.salt}${this.n}`;+ const d = descriptor(id, kind, actor, source, args, { requestId: requestId ?? requestUuid(this.seed, this.n, this.salt), deps, replayOf });+ this.n++; this.ops.push(d); return d;+ }+ marker(): string { return `mk-${this.salt}${this.n}`; }+ put(actor: string, source: string, slug: string, revision: OpArg | null = null, deps: string[] = []) {+ return this.next('put_page', actor, source, { slug, content: pageBody(slug, this.marker()), ...(revision === null ? {} : { expected_revision: revision }) }, deps);+ }+ edit(actor: string, source: string, slug: string, revision: OpArg = '$current', deps: string[] = []) {+ return this.next('edit_page', actor, source, { slug, expected_revision: revision, edits: [{ old_text: 'Marker: ', new_text: `Marker: ${this.marker()} ` }] }, deps);+ }+}++/**+ * The irreducible cross-boundary sequences (never cut): withdrawal followed+ * by a stale publication; two sources with overlapping slugs; competing+ * writers on one page; an authority change while effects are pending+ * (writer revoked mid-sequence); a direct write racing a replayed request.+ * Sync and connector publish racing a direct write are added by the sync+ * family in `families.ts` once their seams exist.+ */+export function crossBoundarySequences(topology: GeneratorTopology, seed = 1): Schedule[] {+ const [a, b] = topology.sources;+ const remoteA = topology.remotes.find(r => r.sourceId === a)!.name;+ const remoteB = topology.remotes.find(r => r.sourceId === b)!.name;+ const out: Schedule[] = [];+ {+ const s = new Builder(seed, 'wd'); const slug = 'people/pat-example';+ const put = s.put('local', a, slug);+ const fact = s.next('remember', 'local', a, { fact: `Pat prefers ${s.marker()}`, entity: slug }, [put.id]);+ s.next('forget', 'local', a, { fact_id: { $ref: fact.id, field: 'fact_id' } }, [fact.id]);+ // Republish the page bytes read before the withdrawal, then delete/restore and re-remember.+ s.next('put_page', 'local', a, { slug, content: '$stale_content', stale_of: fact.id, expected_revision: '$current' }, [fact.id]);+ s.next('put_page', remoteA, a, { slug, content: '$stale_content', stale_of: fact.id, expected_revision: '$current' }, [fact.id]);+ s.next('delete_page', 'local', a, { slug, expected_revision: '$current' }, [put.id]);+ s.next('restore_page', 'local', a, { slug, expected_revision: '$current' }, [put.id]);+ s.next('remember', remoteA, a, { fact: fact.args.fact, entity: slug }, [put.id]);+ out.push({ seed, ops: s.ops, groups: s.groups, label: 'withdrawal_then_stale_publication' });+ }+ {+ const s = new Builder(seed, 'ov');+ const pa = s.put('local', a, 'notes/alpha'); const pb = s.put('local', b, 'notes/alpha');+ s.edit(remoteA, a, 'notes/alpha', '$current', [pa.id]); s.edit(remoteB, b, 'notes/alpha', '$current', [pb.id]);+ // A remote agent naming the other source is refused and writes nothing there.+ s.next('put_page', remoteA, b, { slug: 'notes/alpha', content: pageBody('notes/alpha', s.marker()), expected_revision: '$current' }, [pb.id]);+ const fa = s.next('remember', 'local', a, { fact: `Alpha fact ${s.marker()}`, entity: 'notes/alpha' }, [pa.id]);+ s.next('forget', remoteB, b, { fact_id: { $ref: fa.id, field: 'fact_id' } }, [fa.id]);+ s.next('delete_page', 'local', b, { slug: 'notes/alpha', expected_revision: '$current' }, [pb.id]);+ out.push({ seed, ops: s.ops, groups: s.groups, label: 'overlapping_slugs_two_sources' });+ }+ {+ const s = new Builder(seed, 'cw');+ const p = s.put('local', a, 'notes/beta');+ const e1 = s.edit('local', a, 'notes/beta', { $ref: p.id, field: 'revision' }, [p.id]);+ const e2 = s.edit(remoteA, a, 'notes/beta', { $ref: p.id, field: 'revision' }, [p.id]);+ const e3 = s.put('local', a, 'notes/beta', { $ref: p.id, field: 'revision' }, [p.id]);+ s.groups.push([e1.id, e2.id, e3.id]);+ const t = s.next('takes_add', 'local', a, { slug: 'notes/beta', claim: `Beta claim ${s.marker()}`, kind: 'take', holder: 'world' }, [p.id]);+ const t1 = s.next('takes_supersede', 'local', a, { slug: 'notes/beta', row_num: { $ref: t.id, field: 'row_num' }, claim: `Beta revised ${s.marker()}` }, [t.id]);+ const t2 = s.next('takes_supersede', 'local', a, { slug: 'notes/beta', row_num: { $ref: t.id, field: 'row_num' }, claim: `Beta rival ${s.marker()}` }, [t.id]);+ s.groups.push([t1.id, t2.id]);+ out.push({ seed, ops: s.ops, groups: s.groups, label: 'competing_writers_one_page' });+ }+ {+ const s = new Builder(seed, 'rp');+ const p = s.put(remoteA, a, 'notes/alpha');+ // Same principal, same intent: the same receipt. Same principal, changed intent: idempotency conflict.+ s.next('put_page', remoteA, a, p.args, [p.id], p.requestId, p.id);+ s.next('put_page', remoteA, a, { slug: 'notes/alpha', content: pageBody('notes/alpha', s.marker()) }, [p.id], p.requestId, p.id);+ // Another principal reusing the UUID commits its own request and never sees the original receipt.+ s.next('put_page', remoteB, b, { slug: 'notes/alpha', content: pageBody('notes/alpha', s.marker()) }, [p.id], p.requestId, p.id);+ s.next('put_page', 'local', a, { slug: 'notes/gamma', content: pageBody('notes/gamma', s.marker()) }, [p.id], p.requestId, p.id);+ out.push({ seed, ops: s.ops, groups: s.groups, label: 'caller_bound_replay' });+ }+ {+ const s = new Builder(seed, 'au');+ const p = s.put(remoteA, a, 'meetings/standup');+ s.next('add_timeline_entry', remoteA, a, { slug: 'meetings/standup', date: '2026-09-30', summary: `Standup ${s.marker()}` }, [p.id]);+ s.next('revoke_access', 'local', a, { actor: remoteA }, []);+ s.edit(remoteA, a, 'meetings/standup', '$current', [p.id]);+ s.edit('local', a, 'meetings/standup', '$current', [p.id]);+ out.push({ seed, ops: s.ops, groups: s.groups, label: 'authority_change_pending_effects' });+ }+ return out;+}++/** A random sequence of `length` ops for `seed`, with concurrent groups of 2-3 ops. */+export function randomSchedule(topology: GeneratorTopology, seed: number, length = 24): Schedule {+ const rand = random(seed);+ const pick = <T>(xs: readonly T[]): T => xs[Math.floor(rand() * xs.length)];+ const s = new Builder(seed, 'r');+ const created: OpDescriptor[] = []; const facts: OpDescriptor[] = []; const takes: OpDescriptor[] = [];+ const actorFor = (source: string) => rand() < 0.35 ? topology.remotes.find(r => r.sourceId === source)!.name : 'local';+ while (s.ops.length < length) {+ const source = pick(topology.sources); const slug = pick(SLUGS); const actor = actorFor(source);+ const page = created.filter(d => d.source === source && d.args.slug === slug).at(-1);+ const roll = rand();+ if (!page || roll < 0.18) { created.push(s.put(actor, source, slug, page ? '$current' : null)); continue; }+ if (roll < 0.32) { s.edit(actor, source, slug, rand() < 0.25 ? { $ref: page.id, field: 'revision' } : '$current', [page.id]); continue; }+ if (roll < 0.44) { facts.push(s.next('remember', actor, source, { fact: `Fact ${s.marker()} about ${slug}`, entity: slug }, [page.id])); continue; }+ if (roll < 0.52 && facts.length) { const f = pick(facts); s.next('forget', rand() < 0.2 ? actorFor(pick(topology.sources)) : f.actor, f.source, { fact_id: { $ref: f.id, field: 'fact_id' } }, [f.id]); continue; }+ if (roll < 0.60) { takes.push(s.next('takes_add', 'local', source, { slug, claim: `Claim ${s.marker()}`, kind: 'take', holder: 'world' }, [page.id])); continue; }+ if (roll < 0.66 && takes.length) { const t = pick(takes); s.next('takes_supersede', 'local', t.source, { slug: String(t.args.slug), row_num: { $ref: t.id, field: 'row_num' }, claim: `Revised ${s.marker()}` }, [t.id]); continue; }+ if (roll < 0.74) { s.next('add_timeline_entry', actor, source, { slug, date: `2026-09-${String(10 + Math.floor(rand() * 18))}`, summary: `Event ${s.marker()}` }, [page.id]); continue; }+ if (roll < 0.80) { s.next('delete_page', 'local', source, { slug, expected_revision: '$current' }, [page.id]); continue; }+ if (roll < 0.85) { s.next('restore_page', 'local', source, { slug, expected_revision: '$current' }, [page.id]); continue; }+ if (roll < 0.93 && s.ops.length) {+ const prior = pick(s.ops.filter(d => !d.replayOf && !d.kind.startsWith('$')));+ const mode = rand();+ if (mode < 0.4) s.next(prior.kind, prior.actor, prior.source, prior.args, [prior.id], prior.requestId, prior.id);+ else {+ const other = mode < 0.7 ? pick(['local', ...topology.remotes.map(r => r.name)].filter(a => a !== prior.actor)) : prior.actor;+ const otherSource = other === 'local' ? prior.source : topology.remotes.find(r => r.name === other)!.sourceId;+ s.next('put_page', other, otherSource, { slug: 'notes/beta', content: pageBody('notes/beta', s.marker()), expected_revision: '$current' }, [prior.id], prior.requestId, prior.id);+ }+ continue;+ }+ // A concurrent group: two or three writers on one page from the same base revision.+ const width = 2 + Math.floor(rand() * 2); const ids: string[] = [];+ for (let i = 0; i < width && s.ops.length < length; i++) {+ const d = rand() < 0.5 ? s.edit(actorFor(source), source, slug, { $ref: page.id, field: 'revision' }, [page.id])+ : s.next('remember', actorFor(source), source, { fact: `Concurrent ${s.marker()}`, entity: slug }, [page.id]);+ ids.push(d.id);+ }+ if (ids.length > 1) s.groups.push(ids);+ }+ return { seed, ops: s.ops, groups: s.groups, label: `random-${seed}` };+}diff --git a/scripts/persistence/history-fixture.ts b/scripts/persistence/history-fixture.tsindex 5fe45ce60a..907f5d176f 100644--- a/scripts/persistence/history-fixture.ts+++ b/scripts/persistence/history-fixture.ts@@ -164,37 +164,50 @@ function digestOf(plan: OpDescriptor[], observations: OpObservation[]): string {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-'));+export interface ManagedTopology { world: World; checkouts: string[]; sources: HistoryFixtureSource[]; accessTokenId: string; oauthClientId: string }+/**+ * Register `sources` sources spread across `worktrees` durability-hardened Git+ * checkouts under `root`, activate managed persistence, and authenticate two+ * remote agents through the production token verifier: an OAuth client on the+ * first source and a legacy access token (unified grant columns) on the second.+ */+export async function prepareTopology(engine: BrainEngine, { sources, worktrees, root, prefix = 'history' }:+ { sources: number; worktrees: number; root: string; prefix?: string }): Promise<ManagedTopology> {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 };+ return { id: `${prefix}-${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 client = await provider.registerClientManual(`${prefix} 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 minted = await mintLegacyToken(engine, { name: `${prefix}-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() };+ const world: World = { engine, config: { engine: engine.kind, embedding_disabled: true } as GBrainConfig, remotes, auth: new Map(), observations: new Map() };await authenticateRemotes(world);+ return { world, checkouts, sources: fixtureSources, accessTokenId: minted.id, oauthClientId: client.clientId };+}++/** 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 topology = await prepareTopology(engine, { sources, worktrees, root });+ const { world, checkouts, sources: fixtureSources, accessTokenId, oauthClientId } = topology;+ const remotes = world.remotes;const plan = historyPlan({ pages, seed, sources, worktrees }, fixtureSources.map(s => s.id), remotes);// Sources publish independently; ops within one source run in plan order.@@ -247,7 +260,7 @@ export async function buildHistoryFixture(engine: BrainEngine,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,+ return { root, seed, sources: fixtureSources, remotes, accessTokenId, oauthClientId,observations, queuedRequestId, delayedEffectId: delayedEffectId!, counts, digest: digestOf(plan, observations) };}diff --git a/scripts/persistence/model.ts b/scripts/persistence/model.tsnew file mode 100644index 0000000000..adb35d819e--- /dev/null+++ b/scripts/persistence/model.ts@@ -0,0 +1,344 @@+/**+ * The crash robot's reference model: an independent temporal oracle. It+ * derives expectations from durable receipts (request id -> revision) plus a+ * small state model of page identities, revisions, markers, withdrawals and+ * supersession chains. Committed visibility is checked at the observation+ * point (right after the caller saw the receipt); afterwards only legal+ * transitions are allowed: a page's revision moves only when a committed op+ * touched that page, and a withdrawn fact never becomes visible again.+ *+ * Documented exceptions: `remember` without an entity page writes a DB-only+ * fact (src/core/persistence/memory-mutations.ts) and has no fence row; an+ * explicit `remember` of a withdrawn claim is a new assertion, not a resurrection.+ */+import type { EffectKind } from '../../src/core/persistence/effect-model.ts';+import { EFFECT_FAULT_POINTS, type FaultPoint } from '../../src/core/persistence/fault-points.ts';+import { operationsByName } from '../../src/core/operations.ts';+import { parseFactsFence } from '../../src/core/facts-fence.ts';+import { parseTakesFence } from '../../src/core/takes-fence.ts';+import { contextFor, type OpDescriptor, type OpKind, type OpObservation, type World } from './ops.ts';++/**+ * How the generator reaches each effect kind's mid-effect seam: the op that+ * queues it. A new effect kind without an entry fails typecheck.+ * facts-backstop is queued only when facts extraction is configured; keyless+ * robot brains never queue it, so its seam is exercised by the facts drain.+ */+export const EFFECT_SEAMS = {+ git: { op: 'put_page', point: EFFECT_FAULT_POINTS.git },+ embedding: { op: 'put_page', point: EFFECT_FAULT_POINTS.embedding },+ 'withdrawal-mirror': { op: 'forget', point: EFFECT_FAULT_POINTS['withdrawal-mirror'] },+ 'facts-backstop': { op: 'put_page', point: EFFECT_FAULT_POINTS['facts-backstop'] },+} as const satisfies Record<EffectKind, { op: OpKind; point: FaultPoint }>;++export type ViolationClass = 'lost_write' | 'duplicate_apply' | 'untrue_receipt' | 'wedge' | 'withdrawal_permanence'+ | 'source_isolation' | 'authorization' | 'caller_bound_replay' | 'projection_drift' | 'missing_attribution' | 'orphan_rows' | 'effects_not_terminal';+/** Violations that always block a ship (see the plan's bug-fix bound). */+export const SAFETY_CLASSES: ReadonlySet<ViolationClass> = new Set(['lost_write', 'duplicate_apply', 'untrue_receipt', 'wedge',+ 'withdrawal_permanence', 'source_isolation', 'authorization', 'caller_bound_replay']);+export interface Violation { class: ViolationClass; op?: string; detail: string }++interface PageModel { live: boolean; revision: string | null; markers: Set<string>; lastMarker: string | null }+interface FactModel { id: string; source: string; text: string; entity: string; withdrawn: boolean; op: string }++const MARKER = /mk-[a-z]+\d+/g;+const key = (source: string, slug: string) => `${source}\u0000${slug}`;+function markersIn(text: string | undefined | null): string[] { return text ? [...text.matchAll(MARKER)].map(m => m[0]) : []; }+/** The newest page-body marker: edits insert theirs right after "Marker: ". */+function bodyMarker(text: string | undefined | null): string | null { return /Marker: (mk-[a-z]+\d+)/.exec(text ?? '')?.[1] ?? null; }++export class ReferenceModel {+ pages = new Map<string, PageModel>();+ facts = new Map<string, FactModel>();+ /** Marker -> source of the committed op that introduced it. */+ committedMarkers = new Map<string, string>();+ /** Markers of ops that were refused: they must never become visible. */+ refusedMarkers = new Set<string>();+ /** Re-asserted withdrawn claims (an explicit remember after forget). */+ reasserted = new Set<string>();+ violations: Violation[] = [];+ /** Pages a committed op touched in the current step: their revision may move. */+ touched = new Set<string>();+ revoked = new Set<string>();+ /** Accepted but not yet terminal when the caller stopped waiting: settled by `settlePending`. */+ pending = new Map<string, OpDescriptor>();++ constructor(readonly world: World) {}+ violate(v: Violation) { this.violations.push(v); }++ /** Durable model state, so a worker started after a SIGKILL continues the same oracle. */+ toJSON(): Record<string, unknown> {+ return { pages: [...this.pages].map(([k, p]) => [k, { ...p, markers: [...p.markers] }]), facts: [...this.facts],+ committedMarkers: [...this.committedMarkers], refusedMarkers: [...this.refusedMarkers], reasserted: [...this.reasserted],+ revoked: [...this.revoked], violations: this.violations, pending: [...this.pending] };+ }+ static fromJSON(world: World, state: Record<string, any>): ReferenceModel {+ const m = new ReferenceModel(world);+ m.pages = new Map(state.pages.map(([k, p]: [string, any]) => [k, { ...p, markers: new Set(p.markers) }]));+ m.facts = new Map(state.facts); m.committedMarkers = new Map(state.committedMarkers);+ m.refusedMarkers = new Set(state.refusedMarkers); m.reasserted = new Set(state.reasserted);+ m.revoked = new Set(state.revoked); m.violations = state.violations; m.pending = new Map(state.pending ?? []);+ return m;+ }+ /** Pages an in-flight op names: a crash may or may not have committed it, so their revision may move. */+ allowInFlight(ops: OpDescriptor[]): void {+ for (const d of ops) {+ const slug = d.args.slug ?? d.args.entity;+ if (typeof slug === 'string') this.touched.add(key(d.source, slug));+ if (d.kind === 'forget') for (const f of this.facts.values()) if (f.source === d.source) this.touched.add(key(f.source, f.entity));+ }+ }+ /** Forget pending page-liveness expectations an in-flight delete/restore may have settled either way. */+ relaxInFlight(ops: OpDescriptor[]): void {+ for (const d of ops) if ((d.kind === 'delete_page' || d.kind === 'restore_page' || d.kind === 'put_page') && typeof d.args.slug === 'string') {+ this.pages.delete(key(d.source, d.args.slug));+ }+ }++ page(source: string, slug: string): PageModel {+ let p = this.pages.get(key(source, slug));+ if (!p) { p = { live: false, revision: null, markers: new Set(), lastMarker: null }; this.pages.set(key(source, slug), p); }+ return p;+ }++ /** Ops of the current concurrent group: their observation-point checks wait for `settleGroup`. */+ private deferred = false;++ /** Fold one observed op into the model and check its observation-point promises. */+ async observe(d: OpDescriptor, o: OpObservation, original?: OpObservation): Promise<void> {+ const marker = markersIn(JSON.stringify(d.args)).at(-1) ?? null;+ if (d.replayOf && original) {+ await this.checkReplay(d, o, original);+ // A same-principal replay returns the original receipt; it is not a new write.+ if (d.actor === original.actor) return;+ }+ if (d.actor !== 'local' && this.revoked.has(d.actor) && o.status === 'committed') {+ this.violate({ class: 'authorization', op: d.id, detail: `${d.kind} by revoked ${d.actor} committed` });+ }+ if (o.status === 'pending') { this.pending.set(d.id, d); return; }+ this.pending.delete(d.id);+ if (o.status !== 'committed') {+ if (marker && !this.committedMarkers.has(marker)) this.refusedMarkers.add(marker);+ if (o.status === 'refused' && !o.code) this.violate({ class: 'untrue_receipt', op: d.id, detail: 'refusal without a typed code' });+ return;+ }+ if (marker) { this.committedMarkers.set(marker, d.source); this.refusedMarkers.delete(marker); }+ await MODEL[d.kind](this, d, o);+ }++ /** Start of a step: pages a committed op touches during this step (or a pending op names) may move their revision. */+ beginStep(concurrent: boolean): void {+ this.touched.clear(); this.deferred = concurrent;+ this.allowInFlight([...this.pending.values()]);+ }+ get deferringVisibility(): boolean { return this.deferred; }++ /**+ * After a concurrent group: each touched page's revision must be one a+ * committed group member returned, every committed edit's marker is+ * visible, and every superseded member revision is in the page's history.+ */+ async settleGroup(batch: OpDescriptor[], observed: OpObservation[]): Promise<void> {+ const committed = batch.map((d, i) => ({ d, o: observed[i] })).filter(x => x.o.status === 'committed');+ const bySlug = new Map<string, typeof committed>();+ for (const x of committed) {+ const slug = String(x.d.args.slug ?? x.d.args.entity ?? '');+ if (slug) bySlug.set(key(x.d.source, slug), [...(bySlug.get(key(x.d.source, slug)) ?? []), x]);+ }+ for (const [k, members] of bySlug) {+ const [source, slug] = k.split('\u0000');+ const read = await this.readPage('local', source, slug);+ const revisions = members.map(x => x.o.values.revision).filter(Boolean) as string[];+ if (revisions.length && !revisions.includes(String(read?.revision))) {+ this.violate({ class: 'lost_write', op: members.map(x => x.d.id).join('+'), detail: `concurrent group left ${source}/${slug} at ${String(read?.revision)}, none of the committed revisions ${revisions.join(',')}` });+ }+ for (const x of members) {+ const marker = x.d.kind === 'edit_page' || x.d.kind === 'put_page' ? markersIn(JSON.stringify(x.d.args)).at(-1) : null;+ if (marker && !markersIn(String(read?.content)).includes(marker)) this.violate({ class: 'lost_write', op: x.d.id, detail: `committed concurrent ${x.d.kind} marker ${marker} is not visible` });+ if (x.o.values.revision && x.o.values.revision !== read?.revision) {+ const [kept] = await this.world.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id+ WHERE p.source_id=$1 AND p.slug=$2 AND v.knowledge_revision::text=$3`, [source, slug, x.o.values.revision]);+ if (!kept.n) this.violate({ class: 'untrue_receipt', op: x.d.id, detail: `committed revision ${x.o.values.revision} of ${source}/${slug} never existed` });+ }+ }+ const page = this.page(source, slug);+ page.revision = read?.revision ? String(read.revision) : null;+ if (members.some(x => x.d.kind === 'edit_page' || x.d.kind === 'put_page')) page.lastMarker = bodyMarker(String(read?.content)) ?? page.lastMarker;+ }+ this.deferred = false;+ }++ private async checkReplay(d: OpDescriptor, o: OpObservation, original: OpObservation): Promise<void> {+ const sameActor = d.actor === original.actor;+ const sameIntent = JSON.stringify(d.args) === JSON.stringify(this.world.descriptors?.get(original.id)?.args);+ if (!sameActor) {+ if (o.receipt && original.receipt && o.receipt.revision && o.receipt.revision === original.receipt.revision) {+ this.violate({ class: 'caller_bound_replay', op: d.id, detail: `${d.actor} replaying ${original.actor}'s request id received the original receipt` });+ }+ return;+ }+ if (sameIntent) {+ if (original.status === 'committed' && o.status !== 'committed') this.violate({ class: 'untrue_receipt', op: d.id, detail: `same-intent replay of a committed request returned ${o.status}/${o.code}` });+ if (original.status === 'committed' && o.receipt?.revision && original.receipt?.revision && o.receipt.revision !== original.receipt.revision) {+ this.violate({ class: 'duplicate_apply', op: d.id, detail: 'same-intent replay produced a new revision' });+ }+ } else if (original.status !== 'refused' && o.status === 'committed') {+ this.violate({ class: 'caller_bound_replay', op: d.id, detail: 'changed intent under one request id committed instead of idempotency_conflict' });+ }+ }++ /** Read surfaces an agent uses, under a given actor. */+ async readPage(actor: string, source: string, slug: string): Promise<Record<string, unknown> | null> {+ try {+ return await operationsByName.get_page.handler(contextFor(this.world, actor, source),+ { slug, include_content: true, ...(actor === 'local' ? { source_id: source } : {}) }) as Record<string, unknown>;+ } catch { return null; }+ }+ async recall(actor: string, source: string, entity: string): Promise<string[]> {+ try {+ const r = await operationsByName.recall.handler(contextFor(this.world, actor, source),+ { entity, limit: 100, ...(actor === 'local' ? { source_id: source } : {}) }) as { facts?: { fact?: string }[] };+ return (r.facts ?? []).map(f => String(f.fact ?? ''));+ } catch { return []; }+ }++ /** Invariants over the whole brain; run after every step and after recovery. */+ async checkGlobal(stage: string): Promise<void> {+ const engine = this.world.engine;+ const rows = await engine.executeRaw<{ source_id: string; slug: string; compiled_truth: string; timeline: string; revision: string | null; deleted: boolean; id: number }>(+ 'SELECT id,source_id,slug,compiled_truth,timeline,knowledge_revision::text AS revision,deleted_at IS NOT NULL AS deleted FROM pages');+ const seen = new Set<string>();+ for (const row of rows) {+ const k = key(row.source_id, row.slug); seen.add(k);+ for (const m of markersIn(`${row.compiled_truth}\n${row.timeline}`)) {+ const owner = this.committedMarkers.get(m);+ if (owner && owner !== row.source_id) this.violate({ class: 'source_isolation', detail: `${stage}: ${m} written to ${owner} is visible in ${row.source_id}/${row.slug}` });+ if (!owner && this.refusedMarkers.has(m)) this.violate({ class: 'untrue_receipt', detail: `${stage}: refused write ${m} is visible in ${row.source_id}/${row.slug}` });+ }+ const model = this.pages.get(k);+ if (!model) continue;+ if (model.live === row.deleted) this.violate({ class: model.live ? 'lost_write' : 'untrue_receipt', detail: `${stage}: ${row.source_id}/${row.slug} live=${!row.deleted}, model expects ${model.live}` });+ if (this.touched.has(k)) model.revision = row.revision;+ else if (model.revision && row.revision !== model.revision) {+ this.violate({ class: 'lost_write', detail: `${stage}: ${row.source_id}/${row.slug} revision ${row.revision} != last committed ${model.revision}` });+ }+ if (model.live && model.lastMarker && !markersIn(row.compiled_truth).includes(model.lastMarker)) {+ this.violate({ class: 'lost_write', detail: `${stage}: ${row.source_id}/${row.slug} lost committed marker ${model.lastMarker}` });+ }+ }+ for (const [k, model] of this.pages) if (model.live && !seen.has(k)) this.violate({ class: 'lost_write', detail: `${stage}: committed page ${k.replace('\u0000', '/')} is missing` });+ await this.checkWithdrawals(stage);+ await this.checkProjection(stage, rows.filter(r => !r.deleted));+ await this.checkAttribution(stage);+ }++ private async checkWithdrawals(stage: string): Promise<void> {+ const withdrawn = [...this.facts.values()].filter(f => f.withdrawn && !this.reasserted.has(`${f.source}\u0000${f.text}`));+ for (const fact of withdrawn) {+ const actors = ['local', ...this.world.remotes.filter(r => r.sourceId === fact.source && !this.revoked.has(r.name)).map(r => r.name)];+ for (const actor of actors) {+ if ((await this.recall(actor, fact.source, fact.entity)).includes(fact.text)) {+ this.violate({ class: 'withdrawal_permanence', op: fact.op, detail: `${stage}: withdrawn fact "${fact.text}" returned by recall for ${actor}` });+ }+ }+ const page = await this.readPage('local', fact.source, fact.entity);+ const live = parseFactsFence(String(page?.content ?? '')).facts.filter(f => !f.forgotten && f.validUntil === undefined && f.claim === fact.text);+ if (live.length) this.violate({ class: 'withdrawal_permanence', op: fact.op, detail: `${stage}: withdrawn fact "${fact.text}" is a live row in ${fact.source}/${fact.entity}'s fence` });+ const [db] = await this.world.engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL', [fact.source, fact.text]);+ if (db.n > 0) this.violate({ class: 'withdrawal_permanence', op: fact.op, detail: `${stage}: withdrawn fact "${fact.text}" has ${db.n} active row(s)` });+ }+ }++ private async checkProjection(stage: string, live: { id: number; source_id: string; slug: string }[]): Promise<void> {+ const engine = this.world.engine;+ for (const row of live) {+ const page = await this.readPage('local', row.source_id, row.slug);+ const content = String(page?.content ?? '');+ const takes = parseTakesFence(content).takes;+ const dbTakes = await engine.executeRaw<{ row_num: number; claim: string; active: boolean }>(+ 'SELECT row_num,claim,active FROM takes WHERE page_id=$1 ORDER BY row_num', [row.id]);+ const fence = takes.map(t => `${t.rowNum}:${t.claim}:${t.active}`).sort();+ const db = dbTakes.map(t => `${t.row_num}:${t.claim}:${t.active}`).sort();+ if (JSON.stringify(fence) !== JSON.stringify(db)) this.violate({ class: 'projection_drift', detail: `${stage}: ${row.source_id}/${row.slug} takes fence ${JSON.stringify(fence)} != rows ${JSON.stringify(db)}` });+ const liveFacts = parseFactsFence(content).facts.filter(f => !f.forgotten && f.validUntil === undefined).map(f => f.claim).sort();+ const dbFacts = (await engine.executeRaw<{ fact: string }>(`SELECT fact FROM facts WHERE source_id=$1 AND source_markdown_slug=$2+ AND expired_at IS NULL AND superseded_by IS NULL AND (valid_until IS NULL OR valid_until > now())`, [row.source_id, row.slug])).map(f => f.fact).sort();+ if (JSON.stringify(liveFacts) !== JSON.stringify(dbFacts)) this.violate({ class: 'projection_drift', detail: `${stage}: ${row.source_id}/${row.slug} facts fence ${JSON.stringify(liveFacts)} != rows ${JSON.stringify(dbFacts)}` });+ }+ const [orphans] = await engine.executeRaw<{ takes: number; timeline: number }>(`SELECT+ (SELECT count(*)::int FROM takes t WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id=t.page_id)) AS takes,+ (SELECT count(*)::int FROM timeline_entries e WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id=e.page_id)) AS timeline`);+ if (orphans.takes || orphans.timeline) this.violate({ class: 'orphan_rows', detail: `${stage}: orphan takes=${orphans.takes} timeline=${orphans.timeline}` });+ }++ private async checkAttribution(stage: string): Promise<void> {+ const [missing] = await this.world.engine.executeRaw<{ facts: number; takes: number; timeline: number; pages: number }>(`SELECT+ (SELECT count(*)::int FROM facts WHERE write_principal_kind IS NULL) AS facts,+ (SELECT count(*)::int FROM takes WHERE write_principal_kind IS NULL) AS takes,+ (SELECT count(*)::int FROM timeline_entries WHERE write_principal_kind IS NULL) AS timeline,+ (SELECT count(*)::int FROM pages WHERE deleted_at IS NULL AND revision_principal_kind IS NULL) AS pages`);+ for (const [table, n] of Object.entries(missing)) if (n) this.violate({ class: 'missing_attribution', detail: `${stage}: ${n} ${table} row(s) without write attribution` });+ }++ /** After a drain: nothing pending, every effect terminal, and a fresh write still admits (no wedge). */+ async checkDrained(stage: string): Promise<void> {+ const [pending] = await this.world.engine.executeRaw<{ requests: number; effects: number }>(`SELECT+ (SELECT count(*)::int FROM persistence_requests WHERE state IN ('queued','running','recovering')) AS requests,+ (SELECT count(*)::int FROM persistence_effects WHERE state IN ('queued','running') OR recovery IS NOT NULL) AS effects`);+ if (pending.requests) this.violate({ class: 'wedge', detail: `${stage}: ${pending.requests} request(s) still pending after the drain` });+ if (pending.effects) this.violate({ class: 'effects_not_terminal', detail: `${stage}: ${pending.effects} effect(s) not terminal after the drain` });+ }+}++type Fold = (m: ReferenceModel, d: OpDescriptor, o: OpObservation) => Promise<void>;+const pageWrite = (kind: 'put' | 'edit'): Fold => async (m, d, o) => {+ const slug = String(d.args.slug); const page = m.page(d.source, slug); const k = key(d.source, slug);+ const marker = d.args.content === '$stale_content' ? bodyMarker(o.pageContent)+ : markersIn(String(d.args.content ?? JSON.stringify(d.args.edits ?? ''))).at(-1) ?? null;+ page.live = true; page.revision = o.values.revision ?? null; m.touched.add(k);+ if (kind === 'put') page.markers = new Set(markersIn(o.pageContent));+ if (marker) page.markers.add(marker);+ page.lastMarker = marker;+ if (m.deferringVisibility) return;+ const read = await m.readPage(d.actor === 'local' || m.revoked.has(d.actor) ? 'local' : d.actor, d.source, slug);+ if (!read || read.revision !== o.values.revision) m.violate({ class: 'untrue_receipt', op: d.id, detail: `committed ${d.kind} revision ${o.values.revision} not visible (read ${String(read?.revision)})` });+ else if (page.lastMarker && !markersIn(String(read.content)).includes(page.lastMarker)) m.violate({ class: 'untrue_receipt', op: d.id, detail: `committed ${d.kind} marker ${page.lastMarker} not visible` });+};+const touch = (slugOf: (d: OpDescriptor) => string): Fold => async (m, d, o) => {+ const k = key(d.source, slugOf(d)); m.touched.add(k);+ const page = m.page(d.source, slugOf(d));+ if (o.values.revision) page.revision = o.values.revision;+ else page.revision = null;+};++/** One fold per op kind: how a committed observation moves the model, plus its observation-point check. */+export const MODEL: Record<OpKind, Fold> = {+ put_page: pageWrite('put'),+ edit_page: pageWrite('edit'),+ remember: async (m, d, o) => {+ const text = String(d.args.fact); const entity = String(d.args.entity ?? '');+ if (o.values.fact_id) m.facts.set(o.values.fact_id, { id: o.values.fact_id, source: d.source, text, entity, withdrawn: false, op: d.id });+ if ([...m.facts.values()].some(f => f.withdrawn && f.source === d.source && f.text === text)) m.reasserted.add(`${d.source}\u0000${text}`);+ await touch(() => entity)(m, d, o);+ const status = (o.raw as { status?: string } | undefined)?.status;+ if (!m.deferringVisibility && status !== 'duplicate' && !(await m.recall(m.revoked.has(d.actor) ? 'local' : d.actor, d.source, entity)).includes(text)) {+ m.violate({ class: 'untrue_receipt', op: d.id, detail: `committed remember "${text}" not returned by recall` });+ }+ },+ forget: async (m, d, o) => {+ const id = String((o.raw as { id?: unknown } | undefined)?.id ?? '');+ const fact = m.facts.get(id);+ if (fact) {+ if (fact.source !== d.source) m.violate({ class: 'source_isolation', op: d.id, detail: `forget in ${d.source} expired fact ${id} of ${fact.source}` });+ fact.withdrawn = true; m.reasserted.delete(`${fact.source}\u0000${fact.text}`);+ m.touched.add(key(fact.source, fact.entity)); m.page(fact.source, fact.entity).revision = null;+ }+ },+ takes_add: touch(d => String(d.args.slug)),+ takes_supersede: touch(d => String(d.args.slug)),+ add_timeline_entry: touch(d => String(d.args.slug)),+ delete_page: async (m, d, o) => { await touch(d => String(d.args.slug))(m, d, o); m.page(d.source, String(d.args.slug)).live = false; },+ restore_page: async (m, d, o) => { await touch(d => String(d.args.slug))(m, d, o); m.page(d.source, String(d.args.slug)).live = true; },+ revoke_access: async (m, d) => { m.revoked.add(String(d.args.actor)); },+};diff --git a/scripts/persistence/ops.ts b/scripts/persistence/ops.tsindex 284a824139..de4ffc9605 100644--- a/scripts/persistence/ops.ts+++ b/scripts/persistence/ops.ts@@ -18,9 +18,10 @@ 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';+import { revokeLegacyTokenById } from '../../src/core/token-mint.ts';export const OP_KINDS = ['put_page', 'edit_page', 'remember', 'forget', 'takes_add', 'takes_supersede',- 'add_timeline_entry', 'delete_page', 'restore_page'] as const;+ 'add_timeline_entry', 'delete_page', 'restore_page', 'revoke_access'] 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;@@ -64,6 +65,8 @@ export interface OpObservation {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 page bytes the caller could read right after a committed op on a page (for stale republication). */+ pageContent?: string;/** The raw handler result or error fields, JSON-safe. */raw?: unknown;}@@ -82,6 +85,11 @@ export interface World {/** AuthInfo per remote actor, from the real token verifier. */auth: Map<string, AuthInfo>;observations: Map<string, OpObservation>;+ /** Descriptors by id, and the exact parameters each was submitted with (a same-intent replay resends them). */+ descriptors?: Map<string, OpDescriptor>;+ submitted?: Map<string, Record<string, unknown>>;+ /** Called with the exact parameters right before submission (a crash worker persists them). */+ onSubmit?: (d: OpDescriptor, params: Record<string, unknown>) => void;}export function descriptor(id: string, kind: OpKind, actor: string, source: string, args: Record<string, OpArg>,@@ -108,6 +116,25 @@ export async function authenticateRemotes(world: World): Promise<void> {for (const remote of world.remotes) world.auth.set(remote.name, await provider.verifyAccessToken(remote.token) as unknown as AuthInfo);}+/** Re-verify one actor's bearer token, as a remote transport does on every request. */+async function reauthenticate(world: World, actor: string): Promise<void> {+ const remote = world.remotes.find(r => r.name === actor);+ if (!remote) return;+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(world.engine) });+ world.auth.set(actor, await provider.verifyAccessToken(remote.token) as unknown as AuthInfo);+}++/** Revoke a remote actor's credential through the owner's real revocation path. */+async function revokeAccess(world: World, actor: string): Promise<void> {+ const remote = world.remotes.find(r => r.name === actor);+ if (!remote) throw new Error(`op descriptor: revoke_access names unknown actor ${actor}`);+ const auth = world.auth.get(actor);+ const sql = sqlQueryForEngine(world.engine);+ if (remote.kind === 'oauth_client') {+ await new GBrainOAuthProvider({ sql, transaction: fn => world.engine.transaction(tx => fn(sqlQueryForEngine(tx))) }).revokeClient(auth!.clientId);+ } else await revokeLegacyTokenById(sql, auth!.principal!.id);+}+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() {} } };@@ -135,7 +162,15 @@ function resolveArg(world: World, value: OpArg): unknown {/** 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 original = d.replayOf ? world.descriptors?.get(d.replayOf) : undefined;+ const resent = original && original.actor === d.actor && original.kind === d.kind && JSON.stringify(original.args) === JSON.stringify(d.args)+ ? world.submitted?.get(original.id) : undefined;+ if (resent) return { op: d.kind, params: resent };+ // A resubmission after a crash sends exactly what the interrupted caller sent.+ const interrupted = world.submitted?.get(d.id);+ if (interrupted) return { op: d.kind, params: interrupted };const a = resolveArg(world, d.args as OpArg) as Record<string, unknown>;+ if (a.content === '$stale_content') a.content = world.observations.get(String(a.stale_of))?.pageContent ?? 'missing stale content';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';@@ -153,6 +188,7 @@ export async function paramsFor(world: World, d: OpDescriptor): Promise<{ op: stcase '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 } };+ case 'revoke_access': return { op: 'revoke_access', params: { actor: a.actor } };}}@@ -172,13 +208,22 @@ function receiptOf(value: Record<string, unknown> | undefined): OpObservation['r/** Run one descriptor through its real handler and record what the caller observed. */export async function executeOp(world: World, d: OpDescriptor): Promise<OpObservation> {+ const base = { id: d.id, kind: d.kind, actor: d.actor, source: d.source, requestId: d.requestId };+ if (d.kind === 'revoke_access') {+ await revokeAccess(world, String(d.args.actor));+ const observation: OpObservation = { ...base, status: 'committed', values: {} };+ world.observations.set(d.id, observation);+ return observation;+ }const { op, params } = await paramsFor(world, d);+ (world.submitted ??= new Map()).set(d.id, params);+ world.onSubmit?.(d, params);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 {+ await reauthenticate(world, d.actor);+ const ctx = contextFor(world, d.actor, d.source);const result = await handler(ctx, params) as Record<string, unknown>;const receipt = receiptOf(result);const state = receipt?.state ?? 'committed';@@ -189,11 +234,21 @@ export async function executeOp(world: World, d: OpDescriptor): Promise<OpObservif (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 e = error as { code?: string; name?: string; writeRequest?: Record<string, unknown>; message?: string };+ // The HTTP transport answers a token the verifier rejects with 401 invalid_token.+ if (!e.code && e.name === 'InvalidTokenError') e.code = 'invalid_token';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) } };}+ const slug = typeof params.slug === 'string' ? params.slug : typeof params.entity === 'string' ? params.entity : null;+ if (observation.status === 'committed' && slug) {+ try {+ const page = await operationsByName.get_page.handler(contextFor(world, 'local', d.source),+ { slug, include_content: true, source_id: d.source }) as Record<string, unknown>;+ if (typeof page?.content === 'string') observation.pageContent = page.content;+ } catch { /* deleted or not a page */ }+ }world.observations.set(d.id, observation);return observation;}diff --git a/scripts/persistence/robot-driver.ts b/scripts/persistence/robot-driver.tsnew file mode 100644index 0000000000..1a944955ed--- /dev/null+++ b/scripts/persistence/robot-driver.ts@@ -0,0 +1,157 @@+/**+ * Driver for the crash robot phase of the persistence gate. For each+ * schedule (the five cross-boundary sequences first, then seeded random+ * sequences until the time budget runs out) it runs a counting pass that+ * finds every seam the schedule reaches, then one process-separated run per+ * chosen crash point: a worker freezes at the seam, the driver SIGKILLs it,+ * and a fresh worker recovers, resubmits the interrupted requests and+ * finishes the schedule. Every run is checked by the reference model.+ * Process faults (stale index.lock, hung git child) run once per engine.+ */+import { createHash, randomUUID } from 'node:crypto';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import type postgres from '#postgres';+import { random } from './harness.ts';+import { crossBoundarySequences, randomSchedule, type GeneratorTopology, type Schedule } from './generator.ts';+import type { ProcessFault, RobotConfig, RobotOutcome } from './crash-robot.ts';+import type { FaultPoint } from '../../src/core/persistence/fault-points.ts';+import type { OpDescriptor } from './ops.ts';+import type { spawnWorker as SpawnWorker } from './validate.ts';++export const ROBOT_TOPOLOGY: GeneratorTopology = { sources: ['robot-0', 'robot-1'],+ remotes: [{ name: 'agent-oauth', sourceId: 'robot-0' }, { name: 'agent-token', sourceId: 'robot-1' }] };+export const PROCESS_FAULTS: ProcessFault[] = ['stale_index_lock', 'hung_git'];++/** One executed run, enough to replay it exactly: `--replay` re-injects this entry. */+export interface RobotRun {+ schedule: string; seed: number; length: number; fault?: { point: FaultPoint; nth: number }; process?: ProcessFault;+ ops?: string[]; crashed: boolean; violations: RobotOutcome['violations']; duration_ms: number;+}+export interface RobotOptions {+ engine: 'pglite' | 'postgres'; seed: number; seconds: number; scratch: string; home: string;+ admin?: ReturnType<typeof postgres>; databaseUrl?: string; databases: string[];+ spawn: typeof SpawnWorker; track: (child: ReturnType<typeof SpawnWorker>) => void;+ /** Re-run exactly these entries instead of generating. */+ replay?: RobotRun[];+ /** Keep only these op ids of a schedule (shrinking). */+ keep?: Map<string, Set<string>>;+ worktrees?: number;+ log?: (line: string) => void;+}++export function scheduleFor(label: string, seed: number, length: number): Schedule {+ if (label.startsWith('random-')) return randomSchedule(ROBOT_TOPOLOGY, seed, length);+ const found = crossBoundarySequences(ROBOT_TOPOLOGY, seed).find(s => s.label === label);+ if (!found) throw new Error(`Unknown crash-robot schedule ${label}`);+ return found;+}+/** Drop ops not in `keep`, and any op whose dependencies were dropped; groups shrink with them. */+export function restrict(schedule: Schedule, keep?: Set<string>): Schedule {+ if (!keep) return schedule;+ const kept = new Set<string>();+ const ops: OpDescriptor[] = [];+ for (const d of schedule.ops) {+ if (!keep.has(d.id)) continue;+ if ((d.deps ?? []).some(dep => !kept.has(dep) && schedule.ops.some(o => o.id === dep))) continue;+ kept.add(d.id); ops.push(d);+ }+ return { ...schedule, ops, groups: schedule.groups.map(g => g.filter(id => kept.has(id))).filter(g => g.length > 1) };+}++export async function runRobotPhase(o: RobotOptions) {+ const started = performance.now();+ const runs: RobotRun[] = [];+ const log = o.log ?? (line => process.stderr.write(`[crash-robot] ${o.engine}: ${line}\n`));+ async function fresh(name: string): Promise<{ root: string; dataDir: string; databaseUrl?: string }> {+ const root = join(o.scratch, `robot-${name}-${randomUUID().slice(0, 8)}`); mkdirSync(root, { recursive: true });+ let databaseUrl: string | undefined;+ if (o.admin) {+ const database = `gbrain_persistence_test_${randomUUID().replaceAll('-', '')}`;+ await o.admin.unsafe(`CREATE DATABASE ${database}`); o.databases.push(database);+ const url = new URL(o.databaseUrl!); url.pathname = `/${database}`; databaseUrl = url.toString();+ }+ return { root, dataDir: join(root, 'data'), databaseUrl };+ }+ async function execute(schedule: Schedule, role: 'count' | 'run', extra: Partial<RobotConfig> = {}): Promise<RobotRun & { counts?: Record<string, number> }> {+ const at = performance.now();+ const place = await fresh(`${schedule.label}-${role}`);+ const config: RobotConfig = { kind: o.engine, ...place, schedule, worktrees: o.worktrees ?? 2, statePath: join(place.root, 'state.json'), ...extra };+ const path = join(place.root, 'robot.json'); writeFileSync(path, JSON.stringify(config), { mode: 0o600 });+ const base = { schedule: schedule.label, seed: schedule.seed, length: schedule.ops.length, ...(extra.fault ? { fault: extra.fault } : {}),+ ...(extra.process ? { process: extra.process } : {}), ...(o.keep?.has(schedule.label) ? { ops: schedule.ops.map(d => d.id) } : {}) };+ const child = o.spawn(path, o.home, 'robot', [role]); o.track(child);+ if (role === 'run' && extra.fault) {+ const reached = await Promise.race([child.event('fault', 600_000).then(e => ({ fault: e })), child.event('done', 600_000).then(e => ({ done: e }))]);+ if ('done' in reached) {+ const result = reached.done.result as RobotOutcome;+ return { ...base, crashed: false, violations: result.violations, duration_ms: performance.now() - at };+ }+ await child.kill();+ const recovered = o.spawn(path, o.home, 'robot', ['recover']); o.track(recovered);+ const result = (await recovered.done()).result as RobotOutcome;+ return { ...base, crashed: true, violations: result.violations, duration_ms: performance.now() - at };+ }+ const result = (await child.done()).result as RobotOutcome;+ return { ...base, crashed: false, violations: result.violations, counts: result.counts, duration_ms: performance.now() - at };+ }+ const record = (run: RobotRun) => {+ runs.push(run);+ const what = run.fault ? `${run.fault.point}#${run.fault.nth}` : run.process ?? 'no crash';+ log(`${run.schedule} ${what}: ${run.violations.length ? `${run.violations.length} VIOLATION(S) ${run.violations.map(v => v.class).join(',')}` : 'ok'} (${Math.round(run.duration_ms)} ms)`);+ };++ if (o.replay) {+ for (const entry of o.replay) {+ const schedule = restrict(scheduleFor(entry.schedule, entry.seed, entry.length), entry.ops ? new Set(entry.ops) : o.keep?.get(entry.schedule));+ record(await execute(schedule, entry.fault || entry.process ? 'run' : 'count', { ...(entry.fault ? { fault: entry.fault } : {}), ...(entry.process ? { process: entry.process } : {}) }));+ }+ return summarize(runs, started, o);+ }++ const rand = random(o.seed);+ const budgetMs = o.seconds * 1000;+ const schedules = function* (): Generator<Schedule> {+ yield* crossBoundarySequences(ROBOT_TOPOLOGY, o.seed);+ for (let i = 0; ; i++) yield randomSchedule(ROBOT_TOPOLOGY, (o.seed + 1 + i) >>> 0, 24);+ };+ const crossBoundary = new Set(crossBoundarySequences(ROBOT_TOPOLOGY, o.seed).map(s => s.label));+ for (const schedule of schedules()) {+ // The cross-boundary sequences always run; random sequences fill the remaining budget.+ if (!crossBoundary.has(schedule.label) && performance.now() - started > budgetMs) break;+ const counted = await execute(schedule, 'count'); record(counted);+ const points = Object.entries(counted.counts ?? {}).sort(([a], [b]) => a.localeCompare(b)) as [FaultPoint, number][];+ for (const [point, count] of points) {+ if (!crossBoundary.has(schedule.label) && performance.now() - started > budgetMs) break;+ record(await execute(schedule, 'run', { fault: { point, nth: 1 + Math.floor(rand() * count) } }));+ }+ }+ for (const fault of PROCESS_FAULTS) record(await execute(crossBoundarySequences(ROBOT_TOPOLOGY, o.seed)[1], 'run', { process: fault }));+ return summarize(runs, started, o);+}++function summarize(runs: RobotRun[], started: number, o: RobotOptions) {+ const crashRuns = runs.filter(r => r.fault);+ const points = new Set(crashRuns.map(r => r.fault!.point));+ const violations = runs.flatMap(r => r.violations.map(v => ({ ...v, schedule: r.schedule, seed: r.seed, fault: r.fault, process: r.process })));+ return {+ seed: o.seed, budget_seconds: o.seconds, duration_ms: performance.now() - started,+ schedules: new Set(runs.map(r => `${r.schedule}:${r.seed}`)).size,+ crash_runs: crashRuns.length, crashed_runs: crashRuns.filter(r => r.crashed).length,+ sequences_x_crash_points: crashRuns.length, distinct_crash_points: [...points].sort(),+ process_faults: runs.filter(r => r.process).map(r => ({ fault: r.process, violations: r.violations.length })),+ violations, failing_runs: runs.filter(r => r.violations.length), runs,+ };+}++/** The replay entries of a manifest: its failing runs, or every run of one seed. */+export function replayEntries(source: string, engine: string): RobotRun[] {+ if (/^\d+$/.test(source)) throw new Error('A bare seed replays through --seed; pass a manifest path to --replay');+ const manifest = JSON.parse(readFileSync(resolve(source), 'utf8'));+ const robot = manifest.robot ?? manifest;+ if (manifest.engine && manifest.engine !== engine) throw new Error(`Manifest ${source} was recorded on ${manifest.engine}, not ${engine}`);+ return (robot.failing_runs?.length ? robot.failing_runs : robot.runs) as RobotRun[];+}+export function runDigest(run: Pick<RobotRun, 'schedule' | 'seed' | 'fault' | 'process' | 'ops'>): string {+ return createHash('sha256').update(JSON.stringify([run.schedule, run.seed, run.fault ?? null, run.process ?? null, run.ops ?? null])).digest('hex').slice(0, 12);+}diff --git a/scripts/persistence/shrink.ts b/scripts/persistence/shrink.tsnew file mode 100644index 0000000000..70654fdebb--- /dev/null+++ b/scripts/persistence/shrink.ts@@ -0,0 +1,51 @@+/**+ * Delta-debugging shrinker for crash-robot failures. It removes ops from the+ * failing schedule (dependencies are kept by `restrict`: an op whose producer+ * was removed is removed with it) while the run still shows a violation of+ * the same class. A candidate whose run errors out is an invalid sequence,+ * counted apart from a non-reproducing one. The result is accepted only when+ * it reproduces in 3 of 3 fresh reruns.+ */+import type { RobotRun } from './robot-driver.ts';+import { runDigest } from './robot-driver.ts';++type Execute = (run: RobotRun, keep?: Map<string, Set<string>>) => Promise<{ violations: { class: string }[] }>;+export interface ShrinkResult {+ original: { ops: number; classes: string[] }; shrunk: RobotRun; reruns: number; reproduced: number;+ candidates: number; invalid: number; accepted: boolean; digest: string;+}++export async function shrinkRun(failing: RobotRun, execute: Execute): Promise<ShrinkResult> {+ const classes = new Set<string>(failing.violations.map(v => v.class));+ const { scheduleFor } = await import('./robot-driver.ts');+ const all = failing.ops ?? scheduleFor(failing.schedule, failing.seed, failing.length).ops.map(d => d.id);+ let candidates = 0, invalid = 0;+ const reproduces = async (ops: string[]): Promise<boolean> => {+ candidates++;+ try {+ const result = await execute({ ...failing, ops, violations: [] });+ return result.violations.some(v => classes.has(v.class));+ } catch { invalid++; return false; }+ };+ let current = all;+ let chunks = 2;+ while (current.length > 1) {+ const size = Math.ceil(current.length / chunks);+ let reduced = false;+ for (let start = 0; start < current.length; start += size) {+ const complement = [...current.slice(0, start), ...current.slice(start + size)];+ if (complement.length && await reproduces(complement)) {+ current = complement; chunks = Math.max(2, chunks - 1); reduced = true; break;+ }+ }+ if (!reduced) {+ if (size === 1) break;+ chunks = Math.min(current.length, chunks * 2);+ }+ }+ const shrunk: RobotRun = { ...failing, ops: current, violations: [] };+ let reproduced = 0;+ for (let i = 0; i < 3; i++) if (await reproduces(current)) reproduced++;+ return { original: { ops: all.length, classes: [...classes] }, shrunk, reruns: 3, reproduced, candidates, invalid,+ accepted: reproduced === 3, digest: runDigest(shrunk) };+}diff --git a/scripts/persistence/validate.ts b/scripts/persistence/validate.tsindex bd422726d1..ac550fcbdf 100644--- a/scripts/persistence/validate.ts+++ b/scripts/persistence/validate.ts@@ -8,10 +8,18 @@ import { assertSafeE2eDatabaseUrl } from '../../test/helpers/db-guard.ts';import { distribution, type HarnessConfig } from './harness.ts';import { keylessBrainEnv } from '../../test/helpers/provider-env.ts';import { boundedDiagnostic, diagnosticError, retentionMetadata } from './failure-diagnostics.ts';+import { replayEntries, runDigest, runRobotPhase, type RobotRun } from './robot-driver.ts';+import { shrinkRun } from './shrink.ts';export interface ValidationOptions {engine: 'pglite' | 'postgres'; schedules?: number; operations?: number; seed?: number;crashes?: boolean; databaseUrl?: string; manifest?: string;+ /** Crash-robot time budget in seconds; 0 skips the phase. */+ robotSeconds?: number;+ /** Re-run a recorded manifest's failing crash-robot runs (and nothing else). */+ replay?: string;+ /** Shrink the first failing crash-robot run of a manifest to a minimal reproducing sequence. */+ shrink?: string;}interface Event { event: string; [key: string]: any; }export const CRASH_BOUNDARIES = ['admitted', 'prepared', 'before_publication', 'staging_flushed',@@ -58,6 +66,17 @@ export function spawnWorker(configPath: string, home: string, role: string, argsasync kill() { if (child.exitCode === null) child.kill('SIGKILL'); await child.exited; await reading; } };}+/** The failing runs plus the exact command that replays them and the one that shrinks the first. */+export function robotFailure(failing: RobotRun[], options: ValidationOptions): string {+ const manifest = options.manifest ?? `.context/persistence-${options.engine}-manifest.json`;+ const env = options.engine === 'postgres' ? 'DATABASE_URL=<test url> ' : '';+ const lines = failing.slice(0, 5).map(run => ` ${run.schedule} seed=${run.seed} ${run.fault ? `${run.fault.point}#${run.fault.nth}` : run.process ?? 'no crash'} [${runDigest(run)}]: `+ + run.violations.slice(0, 3).map(v => `${v.class}: ${v.detail}`).join(' | '));+ return [`Crash robot found ${failing.length} failing run(s):`, ...lines,+ `Replay: ${env}bun --no-env-file scripts/persistence/validate.ts --engine=${options.engine} --replay=${manifest}`,+ `Shrink: ${env}bun --no-env-file scripts/persistence/validate.ts --engine=${options.engine} --shrink=${manifest} (writes ${manifest}.shrunk.json)`].join('\n');+}+/** Every PostgreSQL phase owns a new database; disk PGLite always runs in children. */export async function runValidation(options: ValidationOptions) {const counts = { schedules: options.schedules ?? 1000, operations: options.operations ?? 10_000 };@@ -87,7 +106,9 @@ export async function runValidation(options: ValidationOptions) {'src/core/persistence/effect-recovery.ts', 'src/core/persistence/effect-model.ts', 'src/core/persistence/effects.ts','src/core/persistence/coordinator.ts', 'src/core/persistence/consumer.ts','src/core/persistence/journal.ts', 'src/core/persistence/activation.ts', 'src/core/persistence/filesystem-guard.ts',- 'src/core/persistence/identity.ts', 'src/core/persistence/ownership.ts', 'src/core/pglite-engine.ts', 'src/core/postgres-engine.ts'].map(file =>+ 'src/core/persistence/identity.ts', 'src/core/persistence/ownership.ts', 'src/core/pglite-engine.ts', 'src/core/postgres-engine.ts',+ 'src/core/persistence/fault-points.ts', 'scripts/persistence/ops.ts', 'scripts/persistence/model.ts', 'scripts/persistence/generator.ts',+ 'scripts/persistence/crash-robot.ts', 'scripts/persistence/robot-driver.ts', 'scripts/persistence/shrink.ts'].map(file =>[file, createHash('sha256').update(readFileSync(resolve(import.meta.dir, '../..', file))).digest('hex')]));let databaseUrl: string | undefined;if (admin) {@@ -101,6 +122,30 @@ export async function runValidation(options: ValidationOptions) {const path = join(root, 'config.json'); writeFileSync(path, JSON.stringify(config), { mode: 0o600 }); return { config, path };}function start(path: string, role: string, ...args: string[]) { const child = spawnWorker(path, home, role, args); children.push(child); return child; }+ const robotOptions = (extra: Partial<Parameters<typeof runRobotPhase>[0]> = {}) => ({ engine: options.engine, seed: options.seed ?? 5105,+ seconds: options.robotSeconds ?? 300, scratch, home, admin, databaseUrl: options.databaseUrl, databases,+ spawn: spawnWorker, track: (child: ReturnType<typeof spawnWorker>) => { children.push(child); }, ...extra });+ if (options.replay || options.shrink) {+ const entries = replayEntries((options.replay ?? options.shrink)!, options.engine);+ if (options.shrink) {+ manifest.shrink = await shrinkRun(entries.find(e => e.violations.length) ?? entries[0], (run, keep) => runRobotPhase(robotOptions({ replay: [run], ...(keep ? { keep } : {}) })));+ const shrunkPath = `${resolve(options.shrink)}.shrunk.json`;+ writeFileSync(shrunkPath, `${JSON.stringify({ engine: options.engine, reproduced: `${manifest.shrink.reproduced}/${manifest.shrink.reruns}`,+ failing_runs: [manifest.shrink.shrunk] }, null, 2)}\n`);+ process.stderr.write(`[persistence] shrunk ${manifest.shrink.original.ops} ops to ${manifest.shrink.shrunk.ops?.length}; reproduced ${manifest.shrink.reproduced}/3; ${shrunkPath}\n`+ + `[persistence] Replay: bun --no-env-file scripts/persistence/validate.ts --engine=${options.engine} --replay=${shrunkPath}\n`);+ manifest.status = manifest.shrink.accepted ? 'passed' : 'failed'; manifest.full_gate = false; return manifest;+ }+ manifest.robot = await runRobotPhase(robotOptions({ replay: entries }));+ manifest.status = manifest.robot.violations.length ? 'failed' : 'passed'; manifest.full_gate = false;+ if (manifest.robot.violations.length) throw new Error(robotFailure(manifest.robot.failing_runs, options));+ return manifest;+ }+ if (options.robotSeconds !== 0) {+ manifest.robot = await runRobotPhase(robotOptions());+ process.stderr.write(`[persistence] ${options.engine}: crash robot ran ${manifest.robot.sequences_x_crash_points} sequence x crash point runs over ${manifest.robot.schedules} schedules\n`);+ if (manifest.robot.violations.length) throw new Error(robotFailure(manifest.robot.failing_runs, options));+ }if (options.crashes !== false) for (const boundary of CRASH_BOUNDARIES) {const { path } = await phase(`crash-${boundary}`); const requestId = randomUUID();const child = start(path, 'crash', boundary, requestId);@@ -149,7 +194,7 @@ export async function runValidation(options: ValidationOptions) {manifest.status = 'passed';const executedBoundaries = manifest.crash_cases.map((entry: { boundary: string }) => entry.boundary);if (options.crashes !== false) assert.deepEqual(executedBoundaries, [...CRASH_BOUNDARIES]);- manifest.full_gate = counts.schedules >= 1000 && counts.operations >= 10_000+ manifest.full_gate = counts.schedules >= 1000 && counts.operations >= 10_000 && manifest.robot?.violations.length === 0&& executedBoundaries.length === CRASH_BOUNDARIES.length && CRASH_BOUNDARIES.every((boundary, index) => executedBoundaries[index] === boundary)&& manifest.crash_cases.every((entry: { staging_cleanup_verified?: boolean }) => entry.staging_cleanup_verified === true)&& manifest.crash_cases.find((entry: { boundary: string }) => entry.boundary === 'staging_flushed')?.flushed_before_rename_verified === true@@ -207,10 +252,11 @@ export async function runValidation(options: ValidationOptions) {}if (import.meta.main) {const args = new Map(process.argv.slice(2).map(arg => { const [key, ...value] = arg.replace(/^--/, '').split('='); return [key, value.join('=')]; }));- for (const key of args.keys()) assert(['engine', 'schedules', 'operations', 'seed', 'no-crashes', 'manifest'].includes(key), `Unknown option: ${key}`);+ for (const key of args.keys()) assert(['engine', 'schedules', 'operations', 'seed', 'no-crashes', 'manifest', 'robot-seconds', 'replay', 'shrink'].includes(key), `Unknown option: ${key}`);const engine = args.get('engine') ?? 'pglite'; assert(engine === 'pglite' || engine === 'postgres');const result = await runValidation({ engine, schedules: Number(args.get('schedules') ?? 1000), operations: Number(args.get('operations') ?? 10_000),seed: Number(args.get('seed') ?? 5105), crashes: !args.has('no-crashes'), databaseUrl: process.env.DATABASE_URL,+ robotSeconds: Number(args.get('robot-seconds') ?? 300), replay: args.get('replay') || undefined, shrink: args.get('shrink') || undefined,manifest: args.get('manifest') ?? `.context/persistence-${engine}-manifest.json` });process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);}diff --git a/scripts/persistence/worker.ts b/scripts/persistence/worker.tsindex 1b829f662e..59b2907f0f 100644--- a/scripts/persistence/worker.ts+++ b/scripts/persistence/worker.ts@@ -32,6 +32,9 @@ if (mode === 'initialize') {const engine = await openEngine(config, true); await initializeFixtures(engine, config); await engine.disconnect(); emit({ event: 'done' });} else if (mode === 'schedules') {emit({ event: 'done', result: await runSchedules(config) });+} else if (mode === 'robot') {+ const { robotWorker } = await import('./crash-robot.ts');+ emit({ event: 'done', result: await robotWorker(argument as 'count' | 'run' | 'recover', config as unknown as import('./crash-robot.ts').RobotConfig) });} else if (mode === 'runtime-matrix') {const { runtimeCase } = await import('./matrix-cases.ts');emit({ event: 'done', result: await runtimeCase(config as import('./matrix-cases.ts').RuntimeCase) });diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex a9e3e56a23..6f31975cb6 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -15,6 +15,7 @@ import { redactConnectionInfo } from '../audit/redact-connection-info.ts';import { AsyncLocalStorage } from 'node:async_hooks';import { monitorEventLoopDelay, type IntervalHistogram } from 'node:perf_hooks';import { maybeRefreshPlannerStats } from '../planner-stats.ts';+import { faultPoint } from './fault-points.ts';type PhaseObservation = { name: string; started_at: string; deadline_exceeded: boolean; attempt: number; first_conn_ms?: number };/** #5801: the phase a connection checkout belongs to, carried through its async chain. */@@ -482,6 +483,7 @@ export class PersistenceConsumer {}this.preparing.delete(row.id);preparationActive = false;+ await faultPoint('consumer:prepared', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });const done = await publishMutation(this.engine, row, prepared, this.hostId);if (done.state === 'failed') this.log('publication', done.error_code ?? 'storage_error', done.error_message ?? undefined);if (done.state === 'committed' && row.worktree_id && !String(row.intent?.kind).startsWith('managed_sync_')) {diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 930258c21e..93cc757a01 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -30,6 +30,7 @@ import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, pubimport { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { databaseRefusal, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';+import { faultPoint, withFaultPoints } from './fault-points.ts';interface PreparedMutationBase {sourceExclusive?: boolean;@@ -142,7 +143,8 @@ export function decoratePublicationOutcome(row: WriteRequest, prepared: Prepared* publication. A rejected/ambiguous commit is recovered before releasing FIFO.*/export async function publishMutation(engine: BrainEngine, row: WriteRequest, prepared: PreparedMutation,- hostId = localHostId(), hooks: PublicationHooks = {}): Promise<WriteRequest> {+ hostId = localHostId(), callerHooks: PublicationHooks = {}): Promise<WriteRequest> {+ const hooks = withFaultPoints(callerHooks);let lock: NativeLockHandle | null = null;let releaseCapacity: (() => void) | null = null;let binding: WorktreeBinding | null = null;@@ -423,6 +425,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostIdreturn queued;});if (isTerminal(row) && row.blocked_reason !== 'unexpected_staging_bytes') {+ await faultPoint('publication_recovery:before_clear', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });await clearResolvedRecovery(engine, id);row = (await getWriteRequestById(engine, id))!;}diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex d1bd0bc2f0..d54af074ec 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -13,6 +13,7 @@ import { loadConfig } from '../config.ts';import { resolveDefaultVisibility } from '../facts/visibility.ts';import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { refreshFenceClear } from './worktree-refresh-schema.ts';+import { EFFECT_FAULT_POINTS, faultPoint } from './fault-points.ts';/** `snapshot` is the publication's final read of the page, including deleted rows, in this transaction. */export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequest & Partial<Pick<WriteRequest, 'operation' | 'intent' | 'authority' | 'principal_kind' | 'principal_id'>>, snapshot: PageSnapshot | null,@@ -139,6 +140,7 @@ export async function advanceEffectCursor(engine: SqlEngine, effect: Persistence/** An effect with parked targets finishes as failed (`targets_parked`), never as committed. */export async function completeEffect(engine: SqlEngine, effect: PersistenceEffect, outcome: Record<string, unknown> = {}): Promise<void> {+ await faultPoint(EFFECT_FAULT_POINTS[effect.kind], { effectId: effect.id, requestId: effect.request_id, sourceId: effect.source_id });await engine.executeRaw(`UPDATE persistence_effects SETstate=CASE WHEN jsonb_array_length(COALESCE(data->'parked','[]'::jsonb))>0 THEN 'failed' ELSE 'committed' END,error_code=CASE WHEN jsonb_array_length(COALESCE(data->'parked','[]'::jsonb))>0 THEN 'targets_parked' END,diff --git a/src/core/persistence/effect-recovery.ts b/src/core/persistence/effect-recovery.tsindex fd6740de84..8d8912481b 100644--- a/src/core/persistence/effect-recovery.ts+++ b/src/core/persistence/effect-recovery.ts@@ -18,6 +18,7 @@ import { tryAcquirePublicationCapacity } from './pool-capacity.ts';import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, upgradeRecoveryStaging } from './staging.ts';import { declarePersistenceProtocol } from './protocol.ts';import { advanceEffectCursor } from './effect-journal.ts';+import { faultPoint } from './fault-points.ts';const effectStatusFix = (effect: Pick<PersistenceEffect, 'source_id'>): Action => readFix(`Shows source ${effect.source_id}'s canonical owner with its blocking, retrying and parked effects, read-only.`,@@ -89,6 +90,7 @@ async function clearRecovery(tx: BrainEngine, effect: PersistenceEffect): Promisif (effect.recovery_bytes) for (const key of ['brain', `worktree:${effect.worktree_id}`]) {await tx.executeRaw('UPDATE persistence_counters SET recovery_bytes=recovery_bytes-$2 WHERE key=$1', [key, Number(effect.recovery_bytes)]);}+ await faultPoint('effect_recovery:before_clear', { effectId: effect.id, requestId: effect.request_id, sourceId: effect.source_id });await tx.executeRaw('UPDATE persistence_effects SET recovery=NULL,recovery_bytes=0 WHERE id=$1', [effect.id]);}diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsnew file mode 100644index 0000000000..2ff1f7e8c2--- /dev/null+++ b/src/core/persistence/fault-points.ts@@ -0,0 +1,42 @@+/**+ * Named crash seams for the persistence gate (`scripts/persistence/`). Each+ * seam sits at a point where a process death leaves durable state the+ * recovery path must finish: publication boundaries, after an effect's side+ * effect but before its completion is recorded, before a recovery record is+ * cleared, between sync checkpoints, and after the consumer prepared a+ * claimed request. Production never installs a hook, so every call is a+ * no-op there; the gate's workers install one that SIGKILLs or stalls the+ * process at a chosen point.+ */+import type { EffectKind } from './effect-model.ts';+import type { PublicationHooks } from './coordinator.ts';+import type { WriteRequest } from './model.ts';++export type PublicationBoundary = Parameters<NonNullable<PublicationHooks['boundary']>>[0];+export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid`+ | 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'consumer:prepared';+export interface FaultDetail { requestId?: string; effectId?: string | number; sourceId?: string; operation?: string | null }+type FaultHook = (point: FaultPoint, detail: FaultDetail) => Promise<void> | void;++/** The mid-effect seam of every effect kind; a new kind without one fails typecheck. */+export const EFFECT_FAULT_POINTS: Record<EffectKind, FaultPoint> = {+ git: 'effect:git:mid',+ embedding: 'effect:embedding:mid',+ 'withdrawal-mirror': 'effect:withdrawal-mirror:mid',+ 'facts-backstop': 'effect:facts-backstop:mid',+};++let installed: FaultHook | undefined;+/** Gate workers only. */+export function installFaultHook(hook: FaultHook | undefined): void { installed = hook; }+export async function faultPoint(point: FaultPoint, detail: FaultDetail = {}): Promise<void> {+ if (installed) await installed(point, detail);+}+/** Publication hooks that also reach the installed seam; returns the caller's hooks unchanged when none is installed. */+export function withFaultPoints(hooks: PublicationHooks): PublicationHooks {+ if (!installed) return hooks;+ return { ...hooks, async boundary(name: PublicationBoundary, row: WriteRequest) {+ await hooks.boundary?.(name, row);+ await faultPoint(`publication:${name}`, { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });+ } };+}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex b27ca706ca..e7ce54472b 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -34,6 +34,7 @@ import { admitGroup, freezeFollowers, groupableIntent, nextGroupSize, type BulkSimport { isContentRefusal } from '../import-screen.ts';import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, pinnedBlob, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';+import { faultPoint } from './fault-points.ts';import { addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, readSyncHoldPolicy, recordSyncConversion, recoveredReport, writeGitHold } from './sync-holds.ts';export interface ManagedSyncWriteDiagnostic {@@ -105,7 +106,7 @@ async function readCursor(engine: BrainEngine, key: string, cached?: Cursor): Pr}async function saveCursor(engine: BrainEngine, key: string, before: Cursor | null, next: Cursor, requireIdle = false, assertActive?: () => void,inTx?: (tx: BrainEngine) => Promise<unknown>): Promise<Cursor> {- return engine.transaction(async tx => {+ const saved = await engine.transaction(async tx => {assertActive?.();await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");if (requireIdle) {@@ -121,6 +122,8 @@ async function saveCursor(engine: BrainEngine, key: string, before: Cursor | nulassertActive?.();return current;});+ await faultPoint('sync:mid_checkpoint', { sourceId: next.sourceId });+ return saved;}/** Compare-and-swap inside the caller's transaction; a lost swap returns the cursor that won. */async function writeCursor(tx: BrainEngine, key: string, before: Cursor | null, next: Cursor, inTx?: (tx: BrainEngine) => Promise<unknown>): Promise<Cursor> {diff --git a/test/persistence-crash-robot.test.ts b/test/persistence-crash-robot.test.tsnew file mode 100644index 0000000000..593ef56e5a--- /dev/null+++ b/test/persistence-crash-robot.test.ts@@ -0,0 +1,94 @@+/**+ * The crash robot's in-process contracts (scripts/persistence/ops.ts,+ * generator.ts, model.ts, robot-driver.ts, shrink.ts) and the PGLite release+ *+ *+ * Protects: the op-descriptor protocol refuses malformed descriptors; the five+ * cross-boundary sequences exist and pass the reference model through the real+ * operation handlers; schedules are a function of their seed; shrinking keeps+ * dependencies and accepts only a 3/3 reproduction; a PGLite owner releases a+ * claim last written before it started, and never one written after.+ * Fails when: a descriptor field stops being validated, a sequence family+ * disappears or regresses on master, `restrict` keeps an op whose producer was+ * dropped, or a restarted PGLite owner waits out a dead owner's lease.+ * Seams: none (the fault hook stays uninstalled); PGLite.+ */+import { describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { descriptor, parseDescriptor } from '../scripts/persistence/ops.ts';+import { crossBoundarySequences, randomSchedule } from '../scripts/persistence/generator.ts';+import { ROBOT_TOPOLOGY, restrict } from '../scripts/persistence/robot-driver.ts';+import { shrinkRun } from '../scripts/persistence/shrink.ts';+import { runSchedule } from '../scripts/persistence/crash-robot.ts';+import { prepareTopology } from '../scripts/persistence/history-fixture.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { withEnv } from './helpers/with-env.ts';++async function robotBrain<T>(run: (brain: Awaited<ReturnType<typeof prepareTopology>>) => Promise<T>): Promise<T> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-crash-robot-test-'));+ try {+ return await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine();+ try { return await run(await prepareTopology(engine, { sources: 2, worktrees: 2, root: join(home, 'checkouts'), prefix: 'robot' })); }+ finally { await disposePersistenceConsumer(engine); await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++describe('op-descriptor protocol', () => {+ test('accepts a well-formed descriptor and refuses every malformed field', () => {+ const good = descriptor('op-1', 'put_page', 'local', 'robot-0', { slug: 'notes/a', content: 'x' }, { deps: ['op-0'] });+ expect(parseDescriptor(JSON.parse(JSON.stringify(good)))).toEqual(good);+ for (const bad of [{ ...good, v: 2 }, { ...good, id: '' }, { ...good, kind: 'drop_table' }, { ...good, actor: '' },+ { ...good, requestId: 7 }, { ...good, args: [] }, { ...good, deps: [3] }]) {+ expect(() => parseDescriptor(bad)).toThrow(/op descriptor/);+ }+ });+});++describe('generator', () => {+ test('the five cross-boundary sequences are always generated', () => {+ expect(crossBoundarySequences(ROBOT_TOPOLOGY).map(s => s.label)).toEqual(['withdrawal_then_stale_publication',+ 'overlapping_slugs_two_sources', 'competing_writers_one_page', 'caller_bound_replay', 'authority_change_pending_effects']);+ });+ test('a random schedule is a function of its seed and covers every write op', () => {+ expect(JSON.stringify(randomSchedule(ROBOT_TOPOLOGY, 9))).toBe(JSON.stringify(randomSchedule(ROBOT_TOPOLOGY, 9)));+ expect(JSON.stringify(randomSchedule(ROBOT_TOPOLOGY, 10))).not.toBe(JSON.stringify(randomSchedule(ROBOT_TOPOLOGY, 9)));+ const kinds = new Set(Array.from({ length: 40 }, (_, i) => randomSchedule(ROBOT_TOPOLOGY, i).ops.map(d => d.kind)).flat());+ expect([...kinds].sort()).toEqual(['add_timeline_entry', 'delete_page', 'edit_page', 'forget', 'put_page', 'remember',+ 'restore_page', 'takes_add', 'takes_supersede']);+ });+});++describe('shrinking', () => {+ test('restrict drops an op whose producer was dropped and shrinks groups', () => {+ const schedule = crossBoundarySequences(ROBOT_TOPOLOGY)[2];+ const kept = restrict(schedule, new Set(schedule.ops.filter(d => d.id !== 'cw0').map(d => d.id)));+ expect(kept.ops.map(d => d.id)).toEqual([]);+ const partial = restrict(schedule, new Set(['cw0', 'cw1', 'cw4']));+ expect(partial.ops.map(d => d.id)).toEqual(['cw0', 'cw1', 'cw4']);+ expect(partial.groups).toEqual([]);+ });+ test('ddmin finds the minimal reproducing set and requires 3/3', async () => {+ const failing = { schedule: 'random-1', seed: 1, length: 8, crashed: false, duration_ms: 0,+ ops: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], violations: [{ class: 'lost_write' as const, detail: 'x' }] };+ const result = await shrinkRun(failing, async run => ({ violations: run.ops!.includes('c') && run.ops!.includes('f') ? [{ class: 'lost_write' }] : [] }));+ expect(result.shrunk.ops).toEqual(['c', 'f']);+ expect(result).toMatchObject({ reproduced: 3, accepted: true });+ let calls = 0;+ const flaky = await shrinkRun(failing, async () => ({ violations: ++calls % 2 ? [{ class: 'lost_write' }] : [] }));+ expect(flaky.accepted).toBe(false);+ });+});++describe('reference model on master behavior', () => {+ test('the cross-boundary sequences hold every invariant through the real handlers', async () => {+ for (const schedule of crossBoundarySequences(ROBOT_TOPOLOGY)) {+ const result = await robotBrain(({ world }) => runSchedule(world, schedule));+ expect({ label: schedule.label, violations: result.violations }).toEqual({ label: schedule.label, violations: [] });+ }+ }, 180_000);+});