Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

notifier: gbrain jobs work and the autopilot daemon are residents (2a.4 notifier part)

garrytan148cc54d5241
diff --git a/src/commands/autopilot-daemon.ts b/src/commands/autopilot-daemon.ts
index 96fa57595e..8d9a5c8c69 100644
--- a/src/commands/autopilot-daemon.ts
+++ b/src/commands/autopilot-daemon.ts
@@ -164,8 +164,13 @@ export async function runAutopilotDaemon(engine: BrainEngine, args: string[]): P
// a second call is a no-op (disconnect snapshots + nulls the handle), so
// both paths firing is safe.
const shutdownAbort = new AbortController();
+ // GBRA-133 PR 2a.4: the daemon is a resident; its notifier syncs this host's sources on commit (sync.on_commit) and
+ // drains wanted markers, between the wall-clock cycles. Stopped before the engine closes.
+ const { startResidentNotifier } = await import('../core/notifier/resident.ts');
+ const notifier = startResidentNotifier(engine, { resident: 'autopilot', log: line => console.log(line) });
const closeEngine = async () => {
shutdownAbort.abort(new Error('autopilot shutdown'));
+ await notifier?.stop().catch(() => undefined);
if (state.inflightInlineCycle) {
// ponytail: 2s cap keeps us inside process-cleanup's 3s deadline; a
// between-phase abort resolves instantly, a mid-phase one may not.
diff --git a/src/commands/jobs/work.ts b/src/commands/jobs/work.ts
index 130460e558..fcf06e5e34 100644
--- a/src/commands/jobs/work.ts
+++ b/src/commands/jobs/work.ts
@@ -248,11 +248,16 @@ export async function runJobsWork({ args, engine, queue }: JobsCommandContext):
// cannot exit(143) ahead of the drain and orphan in-flight jobs.
const releaseSignalOwner = registerSignalOwner('jobs-work', () => worker.requestShutdown());
+ // GBRA-133 PR 2a.4: the worker is a resident; its notifier syncs this host's sources on commit (sync.on_commit) and
+ // drains wanted markers. One owner per host (the notifier lease); it never delays the first claim.
+ const { startResidentNotifier } = await import('../../core/notifier/resident.ts');
+ const notifier = startResidentNotifier(engine, { resident: 'jobs-worker', log: line => console.error(line) });
try {
reportWorkerStarting('worker_startup');
worker.once('ready', () => reportWorkerReady(childIdentity));
await worker.start();
} finally {
+ await notifier?.stop().catch(() => undefined);
unregisterWorker();
releaseSignalOwner();
if (worker.configurationError) {
diff --git a/src/core/commit-notifier.ts b/src/core/commit-notifier.ts
index 767fe82a1f..fe572b6fcc 100644
--- a/src/core/commit-notifier.ts
+++ b/src/core/commit-notifier.ts
@@ -165,7 +165,7 @@ export const bounded = (raw: string | undefined, fallback: number, min: number,
};
const short = (sha: string | null) => sha ? sha.slice(0, 8) : 'none';
-/** GBRAIN_NOTIFIER=0 (or --no-notifier, which residents map onto it) turns the notifier off for this process. */
+/** GBRAIN_NOTIFIER=0 turns the notifier off for this process. */
export function notifierDisabledByEnv(env: Record<string, string | undefined> = process.env): boolean {
return falsy(env.GBRAIN_NOTIFIER);
}
@@ -187,7 +187,8 @@ export function resolveQuietMs(env: Record<string, string | undefined>): number
return bounded(env.GBRAIN_NOTIFIER_QUIET_MS ?? env.GBRAIN_SERVE_HEAD_DEBOUNCE_MS, QUIET_MS_DEFAULT, 0, 60_000);
}
-export function startCommitNotifier(opts: CommitNotifierOptions): CommitNotifier {
+/** The notifier's settings and its logging and decision helpers, resolved once from its options. */
+function notifierKit(opts: CommitNotifierOptions) {
const env = opts.env ?? process.env;
const pollMs = opts.pollMs ?? resolvePollMs(env);
const quietMs = opts.quietMs ?? resolveQuietMs(env);
@@ -221,6 +222,71 @@ export function startCommitNotifier(opts: CommitNotifierOptions): CommitNotifier
decisions.push({ at: now(), source, decision, ...extra });
if (decisions.length > DECISIONS_CAP) decisions.splice(0, decisions.length - DECISIONS_CAP);
};
+ return { pollMs, quietMs, heartbeatMs, leaseMs, cap, now, pid, ownerId, forcePoll, setTimer, clearTimer, log, logOnce, guard, decisions, decide };
+}
+
+const closeWatch = (rt: Rt) => { if (rt.watchClose) { try { rt.watchClose(); } catch { /* best effort */ } rt.watchClose = null; } };
+const mode = (rt: Rt): DetectionMode => rt.watchClose ? 'watch' : 'poll';
+const markerKey = (rt: Rt) => `${rt.head ?? ''}|${rt.markers.map(m => `${m.intent}:${m.generation}`).join(',')}`;
+const due = (rt: Rt) => (rt.watched && !!rt.head && rt.head !== rt.lastCommit) || rt.markers.length > 0;
+
+/** Merges a fresh source listing into the runtime map (a moved root starts over); returns the sources new to it. */
+function mergeListed(sources: Map<string, Rt>, rows: NotifierSource[]): Rt[] {
+ const seen = new Set<string>();
+ const fresh: Rt[] = [];
+ for (const s of rows) {
+ seen.add(s.sourceId);
+ const prior = sources.get(s.sourceId);
+ if (prior && prior.root === s.root) { prior.gitDir = s.gitDir; prior.commonDir = s.commonDir ?? null; prior.lastCommit = s.lastCommit; prior.kind = s.kind; continue; }
+ if (prior) closeWatch(prior);
+ const rt: Rt = { ...s, head: null, watched: false, watchClose: null, coverageKey: null, lastStartAt: -Infinity, forwarded: null,
+ state: 'idle', attempts: 0, nextRetryAt: 0, blockedKey: null, markers: [], started: false };
+ sources.set(s.sourceId, rt);
+ fresh.push(rt);
+ }
+ for (const [id, rt] of [...sources]) if (!seen.has(id)) { closeWatch(rt); sources.delete(id); }
+ return fresh;
+}
+
+/** The intent a start asks for (full over pull over freshness) and its time slice. */
+function startPlan(rt: Rt, candidates: number, opts: Pick<CommitNotifierOptions, 'firstSliceSeconds' | 'sliceSeconds'>): { intent: MarkerIntent; first: boolean; slice: number | null } {
+ const intent: MarkerIntent = rt.markers.some(m => m.intent === 'full') ? 'full' : rt.markers.some(m => m.intent === 'pull') ? 'pull' : 'freshness';
+ const first = !rt.started;
+ const slice = first && opts.firstSliceSeconds !== undefined && rt.kind !== 'classic' ? opts.firstSliceSeconds : candidates > 1 ? (opts.sliceSeconds ?? null) : null;
+ return { intent, first, slice };
+}
+
+/** The durable state survives the resident: a restart resumes attempts, the next retry and a blocked run. */
+function restoreStates(sources: Map<string, Rt>, states: NotifierSourceRow[], nowMs: number): void {
+ for (const row of states) {
+ const rt = sources.get(row.source_id);
+ if (!rt) continue;
+ rt.state = row.state === 'running' ? 'due' : row.state;
+ rt.attempts = row.attempts;
+ rt.nextRetryAt = row.next_retry_at ? Date.parse(row.next_retry_at) - Date.now() + nowMs : 0;
+ }
+}
+
+/** The capped backoff after a failure: progress resets the count; past the last tier with no progress it is stalled. */
+function retryPlan(priorAttempts: number, progressed: boolean): { attempts: number; wait: number; stalled: boolean } {
+ const attempts = progressed ? 1 : priorAttempts + 1;
+ return { attempts, wait: RETRY_BACKOFF_MS[Math.min(attempts - 1, RETRY_BACKOFF_MS.length - 1)]!, stalled: !progressed && attempts > RETRY_BACKOFF_MS.length };
+}
+
+async function settleWithin(p: Promise<void>, ms: number): Promise<void> {
+ let bound: ReturnType<typeof setTimeout> | undefined;
+ await Promise.race([p, new Promise<void>(resolve => { bound = setTimeout(resolve, ms); bound.unref?.(); })]);
+ clearTimeout(bound);
+}
+
+function snapshotSource(rt: Rt, now: number): NotifierSourceSnapshot {
+ return { source_id: rt.sourceId, kind: rt.kind ?? null, watched: rt.watched, mode: mode(rt), head: rt.head, last_commit: rt.lastCommit, state: rt.state,
+ attempts: rt.attempts, next_retry_in_ms: rt.nextRetryAt ? Math.max(0, rt.nextRetryAt - now) : null,
+ markers: rt.markers.map(m => ({ intent: m.intent, generation: m.generation })) };
+}
+
+export function startCommitNotifier(opts: CommitNotifierOptions): CommitNotifier {
+ const { pollMs, quietMs, heartbeatMs, leaseMs, cap, now, pid, ownerId, forcePoll, setTimer, clearTimer, log, logOnce, guard, decisions, decide } = notifierKit(opts);
let enabled = false;
let excluded = new Set<string>();
@@ -257,10 +323,7 @@ export function startCommitNotifier(opts: CommitNotifierOptions): CommitNotifier
if (nudgeTimer !== null) return;
nudgeTimer = setTimer(() => { nudgeTimer = null; void tick(); }, NUDGE_MS);
};
- const closeWatch = (rt: Rt) => { if (rt.watchClose) { try { rt.watchClose(); } catch { /* best effort */ } rt.watchClose = null; } };
const closeAllWatches = () => { for (const rt of sources.values()) closeWatch(rt); };
- const mode = (rt: Rt): DetectionMode => rt.watchClose ? 'watch' : 'poll';
- const markerKey = (rt: Rt) => `${rt.head ?? ''}|${rt.markers.map(m => `${m.intent}:${m.generation}`).join(',')}`;
const transition = async (rt: Rt, patch: StatePatch) => {
rt.state = patch.state;
@@ -279,29 +342,11 @@ export function startCommitNotifier(opts: CommitNotifierOptions): CommitNotifier
const rows = Array.isArray(listed) ? listed : listed.sources;
skipped = Array.isArray(listed) ? [] : listed.skipped;
for (const s of skipped) logOnce(`skip\u0000${s.sourceId}\u0000${s.reason}`, `${s.sourceId}: not watched here: ${s.reason}`);
- const seen = new Set<string>();
- const fresh: Rt[] = [];
- for (const s of rows) {
- seen.add(s.sourceId);
- const prior = sources.get(s.sourceId);
- if (prior && prior.root === s.root) { prior.gitDir = s.gitDir; prior.commonDir = s.commonDir ?? null; prior.lastCommit = s.lastCommit; prior.kind = s.kind; continue; }
- if (prior) closeWatch(prior);
- const rt: Rt = { ...s, head: null, watched: false, watchClose: null, coverageKey: null, lastStartAt: -Infinity, forwarded: null,
- state: 'idle', attempts: 0, nextRetryAt: 0, blockedKey: null, markers: [], started: false };
- sources.set(s.sourceId, rt);
- fresh.push(rt);
- }
- for (const [id, rt] of [...sources]) if (!seen.has(id)) { closeWatch(rt); sources.delete(id); }
+ const fresh = mergeListed(sources, rows);
if (fresh.length) {
// Restart: the durable state (attempts, next retry, a blocked run) survives the resident.
const states = await guard('reading the notifier states', () => opts.store.readStates(fresh.map(r => r.sourceId)), [] as NotifierSourceRow[]);
- for (const row of states) {
- const rt = sources.get(row.source_id);
- if (!rt) continue;
- rt.state = row.state === 'running' ? 'due' : row.state;
- rt.attempts = row.attempts;
- rt.nextRetryAt = row.next_retry_at ? Date.parse(row.next_retry_at) - Date.now() + now() : 0;
- }
+ restoreStates(sources, states, now());
}
for (const rt of sources.values()) rt.watched = enabled && !excluded.has(rt.sourceId);
for (const rt of sources.values()) {
@@ -341,12 +386,8 @@ export function startCommitNotifier(opts: CommitNotifierOptions): CommitNotifier
}
};
- const due = (rt: Rt) => (rt.watched && !!rt.head && rt.head !== rt.lastCommit) || rt.markers.length > 0;
-
const failure = async (rt: Rt, code: string, message: string, progressed: boolean) => {
- const attempts = progressed ? 1 : rt.attempts + 1;
- const wait = RETRY_BACKOFF_MS[Math.min(attempts - 1, RETRY_BACKOFF_MS.length - 1)]!;
- const stalled = !progressed && attempts > RETRY_BACKOFF_MS.length;
+ const { attempts, wait, stalled } = retryPlan(rt.attempts, progressed);
const tracePath = trace(rt, { event: 'failure', code, error: message, attempts, next_retry_ms: wait, stalled });
await transition(rt, { state: 'retry', reason: stalled ? 'notifier_stalled' : code, firstDue: 'keep', attempts, nextRetryInMs: wait, progress: progressed,
error: { code: stalled ? 'notifier_stalled' : code, message, tracePath } });
@@ -428,10 +469,8 @@ export function startCommitNotifier(opts: CommitNotifierOptions): CommitNotifier
log('the notifier lease moved to another resident before a start; forwarding instead');
return;
}
- const intent: MarkerIntent = rt.markers.some(m => m.intent === 'full') ? 'full' : rt.markers.some(m => m.intent === 'pull') ? 'pull' : 'freshness';
+ const { intent, first, slice } = startPlan(rt, candidates.length, opts);
const markers = [...rt.markers];
- const first = !rt.started;
- const slice = first && opts.firstSliceSeconds !== undefined && rt.kind !== 'classic' ? opts.firstSliceSeconds : candidates.length > 1 ? (opts.sliceSeconds ?? null) : null;
rt.lastStartAt = t;
rt.started = true;
let start: StartResult | null;
@@ -525,15 +564,11 @@ export function startCommitNotifier(opts: CommitNotifierOptions): CommitNotifier
const interval = (opts.setInterval ?? ((fn: () => void, ms: number) => { const h = setInterval(fn, ms); h.unref?.(); return h; }))(() => { void tick(); }, pollMs);
return {
- tick,
- nudge,
+ tick, nudge,
get enabled() { return enabled; },
get owner() { return owner; },
get decisions() { return decisions; },
- snapshot: () => ({ resident: opts.resident, owner, enabled, skipped: [...skipped], sources: [...sources.values()].map(rt => ({
- source_id: rt.sourceId, kind: rt.kind ?? null, watched: rt.watched, mode: mode(rt), head: rt.head, last_commit: rt.lastCommit, state: rt.state,
- attempts: rt.attempts, next_retry_in_ms: rt.nextRetryAt ? Math.max(0, rt.nextRetryAt - now()) : null,
- markers: rt.markers.map(m => ({ intent: m.intent, generation: m.generation })) })) }),
+ snapshot: () => ({ resident: opts.resident, owner, enabled, skipped: [...skipped], sources: [...sources.values()].map(rt => snapshotSource(rt, now())) }),
stop: async () => {
if (!stopped) {
stopped = true;
@@ -543,9 +578,7 @@ export function startCommitNotifier(opts: CommitNotifierOptions): CommitNotifier
closeAllWatches();
}
if (inflight) {
- let bound: ReturnType<typeof setTimeout> | undefined;
- await Promise.race([inflight, new Promise<void>(resolve => { bound = setTimeout(resolve, STOP_SETTLE_MS); bound.unref?.(); })]);
- clearTimeout(bound);
+ await settleWithin(inflight, STOP_SETTLE_MS);
closeAllWatches();
}
if (owner && leased) await guard('releasing the notifier lease', () => opts.store.releaseLease(opts.hostId, ownerId), undefined);
diff --git a/src/core/notifier/resident.ts b/src/core/notifier/resident.ts
index e1f300b1ee..7c970df902 100644
--- a/src/core/notifier/resident.ts
+++ b/src/core/notifier/resident.ts
@@ -175,7 +175,7 @@ export function residentNotifierOptions(engine: BrainEngine, opts: ResidentNotif
}
/**
- * Starts this process's notifier, or returns null when GBRAIN_NOTIFIER=0 (or --no-notifier) turned it off or one is
+ * Starts this process's notifier, or returns null when GBRAIN_NOTIFIER=0 turned it off or one is
* the one started before it is replaced as this process's nudge target. Never awaits anything: the first pass runs in the background, so a resident's startup (an MCP
* handshake, a worker's first claim) never waits on git or a catch-up sync.
*/
diff --git a/test/e2e/s-notifier-residents-postgres.test.ts b/test/e2e/s-notifier-residents-postgres.test.ts
new file mode 100644
index 0000000000..bf3a647426
--- /dev/null
+++ b/test/e2e/s-notifier-residents-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../pathological/s-notifier-residents.test.ts'));
diff --git a/test/pathological/s-notifier-residents.test.ts b/test/pathological/s-notifier-residents.test.ts
new file mode 100644
index 0000000000..af930f9e77
--- /dev/null
+++ b/test/pathological/s-notifier-residents.test.ts
@@ -0,0 +1,129 @@
+/**
+ * GBRA-133 PR 2a.1 / 2a.4: residents. Every resident (serve, serve --http, gbrain jobs work, the autopilot daemon)
+ * starts the notifier the same way; one of them owns the host's notifier through the lease (Postgres), and a resident
+ * start never waits on git or a catch-up.
+ *
+ * Protects:
+ * - two residents on one host: exactly one owns; a clean stop releases the lease (expires it now), so the standby
+ * takes over at its first claim afterwards with a new fencing token;
+ * - an owner that dies without releasing (a kill) is taken over at the standby's first claim after the lease expired,
+ * with a new fencing token, and the dead owner's token no longer passes the check made before each start;
+ * - a resident start returns before its first pass (a HEAD read that never answers does not delay it), reads keep
+ * working and report the source as not monitored until the resident has observed it.
+ * Recorded claims and DB state only, no wall-clock thresholds. The lease cases run on Postgres (PGLite has no lease:
+ * the brain's lock holder owns the notifier); the startup case runs on both.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { startCommitNotifier, type NotifierStore } from '../../src/core/commit-notifier.ts';
+import { claimLease, holdsLease, readLease } from '../../src/core/notifier/store.ts';
+import { __resetResidentNotifierForTests, residentNotifier, residentNotifierOptions, sqlNotifierStore, startResidentNotifier } from '../../src/core/notifier/resident.ts';
+import { readSourceFreshness } from '../../src/core/notifier/status.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { pathologicalArms } from './harness.ts';
+
+const HOST = '00000000-0000-4000-8000-0000000000aa';
+
+async function brain(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>) {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try { await engine.executeRaw('DELETE FROM sync_notifier_leases WHERE host_id = $1', [HOST]); await run(engine); }
+ finally { await engine.executeRaw('DELETE FROM sync_notifier_leases WHERE host_id = $1', [HOST]).catch(() => undefined); await close(); }
+}
+
+interface Claim { won: boolean; expiredBefore: boolean }
+/** The real SQL store, recording each claim with whether the lease had expired (or was free) when it was attempted. */
+function recordingStore(engine: BrainEngine, claims: Claim[], opts: { dropRelease?: boolean } = {}): NotifierStore {
+ const store = sqlNotifierStore(engine);
+ return {
+ ...store,
+ claimLease: async (l) => {
+ const before = await readLease(engine, l.hostId);
+ const r = await store.claimLease(l);
+ claims.push({ won: r !== null && r.owner === true, expiredBefore: before === null || !before.live || before.owner_id === l.ownerId });
+ return r;
+ },
+ ...(opts.dropRelease ? { releaseLease: async () => {} } : {}),
+ };
+}
+
+function resident(engine: BrainEngine, kind: 'serve' | 'jobs-worker', store: NotifierStore, lines: string[]) {
+ return startCommitNotifier(residentNotifierOptions(engine, { resident: kind, log: l => lines.push(l), hostId: HOST, heartbeatMs: 200, pollMs: 200,
+ store, listSources: async () => [], readFlag: async () => false }));
+}
+async function until(what: string, fn: () => boolean | Promise<boolean>, lines: string[], timeoutMs = 30_000) {
+ const deadline = Date.now() + timeoutMs;
+ while (!(await fn())) { if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}; log: ${JSON.stringify(lines)}`); await Bun.sleep(25); }
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`notifier residents (${backend})`, () => {
+ if (backend === 'postgres') {
+ test('one owner per host; a clean stop hands over at the standby\'s first claim afterwards', async () => {
+ await brain(databaseUrl, async engine => {
+ const lines: string[] = []; const aClaims: Claim[] = []; const bClaims: Claim[] = [];
+ const a = resident(engine, 'serve', recordingStore(engine, aClaims), lines);
+ await until('the first owner', () => a.owner, lines);
+ const b = resident(engine, 'jobs-worker', recordingStore(engine, bClaims), lines);
+ await until('the standby to claim twice', () => bClaims.length >= 2, lines);
+ expect(a.owner).toBe(true); expect(b.owner).toBe(false);
+ expect(bClaims.every(c => !c.won)).toBe(true);
+ const firstFence = (await readLease(engine, HOST))!.fence;
+ const standbyClaims = bClaims.length;
+ await a.stop();
+ expect((await readLease(engine, HOST))?.live).toBe(false);
+ await until('the standby to take over', () => b.owner, lines);
+ expect(bClaims.slice(standbyClaims)[0]).toEqual({ won: true, expiredBefore: true });
+ expect((await readLease(engine, HOST))!.resident_kind).toBe('jobs-worker');
+ expect((await readLease(engine, HOST))!.fence).toBe(firstFence + 1);
+ await b.stop();
+ });
+ }, 60_000);
+
+ test('an owner killed without releasing is taken over at the first claim after its lease expired; its fence no longer passes', async () => {
+ await brain(databaseUrl, async engine => {
+ const lines: string[] = []; const aClaims: Claim[] = []; const bClaims: Claim[] = [];
+ const a = resident(engine, 'serve', recordingStore(engine, aClaims, { dropRelease: true }), lines);
+ await until('the first owner', () => a.owner, lines);
+ const deadFence = (await readLease(engine, HOST))!.fence;
+ const deadOwner = (await engine.executeRaw<{ owner_id: string }>('SELECT owner_id FROM sync_notifier_leases WHERE host_id=$1', [HOST]))[0]!.owner_id;
+ const b = resident(engine, 'jobs-worker', recordingStore(engine, bClaims), lines);
+ await until('the standby to claim', () => bClaims.length >= 1, lines);
+ await a.stop();
+ expect(await readLease(engine, HOST)).not.toBeNull();
+ await until('the standby to take over', () => b.owner, lines);
+ const firstAfterExpiry = bClaims.findIndex(c => c.expiredBefore);
+ expect(firstAfterExpiry).toBeGreaterThanOrEqual(0);
+ expect(bClaims[firstAfterExpiry]!.won).toBe(true);
+ expect(bClaims.slice(0, firstAfterExpiry).every(c => !c.won)).toBe(true);
+ const lease = (await readLease(engine, HOST))!;
+ expect(lease.fence).toBe(deadFence + 1);
+ expect(await holdsLease(engine, HOST, deadOwner, deadFence)).toBe(false);
+ const stale = await claimLease(engine, { hostId: HOST, ownerId: deadOwner, kind: 'serve', pid: 1, leaseMs: 60_000 });
+ expect(stale.owner).toBe(false);
+ await b.stop();
+ });
+ }, 60_000);
+ }
+
+ test('a resident start returns before its first pass; reads keep working and say not_monitored until it observes', async () => {
+ await brain(databaseUrl, async engine => {
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('acme-example','acme-example','/nonexistent/acme-example','{}') ON CONFLICT (id) DO NOTHING");
+ await engine.executeRaw('INSERT INTO sync_notifier_sources (source_id, syncer_host_id) VALUES ($1, $2) ON CONFLICT (source_id) DO UPDATE SET syncer_host_id = EXCLUDED.syncer_host_id', ['acme-example', HOST]);
+ __resetResidentNotifierForTests();
+ let revParses = 0;
+ const lines: string[] = [];
+ const started = startResidentNotifier(engine, { resident: 'autopilot', log: l => lines.push(l), hostId: HOST, readFlag: async () => true,
+ listSources: async () => [{ sourceId: 'acme-example', root: '/nonexistent/acme-example', gitDir: null, lastCommit: null, kind: 'classic' as const }],
+ revParse: () => { revParses++; return new Promise<string>(() => {}); } });
+ try {
+ expect(started).not.toBeNull();
+ expect(residentNotifier()?.resident).toBe('autopilot');
+ const fresh = await readSourceFreshness(engine, { sourceId: 'acme-example' });
+ expect(fresh).toEqual([expect.objectContaining({ source_id: 'acme-example', state: 'not_monitored' })]);
+ await until('the background first pass to ask for HEAD', () => revParses > 0, lines);
+ expect((await readSourceFreshness(engine, { sourceId: 'acme-example' }))[0]!.state).toBe('not_monitored');
+ } finally { await started?.stop(); __resetResidentNotifierForTests(); await engine.executeRaw("DELETE FROM sources WHERE id='acme-example'"); }
+ });
+ }, 60_000);
+ });
+}