Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): claim-phase stamps name the preparation step, its wait cause and the owner process (#6278)

garrytanbd8ead4a2c4a
diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.ts
index 76b3dabe67..593bcb492c 100644
--- a/src/core/persistence/claim-phase.ts
+++ b/src/core/persistence/claim-phase.ts
@@ -8,27 +8,84 @@
* the execution token, so a later claim of the same request never reads an
* earlier claim's ages. Recording rides the renewal: no extra statement per write.
*
+ * #6278 adds the step: preparers call `enterClaimStep` at each await
+ * boundary (authority, binding, git, raw hash, origin checks, import screen,
+ * link resolution, adoption reads), which names the step, what the await
+ * waits on (`git`, `fs`, `db`, `pool`; `unknown` when nothing observed it)
+ * and checks the preparation's signal, so cancellation reaches a preparer
+ * between its queries even when the query itself takes no signal. The stamp
+ * also names the owner process (kind, pid, build), so writer status can tell
+ * a sync CLI from a `gbrain serve` without raw SQL. The claim statements
+ * stamp a single claim at claim time and a group stamps each wave's members
+ * at dispatch, so a kill before the first renewal still shows a `preparing`
+ * stamp of the current token (the expired-claim reclaim charges exactly
+ * those, journal.ts).
+ *
* `claimStateOf` reads a request row back. A claim whose renewal cannot reach
* its row (it lapsed while still `running`) is inside a transaction that holds
* the row, or its owner is gone; `publication_started` means files were being
- * published and the recovery path finishes the request.
+ * published and the recovery path finishes the request. `claimStall` is the
+ * running-overdue verdict (`preparation_overdue`) writer status and doctor
+ * attach as `claim.stall`; the terminal give-up is the `preparation_stalled`
+ * receipt, so the two never share a name.
*/
import type { BrainEngine } from '../engine.ts';
+import { VERSION } from '../../version.ts';
export type ClaimPhaseName = 'preparing' | 'publishing';
-export interface ClaimPhaseClock { phase: ClaimPhaseName; claimedAt: number; since: number }
+export const WAITING_ON = ['git', 'fs', 'db', 'pool', 'unknown'] as const;
+export type WaitingOn = typeof WAITING_ON[number];
+export interface ClaimPhaseClock {
+ phase: ClaimPhaseName;
+ claimedAt: number;
+ since: number;
+ /** The preparation step in flight (`enterClaimStep`), null before the first boundary. */
+ step: string | null;
+ stepSince: number;
+ waitingOn: WaitingOn;
+}
+/** The process that holds a claim, as the stamp records it. */
+export interface ClaimOwner { kind: string; pid: number; version: string }
export function startClaimPhase(now = Date.now()): ClaimPhaseClock {
- return { phase: 'preparing', claimedAt: now, since: now };
+ return { phase: 'preparing', claimedAt: now, since: now, step: null, stepSince: now, waitingOn: 'unknown' };
}
export function enterClaimPhase(clock: ClaimPhaseClock, phase: ClaimPhaseName, now = Date.now()): void {
if (clock.phase === phase) return;
clock.phase = phase;
clock.since = now;
+ clock.step = null;
+ clock.stepSince = now;
+ clock.waitingOn = 'unknown';
+}
+/**
+ * A preparer's step boundary: names the step and what its await waits on,
+ * and throws the preparation's abort reason once the budget has cut it off.
+ * `clock` is absent for a preparation outside the consumer (the sync's
+ * waiver and origin checks), which still gets the cancellation check.
+ */
+export function enterClaimStep(clock: ClaimPhaseClock | undefined, step: string, signal?: AbortSignal, waitingOn: WaitingOn = 'unknown', now = Date.now()): void {
+ signal?.throwIfAborted();
+ if (!clock) return;
+ if (clock.step !== step) { clock.step = step; clock.stepSince = now; }
+ clock.waitingOn = waitingOn;
}
-/** The `claim_phase` jsonb a renewal stores for the claim holding `token`. */
-export function claimPhaseStamp(clock: ClaimPhaseClock, token: string | null): string {
- return JSON.stringify({ phase: clock.phase, claimed_at: new Date(clock.claimedAt).toISOString(), since: new Date(clock.since).toISOString(), token });
+
+const OWNER_COMMANDS = new Set(['sync', 'serve', 'jobs', 'autopilot', 'mcp', 'dream', 'cycle', 'sources', 'migrate-graduation', 'put', 'import']);
+let ownerOverride: ClaimOwner | undefined;
+/** The owning process for the stamp: the gbrain command this process runs (`cli` when none is recognisable), its pid and build. */
+export function claimOwner(): ClaimOwner {
+ if (ownerOverride) return ownerOverride;
+ const command = process.argv.slice(2).find(arg => !arg.startsWith('-'));
+ return { kind: command && OWNER_COMMANDS.has(command) ? command : 'cli', pid: process.pid, version: VERSION };
+}
+/** Test seam. */
+export function setClaimOwnerForTest(owner: ClaimOwner | undefined): void { ownerOverride = owner; }
+
+/** The `claim_phase` jsonb a renewal (or a claim, or a group's dispatch mark) stores for the claim holding `token`. */
+export function claimPhaseStamp(clock: ClaimPhaseClock, token: string | null, owner: ClaimOwner = claimOwner()): string {
+ return JSON.stringify({ phase: clock.phase, claimed_at: new Date(clock.claimedAt).toISOString(), since: new Date(clock.since).toISOString(), token,
+ step: clock.step, step_since: new Date(clock.stepSince).toISOString(), waiting_on: clock.waitingOn, owner });
}
/** `persistence.max_claim_ms`: how long a write may hold its claim before doctor reports it as stalled. */
@@ -64,6 +121,13 @@ export interface ClaimState {
phase: ClaimStatePhase;
claim_age_ms: number | null;
phase_age_ms: number | null;
+ /** The preparation step the owner last recorded; null before the first boundary or on a stamp from an older owner. */
+ step: string | null;
+ step_age_ms: number | null;
+ /** What the recorded step waits on; `unknown` when nothing observed it (older stamps included), never inferred. */
+ waiting_on: WaitingOn;
+ /** The process holding the claim, when its stamp recorded one. */
+ owner: ClaimOwner | null;
/** Whether the same request continues without anyone acting (after its lease lapses or its transaction ends). */
resumes_on_its_own: boolean;
why: string;
@@ -81,6 +145,11 @@ const age = (at: unknown, now: number): number | null => {
const ms = typeof at === 'string' || at instanceof Date ? new Date(at).getTime() : NaN;
return Number.isFinite(ms) ? Math.max(0, Math.floor(now - ms)) : null;
};
+function stampOwner(raw: unknown): ClaimOwner | null {
+ const owner = raw && typeof raw === 'object' ? raw as Record<string, unknown> : null;
+ if (!owner || typeof owner.kind !== 'string' || typeof owner.pid !== 'number' || typeof owner.version !== 'string') return null;
+ return { kind: owner.kind, pid: owner.pid, version: owner.version };
+}
export function claimStateOf(row: ClaimRow, now = Date.now()): ClaimState | null {
if (row.state !== 'running') return null;
@@ -88,16 +157,27 @@ export function claimStateOf(row: ClaimRow, now = Date.now()): ClaimState | null
const stamp = raw && typeof raw === 'object' ? raw as Record<string, unknown> : null;
const own = !!stamp && !!row.execution_token && stamp.token === row.execution_token;
const claimAge = own ? age(stamp!.claimed_at, now) : null;
- if (row.publication_started) return { phase: 'file_publication', claim_age_ms: claimAge, phase_age_ms: null, resumes_on_its_own: false,
+ const step = own && typeof stamp!.step === 'string' ? stamp!.step : null;
+ const detail = { step, step_age_ms: step ? age(stamp!.step_since, now) : null,
+ waiting_on: own && (WAITING_ON as readonly unknown[]).includes(stamp!.waiting_on) ? stamp!.waiting_on as WaitingOn : 'unknown' as const,
+ owner: own ? stampOwner(stamp!.owner) : null };
+ if (row.publication_started) return { phase: 'file_publication', claim_age_ms: claimAge, phase_age_ms: null, ...detail, resumes_on_its_own: false,
why: 'Its files were being published; the publication recovery path restores or finishes them when the owning process scans its roots again (after a restart if it hung).' };
- if (row.claim_lapsed) return { phase: 'publication_transaction', claim_age_ms: claimAge, phase_age_ms: null, resumes_on_its_own: true,
+ if (row.claim_lapsed) return { phase: 'publication_transaction', claim_age_ms: claimAge, phase_age_ms: null, ...detail, resumes_on_its_own: true,
why: 'Its claim lapsed while it was still running and nothing was published: a transaction holds the request row (renewals cannot reach it) or its owner is gone. It is requeued once that transaction ends or the owner process exits.' };
- if (!own) return { phase: 'unrecorded', claim_age_ms: null, phase_age_ms: null, resumes_on_its_own: false,
+ if (!own) return { phase: 'unrecorded', claim_age_ms: null, phase_age_ms: null, ...detail, resumes_on_its_own: false,
why: 'The owner has not recorded this claim\'s phase (a claim younger than one renewal, or an owner that predates phase recording).' };
const phase = stamp!.phase === 'publishing' ? 'publishing' : 'preparing';
- return { phase, claim_age_ms: claimAge, phase_age_ms: age(stamp!.since, now), resumes_on_its_own: false,
- why: `Its owner is still renewing the claim while it is ${phase === 'preparing' ? 'preparing the write' : 'publishing the write'}, so the lease never lapses and nothing else on its root runs until that work settles or the owner restarts.` };
+ return { phase, claim_age_ms: claimAge, phase_age_ms: age(stamp!.since, now), ...detail, resumes_on_its_own: false,
+ why: `Its owner is still renewing the claim while it is ${phase === 'preparing' ? 'preparing the write' : 'publishing the write'}${step ? ` (step ${step}, waiting on ${detail.waiting_on})` : ''}, so the lease never lapses and nothing else on its root runs until that work settles or the owner restarts.` };
}
function safeJson(text: string): unknown {
try { return JSON.parse(text); } catch { return null; }
}
+
+/** The running-overdue verdict: a `preparing` claim older than its budget. */
+export interface ClaimStall { reason: 'preparation_overdue'; step: string | null; step_age_ms: number | null; waiting_on: WaitingOn; budget_ms: number }
+export function claimStall(claim: ClaimState | null, budgetMs: number): ClaimStall | null {
+ if (!claim || claim.phase !== 'preparing' || claim.phase_age_ms === null || claim.phase_age_ms < budgetMs) return null;
+ return { reason: 'preparation_overdue', step: claim.step, step_age_ms: claim.step_age_ms, waiting_on: claim.waiting_on, budget_ms: budgetMs };
+}
diff --git a/test/persistence-claim-step.test.ts b/test/persistence-claim-step.test.ts
new file mode 100644
index 0000000000..a6e3ec2263
--- /dev/null
+++ b/test/persistence-claim-step.test.ts
@@ -0,0 +1,93 @@
+/**
+ * #6278: the claim-phase stamp gains the preparation step, what it waits on
+ * and the owner process (claim-phase.ts). Protects: `enterClaimStep` names the
+ * step, keeps the step start across repeated boundaries, resets on a phase
+ * change and throws the preparation's abort reason once cut off (with or
+ * without a clock); `claimStateOf` reads step, step age, waiting_on and owner
+ * only from the current claim's stamp and reads an older owner's stamp as
+ * null/unknown, never inferred; `claimStall` is the `preparation_overdue`
+ * verdict for a preparing claim past its budget and nothing else. Fails when
+ * the stamp drops a field, when an old stamp is misread as a known cause, or
+ * when a publishing or lapsed claim is reported as overdue preparation.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { claimOwner, claimPhaseStamp, claimStall, claimStateOf, enterClaimPhase, enterClaimStep, setClaimOwnerForTest, startClaimPhase } from '../src/core/persistence/claim-phase.ts';
+import { VERSION } from '../src/version.ts';
+
+afterEach(() => setClaimOwnerForTest(undefined));
+
+describe('enterClaimStep', () => {
+ test('names the step and what it waits on, keeps the step start while the step repeats, and the phase change clears it', () => {
+ const clock = startClaimPhase(1_000);
+ expect(clock).toMatchObject({ phase: 'preparing', step: null, waitingOn: 'unknown', stepSince: 1_000 });
+ enterClaimStep(clock, 'authority', undefined, 'db', 1_500);
+ expect(clock).toMatchObject({ step: 'authority', stepSince: 1_500, waitingOn: 'db' });
+ enterClaimStep(clock, 'authority', undefined, 'pool', 2_000);
+ expect(clock).toMatchObject({ step: 'authority', stepSince: 1_500, waitingOn: 'pool' });
+ enterClaimStep(clock, 'git_rev_parse', undefined, 'git', 2_500);
+ expect(clock).toMatchObject({ step: 'git_rev_parse', stepSince: 2_500, waitingOn: 'git' });
+ enterClaimPhase(clock, 'publishing', 3_000);
+ expect(clock).toMatchObject({ phase: 'publishing', since: 3_000, step: null, stepSince: 3_000, waitingOn: 'unknown' });
+ });
+ test('throws the preparation\'s abort reason at the boundary, with or without a clock, and leaves the clock unchanged', () => {
+ const abort = new AbortController();
+ abort.abort({ code: 'preparation_deadline' });
+ const clock = startClaimPhase(1_000);
+ enterClaimStep(clock, 'authority', undefined, 'db', 1_200);
+ expect(() => enterClaimStep(clock, 'binding', abort.signal, 'db', 1_300)).toThrow();
+ try { enterClaimStep(clock, 'binding', abort.signal); } catch (error) { expect(error).toMatchObject({ code: 'preparation_deadline' }); }
+ expect(clock.step).toBe('authority');
+ expect(() => enterClaimStep(undefined, 'origin_check', abort.signal)).toThrow();
+ expect(() => enterClaimStep(undefined, 'origin_check', new AbortController().signal)).not.toThrow();
+ });
+});
+
+describe('claimPhaseStamp and claimStateOf', () => {
+ test('the stamp carries phase, ages, token, step, step start, waiting_on and the owner process', () => {
+ setClaimOwnerForTest({ kind: 'sync', pid: 4242, version: '0.60.200.0' });
+ const clock = startClaimPhase(Date.parse('2026-10-08T03:00:00Z'));
+ enterClaimStep(clock, 'origin_check', undefined, 'db', Date.parse('2026-10-08T03:01:00Z'));
+ expect(JSON.parse(claimPhaseStamp(clock, 'tok-1'))).toEqual({ phase: 'preparing', claimed_at: '2026-10-08T03:00:00.000Z', since: '2026-10-08T03:00:00.000Z', token: 'tok-1',
+ step: 'origin_check', step_since: '2026-10-08T03:01:00.000Z', waiting_on: 'db', owner: { kind: 'sync', pid: 4242, version: '0.60.200.0' } });
+ });
+ test('the default owner is this process: the gbrain command (cli when none), pid and build', () => {
+ const owner = claimOwner();
+ expect(owner).toEqual({ kind: expect.any(String), pid: process.pid, version: VERSION });
+ });
+ test('claimStateOf reads step, step age, waiting_on and owner from the current claim\'s stamp', () => {
+ const now = Date.parse('2026-10-08T03:12:00Z');
+ const stamp = { phase: 'preparing', claimed_at: '2026-10-08T03:00:00Z', since: '2026-10-08T03:00:00Z', token: 't1',
+ step: 'link_resolution', step_since: '2026-10-08T03:02:00Z', waiting_on: 'db', owner: { kind: 'sync', pid: 7, version: '0.60.200.0' } };
+ const state = claimStateOf({ state: 'running', claim_phase: stamp, execution_token: 't1' }, now);
+ expect(state).toMatchObject({ phase: 'preparing', claim_age_ms: 12 * 60_000, phase_age_ms: 12 * 60_000, step: 'link_resolution', step_age_ms: 10 * 60_000,
+ waiting_on: 'db', owner: { kind: 'sync', pid: 7, version: '0.60.200.0' } });
+ expect(state?.why).toContain('step link_resolution, waiting on db');
+ // Another claim's stamp: nothing of it is attributed to the current token.
+ expect(claimStateOf({ state: 'running', claim_phase: stamp, execution_token: 't2' }, now)).toMatchObject({ phase: 'unrecorded', step: null, step_age_ms: null, waiting_on: 'unknown', owner: null });
+ });
+ test('an older owner\'s stamp (no step fields) reads as step null and waiting_on unknown, never inferred', () => {
+ const now = Date.parse('2026-10-08T03:12:00Z');
+ const old = { phase: 'preparing', claimed_at: '2026-10-08T03:00:00Z', since: '2026-10-08T03:00:00Z', token: 't1' };
+ const state = claimStateOf({ state: 'running', claim_phase: JSON.stringify(old), execution_token: 't1' }, now);
+ expect(state).toMatchObject({ phase: 'preparing', step: null, step_age_ms: null, waiting_on: 'unknown', owner: null });
+ const odd = { ...old, step: 'x', step_since: 'not a date', waiting_on: 'lock', owner: { kind: 'sync' } };
+ expect(claimStateOf({ state: 'running', claim_phase: odd, execution_token: 't1' }, now)).toMatchObject({ step: 'x', step_age_ms: null, waiting_on: 'unknown', owner: null });
+ });
+});
+
+describe('claimStall', () => {
+ const now = Date.parse('2026-10-08T03:12:00Z');
+ const preparing = { phase: 'preparing', claimed_at: '2026-10-08T03:00:00Z', since: '2026-10-08T03:00:00Z', token: 't1', step: 'raw_hash', step_since: '2026-10-08T03:05:00Z', waiting_on: 'fs' };
+ test('a preparing claim past its budget is preparation_overdue with the step, its age, waiting_on and the budget', () => {
+ const state = claimStateOf({ state: 'running', claim_phase: preparing, execution_token: 't1' }, now);
+ expect(claimStall(state, 120_000)).toEqual({ reason: 'preparation_overdue', step: 'raw_hash', step_age_ms: 7 * 60_000, waiting_on: 'fs', budget_ms: 120_000 });
+ expect(claimStall(state, 13 * 60_000)).toBeNull();
+ });
+ test('publishing, lapsed, file-publication, unrecorded and non-running claims are never overdue preparation', () => {
+ expect(claimStall(claimStateOf({ state: 'running', claim_phase: { ...preparing, phase: 'publishing' }, execution_token: 't1' }, now), 1)).toBeNull();
+ expect(claimStall(claimStateOf({ state: 'running', claim_phase: preparing, execution_token: 't1', claim_lapsed: true }, now), 1)).toBeNull();
+ expect(claimStall(claimStateOf({ state: 'running', claim_phase: preparing, execution_token: 't1', publication_started: true }, now), 1)).toBeNull();
+ expect(claimStall(claimStateOf({ state: 'running', claim_phase: preparing, execution_token: 'other' }, now), 1)).toBeNull();
+ expect(claimStall(claimStateOf({ state: 'queued', claim_phase: preparing, execution_token: 't1' }, now), 1)).toBeNull();
+ });
+});