Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(fence-repair): attempt claims and memo for paid fence repairs (#6188)

garrytan6f3c7fb4a2d3
diff --git a/src/core/fence-repair/attempts.ts b/src/core/fence-repair/attempts.ts
new file mode 100644
index 0000000000..670c3065a5
--- /dev/null
+++ b/src/core/fence-repair/attempts.ts
@@ -0,0 +1,186 @@
+/**
+ * Attempt claims and the attempt memo for paid (Tier 3) fence repairs.
+ *
+ * One row per repair candidate (source, incarnation, path or slug) in
+ * `op_checkpoints` op `fence-repair-attempt`; `completed_keys[0]` holds the
+ * record. Every change is a compare-and-swap on the record's version `v`, so
+ * two appliers (the maintenance cycle and the CLI) can never both hold a
+ * candidate, and an applier whose claim was taken over cannot publish.
+ *
+ * States: `claimed` → `dispatched` → `settled` → `published` | `rejected`
+ * (gate or unusable answer) | `transient`; a corrective re-ask goes
+ * `settled` → `dispatched` again, at most MAX_DISPATCHES_PER_CLAIM calls per
+ * claim. The memo key is (content sha256, model, fence rules version, prompt
+ * version): a `rejected` or `published` memo is never claimed again until one
+ * of them changes; `transient` (provider unavailable) does not consume it.
+ *
+ * Crash recovery is lease-based: an in-flight claim whose lease expired is
+ * taken over. A stale `claimed` claim spent nothing; a stale `dispatched` or
+ * `settled` claim lost its answer after the money was committed (the daily
+ * ledger settles an expired dispatched reservation at its reserved maximum),
+ * so it counts a crash, and MAX_CRASHES_PER_MEMO crashes reject the memo.
+ *
+ * Records carry location and reason codes only (gate letter, row numbers),
+ * never claim text, holder names or cell values. The 7-day op_checkpoints
+ * purge (`purgeStaleCheckpoints`) does not yet exempt this op; the record
+ * carries `source_id` and `incarnation` so it can join the sync-hold
+ * exemption, which keeps a row while its source incarnation lives.
+ */
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import { sha256, stableJson } from '../persistence/digest.ts';
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+
+export const FENCE_REPAIR_ATTEMPT_OP = 'fence-repair-attempt';
+/** One paid attempt plus at most one corrective re-ask. */
+export const MAX_DISPATCHES_PER_CLAIM = 2;
+export const MAX_CRASHES_PER_MEMO = 2;
+export const DEFAULT_ATTEMPT_LEASE_MS = 10 * 60_000;
+
+export type AttemptState = 'claimed' | 'dispatched' | 'settled' | 'published' | 'rejected' | 'transient';
+const IN_FLIGHT: ReadonlySet<AttemptState> = new Set(['claimed', 'dispatched', 'settled']);
+
+export interface AttemptCandidate { sourceId: string; incarnation: string; key: string }
+export interface AttemptMemoParts { contentSha256: string; model: string; fenceVersion: string | number; promptVersion: string | number }
+
+export interface AttemptRecord {
+ v: number;
+ source_id: string;
+ incarnation: string;
+ candidate: string;
+ memo: string;
+ state: AttemptState;
+ owner: string;
+ lease_until: string;
+ dispatches: number;
+ reservations: string[];
+ crashes: number;
+ reason?: string;
+ gate?: string;
+ rows?: number[];
+ at: string;
+}
+
+export interface AttemptClaim { fingerprint: string; record: AttemptRecord }
+
+export type ClaimResult =
+ | { ok: true; claim: AttemptClaim; recovered?: 'stale_claim' | 'crash_after_dispatch' }
+ | { ok: false; reason: 'claimed_elsewhere' | 'rejected' | 'published'; record: AttemptRecord }
+ | { ok: false; reason: 'store_unavailable' };
+
+export type TransitionResult =
+ | { ok: true; claim: AttemptClaim }
+ | { ok: false; reason: 'lost_claim' | 'dispatch_limit' | 'store_unavailable' };
+
+export interface AttemptStore {
+ claim(candidate: AttemptCandidate, memo: string): Promise<ClaimResult>;
+ dispatched(claim: AttemptClaim, reservationId: string): Promise<TransitionResult>;
+ settled(claim: AttemptClaim): Promise<TransitionResult>;
+ publish(claim: AttemptClaim): Promise<TransitionResult>;
+ reject(claim: AttemptClaim, verdict: { reason: string; gate?: string; rows?: number[] }): Promise<TransitionResult>;
+ transient(claim: AttemptClaim, reason: string): Promise<TransitionResult>;
+ read(candidate: AttemptCandidate): Promise<AttemptRecord | null>;
+}
+
+export function attemptMemoKey(parts: AttemptMemoParts): string {
+ return sha256(stableJson({ content: parts.contentSha256, model: parts.model, fence: String(parts.fenceVersion), prompt: String(parts.promptVersion) }));
+}
+
+export function attemptFingerprint(candidate: AttemptCandidate): string {
+ return sha256(stableJson([candidate.sourceId, candidate.incarnation, candidate.key]));
+}
+
+type ClaimPlan =
+ | { take: true; crashes: number; recovered?: 'stale_claim' | 'crash_after_dispatch' }
+ | { take: false; reason: 'claimed_elsewhere' | 'rejected' | 'published' }
+ | { take: false; reason: 'crash_limit'; crashes: number };
+
+/** What a claim of `memo` may do with the candidate's current record. */
+export function planClaim(current: AttemptRecord | null, memo: string, at: Date): ClaimPlan {
+ if (!current) return { take: true, crashes: 0 };
+ const sameMemo = current.memo === memo;
+ if (IN_FLIGHT.has(current.state)) {
+ if (Date.parse(current.lease_until) > at.getTime()) return { take: false, reason: 'claimed_elsewhere' };
+ const recovered = current.state === 'claimed' ? 'stale_claim' : 'crash_after_dispatch';
+ const crashes = sameMemo ? current.crashes + (recovered === 'crash_after_dispatch' ? 1 : 0) : 0;
+ return crashes >= MAX_CRASHES_PER_MEMO ? { take: false, reason: 'crash_limit', crashes } : { take: true, crashes, recovered };
+ }
+ if (!sameMemo) return { take: true, crashes: 0 };
+ if (current.state === 'published' || current.state === 'rejected') return { take: false, reason: current.state };
+ return { take: true, crashes: current.crashes };
+}
+
+/** The attempt store; `now` and the lease are injectable so tests drive expiry. */
+export function attemptStore(engine: Exec, opts: { now?: () => Date; leaseMs?: number } = {}): AttemptStore {
+ const now = opts.now ?? (() => new Date());
+ const leaseMs = opts.leaseMs ?? DEFAULT_ATTEMPT_LEASE_MS;
+
+ const readRecord = async (fingerprint: string): Promise<AttemptRecord | null> => {
+ const [row] = await engine.executeRaw<{ completed_keys: AttemptRecord[] }>(
+ 'SELECT completed_keys FROM op_checkpoints WHERE op = $1 AND fingerprint = $2', [FENCE_REPAIR_ATTEMPT_OP, fingerprint]);
+ return row?.completed_keys?.[0] ?? null;
+ };
+
+ /** Compare-and-swap: insert when `expected` is null, else replace only the record at version `expected`. */
+ const swap = async (fingerprint: string, expected: number | null, record: AttemptRecord): Promise<boolean> => {
+ const value = JSON.stringify([record]);
+ const rows = expected === null
+ ? await engine.executeRaw(
+ 'INSERT INTO op_checkpoints (op, fingerprint, completed_keys, updated_at) VALUES ($1, $2, $3::text::jsonb, now()) ON CONFLICT (op, fingerprint) DO NOTHING RETURNING 1',
+ [FENCE_REPAIR_ATTEMPT_OP, fingerprint, value])
+ : await engine.executeRaw(
+ "UPDATE op_checkpoints SET completed_keys = $3::text::jsonb, updated_at = now() WHERE op = $1 AND fingerprint = $2 AND (completed_keys->0->>'v')::int = $4 RETURNING 1",
+ [FENCE_REPAIR_ATTEMPT_OP, fingerprint, value, expected]);
+ return rows.length === 1;
+ };
+
+ const stamp = (at: Date) => ({ at: at.toISOString(), lease_until: new Date(at.getTime() + leaseMs).toISOString() });
+
+ const claim = async (candidate: AttemptCandidate, memo: string): Promise<ClaimResult> => {
+ const fingerprint = attemptFingerprint(candidate);
+ const at = now();
+ try {
+ const current = await readRecord(fingerprint);
+ const plan = planClaim(current, memo, at);
+ if (!plan.take && plan.reason === 'crash_limit') {
+ const rejected: AttemptRecord = { ...current!, v: current!.v + 1, state: 'rejected', reason: 'crash_limit', crashes: plan.crashes, ...stamp(at) };
+ if (!await swap(fingerprint, current!.v, rejected)) return { ok: false, reason: 'claimed_elsewhere', record: (await readRecord(fingerprint)) ?? current! };
+ return { ok: false, reason: 'rejected', record: rejected };
+ }
+ if (!plan.take) return { ok: false, reason: plan.reason, record: current! };
+ const record: AttemptRecord = { v: (current?.v ?? 0) + 1, source_id: candidate.sourceId, incarnation: candidate.incarnation, candidate: candidate.key,
+ memo, state: 'claimed', owner: randomUUID(), dispatches: 0, reservations: [], crashes: plan.crashes, ...stamp(at) };
+ if (!await swap(fingerprint, current?.v ?? null, record)) {
+ const winner = await readRecord(fingerprint);
+ return winner ? { ok: false, reason: 'claimed_elsewhere', record: winner } : { ok: false, reason: 'store_unavailable' };
+ }
+ return { ok: true, claim: { fingerprint, record }, ...(plan.recovered ? { recovered: plan.recovered } : {}) };
+ } catch {
+ return { ok: false, reason: 'store_unavailable' };
+ }
+ };
+
+ const transition = async (held: AttemptClaim, from: readonly AttemptState[], change: Partial<AttemptRecord> & { state: AttemptState }): Promise<TransitionResult> => {
+ if (!from.includes(held.record.state)) throw new Error(`fence repair attempt cannot move from ${held.record.state} to ${change.state}`);
+ const record: AttemptRecord = { ...held.record, ...change, v: held.record.v + 1, ...stamp(now()) };
+ try {
+ return await swap(held.fingerprint, held.record.v, record) ? { ok: true, claim: { fingerprint: held.fingerprint, record } } : { ok: false, reason: 'lost_claim' };
+ } catch {
+ return { ok: false, reason: 'store_unavailable' };
+ }
+ };
+
+ return {
+ claim,
+ dispatched: async (held, reservationId) => held.record.dispatches >= MAX_DISPATCHES_PER_CLAIM
+ ? { ok: false, reason: 'dispatch_limit' }
+ : transition(held, ['claimed', 'settled'], { state: 'dispatched', dispatches: held.record.dispatches + 1, reservations: [...held.record.reservations, reservationId] }),
+ settled: held => transition(held, ['dispatched'], { state: 'settled' }),
+ publish: held => transition(held, ['settled'], { state: 'published' }),
+ reject: (held, verdict) => transition(held, ['settled'], { state: 'rejected', reason: verdict.reason,
+ ...(verdict.gate ? { gate: verdict.gate } : {}), ...(verdict.rows ? { rows: [...verdict.rows] } : {}) }),
+ transient: (held, reason) => transition(held, ['claimed', 'dispatched', 'settled'], { state: 'transient', reason }),
+ read: candidate => readRecord(attemptFingerprint(candidate)),
+ };
+}
diff --git a/test/e2e/fence-repair-attempts-postgres.test.ts b/test/e2e/fence-repair-attempts-postgres.test.ts
new file mode 100644
index 0000000000..7e0e375be6
--- /dev/null
+++ b/test/e2e/fence-repair-attempts-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../fence-repair-attempts.test.ts'));
diff --git a/test/fence-repair-attempts.test.ts b/test/fence-repair-attempts.test.ts
new file mode 100644
index 0000000000..14a3b8bbe3
--- /dev/null
+++ b/test/fence-repair-attempts.test.ts
@@ -0,0 +1,183 @@
+/**
+ * #6188 attempt claims and memo for paid fence repairs
+ * (`src/core/fence-repair/attempts.ts`).
+ *
+ * Protects: two appliers (cycle and CLI) never both attempt one candidate; a
+ * rejected memo (content sha256, model, rules version, prompt version) spends
+ * nothing again until one part changes; a transient provider failure does not
+ * consume it; a crash before dispatch is taken over for free, a crash after
+ * dispatch is charged its reserved maximum by the ledger and counts against
+ * the memo; an applier whose claim was taken over cannot publish; at most one
+ * paid attempt plus one re-ask per claim.
+ * Fails when: the claim is a read-then-write without a version check, a
+ * rejected memo is claimable, transient consumes the memo, or a stale claim
+ * blocks the candidate forever.
+ * Seams: an injected clock; PGLite always, Postgres through
+ * test/e2e/fence-repair-attempts-postgres.test.ts (separate sessions for the
+ * concurrent claim).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import {
+ FENCE_REPAIR_ATTEMPT_OP, attemptFingerprint, attemptMemoKey, attemptStore,
+ type AttemptCandidate, type AttemptClaim, type ClaimResult, type TransitionResult,
+} from '../src/core/fence-repair/attempts.ts';
+import { dailyLedger } from '../src/core/budget/daily-ledger.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const LEASE_MS = 60_000;
+
+function clock(iso: string) {
+ let t = Date.parse(iso);
+ return { now: () => new Date(t), advance: (ms: number) => { t += ms; } };
+}
+const candidate = (): AttemptCandidate => ({ sourceId: 'notes-example', incarnation: randomUUID(), key: `path:people/alice-example-${randomUUID()}.md` });
+const memo = (content: string, model = 'anthropic:claude-sonnet-5-5') => attemptMemoKey({ contentSha256: content, model, fenceVersion: 1, promptVersion: 1 });
+const held = (r: ClaimResult | TransitionResult): AttemptClaim => { if (!r.ok) throw new Error(`expected a claim, got ${r.reason}`); return r.claim; };
+
+for (const backend of backends) {
+ describe(`${backend}: fence repair attempts`, () => {
+ let engine: BrainEngine;
+ let sessions: BrainEngine[] = [];
+ let close: () => Promise<void> = async () => {};
+
+ beforeAll(async () => {
+ if (backend === 'pglite') {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ sessions = [pglite];
+ close = () => pglite.disconnect();
+ return;
+ }
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = pg.engine;
+ const extra = await Promise.all(Array.from({ length: 4 }, async () => {
+ const session = new PostgresEngine();
+ await session.connect({ database_url: pg.databaseUrl, poolSize: 2 });
+ return session;
+ }));
+ sessions = [pg.engine, ...extra];
+ close = async () => { for (const session of extra) await session.disconnect(); await pg.close(); };
+ }, 120_000);
+
+ afterAll(async () => { await close(); });
+
+ test('one applier holds a candidate: a second claim is refused, and concurrent claims admit exactly one', async () => {
+ const c = clock('2026-10-06T12:00:00Z');
+ const store = attemptStore(engine, { ...c, leaseMs: LEASE_MS });
+ const target = candidate();
+ const first = await store.claim(target, memo('a'));
+ expect(first).toMatchObject({ ok: true, claim: { record: { state: 'claimed', crashes: 0, dispatches: 0 } } });
+ expect(await store.claim(target, memo('a'))).toMatchObject({ ok: false, reason: 'claimed_elsewhere' });
+ expect(await store.claim(target, memo('b'))).toMatchObject({ ok: false, reason: 'claimed_elsewhere' });
+
+ const contested = candidate();
+ const stores = sessions.map(session => attemptStore(session, { ...c, leaseMs: LEASE_MS }));
+ const claims = await Promise.all(Array.from({ length: 20 }, (_, i) => stores[i % stores.length]!.claim(contested, memo('c'))));
+ expect(claims.filter(r => r.ok)).toHaveLength(1);
+ expect(claims.filter(r => !r.ok).every(r => !r.ok && r.reason === 'claimed_elsewhere')).toBe(true);
+ }, 60_000);
+
+ test('a rejected memo is not claimed again until the content, model, rules or prompt version changes', async () => {
+ const store = attemptStore(engine, { ...clock('2026-10-06T12:00:00Z'), leaseMs: LEASE_MS });
+ const target = candidate();
+ let claim = held(await store.claim(target, memo('a')));
+ claim = held(await store.dispatched(claim, randomUUID()));
+ claim = held(await store.settled(claim));
+ expect(held(await store.reject(claim, { reason: 'claim_changed', gate: 'b', rows: [3, 7] })).record).toMatchObject({ state: 'rejected', gate: 'b', rows: [3, 7] });
+ expect(await store.claim(target, memo('a'))).toMatchObject({ ok: false, reason: 'rejected', record: { reason: 'claim_changed', gate: 'b', rows: [3, 7] } });
+ for (const changed of [memo('a', 'openai:gpt-6-sol'), memo('a-edited'),
+ attemptMemoKey({ contentSha256: 'a', model: 'anthropic:claude-sonnet-5-5', fenceVersion: 2, promptVersion: 1 }),
+ attemptMemoKey({ contentSha256: 'a', model: 'anthropic:claude-sonnet-5-5', fenceVersion: 1, promptVersion: 2 })]) {
+ expect(changed).not.toBe(memo('a'));
+ }
+ expect(await store.claim(target, memo('a', 'openai:gpt-6-sol'))).toMatchObject({ ok: true, claim: { record: { state: 'claimed', crashes: 0 } } });
+ // The purge exemption the integration lane adds keys on these two fields.
+ const [row] = await engine.executeRaw<{ source_id: string; incarnation: string }>(
+ "SELECT completed_keys->0->>'source_id' AS source_id, completed_keys->0->>'incarnation' AS incarnation FROM op_checkpoints WHERE op = $1 AND fingerprint = $2",
+ [FENCE_REPAIR_ATTEMPT_OP, attemptFingerprint(target)]);
+ expect(row).toEqual({ source_id: target.sourceId, incarnation: target.incarnation });
+ });
+
+ test('a transient provider failure does not consume the memo; a published memo is done', async () => {
+ const store = attemptStore(engine, { ...clock('2026-10-06T12:00:00Z'), leaseMs: LEASE_MS });
+ const target = candidate();
+ let claim = held(await store.claim(target, memo('a')));
+ claim = held(await store.dispatched(claim, randomUUID()));
+ expect(held(await store.transient(claim, 'llm_unavailable')).record).toMatchObject({ state: 'transient', reason: 'llm_unavailable' });
+ claim = held(await store.claim(target, memo('a')));
+ claim = held(await store.dispatched(claim, randomUUID()));
+ claim = held(await store.settled(claim));
+ await store.publish(claim);
+ expect(await store.claim(target, memo('a'))).toMatchObject({ ok: false, reason: 'published' });
+ expect(await store.read(target)).toMatchObject({ state: 'published', memo: memo('a') });
+ });
+
+ test('a claim makes at most one paid attempt plus one corrective re-ask', async () => {
+ const store = attemptStore(engine, { ...clock('2026-10-06T12:00:00Z'), leaseMs: LEASE_MS });
+ let claim = held(await store.claim(candidate(), memo('a')));
+ claim = held(await store.settled(held(await store.dispatched(claim, randomUUID()))));
+ claim = held(await store.settled(held(await store.dispatched(claim, randomUUID()))));
+ expect(claim.record.dispatches).toBe(2);
+ expect(await store.dispatched(claim, randomUUID())).toEqual({ ok: false, reason: 'dispatch_limit' });
+ const fresh = held(await store.claim(candidate(), memo('b')));
+ await expect(store.publish(fresh)).rejects.toThrow('cannot move from claimed to published');
+ });
+
+ test('an expired undispatched claim is taken over for free, and the old holder can no longer publish', async () => {
+ const c = clock('2026-10-06T12:00:00Z');
+ const store = attemptStore(engine, { ...c, leaseMs: LEASE_MS });
+ const target = candidate();
+ const stale = held(await store.claim(target, memo('a')));
+ c.advance(LEASE_MS - 1);
+ expect(await store.claim(target, memo('a'))).toMatchObject({ ok: false, reason: 'claimed_elsewhere' });
+ c.advance(2);
+ const taken = await store.claim(target, memo('a'));
+ expect(taken).toMatchObject({ ok: true, recovered: 'stale_claim', claim: { record: { crashes: 0 } } });
+ expect(held(taken).record.owner).not.toBe(stale.record.owner);
+ expect(await store.dispatched(stale, randomUUID())).toEqual({ ok: false, reason: 'lost_claim' });
+ expect(await store.transient(stale, 'llm_unavailable')).toEqual({ ok: false, reason: 'lost_claim' });
+ });
+
+ test('a crash after dispatch is charged its reserved maximum and counts against the memo; two crashes reject it', async () => {
+ const c = clock('2026-10-06T12:00:00Z');
+ const store = attemptStore(engine, { ...c, leaseMs: LEASE_MS });
+ const ledger = dailyLedger(engine, { scope: 'llm_repair', resolver: `test-${randomUUID()}` }, c);
+ const target = candidate();
+ const crashAfterDispatch = async (claim: AttemptClaim) => {
+ const reserved = await ledger.reserve(0.02, { capUsd: 1, ttlMs: LEASE_MS });
+ if (!reserved.ok) throw new Error(reserved.reason);
+ held(await store.dispatched(claim, reserved.reservation.id));
+ expect(await ledger.dispatch(reserved.reservation.id)).toBe(true);
+ c.advance(LEASE_MS + 1);
+ };
+ await crashAfterDispatch(held(await store.claim(target, memo('a'))));
+ const recovered = await store.claim(target, memo('a'));
+ expect(recovered).toMatchObject({ ok: true, recovered: 'crash_after_dispatch', claim: { record: { crashes: 1, dispatches: 0 } } });
+ expect(await ledger.reclaimExpired()).toEqual({ released: 0, settledUncertain: 1 });
+ expect(await ledger.readDay()).toMatchObject({ reservedUsd: 0, committedUsd: 0.02 });
+
+ // A crash after the call settled loses the answer too.
+ const again = held(await store.dispatched(held(recovered), randomUUID()));
+ held(await store.settled(again));
+ c.advance(LEASE_MS + 1);
+ expect(await store.claim(target, memo('a'))).toMatchObject({ ok: false, reason: 'rejected', record: { state: 'rejected', reason: 'crash_limit', crashes: 2 } });
+ expect(await store.claim(target, memo('a-edited'))).toMatchObject({ ok: true, claim: { record: { crashes: 0 } } });
+ });
+ });
+}
+
+if (backends.includes('pglite')) {
+ test('a store error means no claim', async () => {
+ const broken = { executeRaw: async () => { throw new Error('connection refused'); } } as unknown as BrainEngine;
+ const store = attemptStore(broken);
+ expect(await store.claim(candidate(), memo('a'))).toEqual({ ok: false, reason: 'store_unavailable' });
+ });
+}