Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

autopilot --status: grade from the daemon's own next tick (#7003)

garrytan5df6847cd1f9
diff --git a/src/commands/autopilot-daemon.ts b/src/commands/autopilot-daemon.ts
index 97d58d7883..459cd5d2f4 100644
--- a/src/commands/autopilot-daemon.ts
+++ b/src/commands/autopilot-daemon.ts
@@ -13,6 +13,7 @@ import { join } from 'path';
import { loadPreferences } from '../core/preferences.ts';
import { registerCleanup } from '../core/process-cleanup.ts';
import { dispatchAutopilotTick, sleepWatchingHeads } from './autopilot-dispatch.ts';
+import { writeAutopilotHeartbeat } from '../core/autopilot-heartbeat.ts';
import { runNightlyQualityProbeStep, runParserProbeStep } from './autopilot-probes.ts';
import { resolveChildCliInvocation } from '../core/minions/job-isolation.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
@@ -238,6 +239,7 @@ export async function runAutopilotDaemon(engine: BrainEngine, args: string[]): P
// Refresh the lock mtime so another cron-fired autopilot doesn't
// declare the instance stale after 10 minutes (Codex C).
try { utimesSync(lockPath, new Date(), new Date()); } catch { /* best-effort */ }
+ writeAutopilotHeartbeat({ phase: 'cycle', interval_s: null, base_interval_s: baseInterval, next_tick_at: null });
if (processingState && !processingState.snapshot.processing_ready) {
await new Promise(r => setTimeout(r, 250));
@@ -341,7 +343,8 @@ export async function runAutopilotDaemon(engine: BrainEngine, args: string[]): P
await runNightlyQualityProbeStep(engine, cfg);
await runParserProbeStep(engine, cfg);
- // Wait for next cycle (HEAD-driven between ticks when sync.on_commit is on).
+ // Wait for next cycle; #7003: --status grades staleness from this daemon's own next tick.
+ writeAutopilotHeartbeat({ phase: 'sleep', interval_s: interval, base_interval_s: baseInterval, next_tick_at: new Date(Date.now() + interval * 1000).toISOString() });
if (useMinionsDispatch) await sleepWatchingHeads(engine, state, { sleepMs: interval * 1000, baseInterval, jsonMode });
else await new Promise(r => setTimeout(r, interval * 1000));
}
diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.ts
index 171be05589..d085a57c80 100644
--- a/src/commands/autopilot.ts
+++ b/src/commands/autopilot.ts
@@ -20,6 +20,7 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, unlinkSync, chmodSync, statSync } from 'fs';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { readGlobalMaintenanceVerdict } from '../core/minions/global-maintenance-stall.ts';
+import { daemonStaleAfterSeconds, readAutopilotHeartbeat } from '../core/autopilot-heartbeat.ts';
import { detectExecutionEnvironment } from '../core/execution-env.ts';
import { join, dirname, isAbsolute, resolve as resolvePath } from 'path';
import { execSync } from '../core/spawn.ts';
@@ -1482,6 +1483,10 @@ export interface AutopilotStatusReport {
paused_reason: string | null;
heartbeat_age_seconds: number | null;
stale_after_seconds: number;
+ /** #7003: `daemon` when the threshold comes from the running daemon's heartbeat sidecar, `flag` when from --interval. */
+ stale_after_source: 'daemon' | 'flag';
+ /** #7003: the daemon's own next tick (its adaptive interval), when its sidecar says it is sleeping. */
+ next_tick_at: string | null;
last_log: string;
}
@@ -1505,10 +1510,11 @@ export function autopilotStatusExitCode(state: AutopilotState, globalMaintenance
* Pure classifier so the tri-state is testable without an installed daemon.
*
* The heartbeat is the lock mtime, which the tick loop already refreshes every
- * pass (`utimesSync(lockPath, ...)`). Deliberately NOT a new artifact: a second
- * one could disagree with the first, and a daemon still running a pre-upgrade
- * binary would never write it, so a healthy install would report stale until it
- * happened to relaunch.
+ * pass (`utimesSync(lockPath, ...)`). #7003: the threshold comes from the
+ * daemon's own heartbeat sidecar when one matches the lock (its next tick, so an
+ * adaptive 2x sleep is not stale); a missing, foreign or older sidecar (a daemon
+ * still on a pre-#7003 binary) falls back to the flag rule below, so liveness
+ * never depends on the sidecar existing.
*/
export function classifyAutopilotStatus(input: {
installed: boolean;
@@ -1517,6 +1523,8 @@ export function classifyAutopilotStatus(input: {
pausedReason?: string | null;
heartbeatAgeSeconds: number | null;
intervalSeconds: number;
+ /** #7003: the running daemon's own threshold (autopilot-heartbeat.ts daemonStaleAfterSeconds); wins over intervalSeconds. */
+ daemon?: { staleAfter: number; nextTickAt: string | null } | null;
lastLog: string;
}): AutopilotStatusReport {
// Tolerance = 6 intervals. The adaptive scheduler sleeps TWO intervals
@@ -1528,7 +1536,9 @@ export function classifyAutopilotStatus(input: {
// non-positive interval (a typo'd flag upstream) would make staleAfter NaN
// and every age comparison false — reading a long-dead daemon as 'fresh' —
// so the pure layer defends itself too.
- const staleAfter = Number.isFinite(input.intervalSeconds) && input.intervalSeconds > 0
+ const daemon = input.daemon && Number.isFinite(input.daemon.staleAfter) && input.daemon.staleAfter > 0 ? input.daemon : null;
+ const staleAfter = daemon ? daemon.staleAfter
+ : Number.isFinite(input.intervalSeconds) && input.intervalSeconds > 0
? input.intervalSeconds * 6
: 1800;
const pausedReason = input.pausedReason ?? null;
@@ -1552,6 +1562,8 @@ export function classifyAutopilotStatus(input: {
paused_reason: pausedReason,
heartbeat_age_seconds: input.heartbeatAgeSeconds,
stale_after_seconds: staleAfter,
+ stale_after_source: daemon ? 'daemon' : 'flag',
+ next_tick_at: daemon?.nextTickAt ?? null,
last_log: input.lastLog,
};
}
@@ -1578,9 +1590,13 @@ function showStatus(json: boolean, intervalSeconds: number) {
const pausedReason = autopilotPauseReason();
let heartbeatAgeSeconds: number | null = null;
+ let lock: { mtimeMs: number; pid: number | null } | null = null;
try {
const { mtimeMs } = statSync(autopilotLockPath());
heartbeatAgeSeconds = Math.max(0, Math.floor((Date.now() - mtimeMs) / 1000));
+ let pid: number | null = null;
+ try { const n = parseInt(readFileSync(autopilotLockPath(), 'utf-8').trim(), 10); pid = Number.isFinite(n) ? n : null; } catch { /* unreadable: pid unknown */ }
+ lock = { mtimeMs, pid };
} catch { /* never ran, or already cleaned up */ }
const jobStatus = autopilotJobStatus(job);
@@ -1592,6 +1608,7 @@ function showStatus(json: boolean, intervalSeconds: number) {
pausedReason,
heartbeatAgeSeconds,
intervalSeconds,
+ daemon: daemonStaleAfterSeconds(readAutopilotHeartbeat(), lock),
lastLog: lastLine,
});
const processing = readAutopilotProcessingStatus();
diff --git a/src/core/autopilot-heartbeat.ts b/src/core/autopilot-heartbeat.ts
new file mode 100644
index 0000000000..21ff5e8432
--- /dev/null
+++ b/src/core/autopilot-heartbeat.ts
@@ -0,0 +1,66 @@
+/**
+ * #7003: the autopilot daemon's heartbeat sidecar, and how `gbrain autopilot --status` grades staleness from it.
+ *
+ * The lock file's mtime stays the liveness signal (refreshed at the top of every tick). Before this, `--status`
+ * judged it against 6 x the status caller's `--interval` flag (default 300 s), but the daemon sleeps an adaptive
+ * interval (2 x its own `--interval` on a brain scoring 90 or more), so a healthy daemon started with
+ * `--interval 1500` read stale on every long sleep. The daemon now writes this sidecar at the top of each tick
+ * (phase `cycle`) and before each sleep (phase `sleep`, with `next_tick_at`). Grading:
+ * - phase sleep: stale once the lock is older than (next_tick_at - lock mtime) + a grace of max(base interval, 120 s),
+ * the time the next tick has to refresh the lock;
+ * - phase cycle: stale after 6 x the daemon's own base interval (a cycle in progress has no next tick yet);
+ * - no sidecar, one written by another pid than the lock holder, or one older than the lock (a daemon binary that
+ * does not write it): the caller's flag, as before.
+ */
+import { readFileSync, renameSync, writeFileSync } from 'fs';
+import { autopilotHeartbeatPath } from './autopilot-paths.ts';
+
+export interface AutopilotHeartbeat {
+ pid: number;
+ written_at: string;
+ phase: 'cycle' | 'sleep';
+ /** The sleep the daemon chose after its last cycle (adaptive), null during a cycle. */
+ interval_s: number | null;
+ base_interval_s: number;
+ next_tick_at: string | null;
+}
+
+/** Best-effort: a heartbeat that cannot be written leaves --status on the flag fallback. */
+export function writeAutopilotHeartbeat(fields: Omit<AutopilotHeartbeat, 'pid' | 'written_at'>, path = autopilotHeartbeatPath(), now = new Date()): void {
+ try {
+ const body: AutopilotHeartbeat = { pid: process.pid, written_at: now.toISOString(), ...fields };
+ const tmp = `${path}.${process.pid}.tmp`;
+ writeFileSync(tmp, JSON.stringify(body) + '\n');
+ renameSync(tmp, path);
+ } catch { /* status falls back to the flag */ }
+}
+
+export function readAutopilotHeartbeat(path = autopilotHeartbeatPath()): AutopilotHeartbeat | null {
+ try {
+ const raw = JSON.parse(readFileSync(path, 'utf-8')) as Partial<AutopilotHeartbeat>;
+ if (typeof raw.pid !== 'number' || typeof raw.written_at !== 'string' || (raw.phase !== 'cycle' && raw.phase !== 'sleep')
+ || typeof raw.base_interval_s !== 'number') return null;
+ return { pid: raw.pid, written_at: raw.written_at, phase: raw.phase, interval_s: typeof raw.interval_s === 'number' ? raw.interval_s : null,
+ base_interval_s: raw.base_interval_s, next_tick_at: typeof raw.next_tick_at === 'string' ? raw.next_tick_at : null };
+ } catch { return null; }
+}
+
+/** Tolerance for the clock gap between the lock refresh and the sidecar write at the top of a tick. */
+const WRITE_SKEW_MS = 5_000;
+
+/**
+ * The daemon's own staleness threshold in seconds of lock age, or null when the sidecar is absent, foreign or stale
+ * (the caller then uses its flag).
+ */
+export function daemonStaleAfterSeconds(heartbeat: AutopilotHeartbeat | null, lock: { mtimeMs: number; pid: number | null } | null): { staleAfter: number; nextTickAt: string | null } | null {
+ if (!heartbeat || !lock) return null;
+ if (lock.pid !== null && heartbeat.pid !== lock.pid) return null;
+ const writtenMs = Date.parse(heartbeat.written_at);
+ if (!Number.isFinite(writtenMs) || writtenMs < lock.mtimeMs - WRITE_SKEW_MS) return null;
+ const base = Number.isFinite(heartbeat.base_interval_s) && heartbeat.base_interval_s > 0 ? heartbeat.base_interval_s : null;
+ if (base === null) return null;
+ if (heartbeat.phase === 'cycle') return { staleAfter: base * 6, nextTickAt: null };
+ const nextMs = heartbeat.next_tick_at ? Date.parse(heartbeat.next_tick_at) : NaN;
+ if (!Number.isFinite(nextMs)) return null;
+ return { staleAfter: Math.max(0, Math.ceil((nextMs - lock.mtimeMs) / 1000)) + Math.max(base, 120), nextTickAt: heartbeat.next_tick_at };
+}
diff --git a/src/core/autopilot-paths.ts b/src/core/autopilot-paths.ts
index ce1b8d04d5..052865dfcc 100644
--- a/src/core/autopilot-paths.ts
+++ b/src/core/autopilot-paths.ts
@@ -35,6 +35,15 @@ export function autopilotLockPath(): string {
return gbrainPath('autopilot.lock');
}
+/**
+ * #7003: the daemon's heartbeat sidecar beside the lock. It records the daemon's own next tick (its adaptive interval),
+ * so `--status` grades staleness from what the daemon scheduled rather than the caller's `--interval`
+ * (src/core/autopilot-heartbeat.ts). The lock mtime stays the liveness signal.
+ */
+export function autopilotHeartbeatPath(): string {
+ return gbrainPath('autopilot.heartbeat.json');
+}
+
/**
* Written by the generated wrapper when it self-disables (its captured repo path
* is gone). Read by the status command so a stopped daemon explains itself
diff --git a/test/e2e/s-7003-autopilot-heartbeat-postgres.test.ts b/test/e2e/s-7003-autopilot-heartbeat-postgres.test.ts
new file mode 100644
index 0000000000..3d36846703
--- /dev/null
+++ b/test/e2e/s-7003-autopilot-heartbeat-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../pathological/s-7003-autopilot-heartbeat.test.ts'));
diff --git a/test/pathological/s-7003-autopilot-heartbeat.test.ts b/test/pathological/s-7003-autopilot-heartbeat.test.ts
new file mode 100644
index 0000000000..e9f8d06c8a
--- /dev/null
+++ b/test/pathological/s-7003-autopilot-heartbeat.test.ts
@@ -0,0 +1,121 @@
+/**
+ * #7003 (GBRA-133 PR 2a.4): `gbrain autopilot --status` graded the daemon's heartbeat (the lock mtime) against
+ * 6 x the STATUS caller's `--interval` (default 300 s), but the daemon sleeps its own adaptive interval (2 x its
+ * `--interval` on a brain scoring 90 or more), so a healthy daemon started with `--interval 1500` read
+ * "NOT ticking" and exited 1 on every long sleep.
+ *
+ * Protects: the daemon writes a heartbeat sidecar with its own next tick; --status grades from it (stale only once the
+ * lock is older than the next tick plus a grace of its base interval), and falls back to the flag rule when the sidecar
+ * is absent, written by another pid, or older than the lock (a daemon on an older binary). The issue's case: daemon
+ * --interval 1500 at score >= 90 sleeping 3000 s, heartbeat 2700 s old -> fresh; older than 3000 s + its budget -> stale.
+ * Fails when: --status ignores the daemon's schedule, trusts a foreign or outdated sidecar, or the daemon writes none.
+ * Real daemon processes for the write side (PGLite inline; Postgres dispatch with --no-worker).
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, existsSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { classifyAutopilotStatus } from '../../src/commands/autopilot.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { pathologicalArms } from './harness.ts';
+
+const CLI = resolve(import.meta.dir, '../../src/cli.ts');
+const heartbeatModule = () => import('../../src/core/autopilot-heartbeat.ts');
+const T0 = Date.parse('2026-10-18T12:00:00.000Z');
+const iso = (ms: number) => new Date(ms).toISOString();
+
+/** The --status verdict for a lock refreshed at T0 (the top of the last tick) and seen ageSeconds later. */
+async function grade(ageSeconds: number, sidecar: Record<string, unknown> | null, lockPid: number | null = 4242) {
+ const { daemonStaleAfterSeconds } = await heartbeatModule();
+ return classifyAutopilotStatus({
+ installed: true, installTarget: 'linux-systemd' as never, disabledReason: null, pausedReason: null,
+ heartbeatAgeSeconds: ageSeconds, intervalSeconds: 300, lastLog: '',
+ daemon: daemonStaleAfterSeconds(sidecar as never, { mtimeMs: T0, pid: lockPid }),
+ } as Parameters<typeof classifyAutopilotStatus>[0]);
+}
+
+/** Daemon --interval 1500 at score >= 90: a 79 s cycle, then a 3000 s sleep. */
+const sleeping = { pid: 4242, written_at: iso(T0 + 79_000), phase: 'sleep', interval_s: 3000, base_interval_s: 1500, next_tick_at: iso(T0 + 79_000 + 3_000_000) };
+
+describe('#7003 autopilot --status grades from the daemon\'s own next tick', () => {
+ test('the issue\'s case: a 2700 s old heartbeat during a 3000 s adaptive sleep is fresh; past the next tick plus its budget it is stale', async () => {
+ const fresh = await grade(2700, sleeping);
+ expect({ state: fresh.state, source: fresh.stale_after_source, next: fresh.next_tick_at }).toEqual({ state: 'fresh', source: 'daemon', next: sleeping.next_tick_at });
+ expect(fresh.stale_after_seconds).toBe(79 + 3000 + 1500);
+ expect((await grade(79 + 3000 + 1500, sleeping)).state).toBe('fresh');
+ expect((await grade(79 + 3000 + 1501, sleeping)).state).toBe('stale');
+ });
+
+ test('a cycle in progress grades on 6 x the daemon\'s own base interval, not the caller\'s flag', async () => {
+ const cycle = { ...sleeping, written_at: iso(T0 + 1_000), phase: 'cycle', interval_s: null, next_tick_at: null };
+ const r = await grade(2700, cycle);
+ expect({ state: r.state, source: r.stale_after_source, after: r.stale_after_seconds }).toEqual({ state: 'fresh', source: 'daemon', after: 9000 });
+ });
+
+ test('no sidecar, another pid\'s sidecar, or one older than the lock: the flag rule (6 x --interval) as before', async () => {
+ for (const sidecar of [null, { ...sleeping, pid: 999 }, { ...sleeping, written_at: iso(T0 - 600_000) }, { ...sleeping, base_interval_s: 'x' }]) {
+ const r = await grade(2700, sidecar);
+ expect({ state: r.state, source: r.stale_after_source, after: r.stale_after_seconds }).toEqual({ state: 'stale', source: 'flag', after: 1800 });
+ }
+ });
+});
+
+function daemonHome(config: Record<string, unknown>): { home: string; repo: string } {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-7003-'));
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ embedding_disabled: true, self_upgrade: { mode: 'off' }, ...config }));
+ const repo = join(home, 'repo');
+ mkdirSync(repo);
+ execFileSync('git', ['-C', repo, 'init', '-q']);
+ return { home, repo };
+}
+
+function cliEnv(home: string): Record<string, string> {
+ const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_NO_BANNER: '1' };
+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_SUPERVISED', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY']) delete env[key];
+ return env as Record<string, string>;
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ test('#7003 a running daemon writes its next tick and --status --json grades from it (' + backend + ')', async () => {
+ const db = databaseUrl ? await isolatedPersistencePostgres(databaseUrl) : null;
+ const { home, repo } = daemonHome(db ? { engine: 'postgres', database_url: db.databaseUrl } : { engine: 'pglite', database_path: '' });
+ const dbPath = join(home, '.gbrain', 'brain.pglite');
+ if (!db) {
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: dbPath, embedding_disabled: true, self_upgrade: { mode: 'off' } }));
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dbPath });
+ await engine.initSchema();
+ await engine.disconnect();
+ }
+ const sidecarPath = join(home, '.gbrain', 'autopilot.heartbeat.json');
+ const args = ['autopilot', '--repo', repo, '--interval', '1500', ...(db ? ['--no-worker'] : ['--inline'])];
+ const daemon = Bun.spawn({ cmd: [process.execPath, '--no-env-file', CLI, ...args], env: cliEnv(home), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ let output = '';
+ const drain = async (s: ReadableStream<Uint8Array>) => { for await (const c of s) output += new TextDecoder().decode(c); };
+ const drained = Promise.all([drain(daemon.stdout), drain(daemon.stderr)]);
+ try {
+ let sidecar: { pid: number; phase: string; next_tick_at: string | null; base_interval_s: number } | null = null;
+ for (let i = 0; i < 2_400 && daemon.exitCode === null; i++) {
+ if (existsSync(sidecarPath)) { sidecar = JSON.parse(readFileSync(sidecarPath, 'utf8')); if (sidecar?.phase === 'sleep') break; }
+ await Bun.sleep(50);
+ }
+ expect(sidecar?.phase, output.slice(-3000)).toBe('sleep');
+ expect(sidecar!.pid).toBe(daemon.pid);
+ expect(sidecar!.base_interval_s).toBe(1500);
+ const lockMtime = statSync(join(home, '.gbrain', 'autopilot.lock')).mtimeMs;
+ const status = Bun.spawnSync({ cmd: [process.execPath, '--no-env-file', CLI, 'autopilot', '--status', '--json'], env: cliEnv(home), stdout: 'pipe', stderr: 'pipe' });
+ const report = JSON.parse(status.stdout.toString().trim().split('\n').reverse().find(l => l.startsWith('{'))!);
+ expect({ source: report.stale_after_source, next: report.next_tick_at }).toEqual({ source: 'daemon', next: sidecar!.next_tick_at });
+ expect(report.stale_after_seconds).toBe(Math.ceil((Date.parse(sidecar!.next_tick_at!) - lockMtime) / 1000) + 1500);
+ } finally {
+ daemon.kill('SIGTERM');
+ const killer = setTimeout(() => daemon.kill('SIGKILL'), 45_000);
+ await daemon.exited; clearTimeout(killer); await drained;
+ await db?.close();
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 240_000);
+}