Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
autopilot: HEAD-driven freshness dispatch (GBRA-133 2a.4)
garrytan02949581cb33
diff --git a/src/commands/autopilot-daemon.ts b/src/commands/autopilot-daemon.tsindex 96fa57595e..97d58d7883 100644--- a/src/commands/autopilot-daemon.ts+++ b/src/commands/autopilot-daemon.ts@@ -12,7 +12,7 @@ import { gbrainPath as gbrainHomePath, loadConfig, loadConfigFileOnly } from '..import { join } from 'path';import { loadPreferences } from '../core/preferences.ts';import { registerCleanup } from '../core/process-cleanup.ts';-import { dispatchAutopilotTick } from './autopilot-dispatch.ts';+import { dispatchAutopilotTick, sleepWatchingHeads } from './autopilot-dispatch.ts';import { runNightlyQualityProbeStep, runParserProbeStep } from './autopilot-probes.ts';import { resolveChildCliInvocation } from '../core/minions/job-isolation.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';@@ -63,6 +63,8 @@ export interface AutopilotDaemonState {lastFullCycleAt: number;/** Log the pause/resume transition once each, not every poll. */pausedAnnounced: boolean;+ /** GBRA-133 2a.4: per source, the checkout HEAD this daemon last dispatched (or decided) a freshness sync for. */+ freshnessHeads: Map<string, string>;}export async function runAutopilotDaemon(engine: BrainEngine, args: string[]): Promise<void> {@@ -141,6 +143,7 @@ export async function runAutopilotDaemon(engine: BrainEngine, args: string[]): PnoWorkerConsecutiveIdle: 0,lastFullCycleAt: 0,pausedAnnounced: false,+ freshnessHeads: new Map(),};let childSupervisor: ChildWorkerSupervisor | null = null;const processingState = spawnManagedWorker ? new OwnerProcessingState('autopilot', 'default') : null;@@ -338,8 +341,9 @@ export async function runAutopilotDaemon(engine: BrainEngine, args: string[]): Pawait runNightlyQualityProbeStep(engine, cfg);await runParserProbeStep(engine, cfg);- // Wait for next cycle- await new Promise(r => setTimeout(r, interval * 1000));+ // Wait for next cycle (HEAD-driven between ticks when sync.on_commit is on).+ 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-dispatch.ts b/src/commands/autopilot-dispatch.tsindex 5d28f38fa4..af2402e4e6 100644--- a/src/commands/autopilot-dispatch.ts+++ b/src/commands/autopilot-dispatch.ts@@ -22,6 +22,13 @@ import {} from './autopilot-remediation-policy.ts';import type { AutopilotDaemonState } from './autopilot-daemon.ts';import { logError } from './autopilot.ts';+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { execFileBounded } from '../core/bounded-child-exec.ts';+import { gitChildEnv } from '../core/git-env.ts';+import { GIT_OPERATION_MARKERS } from '../core/git/commit-push.ts';+import { SYNC_ON_COMMIT_KEY } from '../core/sync-config-keys.ts';+import { autopilotPaused } from '../core/autopilot-paths.ts';/** Returns cycleOk: false only when the dispatch itself threw. */export async function dispatchAutopilotTick(@@ -63,7 +70,7 @@ export async function dispatchAutopilotTick(const slot = new Date(slotMs).toISOString();const timeoutMs = resolveAutopilotDispatchTimeoutMs(baseInterval, false);- await dispatchFreshnessSyncs(engine, queue, { baseInterval, slot, timeoutMs, jsonMode });+ await dispatchFreshnessSyncs(engine, queue, { baseInterval, slot, timeoutMs, jsonMode, freshnessHeads: state.freshnessHeads });await dispatchAutoDrain(engine, queue, { timeoutMs, jsonMode });const { score, plan, estTotal } = await computeAutopilotPlan(engine, repoPath);@@ -252,14 +259,51 @@ export function connectorAwaitingFirstSync(src: { id: string; config: unknown },return true;}+/** What the freshness loop decided for one checkout source (connector sources are not reported). */+export interface FreshnessDecision {+ source_id: string;+ outcome: 'dispatched' | 'coalesced' | 'fresh' | 'live_job' | 'skipped' | 'failed';+ /** Why a sync was due: the checkout's HEAD differs from the last synced commit, or the wall-clock backstop. */+ trigger?: 'head' | 'interval';+ head?: string | null;+ job_id?: number;+}++/** A checkout's HEAD and whether a rebase, merge, cherry-pick or revert is mid-flight there. Async and bounded; null when git cannot read it. */+export async function readCheckoutHead(root: string): Promise<{ head: string; operation: string | null } | null> {+ const r = await execFileBounded('git', ['-C', root, 'rev-parse', '--absolute-git-dir', 'HEAD'], { timeout: 5_000, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }) });+ if (r.error) return null;+ const [gitDir, head] = r.stdout.trim().split('\n');+ if (!gitDir || !head || !/^[0-9a-f]{40,64}$/.test(head)) return null;+ return { head, operation: GIT_OPERATION_MARKERS.find(marker => existsSync(join(gitDir, marker))) ?? null };+}++/**+ * GBRA-133 2a.4: why a checkout source is due a freshness sync. HEAD-driven first: HEAD differs from the source's last+ * synced commit and this daemon has not already dispatched (or decided) for that HEAD; no ancestry assumption. The+ * wall-clock rule (last_sync_at older than the interval) stays as the backstop for retries, pulls and unreadable HEADs.+ * A HEAD in the middle of a rebase or merge waits for the operation to finish.+ */+export function freshnessTrigger(input: { head: { head: string; operation: string | null } | null; lastCommit: string | null;+ ageMs: number; intervalMs: number; decidedHead?: string }): 'head' | 'interval' | null {+ if (input.ageMs >= input.intervalMs) return 'interval';+ const head = input.head;+ if (!head || head.operation || head.head === input.lastCommit || head.head === input.decidedHead) return null;+ return 'head';+}+/*** v0.40 D17 freshness: runs first each tick, independent of the score gate.+ * `freshnessHeads` (the daemon's per-source map of the HEAD it last dispatched or decided for) keeps a HEAD-driven+ * dispatch to one per HEAD; `onlySourceIds` narrows the pass to the sources the between-tick HEAD probe saw move.*/export async function dispatchFreshnessSyncs(engine: BrainEngine,queue: MinionQueue,- { baseInterval, slot, timeoutMs, jsonMode }: { baseInterval: number; slot: string; timeoutMs: number; jsonMode: boolean },-): Promise<void> {+ { baseInterval, slot, timeoutMs, jsonMode, freshnessHeads = new Map(), onlySourceIds }: { baseInterval: number; slot: string; timeoutMs: number; jsonMode: boolean;+ freshnessHeads?: Map<string, string>; onlySourceIds?: ReadonlySet<string> },+): Promise<FreshnessDecision[]> {+ const decisions: FreshnessDecision[] = [];// ── v0.40 D17: per-source freshness check ────────────────────// Runs first; independent of score gate. Submits a 'sync' job per// source whose last_sync_at is older than the interval. The sync@@ -282,6 +326,7 @@ export async function dispatchFreshnessSyncs(const intervalMs = baseInterval * 1000;const now = Date.now();for (const src of sources) {+ if (onlySourceIds && !onlySourceIds.has(src.id)) continue;if (isConnectorSourceKind(parseSourceConfig(src.config).kind)) {await dispatchConnectorFreshnessSync(queue, src, attempted, activationPending, mismatched, { intervalMs, now, slot, timeoutMs, jsonMode });continue;@@ -292,7 +337,7 @@ export async function dispatchFreshnessSyncs(// reason is stated once per source and reason, and an explicit `gbrain sync --source <id>` is unaffected.const skip = await automaticSyncSkip(engine, src, activationPending);if (skip?.reason !== 'sync_disabled') reportAutomaticSyncSkip(src.id, skip, 'freshness_sync_skipped', jsonMode, (l) => process.stderr.write(l + '\n'));- if (skip) continue;+ if (skip) { decisions.push({ source_id: src.id, outcome: 'skipped' }); continue; }// A local_path this machine cannot use — relative (#3696: cwd is// launchd's, not the registering shell's) or absent on disk and// not a managed clone sync can re-create — would sync a phantom@@ -304,13 +349,20 @@ export async function dispatchFreshnessSyncs(process.stderr.write((jsonMode ? JSON.stringify({ event: 'freshness_source_path_skipped', source_id: src.id, reason: skipWarn }) : skipWarn) + '\n',);+ decisions.push({ source_id: src.id, outcome: 'skipped' });continue;}const lastSyncMs = src.last_sync_at ? new Date(src.last_sync_at).getTime() : 0;const ageMs = now - lastSyncMs;- if (ageMs < intervalMs) continue; // fresh enough- // #6706: a live sync job (any submitter) is already draining this source; coalescing into another submitter's row is refused.- if (await (await import('../core/persistence/sync-movement.ts')).liveSyncJob(engine, src.id) !== null) continue;+ const head = await readCheckoutHead(src.local_path);+ const trigger = freshnessTrigger({ head, lastCommit: src.last_commit, ageMs, intervalMs, decidedHead: freshnessHeads.get(src.id) });+ if (!trigger) { decisions.push({ source_id: src.id, outcome: 'fresh', head: head?.head ?? null }); continue; }+ // #6706: a live sync job (any submitter) is already draining this source; coalescing into another submitter's row+ // is refused. The HEAD stays undecided, so the next tick or HEAD probe dispatches it once that job ends.+ if (await (await import('../core/persistence/sync-movement.ts')).liveSyncJob(engine, src.id) !== null) {+ decisions.push({ source_id: src.id, outcome: 'live_job', trigger, head: head?.head ?? null });+ continue;+ }try {const job = await queue.add('sync',@@ -323,7 +375,9 @@ export async function dispatchFreshnessSyncs(},{queue: 'default',- idempotency_key: `autopilot-sync:${src.id}:${slot}`,+ // A HEAD-driven sync is keyed on the HEAD, never on the wall-clock slot: a slot key would coalesce a new commit+ // into the slot's completed job and drop it until the next slot.+ idempotency_key: trigger === 'head' ? `autopilot-sync:${src.id}:head:${head!.head}` : `autopilot-sync:${src.id}:${slot}`,max_attempts: 2,timeout_ms: timeoutMs,// #6706: single-flight per source. A sync job drains until synced or its deadline, so a tick while one runs@@ -331,15 +385,18 @@ export async function dispatchFreshnessSyncs(maxPending: 1,},);+ if (head) freshnessHeads.set(src.id, head.head);+ decisions.push({ source_id: src.id, outcome: job.coalesced ? 'coalesced' : 'dispatched', trigger, head: head?.head ?? null, job_id: job.id });if (jsonMode) {process.stderr.write(JSON.stringify({event: 'dispatched', job_id: job.id, mode: 'freshness',- source_id: src.id, age_ms: ageMs,+ source_id: src.id, age_ms: ageMs, trigger, ...(head ? { head: head.head } : {}),}) + '\n');} else {- console.log(`[dispatch] job #${job.id} sync (freshness: ${src.id}; age=${Math.floor(ageMs / 60000)}min)`);+ console.log(`[dispatch] job #${job.id} sync (freshness: ${src.id}; ${trigger === 'head' ? `HEAD ${head!.head.slice(0, 8)} not synced` : `age=${Math.floor(ageMs / 60000)}min`})`);}} catch (e) {+ decisions.push({ source_id: src.id, outcome: 'failed', trigger, head: head?.head ?? null });logError('dispatch.freshness', e);}}@@ -347,6 +404,85 @@ export async function dispatchFreshnessSyncs(} catch (e) {logError('dispatch.freshness-gate', e);}+ return decisions;+}++export const HEAD_PROBE_MS_DEFAULT = 3_000;+const HEAD_PROBE_FLAG_EVERY_MS = 30_000;+const HEAD_PROBE_LIST_EVERY_MS = 60_000;++export interface HeadProbeDeps {+ env?: Record<string, string | undefined>;+ now?: () => number;+ sleep?: (ms: number) => Promise<void>;+ readHead?: (root: string) => Promise<{ head: string; operation: string | null } | null>;+ dispatch?: typeof dispatchFreshnessSyncs;+}++/** One probe pass's record: the sources whose HEAD moved past what was synced or decided, and what the dispatch decided. */+export interface HeadProbeRecord { at: number; moved: string[]; decisions: FreshnessDecision[] }++/**+ * GBRA-133 2a.4: the daemon's wait between ticks, HEAD-driven. With `sync.on_commit` on, it reads every checkout's+ * HEAD every `GBRAIN_AUTOPILOT_HEAD_PROBE_MS` (default 3 s, 1 to 30 s; git only, no database read) and runs the freshness+ * dispatch for the sources whose HEAD moved past both their last synced commit and the HEAD this daemon last decided+ * for, so a commit is queued within seconds instead of at the next tick (150 to 600 s). The flag is re-read every 30 s+ * and the source list every 60 s. With the flag off it only sleeps, and the tick's HEAD check stays the trigger.+ * Returns each pass that saw a move (the recorded decisions the tests read).+ */+export async function sleepWatchingHeads(+ engine: BrainEngine,+ state: Pick<AutopilotDaemonState, 'stopping' | 'freshnessHeads'>,+ { sleepMs, baseInterval, jsonMode }: { sleepMs: number; baseInterval: number; jsonMode: boolean },+ deps: HeadProbeDeps = {},+): Promise<HeadProbeRecord[]> {+ const env = deps.env ?? process.env;+ const now = deps.now ?? Date.now;+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)));+ const readHead = deps.readHead ?? readCheckoutHead;+ const dispatch = deps.dispatch ?? dispatchFreshnessSyncs;+ const raw = Number(env.GBRAIN_AUTOPILOT_HEAD_PROBE_MS);+ const probeMs = env.GBRAIN_AUTOPILOT_HEAD_PROBE_MS?.trim() && Number.isFinite(raw) ? Math.min(30_000, Math.max(1_000, Math.round(raw))) : HEAD_PROBE_MS_DEFAULT;+ const records: HeadProbeRecord[] = [];+ const deadline = now() + sleepMs;+ let flagReadAt = -Infinity, enabled = false, listedAt = -Infinity;+ let sources: Array<{ id: string; local_path: string; last_commit: string | null }> = [];+ while (!state.stopping && now() < deadline) {+ await sleep(Math.max(0, Math.min(probeMs, deadline - now())));+ if (state.stopping || now() >= deadline) break;+ try {+ if (now() - flagReadAt >= HEAD_PROBE_FLAG_EVERY_MS) {+ flagReadAt = now();+ enabled = /^(1|true|on|yes)$/i.test((await engine.getConfig(SYNC_ON_COMMIT_KEY))?.trim() ?? '');+ }+ if (!enabled || autopilotPaused()) continue;+ if (now() - listedAt >= HEAD_PROBE_LIST_EVERY_MS) {+ listedAt = now();+ sources = (await loadAllSources(engine)).filter(s => !s.archived && s.local_path && !isConnectorSourceKind(parseSourceConfig(s.config).kind))+ .map(s => ({ id: s.id, local_path: s.local_path!, last_commit: s.last_commit }));+ }+ const moved = new Map<string, string>();+ for (const src of sources) {+ const head = await readHead(src.local_path);+ if (head && !head.operation && head.head !== src.last_commit && head.head !== state.freshnessHeads.get(src.id)) moved.set(src.id, head.head);+ }+ if (!moved.size) continue;+ const { MinionQueue } = await import('../core/minions/queue.ts');+ const slotMs = Math.floor(now() / (baseInterval * 1000)) * baseInterval * 1000;+ const decisions = await dispatch(engine, new MinionQueue(engine), { baseInterval, slot: new Date(slotMs).toISOString(),+ timeoutMs: resolveAutopilotDispatchTimeoutMs(baseInterval, false), jsonMode, freshnessHeads: state.freshnessHeads, onlySourceIds: new Set(moved.keys()) });+ // A source the dispatch skipped or found fresh keeps the HEAD decided, so a skipped source is not re-run every probe;+ // a live sync job or a failed submit leaves it undecided and the next probe tries again.+ for (const d of decisions) {+ const head = moved.get(d.source_id);+ if (head && d.outcome !== 'live_job' && d.outcome !== 'failed') state.freshnessHeads.set(d.source_id, d.head ?? head);+ }+ records.push({ at: now(), moved: [...moved.keys()], decisions });+ } catch (e) {+ logError('dispatch.head-probe', e);+ }+ }+ return records;}/**diff --git a/test/e2e/s-autopilot-head-dispatch-postgres.test.ts b/test/e2e/s-autopilot-head-dispatch-postgres.test.tsnew file mode 100644index 0000000000..358eb9ac31--- /dev/null+++ b/test/e2e/s-autopilot-head-dispatch-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../pathological/s-autopilot-head-dispatch.test.ts'));diff --git a/test/pathological/s-autopilot-head-dispatch.test.ts b/test/pathological/s-autopilot-head-dispatch.test.tsnew file mode 100644index 0000000000..4124dedaad--- /dev/null+++ b/test/pathological/s-autopilot-head-dispatch.test.ts@@ -0,0 +1,146 @@+/**+ * GBRA-133 PR 2a.4 (latency finding 6.7): autopilot dispatched a freshness sync only when last_sync_at was older than+ * its interval (autopilot-dispatch.ts), checked once per cycle of 150 to 600 s, so a commit made right after a sync+ * waited for the next slot: Phase 1 measured up to 430 s per commit on Postgres without a serve.+ *+ * Protects: the freshness loop is HEAD-driven. A checkout whose HEAD differs from the source's last synced commit gets+ * one sync job at the next tick (keyed on the HEAD, so a completed job in the same slot never swallows a new commit),+ * classic and managed alike; the same HEAD is dispatched once; a HEAD in the middle of a rebase waits for it to finish;+ * the wall-clock rule stays the backstop. With sync.on_commit on, the daemon's wait between ticks reads HEADs every few+ * seconds and dispatches the moved source without waiting for the tick; with it off the wait reads nothing.+ * Fails when: a fresh-by-clock source with a new commit gets no job, a HEAD is dispatched twice, a mid-rebase HEAD is+ * synced, or the between-tick probe misses a commit. PGLite always, Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { mkdirSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { MinionWorker } from '../../src/core/minions/worker.ts';+import { makeSyncHandler } from '../../src/core/minions/handlers/sync.ts';+import { dispatchFreshnessSyncs } from '../../src/commands/autopilot-dispatch.ts';+import { pathologicalArms } from './harness.ts';+import { md, withProbeEngine, withProbeRepo, type ProbeRepo, type SyncMode } from './s-blockers-fixture.ts';++interface QueuedSync { id: number; status: string; idempotency_key: string | null }+const syncJobs = (engine: BrainEngine, sourceId: string) => engine.executeRaw<QueuedSync>(+ "SELECT id, status, idempotency_key FROM minion_jobs WHERE name='sync' AND data->>'sourceId'=$1 ORDER BY id", [sourceId]);++async function quietly<T>(run: () => Promise<T>): Promise<T> {+ const write = process.stderr.write.bind(process.stderr);+ const log = console.log;+ (process.stderr as { write: unknown }).write = () => true;+ console.log = () => {};+ try { return await run(); } finally { (process.stderr as { write: unknown }).write = write; console.log = log; }+}++const tick = (engine: BrainEngine, freshnessHeads = new Map<string, string>(), baseInterval = 300) => quietly(() => dispatchFreshnessSyncs(engine, new MinionQueue(engine),+ { baseInterval, slot: '2026-10-18T00:00:00.000Z', timeoutMs: 120_000, jsonMode: true, freshnessHeads } as Parameters<typeof dispatchFreshnessSyncs>[2]));++async function runQueued(engine: BrainEngine, jobId: number): Promise<string | undefined> {+ const queue = new MinionQueue(engine);+ const worker = new MinionWorker(engine, { pollInterval: 25, concurrency: 1 });+ worker.register('sync', makeSyncHandler(engine));+ const running = worker.start();+ try {+ for (let i = 0; i < 4_800; i++) {+ const status = (await queue.getJob(jobId))?.status;+ if (status === 'completed' || status === 'failed' || status === 'dead') return status;+ await new Promise(resolve => setTimeout(resolve, 25));+ }+ } finally { worker.stop(); await running; }+ return (await queue.getJob(jobId))?.status;+}++/** A synced source (last_commit = HEAD, last_sync_at = now), then one more commit nothing has synced. */+async function syncedThenCommitted(r: ProbeRepo, name: string): Promise<string> {+ await r.sync();+ expect(await r.lastCommit()).toBe(r.head());+ r.write(name + '.md', md(name)); r.commitAll(name);+ return r.head();+}++const live = async (r: ProbeRepo, slug: string) =>+ (await r.engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [r.sourceId, slug])).length > 0;++for (const { backend, databaseUrl } of pathologicalArms()) {+ for (const mode of ['classic', 'managed'] as SyncMode[]) {+ const withRepo = (run: (r: ProbeRepo) => Promise<void>) => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, mode, home, run));++ describe('autopilot freshness is HEAD-driven (' + backend + ', ' + mode + ')', () => {+ test('a commit right after a sync gets one sync job at the next tick, keyed on its HEAD, and the job makes it visible', async () => {+ await withRepo(async r => {+ const head = await syncedThenCommitted(r, 'after-sync');+ await tick(r.engine);+ const jobs = await syncJobs(r.engine, r.sourceId);+ expect(jobs.map(j => j.idempotency_key)).toEqual(['autopilot-sync:' + r.sourceId + ':head:' + head]);+ expect(await runQueued(r.engine, jobs[0]!.id)).toBe('completed');+ expect(await r.lastCommit()).toBe(head);+ expect(await live(r, 'after-sync')).toBe(true);+ });+ }, 240_000);++ test('the same HEAD is dispatched once: a second tick adds nothing, and a restarted daemon coalesces onto the same job', async () => {+ await withRepo(async r => {+ await syncedThenCommitted(r, 'once');+ const heads = new Map<string, string>();+ await tick(r.engine, heads);+ await tick(r.engine, heads);+ const restarted = await tick(r.engine);+ expect((await syncJobs(r.engine, r.sourceId)).length).toBe(1);+ expect(restarted.find(d => d.source_id === r.sourceId)?.outcome).toBe('coalesced');+ });+ }, 240_000);++ test('a HEAD in the middle of a rebase waits; once the rebase is gone the next tick dispatches it', async () => {+ await withRepo(async r => {+ const head = await syncedThenCommitted(r, 'mid-rebase');+ const marker = join(r.root, '.git', 'rebase-merge');+ mkdirSync(marker);+ await tick(r.engine);+ expect(await syncJobs(r.engine, r.sourceId)).toEqual([]);+ rmSync(marker, { recursive: true, force: true });+ await tick(r.engine);+ expect((await syncJobs(r.engine, r.sourceId)).map(j => j.idempotency_key)).toEqual(['autopilot-sync:' + r.sourceId + ':head:' + head]);+ });+ }, 240_000);++ test('the wall-clock rule stays the backstop: a synced HEAD whose last sync is older than the interval is dispatched on the slot key', async () => {+ await withRepo(async r => {+ await r.sync();+ await tick(r.engine);+ expect(await syncJobs(r.engine, r.sourceId)).toEqual([]);+ await tick(r.engine, new Map(), 0.001);+ expect((await syncJobs(r.engine, r.sourceId)).map(j => j.idempotency_key)).toEqual(['autopilot-sync:' + r.sourceId + ':2026-10-18T00:00:00.000Z']);+ });+ }, 240_000);++ test('between ticks, with sync.on_commit on, the HEAD probe dispatches a new commit at its first pass; with it off nothing is read', async () => {+ const { sleepWatchingHeads } = await import('../../src/commands/autopilot-dispatch.ts');+ await withRepo(async r => {+ const head = await syncedThenCommitted(r, 'between-ticks');+ let clock = 1_000_000;+ let reads = 0;+ const deps = {+ env: { GBRAIN_AUTOPILOT_HEAD_PROBE_MS: '3000' }, now: () => clock,+ sleep: async (ms: number) => { clock += ms; },+ readHead: async (root: string) => { reads++; return (await import('../../src/commands/autopilot-dispatch.ts')).readCheckoutHead(root); },+ };+ const state = { stopping: false, freshnessHeads: new Map<string, string>() };+ const off = await quietly(() => sleepWatchingHeads(r.engine, state, { sleepMs: 30_000, baseInterval: 300, jsonMode: true }, deps));+ expect({ off, reads, jobs: await syncJobs(r.engine, r.sourceId) }).toEqual({ off: [], reads: 0, jobs: [] });++ await r.engine.setConfig('sync.on_commit', 'true');+ clock = 2_000_000;+ const on = await quietly(() => sleepWatchingHeads(r.engine, state, { sleepMs: 30_000, baseInterval: 300, jsonMode: true }, deps));+ expect(on.length).toBe(1);+ expect(on[0]!.at).toBe(2_003_000);+ expect(on[0]!.moved).toEqual([r.sourceId]);+ expect(on[0]!.decisions.filter(d => d.source_id === r.sourceId)).toMatchObject([{ outcome: 'dispatched', trigger: 'head', head }]);+ expect(state.freshnessHeads.get(r.sourceId)).toBe(head);+ expect((await syncJobs(r.engine, r.sourceId)).map(j => j.idempotency_key)).toEqual(['autopilot-sync:' + r.sourceId + ':head:' + head]);+ });+ }, 240_000);+ });+ }+}