Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence-gate): agent-envelope check for sync and connector runs; known deferrals

garrytana6e5418444f1
diff --git a/TODOS.md b/TODOS.md
index 17abadfb75..e6c7611cb5 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -6,6 +6,8 @@ Context: `scripts/persistence/README.md` ("Crash robot"), `scripts/persistence/{
- [ ] **P2 — A restarted Postgres owner waits out its dead predecessor's claims.**
**What:** after a Postgres owner process dies, its running effects resume only when their 2-minute lease expires (requests: 30 s), and a withdrawal mirror it held blocks writes to that page until then. PGLite releases them at once (one process per datastore). **Why:** a crashed `gbrain serve` on Postgres stalls Git, embedding and withdrawal work for 2 minutes. **Fix:** record the claiming host and process (pid plus start time) on each claim; a consumer on the same host releases claims whose process has exited. Other hosts keep the lease. The crash robot then drops its 140 s Postgres drain bound to 20 s and pull requests stop skipping lease-bound seams. **Effort:** M. **Priority:** P2.
+- [ ] **P1 — A held sync lock reaches agents as internal_error.**
+ **What:** after an owner dies mid connector run, the source's sync lock row stays until its TTL lapses (a same-host dead holder is stolen after the grace window). Meanwhile a connector run (`LockUnavailableError`) and a sync (`SyncLockBusyError`) reach MCP callers as `internal_error` ("server-side failure, report it"). Crash robot: `sync_and_connector_race_direct_write`, seed 5105, SIGKILL at `publication:after_commit` #31 (Postgres), recorded under the manifest's `deferred`. **Why:** the agent reports a bug instead of waiting and retrying. **Fix:** map both errors to the registered `sync_in_progress` (retryable) with the holder, its age and the retry-after in `why`/`fix` (agent-output rows, GBRA-42's contract), then drop the robot's `KNOWN_DEFERRALS` entry and un-skip the test in `test/persistence-crash-robot.test.ts`. **Effort:** S. **Priority:** P1.
- [ ] **P1 — Process faults: ENOSPC on the file target and a lost child exit.**
**What:** the robot covers SIGKILL at every seam, a stale `index.lock`, a hung git commit and Postgres session drops. **Fix:** an ENOSPC fault on the canonical file write (a tmpfs-sized checkout) and a git child whose exit event is lost; each must end in a terminal state or a typed error. **Effort:** M. **Priority:** P1.
- [ ] **P1 — Seeded mutation pass over the coordinator and effects.**
diff --git a/scripts/persistence/crash-robot.ts b/scripts/persistence/crash-robot.ts
index 6203ac9981..250dda5ad8 100644
--- a/scripts/persistence/crash-robot.ts
+++ b/scripts/persistence/crash-robot.ts
@@ -21,7 +21,7 @@ import postgres from '#postgres';
import { prepareTopology } from './history-fixture.ts';
import { installLockOrderTrace, lockOrderReport } from './lock-order.ts';
import { executeOp, type OpDescriptor, type OpObservation, type World } from './ops.ts';
-import { ReferenceModel, retryingRead, SAFETY_CLASSES, type Violation } from './model.ts';
+import { KNOWN_DEFERRALS, ReferenceModel, retryingRead, SAFETY_CLASSES, type Violation } from './model.ts';
import type { Schedule } from './generator.ts';
import { pageBody } from './generator.ts';
import { descriptor } from './ops.ts';
@@ -135,6 +135,8 @@ export interface RobotOutcome extends Omit<ScheduleResult, 'observations'> {
crashed: boolean; fault?: RobotConfig['fault']; process?: ProcessFault; counts?: Record<string, number>; inFlight?: string[];
/** What each caller observed, kept only for a run with violations. */
trace?: string[];
+ /** Known findings outside the safety classes, filed in TODOS.md: reported, never failing the gate. */
+ deferred?: (Violation & { todo: string })[];
}
function writeState(config: RobotConfig, world: World, model: ReferenceModel, checkouts: string[], next: number, inFlight: string[]): void {
@@ -168,8 +170,12 @@ function finalize(config: RobotConfig, model: ReferenceModel, extra: Partial<Rob
const trace = model.violations.length ? [...model.world.observations.values()].map(o =>
`${o.id} ${o.kind} ${o.actor}@${o.source} ${o.status}${o.code ? `/${o.code}` : ''}${o.values.revision ? ` rev=${o.values.revision}` : ''}`
+ `${o.receipt ? ` receipt=${o.receipt.state}` : ''}${o.status === 'refused' ? ` ${JSON.stringify(o.raw).slice(0, 300)}` : ''}`) : undefined;
+ const deferredOf = (v: Violation) => KNOWN_DEFERRALS.find(k => k.class === v.class && k.match.test(v.detail));
+ const deferred = model.violations.filter(v => deferredOf(v)).map(v => ({ ...v, todo: deferredOf(v)!.todo }));
+ const violations = model.violations.filter(v => !deferredOf(v));
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, ...(trace ? { trace } : {}) };
+ violations, safety: violations.filter(v => SAFETY_CLASSES.has(v.class)), ...extra, ...(trace ? { trace } : {}),
+ ...(deferred.length ? { deferred } : {}) };
}
/**
@@ -360,6 +366,8 @@ export async function robotWorker(role: 'count' | 'run' | 'recover', config: Rob
const observed = await Promise.all(inFlight.map(d => executeOp(world, d)));
model.beginStep(true);
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);
+ // A refused resubmission says nothing about the interrupted attempt, which may have committed.
+ for (let k = 0; k < inFlight.length; k++) if (observed[k].status === 'refused') model.uncertain(inFlight[k]);
await model.settleLate(inFlight, observed);
await model.checkGlobal('after resubmission');
}
diff --git a/scripts/persistence/model.ts b/scripts/persistence/model.ts
index 334fb49f45..492b58a69d 100644
--- a/scripts/persistence/model.ts
+++ b/scripts/persistence/model.ts
@@ -46,6 +46,15 @@ export async function retryingRead<T>(read: () => Promise<T>): Promise<T> {
/** Non-error outcomes a sync or connector run reports as its status (not error codes). */
const EXTERNAL_RESULT_CODES = new Set(['blocked_by_failures', 'dry_run']);
+/**
+ * Findings outside the safety classes, filed in TODOS.md with a skipped test,
+ * stay visible in the manifest (`deferred`) without failing the gate.
+ */
+export const KNOWN_DEFERRALS: { class: ViolationClass; match: RegExp; todo: string }[] = [
+ { class: 'untyped_error', match: /\(internal_error\)[\s\S]*(LockUnavailableError|SyncLockBusyError)/,
+ todo: 'TODOS.md "A held sync lock reaches agents as internal_error"' },
+];
+
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'
| 'untyped_error' | 'lock_order';
@@ -97,6 +106,14 @@ export class ReferenceModel {
m.revoked = new Set(state.revoked); m.violations = state.violations; m.pending = new Map(state.pending ?? []);
return m;
}
+ /** An interrupted op whose outcome is unknown: its marker may legally be visible, in its own source only. */
+ uncertain(d: OpDescriptor): void {
+ const marker = markersIn(JSON.stringify(d.args)).at(-1);
+ if (!marker) return;
+ this.refusedMarkers.delete(marker); this.committedMarkers.set(marker, d.source);
+ const slug = d.kind === 'connector_publish' ? CONNECTOR_SLUG : d.args.slug;
+ if (typeof slug === 'string') this.pages.delete(key(d.source, slug));
+ }
/** 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) {
@@ -136,9 +153,9 @@ export class ReferenceModel {
this.pending.delete(d.id);
if (o.status !== 'committed') {
if (marker && !this.committedMarkers.has(marker)) this.refusedMarkers.add(marker);
- // The agent sees the MCP envelope: its code must be a registered one.
+ // The agent sees the MCP envelope: its code must be a registered one, and not the unknown-failure fallback.
const agentCode = o.agentCode ?? o.code;
- if (o.status === 'refused' && (!agentCode || !isRegistryCode(agentCode)) && !EXTERNAL_RESULT_CODES.has(o.code ?? '')) {
+ if (o.status === 'refused' && agentCode !== 'http:401' && (!agentCode || !isRegistryCode(agentCode) || agentCode === 'internal_error') && !EXTERNAL_RESULT_CODES.has(o.code ?? '')) {
this.violate({ class: 'untyped_error', op: d.id, detail: `${d.kind} failed without a registered agent error code (${agentCode}): ${JSON.stringify(o.raw).slice(0, 300)}` });
}
return;
diff --git a/scripts/persistence/ops.ts b/scripts/persistence/ops.ts
index cc6846a278..39e16596ef 100644
--- a/scripts/persistence/ops.ts
+++ b/scripts/persistence/ops.ts
@@ -273,6 +273,12 @@ function receiptOf(value: Record<string, unknown> | undefined): OpObservation['r
source_id: r.source_id as string | undefined };
}
+/** The code of the agent-contract envelope an MCP caller receives for this failure. */
+function agentEnvelopeCode(error: unknown, op: string): string {
+ return toAgentError(error, { transport: 'http', op, mutating: true, idempotent: true, outcome: 'unknown',
+ render: dispatchRenderContext({ transport: 'http', remote: true } as DispatchOpts) }).code;
+}
+
/** 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 };
@@ -295,7 +301,8 @@ export async function executeOp(world: World, d: OpDescriptor): Promise<OpObserv
...(['synced', 'first_sync', 'up_to_date', 'partial'].includes(status) ? {} : { code: status }), values: {}, raw: jsonSafe({ status, reason: result.reason }) };
} catch (error) {
const e = error as { code?: string; message?: string };
- observation = { ...base, status: 'refused', code: e.code ?? 'uncoded_error', values: {}, raw: { code: e.code, message: e.message?.slice(0, 400) } };
+ observation = { ...base, status: 'refused', code: e.code ?? 'uncoded_error', agentCode: agentEnvelopeCode(error, 'sync_brain'),
+ values: {}, raw: { code: e.code, name: (error as Error).name, message: e.message?.slice(0, 400) } };
}
world.observations.set(d.id, observation);
return observation;
@@ -325,9 +332,9 @@ export async function executeOp(world: World, d: OpDescriptor): Promise<OpObserv
const receipt = receiptOf(e.writeRequest);
// A memory verb reports an accepted, unfinished write as `unavailable` carrying its pending receipt.
const pending = e.code === 'write_pending' || (receipt !== undefined && !['committed', 'failed', 'conflict', 'cancelled'].includes(receipt.state));
- const envelope = toAgentError(error, { transport: 'http', op, mutating: true, idempotent: true, outcome: 'unknown',
- render: dispatchRenderContext({ transport: 'http', remote: true } as DispatchOpts) });
- observation = { ...base, status: pending ? 'pending' : 'refused', code: e.code ?? 'uncoded_error', agentCode: envelope.code,
+ // A token the verifier rejects never reaches an operation: the HTTP transport answers 401 invalid_token.
+ const agentCode = e.name === 'InvalidTokenError' ? 'http:401' : agentEnvelopeCode(error, op);
+ observation = { ...base, status: pending ? 'pending' : 'refused', code: e.code ?? 'uncoded_error', agentCode,
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;
diff --git a/scripts/persistence/robot-driver.ts b/scripts/persistence/robot-driver.ts
index 89608e3bea..23e24e9db8 100644
--- a/scripts/persistence/robot-driver.ts
+++ b/scripts/persistence/robot-driver.ts
@@ -35,6 +35,7 @@ export function leaseBoundSeam(point: FaultPoint): boolean { return point.starts
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; trace?: string[];
+ deferred?: RobotOutcome['deferred'];
}
export interface RobotOptions {
engine: 'pglite' | 'postgres'; seed: number; seconds: number; scratch: string; home: string;
@@ -95,15 +96,15 @@ export async function runRobotPhase(o: RobotOptions) {
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, trace: result.trace, duration_ms: performance.now() - at };
+ return { ...base, crashed: false, violations: result.violations, deferred: result.deferred, trace: result.trace, duration_ms: performance.now() - at };
}
await child.kill();
const recovered = o.spawn(path, o.home, 'robot', ['recover'], environment); o.track(recovered);
const result = (await recovered.done()).result as RobotOutcome;
- return { ...base, crashed: true, violations: result.violations, trace: result.trace, duration_ms: performance.now() - at };
+ return { ...base, crashed: true, violations: result.violations, deferred: result.deferred, trace: result.trace, duration_ms: performance.now() - at };
}
const result = (await child.done()).result as RobotOutcome;
- return { ...base, crashed: false, violations: result.violations, trace: result.trace, counts: result.counts, duration_ms: performance.now() - at };
+ return { ...base, crashed: false, violations: result.violations, deferred: result.deferred, trace: result.trace, counts: result.counts, duration_ms: performance.now() - at };
}
const record = (run: RobotRun) => {
runs.push(run);
@@ -174,7 +175,8 @@ function summarize(runs: RobotRun[], started: number, o: RobotOptions) {
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,
+ violations, deferred: runs.flatMap(r => (r.deferred ?? []).map(v => ({ ...v, schedule: r.schedule, seed: r.seed, fault: r.fault }))),
+ failing_runs: runs.filter(r => r.violations.length), runs,
};
}
diff --git a/test/persistence-crash-robot.test.ts b/test/persistence-crash-robot.test.ts
index 29e9de5cb3..0305a41b2b 100644
--- a/test/persistence-crash-robot.test.ts
+++ b/test/persistence-crash-robot.test.ts
@@ -28,6 +28,9 @@ import { claimPersistenceEffect, releaseAbandonedClaims } from '../src/core/pers
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
import { withEnv } from './helpers/with-env.ts';
+import { toAgentError } from '../src/core/agent-output.ts';
+import { dispatchRenderContext, type DispatchOpts } from '../src/mcp/dispatch.ts';
+import { LockUnavailableError } from '../src/core/db-lock.ts';
async function robotBrain<T>(run: (brain: Awaited<ReturnType<typeof prepareTopology>>) => Promise<T>): Promise<T> {
const home = mkdtempSync(join(tmpdir(), 'gbrain-crash-robot-test-'));
@@ -115,6 +118,13 @@ describe('lock order', () => {
}, 120_000);
});
+// TODOS.md "A held sync lock reaches agents as internal_error": fails until the agent rows map the lock errors.
+test.skip('a held sync lock reaches agents as the retryable sync_in_progress code', () => {
+ const envelope = toAgentError(new LockUnavailableError('gbrain-sync:robot-gh'), { transport: 'http', op: 'sync_brain', mutating: true,
+ idempotent: true, outcome: 'unknown', render: dispatchRenderContext({ transport: 'http', remote: true } as DispatchOpts) });
+ expect(envelope.code).toBe('sync_in_progress');
+});
+
describe('PGLite releases claims a dead owner left behind', () => {
test('a claim written before this owner started is released; a newer one is kept', async () => {
await robotBrain(async ({ world, checkouts }) => {