Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

notifier: CommitNotifier core, durable store (v261) and the serve adapter

garrytan51b1ffe4e012
diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.ts
index 28b576331c..3642556d04 100644
--- a/src/commands/serve-http.ts
+++ b/src/commands/serve-http.ts
@@ -915,7 +915,7 @@ ${bootstrapFromEnv
const movementWatch = startMovementWatch(engine, { log: (line) => console.error(line) });
// #6858 ask 6: on-commit sync of this host's managed checkouts while `sync.on_commit` is on (serve-head-watcher.ts).
const { startServeHeadWatcher } = await import('../core/serve-head-watcher.ts');
- const headWatcher = startServeHeadWatcher(engine, { log: (line) => console.error(line) });
+ const headWatcher = startServeHeadWatcher(engine, { log: (line) => console.error(line), resident: 'serve-http' });
const deregisterEngineCleanup = registerCleanup('pglite-engine-disconnect', async () => {
await headWatcher.stop();
movementWatch.stop();
diff --git a/src/core/commit-notifier.ts b/src/core/commit-notifier.ts
new file mode 100644
index 0000000000..767fe82a1f
--- /dev/null
+++ b/src/core/commit-notifier.ts
@@ -0,0 +1,554 @@
+/**
+ * GBRA-133 PR 2a: CommitNotifier, the one place a commit becomes a sync without anyone running one. Extracted from the
+ * serve's on-commit watcher (serve-head-watcher.ts, #6858 ask 6), which is now the serve's adapter over this loop.
+ *
+ * Residents: `gbrain serve` (stdio and http), `gbrain jobs work` and the autopilot daemon start it (notifier/resident.ts).
+ * Ownership: one owner per host and brain. On Postgres the owner holds the host's row in sync_notifier_leases (atomic
+ * claim, conditional renew, a fencing token re-checked before every start, takeover once a lease interval is missed);
+ * a non-owner keeps its fs.watch and forwards a HEAD move as a freshness wanted marker. On PGLite the process holding
+ * the database (the serve, whose IPC socket takes `sync_nudge`) is the owner; no lease row is written.
+ *
+ * What it watches: managed sources whose worktree this host owns, and classic sources whose last sync ran on this host
+ * (sync_notifier_sources.syncer_host_id) or that GBRAIN_NOTIFIER_CLASSIC_SOURCES binds here; any other source is
+ * skipped with a reason. HEAD is watched while `sync.on_commit` is on and the source is not listed in
+ * `sync.on_commit.sources` (the exclusion list); wanted markers (sync trigger, webhook, busy delegated syncs) are
+ * drained regardless of the flag. It never pulls on its own: a commit-triggered run imports the checkout's HEAD.
+ *
+ * Detection: fs.watch on the git dirs (notifier/detect.ts) brings the next poll forward; the async rev-parse poll every
+ * `GBRAIN_NOTIFIER_POLL_MS` (alias GBRAIN_SERVE_HEAD_POLL_MS, default 3 s) is the source of truth; a source whose dirs
+ * cannot be watched runs in poll mode, and the mode is reported. Start rule: leading edge when the checkout is quiet
+ * (no rebase/merge/cherry-pick state, no index.lock), then a trailing window `GBRAIN_NOTIFIER_QUIET_MS` (alias
+ * GBRAIN_SERVE_HEAD_DEBOUNCE_MS, default 400 ms) before the next start of the same source.
+ *
+ * Scheduling: per-source single flight, a host cap (1 on PGLite; the in-process runner is one job at a time), and fair
+ * order (the source started least recently goes first), so a long or blocked source never starves another. Durable
+ * states per source (store.ts): due, running, retry with next_retry_at (5 s, 15 s, 1 min, 5 min), operator_blocked;
+ * first_due_at is kept until convergence is verified (last_commit equals the observed HEAD and no marker is due). A
+ * failed or refused start, an error or blocked run, and a resumable stop keep the source due; after the 5-minute tier
+ * with no progress the reason becomes notifier_stalled, with the exact fix and the trace file in sync status.
+ *
+ * Cost when idle: one git call per watched checkout per poll, a marker read every MARKER_SCAN_MS (or at once on a
+ * nudge), and on Postgres the lease renewal every heartbeat. State and coverage rows are written on change only.
+ * Every error is caught and logged once per distinct message; the loop never throws into its resident.
+ */
+import { randomUUID } from 'node:crypto';
+import type { DetectionMode, MarkerIntent, NotifierSourceRow, NotifierState, StatePatch, WantedMarker } from './notifier/store.ts';
+
+export type ResidentKind = 'serve' | 'serve-http' | 'jobs-worker' | 'autopilot';
+
+export const POLL_MS_DEFAULT = 3_000;
+export const QUIET_MS_DEFAULT = 400;
+export const FLAG_EVERY_MS = 30_000;
+export const LIST_EVERY_MS = 60_000;
+export const MARKER_SCAN_MS = 15_000;
+export const HEARTBEAT_MS_DEFAULT = 10_000;
+/** Capped retry backoff while a source stays due; past the last tier with no progress the reason is notifier_stalled. */
+export const RETRY_BACKOFF_MS = [5_000, 15_000, 60_000, 300_000] as const;
+export const STOP_SETTLE_MS = 3_000;
+const NUDGE_MS = 250;
+const LOG_ONCE_CAP = 200;
+const DECISIONS_CAP = 500;
+
+export interface NotifierSource {
+ sourceId: string;
+ root: string;
+ gitDir: string | null;
+ commonDir?: string | null;
+ lastCommit: string | null;
+ kind?: 'managed' | 'classic';
+}
+export interface SkippedSource { sourceId: string; reason: string }
+export type StartResult = { jobId: string } | { busy: true } | { refused: string };
+export interface JobStatus { state: 'running' | 'aborting' | 'done' | 'error'; outcome?: 'synced' | 'resumable' | 'blocked'; reason?: string; error?: string }
+export interface StartRequest { intent: MarkerIntent; sliceSeconds: number | null; first: boolean }
+
+/** A recorded scheduling decision (tests and the notifier block read these instead of wall-clock timing). */
+export interface NotifierDecision { at: number; source: string; decision: string; waitMs?: number; detail?: string }
+
+/** The durable seam; the default is the SQL store (notifier/store.ts), tests pass an in-memory one. */
+export interface NotifierStore {
+ /** Postgres: claim or renew the host lease. Returns null when this brain has no lease (PGLite: the lock holder owns). */
+ claimLease(l: { hostId: string; ownerId: string; kind: string; pid: number; leaseMs: number }): Promise<{ owner: true; fence: number } | { owner: false; holderKind: string | null } | null>;
+ holdsLease(hostId: string, ownerId: string, fence: number): Promise<boolean>;
+ releaseLease(hostId: string, ownerId: string): Promise<void>;
+ dueMarkers(sourceIds: string[]): Promise<WantedMarker[]>;
+ /** Of these minion job ids, the ones still waiting or running (their worker drains the marker). */
+ liveJobs(jobIds: number[]): Promise<Set<number>>;
+ forward(sourceId: string, head: string): Promise<void>;
+ settleMarkers(sourceId: string, read: WantedMarker[], run: { pulled: boolean; full: boolean }): Promise<WantedMarker[]>;
+ readStates(sourceIds: string[]): Promise<NotifierSourceRow[]>;
+ writeState(sourceId: string, patch: StatePatch): Promise<void>;
+ writeCoverage(sourceId: string, c: { head: string | null; mode: DetectionMode; ownerHostId: string; ownerKind: string; ownerPid: number }): Promise<void>;
+}
+
+export interface CommitNotifierOptions {
+ resident: ResidentKind;
+ log: (line: string) => void;
+ hostId: string;
+ /** 1 on PGLite (and with the in-process runner); the scheduler never runs more starts than this at once. */
+ maxConcurrent?: number;
+ pollMs?: number;
+ quietMs?: number;
+ heartbeatMs?: number;
+ /** Seconds a commit-triggered run may take before it stops resumable; null leaves the runner's own deadline. */
+ sliceSeconds?: number | null;
+ /** Seconds the first run after a resident starts may take (managed); classic first runs are unbounded but in the background. */
+ firstSliceSeconds?: number | null;
+ env?: Record<string, string | undefined>;
+ now?: () => number;
+ pid?: number;
+ setInterval?: (fn: () => void, ms: number) => unknown;
+ clearInterval?: (handle: unknown) => void;
+ setTimeout?: (fn: () => void, ms: number) => unknown;
+ clearTimeout?: (handle: unknown) => void;
+ store: NotifierStore;
+ readFlag: () => Promise<boolean>;
+ readExcluded?: () => Promise<string[]>;
+ listSources: () => Promise<NotifierSource[] | { sources: NotifierSource[]; skipped: SkippedSource[] }>;
+ lastCommit: (sourceId: string) => Promise<string | null>;
+ revParse: (root: string) => Promise<string>;
+ quiet?: (source: NotifierSource) => boolean;
+ syncRunning?: () => boolean | Promise<boolean>;
+ drainHeld?: (sourceId: string) => Promise<boolean>;
+ startSync: (sourceId: string, req: StartRequest) => Promise<StartResult>;
+ jobStatus: (jobId: string) => JobStatus | null;
+ watch?: (source: NotifierSource, onChange: () => void) => (() => void) | null;
+ trace?: (sourceId: string, event: Record<string, unknown>) => string | null;
+}
+
+export interface NotifierSourceSnapshot {
+ source_id: string;
+ kind: 'managed' | 'classic' | null;
+ watched: boolean;
+ mode: DetectionMode;
+ head: string | null;
+ last_commit: string | null;
+ state: NotifierState;
+ attempts: number;
+ next_retry_in_ms: number | null;
+ markers: Array<{ intent: MarkerIntent; generation: number }>;
+}
+
+export interface CommitNotifier {
+ tick(): Promise<void>;
+ /** Brings the next step forward (an IPC nudge or a marker write in this process). */
+ nudge(): void;
+ stop(): Promise<void>;
+ readonly enabled: boolean;
+ readonly owner: boolean;
+ readonly decisions: readonly NotifierDecision[];
+ snapshot(): { resident: ResidentKind; owner: boolean; enabled: boolean; sources: NotifierSourceSnapshot[]; skipped: SkippedSource[] };
+}
+
+interface Rt extends NotifierSource {
+ head: string | null;
+ watched: boolean;
+ watchClose: (() => void) | null;
+ coverageKey: string | null;
+ lastStartAt: number;
+ forwarded: string | null;
+ state: NotifierState;
+ attempts: number;
+ nextRetryAt: number;
+ blockedKey: string | null;
+ markers: WantedMarker[];
+ started: boolean;
+}
+
+interface RunningJob { id: string; sourceId: string; head: string | null; lastCommit: string | null; intent: MarkerIntent; markers: WantedMarker[] }
+
+const truthy = (value: string | null | undefined) => typeof value === 'string' && /^(1|true|on|yes)$/i.test(value.trim());
+const falsy = (value: string | null | undefined) => typeof value === 'string' && /^(0|false|off|no)$/i.test(value.trim());
+export const bounded = (raw: string | undefined, fallback: number, min: number, max: number) => {
+ const value = raw === undefined || raw.trim() === '' ? NaN : Number(raw);
+ return Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : fallback;
+};
+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. */
+export function notifierDisabledByEnv(env: Record<string, string | undefined> = process.env): boolean {
+ return falsy(env.GBRAIN_NOTIFIER);
+}
+
+/** The one parser for `sync.on_commit` (watcher, doctor and status share it). */
+export function parseOnCommit(value: string | null | undefined): boolean {
+ return truthy(value);
+}
+
+/** The `sync.on_commit.sources` exclusion list: comma or whitespace separated source ids. */
+export function parseExcludedSources(value: string | null | undefined): string[] {
+ return (value ?? '').split(/[\s,]+/).map(s => s.trim()).filter(Boolean);
+}
+
+export function resolvePollMs(env: Record<string, string | undefined>): number {
+ return bounded(env.GBRAIN_NOTIFIER_POLL_MS ?? env.GBRAIN_SERVE_HEAD_POLL_MS, POLL_MS_DEFAULT, 1_000, 30_000);
+}
+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 {
+ const env = opts.env ?? process.env;
+ const pollMs = opts.pollMs ?? resolvePollMs(env);
+ const quietMs = opts.quietMs ?? resolveQuietMs(env);
+ const heartbeatMs = opts.heartbeatMs ?? bounded(env.GBRAIN_NOTIFIER_HEARTBEAT_MS, HEARTBEAT_MS_DEFAULT, 200, 120_000);
+ const leaseMs = heartbeatMs * 2;
+ const cap = Math.max(1, opts.maxConcurrent ?? 1);
+ const now = opts.now ?? Date.now;
+ const pid = opts.pid ?? process.pid;
+ const ownerId = randomUUID();
+ const forcePoll = (env.GBRAIN_NOTIFIER_DETECTION ?? '').trim().toLowerCase() === 'poll';
+ const setTimer = opts.setTimeout ?? ((fn: () => void, ms: number) => { const t = setTimeout(fn, ms); t.unref?.(); return t; });
+ const clearTimer = opts.clearTimeout ?? ((h: unknown) => clearTimeout(h as ReturnType<typeof setTimeout>));
+ const tag = opts.resident === 'serve' || opts.resident === 'serve-http' ? '[serve-sync] on-commit' : `[notifier:${opts.resident}]`;
+ const log = (line: string) => { try { opts.log(`${tag}: ${line}`); } catch { /* logging never breaks the loop */ } };
+ const logged = new Set<string>();
+ const logOnce = (key: string, line: string) => {
+ if (logged.has(key)) return;
+ if (logged.size >= LOG_ONCE_CAP) logged.clear();
+ logged.add(key);
+ log(line);
+ };
+ const guard = async <T>(what: string, fn: () => Promise<T>, fallback: T): Promise<T> => {
+ try { return await fn(); } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ logOnce(`${what}\u0000${message}`, `${what} failed: ${message} (logged once; the notifier keeps polling)`);
+ return fallback;
+ }
+ };
+ const decisions: NotifierDecision[] = [];
+ const decide = (source: string, decision: string, extra: { waitMs?: number; detail?: string } = {}) => {
+ decisions.push({ at: now(), source, decision, ...extra });
+ if (decisions.length > DECISIONS_CAP) decisions.splice(0, decisions.length - DECISIONS_CAP);
+ };
+
+ let enabled = false;
+ let excluded = new Set<string>();
+ let owner = false;
+ let fence: number | null = null;
+ let leased = false;
+ let stopped = false;
+ let flagReadAt = -Infinity;
+ let listedAt = -Infinity;
+ let markersAt = -Infinity;
+ let leaseAt = -Infinity;
+ let nudged = false;
+ let firstPass = true;
+ const sources = new Map<string, Rt>();
+ let skipped: SkippedSource[] = [];
+ const running = new Map<string, RunningJob>();
+ let fireTimer: unknown = null;
+ let fireAt = Infinity;
+ let nudgeTimer: unknown = null;
+ let inflight: Promise<void> | null = null;
+ let again = false;
+
+ const armFire = (ms: number) => {
+ if (stopped) return;
+ const at = now() + ms;
+ if (fireTimer !== null && fireAt <= at) return;
+ if (fireTimer !== null) clearTimer(fireTimer);
+ fireAt = at;
+ fireTimer = setTimer(() => { fireTimer = null; fireAt = Infinity; void tick(); }, ms + 20);
+ };
+ const nudge = () => {
+ if (stopped) return;
+ nudged = true;
+ 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;
+ if (patch.attempts !== undefined) rt.attempts = patch.attempts;
+ rt.nextRetryAt = patch.nextRetryInMs ? now() + patch.nextRetryInMs : 0;
+ await guard(`recording the notifier state of ${rt.sourceId}`, () => opts.store.writeState(rt.sourceId, patch), undefined);
+ };
+ const trace = (rt: Rt, event: Record<string, unknown>): string | null => {
+ try { return opts.trace?.(rt.sourceId, { at: new Date(now()).toISOString(), source_id: rt.sourceId, resident: opts.resident, head: rt.head, last_commit: rt.lastCommit, ...event }) ?? null; }
+ catch { return null; }
+ };
+
+ const refreshSources = async () => {
+ const listed = await guard('listing the sources this host syncs', opts.listSources, null);
+ if (!listed || stopped) return;
+ 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); }
+ 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;
+ }
+ }
+ for (const rt of sources.values()) rt.watched = enabled && !excluded.has(rt.sourceId);
+ for (const rt of sources.values()) {
+ if (stopped) return;
+ if (!rt.watched || forcePoll || !opts.watch) { if (!rt.watched) closeWatch(rt); continue; }
+ if (rt.watchClose) continue;
+ const close = await guard(`watching ${rt.root}`, async () => opts.watch!(rt, nudge), null);
+ if (close && stopped) { try { close(); } catch { /* best effort */ } return; }
+ rt.watchClose = close;
+ }
+ };
+
+ const ownership = async () => {
+ const r = await guard('claiming the notifier lease', () => opts.store.claimLease({ hostId: opts.hostId, ownerId, kind: opts.resident, pid, leaseMs }), undefined);
+ if (r === undefined) return;
+ if (r === null) { leased = false; if (!owner) { owner = true; log(`owner of this host's notifier (${opts.resident})`); } return; }
+ leased = true;
+ if (r.owner) {
+ if (!owner) log(`owner of this host's notifier (${opts.resident}, fence ${r.fence})`);
+ owner = true; fence = r.fence;
+ } else {
+ if (owner) log(`another resident took over the notifier (${r.holderKind ?? 'unknown'}); forwarding HEAD moves`);
+ owner = false; fence = null;
+ }
+ };
+
+ const observe = async (rt: Rt, heads: Map<string, string | null>) => {
+ if (!heads.has(rt.root)) heads.set(rt.root, await guard(`reading HEAD in ${rt.root}`, () => opts.revParse(rt.root), null));
+ const head = heads.get(rt.root) ?? null;
+ if (head && head !== rt.head) { rt.head = head; decide(rt.sourceId, 'head_moved', { detail: short(head) }); }
+ if (!owner) return;
+ const key = `${rt.head}|${mode(rt)}|${opts.hostId}|${opts.resident}|${pid}`;
+ if (key !== rt.coverageKey) {
+ rt.coverageKey = key;
+ await guard(`recording what the notifier sees of ${rt.sourceId}`, () => opts.store.writeCoverage(rt.sourceId,
+ { head: rt.head, mode: mode(rt), ownerHostId: opts.hostId, ownerKind: opts.resident, ownerPid: pid }), undefined);
+ }
+ };
+
+ 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 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 } });
+ decide(rt.sourceId, stalled ? 'stalled' : 'retry', { waitMs: wait, detail: code });
+ if (stalled) logOnce(`stalled\u0000${rt.sourceId}`, `${rt.sourceId}: notifier_stalled: no progress after ${attempts} attempts (last: ${code}: ${message}); retrying every ${Math.round(wait / 1000)} s. Run gbrain sync --source ${rt.sourceId} --no-pull to see the error${tracePath ? `; trace: ${tracePath}` : ''}`);
+ else logOnce(`fail\u0000${rt.sourceId}\u0000${code}\u0000${message}`, `${rt.sourceId}: ${code}: ${message}; the source stays due, retry in ${Math.round(wait / 1000)} s`);
+ armFire(wait);
+ };
+
+ const settle = async (job: RunningJob, st: JobStatus | null) => {
+ running.delete(job.sourceId);
+ const rt = sources.get(job.sourceId);
+ if (!rt) return;
+ const lastCommit = await guard(`reading the last synced commit of ${rt.sourceId}`, () => opts.lastCommit(rt.sourceId), rt.lastCommit);
+ rt.lastCommit = lastCommit;
+ const progressed = lastCommit !== job.lastCommit;
+ if (st?.state === 'done' && st.outcome === 'blocked') {
+ rt.blockedKey = markerKey(rt);
+ const tracePath = trace(rt, { event: 'blocked', reason: st.reason ?? null });
+ await transition(rt, { state: 'operator_blocked', reason: st.reason ?? 'blocked', firstDue: 'keep', progress: progressed,
+ error: { code: 'sync_blocked', message: `the sync stopped blocked (${st.reason ?? 'unknown'})`, tracePath } });
+ decide(rt.sourceId, 'operator_blocked', { detail: st.reason });
+ logOnce(`job-blocked\u0000${rt.sourceId}\u0000${st.reason ?? ''}`, `${rt.sourceId}: the sync stopped blocked (${st.reason ?? 'unknown'}); see gbrain sync status --source ${rt.sourceId} (retried when HEAD moves or a new request arrives)`);
+ return;
+ }
+ if (st?.state === 'done' && st.outcome === 'resumable') {
+ if (!progressed) return failure(rt, 'sync_resumable', `the sync stopped resumable (${st.reason ?? 'partial'}) without advancing`, false);
+ log(`${rt.sourceId}: the sync stopped resumable (${st.reason ?? 'partial'}); the commit is not yet searchable, resuming`);
+ await transition(rt, { state: 'due', firstDue: 'keep', attempts: 0, progress: true });
+ decide(rt.sourceId, 'resume');
+ armFire(quietMs);
+ return;
+ }
+ if (!st || st.state === 'error') {
+ return failure(rt, 'sync_failed', st?.error ?? 'the sync job disappeared', progressed);
+ }
+ rt.markers = await guard(`settling the wanted markers of ${rt.sourceId}`,
+ () => opts.store.settleMarkers(rt.sourceId, job.markers, { pulled: job.intent === 'pull', full: job.intent === 'full' }), rt.markers);
+ if (!due(rt)) {
+ await transition(rt, { state: 'idle', reason: null, firstDue: 'clear', attempts: 0, progress: progressed, error: null });
+ decide(rt.sourceId, 'converged', { detail: short(lastCommit) });
+ return;
+ }
+ await transition(rt, { state: 'due', firstDue: 'keep', attempts: 0, progress: progressed });
+ decide(rt.sourceId, 'follow_up', { detail: `head ${short(rt.head)} vs ${short(lastCommit)}${rt.markers.length ? `, ${rt.markers.length} marker(s)` : ''}` });
+ armFire(quietMs);
+ };
+
+ const schedule = async () => {
+ const t = now();
+ const candidates = [...sources.values()]
+ .filter(rt => !running.has(rt.sourceId) && due(rt))
+ .sort((a, b) => a.lastStartAt - b.lastStartAt || a.sourceId.localeCompare(b.sourceId));
+ for (const rt of candidates) {
+ if (stopped || !owner) return;
+ if (rt.state === 'idle') await transition(rt, { state: 'due', firstDue: 'keep' });
+ if (rt.state === 'operator_blocked') {
+ if (rt.blockedKey === markerKey(rt)) continue;
+ rt.blockedKey = null;
+ await transition(rt, { state: 'due', firstDue: 'keep', attempts: 0 });
+ }
+ if (rt.state === 'retry' && t < rt.nextRetryAt) { decide(rt.sourceId, 'defer_retry', { waitMs: rt.nextRetryAt - t }); continue; }
+ const sinceStart = t - rt.lastStartAt;
+ if (sinceStart < quietMs) { decide(rt.sourceId, 'defer_window', { waitMs: quietMs - sinceStart }); armFire(quietMs - sinceStart); continue; }
+ if (opts.quiet && !opts.quiet(rt)) { decide(rt.sourceId, 'defer_git_busy'); armFire(pollMs); continue; }
+ if (running.size >= cap) { decide(rt.sourceId, 'defer_cap'); return; }
+ const synced = await guard(`reading the last synced commit of ${rt.sourceId}`, () => opts.lastCommit(rt.sourceId), rt.lastCommit);
+ if (stopped) return;
+ rt.lastCommit = synced;
+ if (!due(rt)) {
+ await transition(rt, { state: 'idle', reason: null, firstDue: 'clear', attempts: 0, error: null });
+ decide(rt.sourceId, 'converged', { detail: 'covered by another run' });
+ continue;
+ }
+ if (opts.drainHeld && await guard(`reading the drain lease of ${rt.sourceId}`, () => opts.drainHeld!(rt.sourceId), true)) { decide(rt.sourceId, 'defer_drain_lease'); continue; }
+ if (opts.syncRunning && await opts.syncRunning()) { decide(rt.sourceId, 'defer_busy'); return; }
+ if (leased && fence !== null && !await guard('checking the notifier lease', () => opts.store.holdsLease(opts.hostId, ownerId, fence!), false)) {
+ owner = false; fence = null; decide(rt.sourceId, 'not_owner');
+ 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 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;
+ try { start = await opts.startSync(rt.sourceId, { intent, sliceSeconds: slice, first }); }
+ catch (error) { start = null; await failure(rt, 'start_failed', error instanceof Error ? error.message : String(error), false); continue; }
+ if ('busy' in start) { decide(rt.sourceId, 'defer_busy'); rt.lastStartAt = -Infinity; return; }
+ if ('refused' in start) { await failure(rt, 'start_refused', start.refused, false); continue; }
+ running.set(rt.sourceId, { id: start.jobId, sourceId: rt.sourceId, head: rt.head, lastCommit: rt.lastCommit, intent, markers });
+ await transition(rt, { state: 'running', firstDue: 'keep' });
+ decide(rt.sourceId, 'start', { detail: `${intent}${slice ? ` slice ${slice}s` : ''}` });
+ log(`${rt.sourceId}: ${intent === 'freshness' ? `HEAD moved to ${short(rt.head)} (last synced ${short(rt.lastCommit)})` : `a ${intent} request is pending`}; started ${rt.kind === 'classic' ? 'classic' : 'managed'} sync job ${start.jobId}`);
+ }
+ };
+
+ const step = async () => {
+ const t = now();
+ if (t - flagReadAt >= FLAG_EVERY_MS) {
+ flagReadAt = t;
+ const on = await guard('reading sync.on_commit', opts.readFlag, enabled);
+ const ex = opts.readExcluded ? await guard('reading sync.on_commit.sources', opts.readExcluded, [...excluded]) : [];
+ if (stopped) return;
+ excluded = new Set(ex);
+ if (on !== enabled) {
+ enabled = on;
+ listedAt = -Infinity;
+ log(on ? `enabled (poll ${pollMs} ms, quiet window ${quietMs} ms)` : 'disabled');
+ }
+ }
+ if (stopped) return;
+ if (t - leaseAt >= heartbeatMs) { leaseAt = t; await ownership(); }
+ if (t - listedAt >= LIST_EVERY_MS) { listedAt = t; await refreshSources(); }
+ if (stopped) return;
+ for (const rt of sources.values()) {
+ const w = enabled && !excluded.has(rt.sourceId);
+ if (w !== rt.watched) { rt.watched = w; if (!w) closeWatch(rt); else listedAt = -Infinity; }
+ }
+ const wasNudged = nudged;
+ nudged = false;
+ const heads = new Map<string, string | null>();
+ if (!owner) {
+ // A non-owner forwards a HEAD move it saw through its own watch; the owner drains the freshness marker.
+ if (!wasNudged) return;
+ for (const rt of sources.values()) {
+ if (stopped || !rt.watched) continue;
+ await observe(rt, heads);
+ if (rt.head && rt.head !== rt.lastCommit && rt.head !== rt.forwarded) {
+ rt.forwarded = rt.head;
+ await guard(`forwarding a HEAD move of ${rt.sourceId}`, () => opts.store.forward(rt.sourceId, rt.head!), undefined);
+ decide(rt.sourceId, 'forwarded', { detail: short(rt.head) });
+ }
+ }
+ return;
+ }
+ for (const rt of sources.values()) {
+ if (stopped) return;
+ if (rt.watched) await observe(rt, heads);
+ }
+ if (wasNudged || firstPass || t - markersAt >= MARKER_SCAN_MS) {
+ markersAt = t;
+ firstPass = false;
+ const ids = [...sources.keys()];
+ const markers = ids.length ? await guard('reading wanted markers', () => opts.store.dueMarkers(ids), null) : [];
+ if (markers) {
+ const jobIds = markers.flatMap(m => m.job_id === null ? [] : [m.job_id]);
+ const live = jobIds.length ? await guard('reading queued sync jobs', () => opts.store.liveJobs(jobIds), new Set<number>()) : new Set<number>();
+ // A managed source never pulls: its pull markers (a push webhook) wait for gbrain sources refresh, not for this loop.
+ for (const rt of sources.values()) rt.markers = markers.filter(m => m.source_id === rt.sourceId && (m.job_id === null || !live.has(m.job_id))
+ && !(m.intent === 'pull' && rt.kind === 'managed'));
+ }
+ }
+ for (const job of [...running.values()]) {
+ const st = opts.jobStatus(job.id);
+ if (st && st.state !== 'done' && st.state !== 'error') continue;
+ await settle(job, st);
+ }
+ if (stopped) return;
+ await schedule();
+ };
+
+ const tick = (): Promise<void> => {
+ if (stopped) return Promise.resolve();
+ if (inflight) { again = true; return inflight; }
+ inflight = (async () => {
+ do {
+ again = false;
+ try { await step(); } catch (error) { logOnce(`step\u0000${String(error)}`, `unexpected error: ${error instanceof Error ? error.message : String(error)}`); }
+ } while (again && !stopped);
+ })().finally(() => { inflight = null; });
+ return inflight;
+ };
+
+ const interval = (opts.setInterval ?? ((fn: () => void, ms: number) => { const h = setInterval(fn, ms); h.unref?.(); return h; }))(() => { void tick(); }, pollMs);
+ return {
+ 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 })) })) }),
+ stop: async () => {
+ if (!stopped) {
+ stopped = true;
+ (opts.clearInterval ?? ((h: unknown) => clearInterval(h as ReturnType<typeof setInterval>)))(interval);
+ if (fireTimer !== null) clearTimer(fireTimer);
+ if (nudgeTimer !== null) clearTimer(nudgeTimer);
+ 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);
+ closeAllWatches();
+ }
+ if (owner && leased) await guard('releasing the notifier lease', () => opts.store.releaseLease(opts.hostId, ownerId), undefined);
+ },
+ };
+}
diff --git a/src/core/notifier/detect.ts b/src/core/notifier/detect.ts
new file mode 100644
index 0000000000..0616fe6397
--- /dev/null
+++ b/src/core/notifier/detect.ts
@@ -0,0 +1,64 @@
+/**
+ * GBRA-133 PR 2a: how the commit notifier sees a checkout move (core in ../commit-notifier.ts).
+ *
+ * - `resolveGitDirs` resolves `--absolute-git-dir` and `--git-common-dir`, so a linked worktree watches both its own git
+ * dir (HEAD, logs/HEAD, index.lock, rebase state) and the shared one (refs/heads, packed-refs).
+ * - `watchGitDirs` registers a non-persistent fs.watch on the git dir, its logs/, the common dir and its refs/heads; an
+ * event only brings the next poll forward (the async rev-parse poll stays the source of truth). When no directory can
+ * be watched it returns null and the source runs in poll mode; `GBRAIN_NOTIFIER_DETECTION=poll` forces poll mode.
+ * - `gitQuiet` is the quiet predicate: no rebase, merge, cherry-pick, revert or sequencer state (the list
+ * git/commit-push.ts refuses on) and no index.lock, so a sync never starts in the middle of a multi-commit operation.
+ * Every git call runs with GIT_OPTIONAL_LOCKS=0 and never writes into the checkout.
+ */
+import { existsSync, watch as fsWatch } from 'node:fs';
+import { isAbsolute, join, resolve } from 'node:path';
+import { execFileBounded } from '../bounded-child-exec.ts';
+import { gitChildEnv } from '../git-env.ts';
+import { GIT_OPERATION_MARKERS } from '../git/commit-push.ts';
+
+export async function git(root: string, args: string[]): Promise<string> {
+ const r = await execFileBounded('git', ['-C', root, ...args], { timeout: 5_000, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }) });
+ if (r.error) throw new Error((r.stderr || r.error.message).trim().split('\n')[0] || 'git failed');
+ return r.stdout.trim();
+}
+
+export async function revParseHead(root: string): Promise<string> {
+ return git(root, ['rev-parse', '--verify', '-q', 'HEAD']);
+}
+
+export async function resolveGitDirs(root: string): Promise<{ gitDir: string; commonDir: string } | null> {
+ const out = await git(root, ['rev-parse', '--absolute-git-dir', '--git-common-dir']).catch(() => null);
+ if (!out) return null;
+ const [gitDir, common] = out.split('\n').map(line => line.trim());
+ if (!gitDir) return null;
+ const commonDir = !common ? gitDir : isAbsolute(common) ? common : resolve(root, common);
+ return { gitDir, commonDir };
+}
+
+/** The directories a commit, checkout, reset or ref update touches, deduplicated, existing ones only. */
+export function watchTargets(gitDir: string, commonDir: string | null): string[] {
+ const dirs = [gitDir, join(gitDir, 'logs')];
+ if (commonDir) dirs.push(commonDir, join(commonDir, 'logs'), join(commonDir, 'refs', 'heads'));
+ return [...new Set(dirs)].filter(dir => existsSync(dir));
+}
+
+export type WatchFn = (dirs: string[], onChange: () => void) => (() => void) | null;
+
+export const watchGitDirs: WatchFn = (dirs, onChange) => {
+ const closers: Array<() => void> = [];
+ for (const dir of dirs) {
+ try {
+ const w = fsWatch(dir, { persistent: false }, () => onChange());
+ w.on('error', () => { try { w.close(); } catch { /* already closed */ } });
+ closers.push(() => w.close());
+ } catch { /* this directory stays poll-only */ }
+ }
+ return closers.length ? () => { for (const close of closers) { try { close(); } catch { /* already closed */ } } } : null;
+};
+
+/** The quiet predicate: true when no multi-step git operation or index write is in progress in this worktree. */
+export function gitQuiet(gitDir: string | null): boolean {
+ if (!gitDir) return true;
+ if (existsSync(join(gitDir, 'index.lock'))) return false;
+ return !GIT_OPERATION_MARKERS.some(marker => existsSync(join(gitDir, marker)));
+}
diff --git a/src/core/notifier/resident.ts b/src/core/notifier/resident.ts
new file mode 100644
index 0000000000..c3c65fbb60
--- /dev/null
+++ b/src/core/notifier/resident.ts
@@ -0,0 +1,200 @@
+/**
+ * GBRA-133 PR 2a: the commit notifier inside a resident process (serve stdio and http, `gbrain jobs work`, the
+ * autopilot daemon). Supplies the production seams of ../commit-notifier.ts:
+ * - the SQL store (store.ts) with the host lease on Postgres and none on PGLite (the lock holder owns);
+ * - the sources this host syncs: managed sources whose worktree it owns, classic sources it last synced
+ * (syncer_host_id) or that `GBRAIN_NOTIFIER_CLASSIC_SOURCES` binds here; every other source is skipped with a reason;
+ * - starts through the in-process delegated sync runner (serve-sync-runner.ts) as this host's `cli` writer, one job
+ * at a time, never pulling unless a pull request (marker) asked for it;
+ * - a per-source trace file (`<gbrain home>/notifier/<source>.jsonl`, bounded) named by sync status.
+ * One notifier per process: `nudgeResidentNotifier` (the IPC sync_nudge handler, the serve runner) reaches it.
+ */
+import { randomUUID } from 'node:crypto';
+import { appendFileSync, mkdirSync, statSync, writeFileSync, readFileSync } from 'node:fs';
+import { dirname } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { gbrainPath } from '../config.ts';
+import { SYNC_ON_COMMIT_KEY } from '../sync-config-keys.ts';
+import { localHostId } from '../persistence/identity.ts';
+import {
+ notifierDisabledByEnv, parseExcludedSources, parseOnCommit, startCommitNotifier,
+ type CommitNotifier, type CommitNotifierOptions, type NotifierSource, type NotifierStore, type ResidentKind, type SkippedSource,
+} from '../commit-notifier.ts';
+import {
+ claimLease, holdsLease, readDueMarkers, readNotifierSources, releaseLease, settleMarkers, upsertMarker, writeCoverage, writeState, pruneSatisfiedMarkers,
+} from './store.ts';
+import { gitQuiet, resolveGitDirs, revParseHead, watchGitDirs, watchTargets } from './detect.ts';
+
+/** Per-source opt-out: source ids whose HEAD the notifier does not watch (markers still drain). */
+export const SYNC_ON_COMMIT_SOURCES_KEY = 'sync.on_commit.sources';
+const TRACE_MAX_BYTES = 256 * 1024;
+
+let active: { notifier: CommitNotifier; resident: ResidentKind } | null = null;
+
+/** The notifier running in this process, if any (the IPC handler and the serve runner nudge it). */
+export function residentNotifier(): { notifier: CommitNotifier; resident: ResidentKind } | null { return active; }
+export function nudgeResidentNotifier(): boolean { if (!active) return false; active.notifier.nudge(); return true; }
+
+export function sqlNotifierStore(engine: BrainEngine): NotifierStore {
+ return {
+ claimLease: async (l) => {
+ if (engine.kind === 'pglite') return null;
+ const r = await claimLease(engine, l);
+ return r.owner ? r : { owner: false, holderKind: r.holder?.resident_kind ?? null };
+ },
+ holdsLease: (hostId, ownerId, fence) => holdsLease(engine, hostId, ownerId, fence),
+ releaseLease: (hostId, ownerId) => releaseLease(engine, hostId, ownerId),
+ dueMarkers: async (ids) => { await pruneSatisfiedMarkers(engine, ids); return readDueMarkers(engine, ids); },
+ liveJobs: async (ids) => new Set((await engine.executeRaw<{ id: unknown }>(
+ "SELECT id FROM minion_jobs WHERE id = ANY($1::bigint[]) AND status IN ('waiting','active','delayed','waiting-children','paused')", [ids])).map(r => Number(r.id))),
+ forward: async (sourceId, head) => { await upsertMarker(engine, { sourceId, intent: 'freshness', wantedHead: head, requestedBy: 'notifier' }); },
+ settleMarkers: (sourceId, read, run) => settleMarkers(engine, sourceId, read, run),
+ readStates: (ids) => readNotifierSources(engine, ids),
+ writeState: (sourceId, patch) => writeState(engine, sourceId, patch),
+ writeCoverage: (sourceId, c) => writeCoverage(engine, sourceId, c),
+ };
+}
+
+/** Source ids `GBRAIN_NOTIFIER_CLASSIC_SOURCES` binds to this host (classic sources this host syncs without a recorded run). */
+export function classicBinding(env: Record<string, string | undefined> = process.env): Set<string> {
+ return new Set(parseExcludedSources(env.GBRAIN_NOTIFIER_CLASSIC_SOURCES));
+}
+
+/** The sources this host's notifier syncs, and the ones it skips with the reason. */
+export async function listHostSources(engine: BrainEngine, hostId: string, env: Record<string, string | undefined> = process.env): Promise<{ sources: NotifierSource[]; skipped: SkippedSource[] }> {
+ const { readManagedMode } = await import('../persistence/managed-mode.ts');
+ const managed = await readManagedMode(engine).catch(() => false);
+ const rows = await engine.executeRaw<{ id: string; local_path: string | null; last_commit: string | null; bound: boolean; owner: string | null; root: string | null; syncer: string | null }>(
+ `SELECT s.id, s.local_path, s.last_commit, (b.source_id IS NOT NULL) AS bound, w.owner_host_id::text AS owner, h.local_path AS root, n.syncer_host_id AS syncer
+ FROM sources s
+ LEFT JOIN persistence_source_bindings b ON b.source_id = s.id AND b.source_incarnation = s.incarnation
+ LEFT JOIN persistence_worktrees w ON w.id = b.worktree_id
+ LEFT JOIN persistence_host_bindings h ON h.worktree_id = w.id AND h.host_id = w.owner_host_id
+ LEFT JOIN sync_notifier_sources n ON n.source_id = s.id
+ WHERE NOT s.archived ORDER BY s.id`);
+ const bind = classicBinding(env);
+ const sources: NotifierSource[] = [];
+ const skipped: SkippedSource[] = [];
+ const dirs = new Map<string, Awaited<ReturnType<typeof resolveGitDirs>>>();
+ for (const row of rows) {
+ let root: string | null;
+ let kind: 'managed' | 'classic';
+ if (managed && (row.bound === true || (row.bound as unknown) === 't')) {
+ kind = 'managed';
+ if (row.owner !== hostId) { skipped.push({ sourceId: row.id, reason: `its managed worktree is owned by host ${String(row.owner ?? 'none').slice(0, 8)}; that host's resident syncs it` }); continue; }
+ root = row.root;
+ } else if (managed) {
+ skipped.push({ sourceId: row.id, reason: 'not bound to a managed worktree (gbrain sources writer status)' });
+ continue;
+ } else {
+ kind = 'classic';
+ root = row.local_path;
+ if (!bind.has(row.id) && row.syncer !== hostId) {
+ skipped.push({ sourceId: row.id, reason: row.syncer
+ ? `classic source last synced on host ${row.syncer.slice(0, 8)}; its resident there watches it (or bind it here with GBRAIN_NOTIFIER_CLASSIC_SOURCES=${row.id})`
+ : `classic source with no recorded syncer host; run gbrain sync --source ${row.id} once on the host that syncs it, or set GBRAIN_NOTIFIER_CLASSIC_SOURCES=${row.id}` });
+ continue;
+ }
+ }
+ if (!root) { skipped.push({ sourceId: row.id, reason: 'no local checkout path' }); continue; }
+ if (!dirs.has(root)) dirs.set(root, await resolveGitDirs(root));
+ const d = dirs.get(root) ?? null;
+ if (!d) { skipped.push({ sourceId: row.id, reason: `${root} is not a git checkout on this host` }); continue; }
+ sources.push({ sourceId: row.id, root, gitDir: d.gitDir, commonDir: d.commonDir, lastCommit: row.last_commit, kind });
+ }
+ return { sources, skipped };
+}
+
+/** Appends one JSON line to the source's trace file (truncated to its newer half past TRACE_MAX_BYTES); returns the path. */
+export function appendTrace(sourceId: string, event: Record<string, unknown>): string {
+ const path = gbrainPath('notifier', `${sourceId.replace(/[^A-Za-z0-9._-]/g, '_')}.jsonl`);
+ mkdirSync(dirname(path), { recursive: true });
+ try {
+ if (statSync(path).size > TRACE_MAX_BYTES) {
+ const text = readFileSync(path, 'utf8');
+ writeFileSync(path, text.slice(text.indexOf('\n', Math.floor(text.length / 2)) + 1));
+ }
+ } catch { /* new file */ }
+ appendFileSync(path, JSON.stringify(event) + '\n');
+ return path;
+}
+
+/** The production start: the in-process delegated runner, as this host's cli writer, never pulling unless asked. */
+export function runnerStart(engine: BrainEngine): Pick<CommitNotifierOptions, 'startSync' | 'jobStatus' | 'syncRunning' | 'drainHeld'> {
+ let runner: typeof import('../serve-sync-runner.ts') | null = null;
+ const load = async () => runner ??= await import('../serve-sync-runner.ts');
+ return {
+ startSync: async (sourceId, req) => {
+ const r = await load();
+ const { registerLocalWriter } = await import('../persistence/identity.ts');
+ const local = await registerLocalWriter(engine, 'cli');
+ const { resolveSyncHardDeadline } = await import('../sync-reconcile.ts');
+ const deadline = resolveSyncHardDeadline([], { isTty: false, env: process.env });
+ const hard = deadline ? Math.max(1, Math.round(deadline.deadlineMs / 1000)) : 3600;
+ const timeoutSeconds = req.sliceSeconds ? Math.min(hard, Math.max(1, Math.round(req.sliceSeconds))) : hard;
+ const start = await r.startDelegatedSync(engine, { sourceId, noPull: req.intent !== 'pull', ...(req.intent === 'full' ? { full: true } : {}), timeoutSeconds, origin: 'background' },
+ `on-commit-${randomUUID()}`, { registration: { id: local.id, credential: local.credential, lane: 'cli' } });
+ if (start.ok && start.jobId) return { jobId: start.jobId };
+ if (start.error === 'busy' || start.error === 'shutting_down') return { busy: true };
+ return { refused: String(start.refusal?.message ?? start.error ?? 'refused') };
+ },
+ jobStatus: (jobId) => {
+ const s = runner?.getDelegatedSyncStatus(jobId);
+ if (!s || !s.ok || !s.state) return null;
+ return { state: s.state, ...(s.drain ? { outcome: s.drain.outcome, ...(s.drain.stop_reason ? { reason: s.drain.stop_reason } : {}) } : {}), ...(s.jobError ? { error: s.jobError } : {}) };
+ },
+ syncRunning: async () => (await load()).isDelegatedSyncRunning(),
+ drainHeld: async (sourceId) => (await (await import('../persistence/sync-lease.ts')).readDrainHolder(engine, sourceId)) !== null,
+ };
+}
+
+export type ResidentNotifierOptions = Partial<Omit<CommitNotifierOptions, 'resident' | 'log'>> & { resident: ResidentKind; log: (line: string) => void };
+
+/** The production defaults for every seam the caller did not inject. */
+export function residentNotifierOptions(engine: BrainEngine, opts: ResidentNotifierOptions): CommitNotifierOptions {
+ const env = opts.env ?? process.env;
+ // Host identity: the persistence host id (minted on first use, as a managed claim or a recorded classic sync does).
+ const hostId = opts.hostId ?? localHostId();
+ const defaults: Omit<CommitNotifierOptions, 'resident' | 'log' | 'hostId'> = {
+ store: sqlNotifierStore(engine),
+ maxConcurrent: 1,
+ firstSliceSeconds: 30,
+ sliceSeconds: 120,
+ readFlag: async () => parseOnCommit(await engine.getConfig(SYNC_ON_COMMIT_KEY)),
+ readExcluded: async () => parseExcludedSources(await engine.getConfig(SYNC_ON_COMMIT_SOURCES_KEY)),
+ listSources: () => listHostSources(engine, hostId, env),
+ lastCommit: async (sourceId) => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]))[0]?.last_commit ?? null,
+ revParse: revParseHead,
+ quiet: (s) => gitQuiet(s.gitDir),
+ watch: (s, onChange) => s.gitDir ? watchGitDirs(watchTargets(s.gitDir, s.commonDir ?? null), onChange) : null,
+ trace: appendTrace,
+ ...runnerStart(engine),
+ };
+ return { ...defaults, ...Object.fromEntries(Object.entries(opts).filter(([, v]) => v !== undefined)), hostId } as CommitNotifierOptions;
+}
+
+/**
+ * Starts this process's notifier, or returns null when GBRAIN_NOTIFIER=0 (or --no-notifier) 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.
+ */
+export function startResidentNotifier(engine: BrainEngine, opts: ResidentNotifierOptions): CommitNotifier | null {
+ if (notifierDisabledByEnv(opts.env ?? process.env)) { try { opts.log(`[notifier:${opts.resident}] off (GBRAIN_NOTIFIER=0); commits on this host are not synced by this process`); } catch { /* log only */ } return null; }
+ const notifier = startCommitNotifier(residentNotifierOptions(engine, opts));
+ const entry = { notifier, resident: opts.resident };
+ active = entry;
+ const stop = notifier.stop;
+ const wrapped: CommitNotifier = Object.assign(Object.create(Object.getPrototypeOf(notifier)), notifier, {
+ stop: async () => { if (active === entry) active = null; await stop(); },
+ });
+ Object.defineProperties(wrapped, {
+ enabled: { get: () => notifier.enabled }, owner: { get: () => notifier.owner }, decisions: { get: () => notifier.decisions },
+ });
+ entry.notifier = wrapped;
+ // Catch up at once on whatever moved while no resident ran (in the background).
+ (opts.setTimeout ?? ((fn: () => void, ms: number) => { const t = setTimeout(fn, ms); t.unref?.(); return t; }))(() => { void notifier.tick(); }, 0);
+ return wrapped;
+}
+
+/** Tests: forget the process notifier without stopping it (each test stops its own). */
+export function __resetResidentNotifierForTests(): void { active = null; }
diff --git a/src/core/notifier/store.ts b/src/core/notifier/store.ts
new file mode 100644
index 0000000000..bea3ce4db5
--- /dev/null
+++ b/src/core/notifier/store.ts
@@ -0,0 +1,278 @@
+/**
+ * GBRA-133 PR 2a: the commit notifier's durable state (migration v261).
+ *
+ * - Wanted markers (`sync_wanted_markers`): one row per source and intent class.
+ * `freshness` asks for the checkout's HEAD to become searchable (never pulls);
+ * `pull` asks for an upstream pull; `full` for a full walk. Explicit intents
+ * never coalesce into freshness: each class is its own row. Every upsert bumps
+ * `generation` and keeps `first_due_at`; a drainer deletes a row only WHERE
+ * generation equals the value it read, so a request that lands while the
+ * drainer's run is going survives it and starts one more run.
+ * - The notifier lease (`sync_notifier_leases`): one owner per host. A claim
+ * succeeds when the row is free, expired or already ours; a takeover bumps
+ * the fencing token, which the owner re-checks before each start.
+ * - Per-source notifier state and coverage (`sync_notifier_sources`): due /
+ * running / retry (next_retry_at) / operator_blocked, first_due_at kept until
+ * verified convergence, the last error with its trace file, the classic
+ * syncer host, and the observation the freshness notice reads.
+ *
+ * Callers on a brain whose schema predates v261 catch `missingTable` and treat
+ * it as "no markers, nothing monitored".
+ */
+import type { BrainEngine } from '../engine.ts';
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+
+export const MARKER_INTENTS = ['freshness', 'pull', 'full'] as const;
+export type MarkerIntent = typeof MARKER_INTENTS[number];
+export type MarkerRequester = 'sync_trigger' | 'webhook' | 'notifier' | 'delegated_sync' | 'lock_busy' | 'sync_nudge';
+
+export interface WantedMarker {
+ source_id: string;
+ intent: MarkerIntent;
+ wanted_head: string | null;
+ generation: number;
+ first_due_at: string;
+ updated_at: string;
+ requested_by: string;
+ job_id: number | null;
+}
+
+export type NotifierState = 'idle' | 'due' | 'running' | 'retry' | 'operator_blocked';
+export type DetectionMode = 'watch' | 'poll';
+
+export interface NotifierSourceRow {
+ source_id: string;
+ syncer_host_id: string | null;
+ state: NotifierState;
+ reason: string | null;
+ first_due_at: string | null;
+ attempts: number;
+ next_retry_at: string | null;
+ last_progress_at: string | null;
+ last_error_code: string | null;
+ last_error: string | null;
+ last_error_at: string | null;
+ trace_path: string | null;
+ observed_head: string | null;
+ observed_at: string | null;
+ detection_mode: DetectionMode | null;
+ owner_host_id: string | null;
+ owner_kind: string | null;
+ owner_pid: number | null;
+ owner_seen_at: string | null;
+}
+
+/** True when the error says a v261 table does not exist yet (a brain mid-upgrade). */
+export function missingTable(error: unknown): boolean {
+ const e = error as { code?: unknown; message?: unknown } | null;
+ return e?.code === '42P01' || /relation "sync_(wanted_markers|notifier_leases|notifier_sources)" does not exist/.test(String(e?.message ?? ''));
+}
+
+const iso = (v: unknown): string | null => v === null || v === undefined ? null : v instanceof Date ? v.toISOString() : new Date(String(v)).toISOString();
+const num = (v: unknown): number => typeof v === 'number' ? v : Number(v);
+const optNum = (v: unknown): number | null => v === null || v === undefined ? null : num(v);
+const optStr = (v: unknown): string | null => v === null || v === undefined ? null : String(v);
+
+function toMarker(row: Record<string, unknown>): WantedMarker {
+ return {
+ source_id: String(row.source_id), intent: row.intent as MarkerIntent, wanted_head: optStr(row.wanted_head),
+ generation: num(row.generation), first_due_at: iso(row.first_due_at)!, updated_at: iso(row.updated_at)!,
+ requested_by: String(row.requested_by), job_id: optNum(row.job_id),
+ };
+}
+
+function toSourceRow(row: Record<string, unknown>): NotifierSourceRow {
+ return {
+ source_id: String(row.source_id), syncer_host_id: optStr(row.syncer_host_id), state: row.state as NotifierState,
+ reason: optStr(row.reason), first_due_at: iso(row.first_due_at), attempts: num(row.attempts ?? 0),
+ next_retry_at: iso(row.next_retry_at), last_progress_at: iso(row.last_progress_at), last_error_code: optStr(row.last_error_code),
+ last_error: optStr(row.last_error), last_error_at: iso(row.last_error_at), trace_path: optStr(row.trace_path),
+ observed_head: optStr(row.observed_head), observed_at: iso(row.observed_at), detection_mode: row.detection_mode ? row.detection_mode as DetectionMode : null,
+ owner_host_id: optStr(row.owner_host_id), owner_kind: optStr(row.owner_kind), owner_pid: optNum(row.owner_pid), owner_seen_at: iso(row.owner_seen_at),
+ };
+}
+
+// ── Wanted markers ───────────────────────────────────────────────────────────
+
+/**
+ * Records (or re-records) what a source should reach. A re-record keeps first_due_at (unless the source was re-created)
+ * and bumps generation; `wanted_head` takes the newer value (null: whatever the checkout or upstream holds at run time).
+ */
+export async function upsertMarker(engine: Exec, m: { sourceId: string; intent: MarkerIntent; wantedHead: string | null; requestedBy: MarkerRequester; jobId?: number | null }): Promise<WantedMarker> {
+ const [row] = await engine.executeRaw<Record<string, unknown>>(
+ `INSERT INTO sync_wanted_markers (source_id, intent, source_incarnation, wanted_head, generation, first_due_at, updated_at, requested_by, job_id)
+ SELECT s.id, $2, s.incarnation::text, $3, 1, now(), now(), $4, $5 FROM sources s WHERE s.id = $1
+ ON CONFLICT (source_id, intent) DO UPDATE SET wanted_head = EXCLUDED.wanted_head, generation = sync_wanted_markers.generation + 1,
+ updated_at = now(), requested_by = EXCLUDED.requested_by, job_id = COALESCE(EXCLUDED.job_id, sync_wanted_markers.job_id),
+ first_due_at = CASE WHEN sync_wanted_markers.source_incarnation IS DISTINCT FROM EXCLUDED.source_incarnation THEN now() ELSE sync_wanted_markers.first_due_at END,
+ source_incarnation = EXCLUDED.source_incarnation
+ RETURNING *`,
+ [m.sourceId, m.intent, m.wantedHead, m.requestedBy, m.jobId ?? null]);
+ if (!row) throw new Error(`source ${m.sourceId} does not exist; no wanted marker recorded`);
+ return toMarker(row);
+}
+
+/** Names the queued job that will drain a marker, only while the marker is still the generation the submitter wrote. */
+export async function attachMarkerJob(engine: Exec, sourceId: string, intent: MarkerIntent, generation: number, jobId: number): Promise<void> {
+ await engine.executeRaw('UPDATE sync_wanted_markers SET job_id = $4 WHERE source_id = $1 AND intent = $2 AND generation = $3', [sourceId, intent, generation, jobId]);
+}
+
+export async function readMarkers(engine: Exec, sourceIds?: string[]): Promise<WantedMarker[]> {
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ 'SELECT * FROM sync_wanted_markers WHERE ($1::text[] IS NULL OR source_id = ANY($1::text[])) ORDER BY first_due_at, source_id, intent LIMIT 1000', [sourceIds ?? null]);
+ return rows.map(toMarker);
+}
+
+/**
+ * Markers that still ask for work: every pull/full marker, and a freshness marker whose wanted_head differs from the
+ * source's last_commit (a null wanted_head is due until a run drains it). No ancestry assumption.
+ */
+export async function readDueMarkers(engine: Exec, sourceIds?: string[]): Promise<WantedMarker[]> {
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT m.* FROM sync_wanted_markers m JOIN sources s ON s.id = m.source_id
+ WHERE ($1::text[] IS NULL OR m.source_id = ANY($1::text[]))
+ AND (m.intent <> 'freshness' OR m.wanted_head IS NULL OR m.wanted_head IS DISTINCT FROM s.last_commit)
+ ORDER BY m.first_due_at, m.source_id, m.intent LIMIT 1000`, [sourceIds ?? null]);
+ return rows.map(toMarker);
+}
+
+/**
+ * Deletes freshness and pull markers that name a head the source already reached (a CLI sync, a refresh or another
+ * resident got there first). State-based, so a newer request naming a newer head is never matched.
+ */
+export async function pruneSatisfiedMarkers(engine: Exec, sourceIds: string[]): Promise<void> {
+ await engine.executeRaw(
+ `DELETE FROM sync_wanted_markers m USING sources s WHERE m.source_id = s.id AND m.source_id = ANY($1::text[])
+ AND m.intent IN ('freshness','pull') AND m.wanted_head IS NOT NULL AND m.wanted_head = s.last_commit`, [sourceIds]);
+}
+
+/** Deletes the marker only when nobody re-recorded it since `generation` was read. */
+export async function clearMarker(engine: Exec, sourceId: string, intent: MarkerIntent, generation: number): Promise<boolean> {
+ const rows = await engine.executeRaw<{ source_id: string }>(
+ 'DELETE FROM sync_wanted_markers WHERE source_id = $1 AND intent = $2 AND generation = $3 RETURNING source_id', [sourceId, intent, generation]);
+ return rows.length > 0;
+}
+
+/**
+ * After a completed run: clears every marker of the source the run satisfied, generation-checked against `read` (the
+ * rows the drainer read before it started), and returns the markers that are still due afterwards.
+ * - freshness clears when last_commit equals its wanted_head (or the marker named no head);
+ * - pull clears when the run pulled (`pulled`), full when the run was a full walk (`full`).
+ */
+export async function settleMarkers(engine: Exec, sourceId: string, read: WantedMarker[], run: { pulled: boolean; full: boolean }): Promise<WantedMarker[]> {
+ for (const m of read) {
+ if (m.source_id !== sourceId) continue;
+ if (m.intent === 'pull' && !run.pulled) continue;
+ if (m.intent === 'full' && !run.full) continue;
+ if (m.intent === 'freshness') {
+ await engine.executeRaw(
+ `DELETE FROM sync_wanted_markers m USING sources s WHERE m.source_id = s.id AND m.source_id = $1 AND m.intent = 'freshness'
+ AND m.generation = $2 AND (m.wanted_head IS NULL OR m.wanted_head IS NOT DISTINCT FROM s.last_commit)`, [sourceId, m.generation]);
+ continue;
+ }
+ await clearMarker(engine, sourceId, m.intent, m.generation);
+ }
+ return readDueMarkers(engine, [sourceId]);
+}
+
+// ── Notifier lease ───────────────────────────────────────────────────────────
+
+export interface LeaseHolder { owner_id: string; fence: number; resident_kind: string; pid: number | null; expires_at: string; live: boolean }
+
+/** Claims or renews the host's notifier lease: the fencing token when this resident owns it, else the current holder. */
+export async function claimLease(engine: Exec, l: { hostId: string; ownerId: string; kind: string; pid: number; leaseMs: number }): Promise<{ owner: true; fence: number } | { owner: false; holder: LeaseHolder | null }> {
+ const [won] = await engine.executeRaw<{ fence: unknown }>(
+ `INSERT INTO sync_notifier_leases (host_id, owner_id, fence, resident_kind, pid, renewed_at, expires_at)
+ VALUES ($1, $2, 1, $3, $4, now(), now() + $5::int * interval '1 millisecond')
+ ON CONFLICT (host_id) DO UPDATE SET owner_id = EXCLUDED.owner_id, resident_kind = EXCLUDED.resident_kind, pid = EXCLUDED.pid,
+ fence = sync_notifier_leases.fence + CASE WHEN sync_notifier_leases.owner_id = EXCLUDED.owner_id THEN 0 ELSE 1 END,
+ renewed_at = now(), expires_at = EXCLUDED.expires_at
+ WHERE sync_notifier_leases.owner_id = EXCLUDED.owner_id OR sync_notifier_leases.expires_at <= now()
+ RETURNING fence`, [l.hostId, l.ownerId, l.kind, l.pid, Math.max(1, Math.round(l.leaseMs))]);
+ if (won) return { owner: true, fence: num(won.fence) };
+ return { owner: false, holder: await readLease(engine, l.hostId) };
+}
+
+export async function readLease(engine: Exec, hostId: string): Promise<LeaseHolder | null> {
+ const [row] = await engine.executeRaw<Record<string, unknown>>(
+ 'SELECT owner_id, fence, resident_kind, pid, expires_at, expires_at > now() AS live FROM sync_notifier_leases WHERE host_id = $1', [hostId]);
+ return row ? { owner_id: String(row.owner_id), fence: num(row.fence), resident_kind: String(row.resident_kind),
+ pid: optNum(row.pid), expires_at: iso(row.expires_at)!, live: row.live === true || row.live === 't' } : null;
+}
+
+/** The fencing check before a start: still the owner, with the token this resident claimed, and unexpired. */
+export async function holdsLease(engine: Exec, hostId: string, ownerId: string, fence: number): Promise<boolean> {
+ const rows = await engine.executeRaw<{ host_id: string }>(
+ 'SELECT host_id FROM sync_notifier_leases WHERE host_id = $1 AND owner_id = $2 AND fence = $3 AND expires_at > now()', [hostId, ownerId, fence]);
+ return rows.length > 0;
+}
+
+/** Releases the lease only while this resident still holds it, so a clean stop hands over at once. */
+export async function releaseLease(engine: Exec, hostId: string, ownerId: string): Promise<void> {
+ await engine.executeRaw('UPDATE sync_notifier_leases SET expires_at = now() WHERE host_id = $1 AND owner_id = $2', [hostId, ownerId]);
+}
+
+// ── Per-source state and coverage ────────────────────────────────────────────
+
+export async function readNotifierSources(engine: Exec, sourceIds?: string[]): Promise<NotifierSourceRow[]> {
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ 'SELECT * FROM sync_notifier_sources WHERE ($1::text[] IS NULL OR source_id = ANY($1::text[])) ORDER BY source_id', [sourceIds ?? null]);
+ return rows.map(toSourceRow);
+}
+
+export interface StatePatch {
+ state: NotifierState;
+ reason?: string | null;
+ /** 'keep' keeps first_due_at (setting it when null); 'clear' sets it NULL (verified convergence). */
+ firstDue: 'keep' | 'clear';
+ attempts?: number;
+ nextRetryInMs?: number | null;
+ progress?: boolean;
+ /** null clears the last error; omitted keeps it. */
+ error?: { code: string; message: string; tracePath: string | null } | null;
+}
+
+/** One write per transition, never per poll. */
+export async function writeState(engine: Exec, sourceId: string, p: StatePatch): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO sync_notifier_sources (source_id, source_incarnation, state, reason, first_due_at, attempts, next_retry_at, last_progress_at,
+ last_error_code, last_error, last_error_at, trace_path, updated_at)
+ SELECT s.id, s.incarnation::text, $2, $3, CASE WHEN $4::text = 'keep' THEN now() END, COALESCE($5::int, 0),
+ CASE WHEN $6::int IS NULL THEN NULL ELSE now() + $6::int * interval '1 millisecond' END, CASE WHEN $7::boolean THEN now() END,
+ $8::text, $9::text, CASE WHEN $8::text IS NULL THEN NULL ELSE now() END, $10::text, now()
+ FROM sources s WHERE s.id = $1
+ ON CONFLICT (source_id) DO UPDATE SET state = EXCLUDED.state, reason = EXCLUDED.reason,
+ first_due_at = CASE WHEN $4::text = 'clear' THEN NULL ELSE COALESCE(sync_notifier_sources.first_due_at, now()) END,
+ attempts = COALESCE($5::int, sync_notifier_sources.attempts), next_retry_at = EXCLUDED.next_retry_at,
+ last_progress_at = CASE WHEN $7::boolean THEN now() ELSE sync_notifier_sources.last_progress_at END,
+ last_error_code = CASE WHEN $11::boolean THEN EXCLUDED.last_error_code ELSE sync_notifier_sources.last_error_code END,
+ last_error = CASE WHEN $11::boolean THEN EXCLUDED.last_error ELSE sync_notifier_sources.last_error END,
+ last_error_at = CASE WHEN $11::boolean THEN EXCLUDED.last_error_at ELSE sync_notifier_sources.last_error_at END,
+ trace_path = CASE WHEN $11::boolean THEN EXCLUDED.trace_path ELSE sync_notifier_sources.trace_path END,
+ source_incarnation = EXCLUDED.source_incarnation, updated_at = now()`,
+ [sourceId, p.state, p.reason ?? null, p.firstDue, p.attempts ?? null, p.nextRetryInMs ?? null, p.progress === true,
+ p.error?.code ?? null, p.error?.message?.slice(0, 2000) ?? null, p.error?.tracePath ?? null, p.error !== undefined]);
+}
+
+export interface Coverage { head: string | null; mode: DetectionMode; ownerHostId: string; ownerKind: string; ownerPid: number }
+
+/** The coverage record, written when HEAD, mode or owner changed (the notifier compares before calling). */
+export async function writeCoverage(engine: Exec, sourceId: string, c: Coverage): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO sync_notifier_sources (source_id, source_incarnation, observed_head, observed_at, detection_mode, owner_host_id, owner_kind, owner_pid, owner_seen_at, updated_at)
+ SELECT s.id, s.incarnation::text, $2, now(), $3, $4, $5, $6, now(), now() FROM sources s WHERE s.id = $1
+ ON CONFLICT (source_id) DO UPDATE SET observed_head = EXCLUDED.observed_head, observed_at = now(), detection_mode = EXCLUDED.detection_mode,
+ owner_host_id = EXCLUDED.owner_host_id, owner_kind = EXCLUDED.owner_kind, owner_pid = EXCLUDED.owner_pid, owner_seen_at = now(),
+ source_incarnation = EXCLUDED.source_incarnation, updated_at = now()`,
+ [sourceId, c.head, c.mode, c.ownerHostId, c.ownerKind, c.ownerPid]);
+}
+
+/** Records the host that advanced a classic source's last_commit; a no-op write when it did not change. */
+export async function recordSyncerHost(engine: Exec, sourceId: string, hostId: string): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO sync_notifier_sources (source_id, source_incarnation, syncer_host_id, syncer_recorded_at, updated_at)
+ SELECT s.id, s.incarnation::text, $2, now(), now() FROM sources s WHERE s.id = $1
+ ON CONFLICT (source_id) DO UPDATE SET syncer_host_id = EXCLUDED.syncer_host_id, syncer_recorded_at = now(), updated_at = now()
+ WHERE sync_notifier_sources.syncer_host_id IS DISTINCT FROM EXCLUDED.syncer_host_id`, [sourceId, hostId]);
+}
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 47a722ef15..95d55d02c0 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -2553,6 +2553,52 @@ DO \$rls\$ BEGIN
END IF;
END \$rls\$;
+CREATE TABLE IF NOT EXISTS sync_wanted_markers (
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ intent TEXT NOT NULL CHECK (intent IN ('freshness','pull','full')),
+ source_incarnation TEXT,
+ wanted_head TEXT,
+ generation BIGINT NOT NULL DEFAULT 1,
+ first_due_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ requested_by TEXT NOT NULL,
+ job_id BIGINT,
+ PRIMARY KEY (source_id, intent)
+);
+CREATE TABLE IF NOT EXISTS sync_notifier_leases (
+ host_id TEXT PRIMARY KEY,
+ owner_id TEXT NOT NULL,
+ fence BIGINT NOT NULL DEFAULT 1,
+ resident_kind TEXT NOT NULL,
+ pid INTEGER,
+ renewed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ expires_at TIMESTAMPTZ NOT NULL
+);
+CREATE TABLE IF NOT EXISTS sync_notifier_sources (
+ source_id TEXT PRIMARY KEY REFERENCES sources(id) ON DELETE CASCADE,
+ source_incarnation TEXT,
+ syncer_host_id TEXT,
+ syncer_recorded_at TIMESTAMPTZ,
+ state TEXT NOT NULL DEFAULT 'idle' CHECK (state IN ('idle','due','running','retry','operator_blocked')),
+ reason TEXT,
+ first_due_at TIMESTAMPTZ,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_retry_at TIMESTAMPTZ,
+ last_progress_at TIMESTAMPTZ,
+ last_error_code TEXT,
+ last_error TEXT,
+ last_error_at TIMESTAMPTZ,
+ trace_path TEXT,
+ observed_head TEXT,
+ observed_at TIMESTAMPTZ,
+ detection_mode TEXT CHECK (detection_mode IN ('watch','poll')),
+ owner_host_id TEXT,
+ owner_kind TEXT,
+ owner_pid INTEGER,
+ owner_seen_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
`;
export function getPGLiteSchema(
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index ded1541645..80c25099fd 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -3327,4 +3327,53 @@ DO \$rls\$ BEGIN
END IF;
END \$rls\$;
-- END GENERATED from src/core/belief/schema.ts (BELIEF_LEDGER_SCHEMA_SQL)
+
+-- GBRA-133 PR 2a (migration v261): commit notifier wanted markers, the
+-- per-host notifier lease and per-source notifier state + coverage record
+-- (src/core/notifier/store.ts).
+CREATE TABLE IF NOT EXISTS sync_wanted_markers (
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ intent TEXT NOT NULL CHECK (intent IN ('freshness','pull','full')),
+ source_incarnation TEXT,
+ wanted_head TEXT,
+ generation BIGINT NOT NULL DEFAULT 1,
+ first_due_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ requested_by TEXT NOT NULL,
+ job_id BIGINT,
+ PRIMARY KEY (source_id, intent)
+);
+CREATE TABLE IF NOT EXISTS sync_notifier_leases (
+ host_id TEXT PRIMARY KEY,
+ owner_id TEXT NOT NULL,
+ fence BIGINT NOT NULL DEFAULT 1,
+ resident_kind TEXT NOT NULL,
+ pid INTEGER,
+ renewed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ expires_at TIMESTAMPTZ NOT NULL
+);
+CREATE TABLE IF NOT EXISTS sync_notifier_sources (
+ source_id TEXT PRIMARY KEY REFERENCES sources(id) ON DELETE CASCADE,
+ source_incarnation TEXT,
+ syncer_host_id TEXT,
+ syncer_recorded_at TIMESTAMPTZ,
+ state TEXT NOT NULL DEFAULT 'idle' CHECK (state IN ('idle','due','running','retry','operator_blocked')),
+ reason TEXT,
+ first_due_at TIMESTAMPTZ,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_retry_at TIMESTAMPTZ,
+ last_progress_at TIMESTAMPTZ,
+ last_error_code TEXT,
+ last_error TEXT,
+ last_error_at TIMESTAMPTZ,
+ trace_path TEXT,
+ observed_head TEXT,
+ observed_at TIMESTAMPTZ,
+ detection_mode TEXT CHECK (detection_mode IN ('watch','poll')),
+ owner_host_id TEXT,
+ owner_kind TEXT,
+ owner_pid INTEGER,
+ owner_seen_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
`;
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 52cfaf76dd..e10967188f 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 260;
+export const LATEST_SCHEMA_VERSION = 261;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index c5a418daa8..b33ab64ade 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -261,6 +261,7 @@ import { v257 } from './v257-pages-live-origin-key.ts';
import { v258 } from './v258-pages-links-extract-failure.ts';
import { v259 } from './v259-ingest-log-marked-index.ts';
import { v260 } from './v260-segmented-page-size-index.ts';
+import { v261 } from './v261-commit-notifier.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -520,4 +521,5 @@ export const MIGRATIONS: Migration[] = [
v258,
v259,
v260,
+ v261,
];
diff --git a/src/core/schema-migrations/v261-commit-notifier.ts b/src/core/schema-migrations/v261-commit-notifier.ts
new file mode 100644
index 0000000000..75b5fad6f1
--- /dev/null
+++ b/src/core/schema-migrations/v261-commit-notifier.ts
@@ -0,0 +1,72 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); the fresh-install
+// copy in src/schema.sql carries the same tables.
+//
+// GBRA-133 PR 2a (commit triggers that never drop a commit; core in
+// src/core/commit-notifier.ts and src/core/notifier/store.ts):
+// - sync_wanted_markers: one row per source and intent class (freshness, pull,
+// full). A submitter (gbrain sync trigger, the GitHub webhook, a busy
+// delegated sync, a resident forwarding a HEAD move) upserts it and bumps
+// generation; a drainer deletes it only WHERE generation equals the value it
+// read, so a newer request survives the run that was already going.
+// - sync_notifier_leases: the one notifier owner per host (conditional renew,
+// a fencing token bumped on every takeover, expiry after one missed lease).
+// - sync_notifier_sources: per-source notifier state (due, running, retry with
+// next_retry_at, operator_blocked), first_due_at kept until verified
+// convergence, the last error and its trace file, the classic syncer host,
+// and the coverage record the freshness notice reads (observed HEAD, time,
+// detection mode, owner liveness). Written on change, never on every poll.
+// DDL only, nothing to backfill: an absent row reads as "not monitored".
+export const v261: Migration = {
+ version: 261,
+ name: 'commit_notifier',
+ idempotent: true,
+ sql: `
+ CREATE TABLE IF NOT EXISTS sync_wanted_markers (
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ intent TEXT NOT NULL CHECK (intent IN ('freshness','pull','full')),
+ source_incarnation TEXT,
+ wanted_head TEXT,
+ generation BIGINT NOT NULL DEFAULT 1,
+ first_due_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ requested_by TEXT NOT NULL,
+ job_id BIGINT,
+ PRIMARY KEY (source_id, intent)
+ );
+ CREATE TABLE IF NOT EXISTS sync_notifier_leases (
+ host_id TEXT PRIMARY KEY,
+ owner_id TEXT NOT NULL,
+ fence BIGINT NOT NULL DEFAULT 1,
+ resident_kind TEXT NOT NULL,
+ pid INTEGER,
+ renewed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ expires_at TIMESTAMPTZ NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS sync_notifier_sources (
+ source_id TEXT PRIMARY KEY REFERENCES sources(id) ON DELETE CASCADE,
+ source_incarnation TEXT,
+ syncer_host_id TEXT,
+ syncer_recorded_at TIMESTAMPTZ,
+ state TEXT NOT NULL DEFAULT 'idle' CHECK (state IN ('idle','due','running','retry','operator_blocked')),
+ reason TEXT,
+ first_due_at TIMESTAMPTZ,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_retry_at TIMESTAMPTZ,
+ last_progress_at TIMESTAMPTZ,
+ last_error_code TEXT,
+ last_error TEXT,
+ last_error_at TIMESTAMPTZ,
+ trace_path TEXT,
+ observed_head TEXT,
+ observed_at TIMESTAMPTZ,
+ detection_mode TEXT CHECK (detection_mode IN ('watch','poll')),
+ owner_host_id TEXT,
+ owner_kind TEXT,
+ owner_pid INTEGER,
+ owner_seen_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ );
+ `,
+};
diff --git a/src/core/serve-head-watcher.ts b/src/core/serve-head-watcher.ts
index 27d6ba9145..39a20c4252 100644
--- a/src/core/serve-head-watcher.ts
+++ b/src/core/serve-head-watcher.ts
@@ -1,327 +1,76 @@
/**
- * #6858 ask 6, option C (Garry's "rec", via GBRA-108): on-commit sync inside the resident serve.
+ * #6858 ask 6 (option C), reworked by GBRA-133 PR 2a: the serve's adapter over the commit notifier
+ * (core in ./commit-notifier.ts, production seams in ./notifier/resident.ts).
*
- * With `sync.on_commit` true, `gbrain serve` polls `git rev-parse HEAD` in the checkout of every managed source this host
- * owns (its worktree's `owner_host_id` is this host) every `GBRAIN_SERVE_HEAD_POLL_MS` (default 3 s, 1 to 30 s), plus a
- * best-effort `fs.watch` on the git dir (and its `logs/`) that only brings the next poll forward; the poll is the source
- * of truth. A HEAD move arms a trailing debounce (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`, default 3 s, 0 to 60 s); when HEAD
- * has been still that long and differs from what the source last synced, the watcher starts ONE managed sync through
- * the unchanged `startDelegatedSync` (`noPull`, background origin, the sync hard deadline) as this host's `cli` writer,
- * the registration a `gbrain sync` on this host uses.
- *
- * Single flight: while any delegated sync runs, or another process holds the source's drain lease, nothing starts and
- * the move stays pending; when the running sync ends the pending move starts one more sync, and a move during the
- * watcher's own sync starts exactly one follow-up once it ends (HEAD then differs from the HEAD that sync started at),
- * so a commit is never left for cron. A sync that ends resumable (deadline or another partial stop) is "not yet
- * searchable", not a failure: the watcher resumes it after the debounce, up to MAX_RESUMES times in a row, then leaves
- * it to the next HEAD move or scheduled sync. A refused or failed start is logged and not retried until HEAD moves.
- *
- * Cost when idle: one git call per checkout per poll and no database read except the flag (re-read every 30 s, so
- * flipping `sync.on_commit` needs no restart) and the source list (every 60 s while on). With the flag off nothing
- * else runs: no git call, no sync. It never writes into the checkout or `.git` (`GIT_OPTIONAL_LOCKS=0`). Every error
- * is caught and logged once per distinct message; the loop never throws into serve. serve.ts starts it beside the
- * movement watch (installResidentTickers) and awaits its stop before shutdownDelegatedSync; serve-http.ts (runServeHttp)
- * starts it beside the movement watch and awaits its stop on the same shutdown path, before the engine disconnects.
- * `stop()` re-checks after every await, so discovery or a git read in flight when it lands installs nothing and runs
- * no further git or database call; its promise settles once that step has (bounded by STOP_SETTLE_MS).
+ * `gbrain serve` (stdio, serve.ts installResidentTickers) and `gbrain serve --http` (serve-http.ts runServeHttp) start
+ * the host's notifier through `startServeHeadWatcher` and await `stop()` before the delegated sync runner shuts down
+ * and the engine disconnects. With `sync.on_commit` on it watches every source this host syncs (managed sources whose
+ * worktree it owns and, since 2a, classic sources it last synced), starts a sync on the leading edge of a quiet HEAD
+ * move (`GBRAIN_NOTIFIER_QUIET_MS`, alias GBRAIN_SERVE_HEAD_DEBOUNCE_MS, default 400 ms, replaces the fixed 3 s
+ * debounce) and keeps a source due across failed or refused starts, error and blocked runs and resumable stops (the
+ * lost wake of #6858's first cut). Wanted markers (sync trigger, sync_nudge, the webhook) drain with the flag off too.
+ * The option names below are the seams the serve tests drive; every one defaults to production.
*/
-import { randomUUID } from 'node:crypto';
-import { existsSync, watch as fsWatch } from 'node:fs';
-import { join } from 'node:path';
import type { BrainEngine } from './engine.ts';
-import { execFileBounded } from './bounded-child-exec.ts';
-import { gitChildEnv } from './git-env.ts';
-import { SYNC_ON_COMMIT_KEY } from './sync-config-keys.ts';
-
-export const HEAD_POLL_MS_DEFAULT = 3_000;
-export const HEAD_DEBOUNCE_MS_DEFAULT = 3_000;
-export const HEAD_FLAG_EVERY_MS = 30_000;
-export const HEAD_LIST_EVERY_MS = 60_000;
-/** Resumable syncs in a row the watcher resumes on its own before it leaves the source to the next move or cron. */
-export const MAX_RESUMES = 3;
+import {
+ FLAG_EVERY_MS, LIST_EVERY_MS, POLL_MS_DEFAULT, QUIET_MS_DEFAULT, STOP_SETTLE_MS as NOTIFIER_STOP_SETTLE_MS,
+ type CommitNotifier, type JobStatus, type NotifierStore, type StartRequest, type StartResult,
+} from './commit-notifier.ts';
+import { startResidentNotifier } from './notifier/resident.ts';
+
+export const HEAD_POLL_MS_DEFAULT = POLL_MS_DEFAULT;
+export const HEAD_DEBOUNCE_MS_DEFAULT = QUIET_MS_DEFAULT;
+export const HEAD_FLAG_EVERY_MS = FLAG_EVERY_MS;
+export const HEAD_LIST_EVERY_MS = LIST_EVERY_MS;
/** How long `stop()` waits for an in-flight step before it resolves anyway (inside the stdio serve's 5 s cleanup deadline). */
-export const STOP_SETTLE_MS = 3_000;
-const NUDGE_MS = 250;
-const LOG_ONCE_CAP = 200;
+export const STOP_SETTLE_MS = NOTIFIER_STOP_SETTLE_MS;
-export interface WatchedSource { sourceId: string; root: string; gitDir: string | null; lastCommit: string | null }
-export type OnCommitStart = { jobId: string } | { busy: true } | { refused: string };
-export interface OnCommitJobStatus { state: 'running' | 'aborting' | 'done' | 'error'; outcome?: 'synced' | 'resumable' | 'blocked'; reason?: string; error?: string }
+export interface WatchedSource { sourceId: string; root: string; gitDir: string | null; commonDir?: string | null; lastCommit: string | null; kind?: 'managed' | 'classic' }
+export type OnCommitStart = StartResult;
+export type OnCommitJobStatus = JobStatus;
export interface ServeHeadWatcherOptions {
log: (line: string) => void;
+ resident?: 'serve' | 'serve-http';
pollMs?: number;
+ /** The trailing quiet window (GBRAIN_NOTIFIER_QUIET_MS); the name is kept from the debounce it replaced. */
debounceMs?: number;
+ heartbeatMs?: number;
env?: Record<string, string | undefined>;
now?: () => number;
setInterval?: (fn: () => void, ms: number) => unknown;
clearInterval?: (handle: unknown) => void;
setTimeout?: (fn: () => void, ms: number) => unknown;
clearTimeout?: (handle: unknown) => void;
+ hostId?: string;
+ store?: NotifierStore;
readFlag?: () => Promise<boolean>;
+ readExcluded?: () => Promise<string[]>;
listSources?: () => Promise<WatchedSource[]>;
/** The source's last synced commit (`sources.last_commit`), re-read right before a start. */
lastCommit?: (sourceId: string) => Promise<string | null>;
revParse?: (root: string) => Promise<string>;
+ quiet?: (source: WatchedSource) => boolean;
syncRunning?: () => boolean | Promise<boolean>;
drainHeld?: (sourceId: string) => Promise<boolean>;
- startSync?: (sourceId: string) => Promise<OnCommitStart>;
+ startSync?: (sourceId: string, req: StartRequest) => Promise<OnCommitStart>;
jobStatus?: (jobId: string) => OnCommitJobStatus | null;
watch?: (gitDir: string, onChange: () => void) => (() => void) | null;
}
-/** `stop()` stops polling at once and resolves when the in-flight step has settled (at most STOP_SETTLE_MS); await it before the engine disconnects. */
-export interface ServeHeadWatcher { tick(): Promise<void>; stop(): Promise<void>; readonly enabled: boolean }
-
-interface SourceState extends WatchedSource { head: string | null; movedAt: number | null; synced: string | null; resumes: number }
+/** `stop()` stops polling at once and resolves when the in-flight step has settled (at most STOP_SETTLE_MS). */
+export type ServeHeadWatcher = Pick<CommitNotifier, 'tick' | 'stop' | 'enabled' | 'nudge' | 'owner' | 'decisions' | 'snapshot'>;
-const truthy = (value: string | null | undefined) => typeof value === 'string' && /^(1|true|on|yes)$/i.test(value.trim());
-const bounded = (raw: string | undefined, fallback: number, min: number, max: number) => {
- const value = raw === undefined || raw.trim() === '' ? NaN : Number(raw);
- return Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : fallback;
-};
-const short = (sha: string | null) => sha ? sha.slice(0, 8) : 'none';
-
-async function git(root: string, args: string[]): Promise<string> {
- const r = await execFileBounded('git', ['-C', root, ...args], { timeout: 5_000, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }) });
- if (r.error) throw new Error((r.stderr || r.error.message).trim().split('\n')[0] || 'git failed');
- return r.stdout.trim();
-}
-
-function defaultDeps(engine: BrainEngine): Required<Pick<ServeHeadWatcherOptions, 'readFlag' | 'listSources' | 'lastCommit' | 'revParse' | 'syncRunning' | 'drainHeld' | 'startSync' | 'jobStatus' | 'watch'>> {
- let runner: typeof import('./serve-sync-runner.ts') | null = null;
- const loadRunner = async () => runner ??= await import('./serve-sync-runner.ts');
- return {
- readFlag: async () => truthy(await engine.getConfig(SYNC_ON_COMMIT_KEY)),
- listSources: async () => {
- const { readManagedMode } = await import('./persistence/managed-mode.ts');
- if (!await readManagedMode(engine)) return [];
- const { existingLocalHostId } = await import('./persistence/identity.ts');
- const host = existingLocalHostId();
- if (!host) return [];
- const rows = await engine.executeRaw<{ source_id: string; root: string; last_commit: string | null }>(`SELECT b.source_id, h.local_path AS root, s.last_commit
- FROM persistence_source_bindings b JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation AND NOT s.archived
- JOIN persistence_worktrees w ON w.id=b.worktree_id JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=w.owner_host_id
- WHERE w.owner_host_id::text=$1 ORDER BY b.source_id`, [host]);
- const gitDirs = new Map<string, string | null>();
- const out: WatchedSource[] = [];
- for (const row of rows) {
- if (!gitDirs.has(row.root)) gitDirs.set(row.root, await git(row.root, ['rev-parse', '--absolute-git-dir']).catch(() => null));
- out.push({ sourceId: row.source_id, root: row.root, gitDir: gitDirs.get(row.root) ?? null, lastCommit: row.last_commit });
- }
- return out;
- },
- lastCommit: async (sourceId) => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]))[0]?.last_commit ?? null,
- revParse: (root) => git(root, ['rev-parse', '--verify', '-q', 'HEAD']),
- syncRunning: async () => (await loadRunner()).isDelegatedSyncRunning(),
- drainHeld: async (sourceId) => (await (await import('./persistence/sync-lease.ts')).readDrainHolder(engine, sourceId)) !== null,
- startSync: async (sourceId) => {
- const r = await loadRunner();
- const { registerLocalWriter } = await import('./persistence/identity.ts');
- const local = await registerLocalWriter(engine, 'cli');
- const { resolveSyncHardDeadline } = await import('./sync-reconcile.ts');
- const deadline = resolveSyncHardDeadline([], { isTty: false, env: process.env });
- const timeoutSeconds = deadline ? Math.max(1, Math.round(deadline.deadlineMs / 1000)) : 3600;
- const start = await r.startDelegatedSync(engine, { sourceId, noPull: true, timeoutSeconds, origin: 'background' }, `on-commit-${randomUUID()}`,
- { registration: { id: local.id, credential: local.credential, lane: 'cli' } });
- if (start.ok && start.jobId) return { jobId: start.jobId };
- if (start.error === 'busy' || start.error === 'shutting_down') return { busy: true };
- return { refused: String(start.refusal?.message ?? start.error ?? 'refused') };
- },
- jobStatus: (jobId) => {
- const s = runner?.getDelegatedSyncStatus(jobId);
- if (!s || !s.ok || !s.state) return null;
- return { state: s.state, ...(s.drain ? { outcome: s.drain.outcome, ...(s.drain.stop_reason ? { reason: s.drain.stop_reason } : {}) } : {}), ...(s.jobError ? { error: s.jobError } : {}) };
- },
- watch: (gitDir, onChange) => {
- const closers: Array<() => void> = [];
- for (const dir of [gitDir, join(gitDir, 'logs')]) {
- if (!existsSync(dir)) continue;
- try {
- const w = fsWatch(dir, { persistent: false }, () => onChange());
- w.on('error', () => { try { w.close(); } catch { /* already closed */ } });
- closers.push(() => w.close());
- } catch { /* best effort: polling is the source of truth */ }
- }
- return closers.length ? () => { for (const close of closers) { try { close(); } catch { /* already closed */ } } } : null;
- },
- };
-}
+const INERT: ServeHeadWatcher = { tick: async () => {}, stop: async () => {}, nudge: () => {}, enabled: false, owner: false, decisions: [],
+ snapshot: () => ({ resident: 'serve', owner: false, enabled: false, sources: [], skipped: [] }) };
export function startServeHeadWatcher(engine: BrainEngine, opts: ServeHeadWatcherOptions): ServeHeadWatcher {
- const env = opts.env ?? process.env;
- const pollMs = opts.pollMs ?? bounded(env.GBRAIN_SERVE_HEAD_POLL_MS, HEAD_POLL_MS_DEFAULT, 1_000, 30_000);
- const debounceMs = opts.debounceMs ?? bounded(env.GBRAIN_SERVE_HEAD_DEBOUNCE_MS, HEAD_DEBOUNCE_MS_DEFAULT, 0, 60_000);
- const d = { ...defaultDeps(engine), ...Object.fromEntries(Object.entries(opts).filter(([, v]) => v !== undefined)) } as ReturnType<typeof defaultDeps> & ServeHeadWatcherOptions;
- const now = opts.now ?? Date.now;
- const setTimer = opts.setTimeout ?? ((fn: () => void, ms: number) => { const t = setTimeout(fn, ms); t.unref?.(); return t; });
- const clearTimer = opts.clearTimeout ?? ((h: unknown) => clearTimeout(h as ReturnType<typeof setTimeout>));
- const log = (line: string) => { try { opts.log(`[serve-sync] on-commit: ${line}`); } catch { /* logging never breaks the loop */ } };
- const logged = new Set<string>();
- const logOnce = (key: string, line: string) => {
- if (logged.has(key)) return;
- if (logged.size >= LOG_ONCE_CAP) logged.clear();
- logged.add(key);
- log(line);
- };
- const guard = async <T>(what: string, fn: () => Promise<T>, fallback: T): Promise<T> => {
- try { return await fn(); } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- logOnce(`${what}\u0000${message}`, `${what} failed: ${message} (logged once; the watcher keeps polling)`);
- return fallback;
- }
- };
-
- let enabled = false;
- let stopped = false;
- let flagReadAt = -Infinity;
- let listedAt = -Infinity;
- let job: { id: string; sourceId: string; head: string } | null = null;
- const sources = new Map<string, SourceState>();
- const watchers = new Map<string, () => void>();
- let fireTimer: unknown = null;
- let nudgeTimer: unknown = null;
- let inflight: Promise<void> | null = null;
- let again = false;
-
- const closeWatchers = () => { for (const close of watchers.values()) { try { close(); } catch { /* best effort */ } } watchers.clear(); };
- const armFire = (ms: number) => {
- if (stopped) return;
- if (fireTimer !== null) clearTimer(fireTimer);
- fireTimer = setTimer(() => { fireTimer = null; void tick(); }, ms + 50);
- };
- const nudge = () => {
- if (stopped || nudgeTimer !== null) return;
- nudgeTimer = setTimer(() => { nudgeTimer = null; void tick(); }, NUDGE_MS);
- };
-
- const refreshSources = async () => {
- const listed = await guard('listing managed sources', d.listSources, null);
- if (!listed || stopped) return;
- const seen = new Set<string>();
- for (const s of listed) {
- seen.add(s.sourceId);
- const prior = sources.get(s.sourceId);
- if (prior && prior.root === s.root) { prior.gitDir = s.gitDir; continue; }
- sources.set(s.sourceId, { ...s, head: null, movedAt: null, synced: s.lastCommit, resumes: 0 });
- }
- for (const id of [...sources.keys()]) if (!seen.has(id)) sources.delete(id);
- const dirs = new Set([...sources.values()].map(s => s.gitDir).filter((dir): dir is string => !!dir));
- for (const [dir, close] of watchers) if (!dirs.has(dir)) { try { close(); } catch { /* best effort */ } watchers.delete(dir); }
- for (const dir of dirs) {
- if (watchers.has(dir)) continue;
- const close = await guard(`watching ${dir}`, async () => d.watch(dir, nudge), null);
- if (close && stopped) { try { close(); } catch { /* best effort */ } return; }
- if (close) watchers.set(dir, close);
- }
- };
-
- const settle = (j: NonNullable<typeof job>, st: OnCommitJobStatus | null) => {
- job = null;
- const s = sources.get(j.sourceId);
- if (!s) return;
- if (st?.state === 'done' && st.outcome === 'resumable') {
- if (++s.resumes <= MAX_RESUMES) {
- log(`${s.sourceId}: the sync stopped resumable (${st.reason ?? 'partial'}); the commit is not yet searchable, resuming (${s.resumes}/${MAX_RESUMES})`);
- s.movedAt = now();
- armFire(debounceMs);
- return;
- }
- log(`${s.sourceId}: still resumable after ${MAX_RESUMES} passes; the next HEAD move or scheduled sync resumes it`);
- } else if (st?.state === 'error') {
- logOnce(`job-error\u0000${s.sourceId}\u0000${st.error ?? ''}`, `${s.sourceId}: the sync failed: ${st.error ?? 'unknown error'} (not retried until HEAD moves)`);
- } else if (st?.state === 'done' && st.outcome === 'blocked') {
- logOnce(`job-blocked\u0000${s.sourceId}\u0000${st.reason ?? ''}`, `${s.sourceId}: the sync stopped blocked (${st.reason ?? 'unknown'}); see gbrain sync status --source ${s.sourceId} (not retried until HEAD moves)`);
- }
- s.resumes = 0;
- s.synced = j.head;
- if (s.head && s.head !== j.head) armFire(debounceMs);
- };
-
- const step = async () => {
- const t = now();
- if (t - flagReadAt >= HEAD_FLAG_EVERY_MS) {
- flagReadAt = t;
- const on = await guard('reading sync.on_commit', d.readFlag, enabled);
- if (stopped) return;
- if (on !== enabled) {
- enabled = on;
- listedAt = -Infinity;
- if (!on) { sources.clear(); closeWatchers(); job = null; }
- log(on ? `enabled (poll ${pollMs} ms, debounce ${debounceMs} ms)` : 'disabled');
- }
- }
- if (!enabled || stopped) return;
- if (t - listedAt >= HEAD_LIST_EVERY_MS) { listedAt = t; await refreshSources(); }
- const heads = new Map<string, string | null>();
- for (const s of sources.values()) {
- if (stopped) return;
- if (!heads.has(s.root)) heads.set(s.root, await guard(`reading HEAD in ${s.root}`, () => d.revParse(s.root), null));
- const head = heads.get(s.root) ?? null;
- if (head && head !== s.head) { s.head = head; s.movedAt = t; armFire(debounceMs); }
- }
- if (job) {
- const st = d.jobStatus(job.id);
- if (st && st.state !== 'done' && st.state !== 'error') return;
- settle(job, st);
- }
- if (stopped) return;
- // Every due source in order: one whose drain lease is held or whose last_commit already covers HEAD is skipped, so a
- // long sync of one source never starves another; at most one start per step (global single flight on syncRunning).
- const due = [...sources.values()].filter(s => s.head && s.head !== s.synced && (s.movedAt === null || now() - s.movedAt >= debounceMs));
- if (!due.length || await d.syncRunning()) return;
- for (const s of due) {
- if (stopped) return;
- const synced = await guard(`reading the last synced commit of ${s.sourceId}`, () => d.lastCommit(s.sourceId), null);
- if (stopped) return;
- if (synced && synced === s.head) { s.synced = synced; s.resumes = 0; continue; }
- const held = await guard(`reading the drain lease of ${s.sourceId}`, () => d.drainHeld(s.sourceId), true);
- if (stopped) return;
- if (held) continue;
- const head = s.head!;
- const start = await guard(`starting a sync of ${s.sourceId}`, () => d.startSync(s.sourceId), null);
- if (!start) { s.synced = head; return; }
- if ('busy' in start) return;
- if ('refused' in start) {
- logOnce(`refused\u0000${s.sourceId}\u0000${start.refused}`, `${s.sourceId}: the serve refused the sync: ${start.refused} (not retried until HEAD moves)`);
- s.synced = head;
- return;
- }
- job = { id: start.jobId, sourceId: s.sourceId, head };
- log(`${s.sourceId}: HEAD moved to ${short(head)} (last synced ${short(s.synced)}); started managed sync job ${start.jobId}`);
- return;
- }
- };
-
- const tick = (): Promise<void> => {
- if (stopped) return Promise.resolve();
- if (inflight) { again = true; return inflight; }
- inflight = (async () => {
- do {
- again = false;
- try { await step(); } catch (error) { logOnce(`step\u0000${String(error)}`, `unexpected error: ${error instanceof Error ? error.message : String(error)}`); }
- } while (again && !stopped);
- })().finally(() => { inflight = null; });
- return inflight;
- };
-
- const interval = (opts.setInterval ?? ((fn: () => void, ms: number) => { const h = setInterval(fn, ms); h.unref?.(); return h; }))(() => { void tick(); }, pollMs);
- return {
- tick,
- get enabled() { return enabled; },
- stop: async () => {
- if (!stopped) {
- stopped = true;
- (opts.clearInterval ?? ((h: unknown) => clearInterval(h as ReturnType<typeof setInterval>)))(interval);
- if (fireTimer !== null) clearTimer(fireTimer);
- if (nudgeTimer !== null) clearTimer(nudgeTimer);
- closeWatchers();
- }
- if (!inflight) return;
- let bound: ReturnType<typeof setTimeout> | undefined;
- await Promise.race([inflight, new Promise<void>(resolve => { bound = setTimeout(resolve, STOP_SETTLE_MS); bound.unref?.(); })]);
- clearTimeout(bound);
- closeWatchers();
- },
- };
+ const { debounceMs, watch, listSources, resident, ...rest } = opts;
+ return startResidentNotifier(engine, {
+ ...rest,
+ resident: resident ?? 'serve',
+ ...(debounceMs !== undefined ? { quietMs: debounceMs } : {}),
+ ...(listSources ? { listSources } : {}),
+ ...(watch ? { watch: (s: WatchedSource, onChange: () => void) => s.gitDir ? watch(s.gitDir, onChange) : null } : {}),
+ }) ?? INERT;
}
diff --git a/src/schema.sql b/src/schema.sql
index b6db8a6ca3..ae1c0cd2e6 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -3323,3 +3323,52 @@ DO $rls$ BEGIN
END IF;
END $rls$;
-- END GENERATED from src/core/belief/schema.ts (BELIEF_LEDGER_SCHEMA_SQL)
+
+-- GBRA-133 PR 2a (migration v261): commit notifier wanted markers, the
+-- per-host notifier lease and per-source notifier state + coverage record
+-- (src/core/notifier/store.ts).
+CREATE TABLE IF NOT EXISTS sync_wanted_markers (
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ intent TEXT NOT NULL CHECK (intent IN ('freshness','pull','full')),
+ source_incarnation TEXT,
+ wanted_head TEXT,
+ generation BIGINT NOT NULL DEFAULT 1,
+ first_due_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ requested_by TEXT NOT NULL,
+ job_id BIGINT,
+ PRIMARY KEY (source_id, intent)
+);
+CREATE TABLE IF NOT EXISTS sync_notifier_leases (
+ host_id TEXT PRIMARY KEY,
+ owner_id TEXT NOT NULL,
+ fence BIGINT NOT NULL DEFAULT 1,
+ resident_kind TEXT NOT NULL,
+ pid INTEGER,
+ renewed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ expires_at TIMESTAMPTZ NOT NULL
+);
+CREATE TABLE IF NOT EXISTS sync_notifier_sources (
+ source_id TEXT PRIMARY KEY REFERENCES sources(id) ON DELETE CASCADE,
+ source_incarnation TEXT,
+ syncer_host_id TEXT,
+ syncer_recorded_at TIMESTAMPTZ,
+ state TEXT NOT NULL DEFAULT 'idle' CHECK (state IN ('idle','due','running','retry','operator_blocked')),
+ reason TEXT,
+ first_due_at TIMESTAMPTZ,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_retry_at TIMESTAMPTZ,
+ last_progress_at TIMESTAMPTZ,
+ last_error_code TEXT,
+ last_error TEXT,
+ last_error_at TIMESTAMPTZ,
+ trace_path TEXT,
+ observed_head TEXT,
+ observed_at TIMESTAMPTZ,
+ detection_mode TEXT CHECK (detection_mode IN ('watch','poll')),
+ owner_host_id TEXT,
+ owner_kind TEXT,
+ owner_pid INTEGER,
+ owner_seen_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/test/helpers/notifier-memory-store.ts b/test/helpers/notifier-memory-store.ts
new file mode 100644
index 0000000000..d708642ed1
--- /dev/null
+++ b/test/helpers/notifier-memory-store.ts
@@ -0,0 +1,94 @@
+/**
+ * An in-memory NotifierStore (src/core/commit-notifier.ts) for driving the notifier through its seams with a fake clock.
+ * `leases` is shared between stores to model several residents on one host (Postgres); omit it for the PGLite shape
+ * (no lease: the process holding the database owns). Markers keep the SQL store's generation rules.
+ */
+import type { NotifierStore } from '../../src/core/commit-notifier.ts';
+import type { MarkerIntent, NotifierSourceRow, StatePatch, WantedMarker } from '../../src/core/notifier/store.ts';
+
+export interface MemoryLeases { rows: Map<string, { ownerId: string; fence: number; kind: string; expiresAt: number }>; now: () => number }
+
+export interface MemoryNotifierStore extends NotifierStore {
+ markers: Map<string, WantedMarker>;
+ states: Map<string, NotifierSourceRow>;
+ writes: Array<{ kind: 'state' | 'coverage' | 'marker'; sourceId: string; detail: string }>;
+ lastCommit: (sourceId: string) => string | null;
+ upsert(sourceId: string, intent: MarkerIntent, wantedHead: string | null, jobId?: number | null): WantedMarker;
+}
+
+const empty = (sourceId: string): NotifierSourceRow => ({ source_id: sourceId, syncer_host_id: null, state: 'idle', reason: null, first_due_at: null, attempts: 0,
+ next_retry_at: null, last_progress_at: null, last_error_code: null, last_error: null, last_error_at: null, trace_path: null, observed_head: null,
+ observed_at: null, detection_mode: null, owner_host_id: null, owner_kind: null, owner_pid: null, owner_seen_at: null });
+
+export function memoryNotifierStore(opts: { leases?: MemoryLeases; lastCommit?: (sourceId: string) => string | null; liveJobs?: Set<number> } = {}): MemoryNotifierStore {
+ const markers = new Map<string, WantedMarker>();
+ const states = new Map<string, NotifierSourceRow>();
+ const writes: MemoryNotifierStore['writes'] = [];
+ const lastCommit = opts.lastCommit ?? (() => null);
+ const key = (s: string, i: string) => `${s}\u0000${i}`;
+ const at = () => new Date(opts.leases?.now() ?? Date.now()).toISOString();
+ const upsert = (sourceId: string, intent: MarkerIntent, wantedHead: string | null, jobId: number | null = null): WantedMarker => {
+ const prior = markers.get(key(sourceId, intent));
+ const m: WantedMarker = { source_id: sourceId, intent, wanted_head: wantedHead, generation: (prior?.generation ?? 0) + 1,
+ first_due_at: prior?.first_due_at ?? at(), updated_at: at(), requested_by: 'test', job_id: jobId ?? prior?.job_id ?? null };
+ markers.set(key(sourceId, intent), m);
+ writes.push({ kind: 'marker', sourceId, detail: `${intent}:${m.generation}` });
+ return m;
+ };
+ const due = (ids: string[]) => [...markers.values()].filter(m => ids.includes(m.source_id)
+ && (m.intent !== 'freshness' || m.wanted_head === null || m.wanted_head !== lastCommit(m.source_id)));
+ return {
+ markers, states, writes, lastCommit, upsert,
+ claimLease: async (l) => {
+ if (!opts.leases) return null;
+ const t = opts.leases.now();
+ const row = opts.leases.rows.get(l.hostId);
+ if (!row || row.ownerId === l.ownerId || row.expiresAt <= t) {
+ const fence = !row ? 1 : row.ownerId === l.ownerId ? row.fence : row.fence + 1;
+ opts.leases.rows.set(l.hostId, { ownerId: l.ownerId, fence, kind: l.kind, expiresAt: t + l.leaseMs });
+ return { owner: true, fence };
+ }
+ return { owner: false, holderKind: row.kind };
+ },
+ holdsLease: async (hostId, ownerId, fence) => {
+ const row = opts.leases?.rows.get(hostId);
+ return !!row && row.ownerId === ownerId && row.fence === fence && row.expiresAt > opts.leases!.now();
+ },
+ releaseLease: async (hostId, ownerId) => {
+ const row = opts.leases?.rows.get(hostId);
+ if (row && row.ownerId === ownerId) row.expiresAt = opts.leases!.now();
+ },
+ dueMarkers: async (ids) => due(ids),
+ liveJobs: async (ids) => new Set(ids.filter(id => opts.liveJobs?.has(id))),
+ forward: async (sourceId, head) => { upsert(sourceId, 'freshness', head); },
+ settleMarkers: async (sourceId, read, run) => {
+ for (const m of read) {
+ const cur = markers.get(key(sourceId, m.intent));
+ if (!cur || cur.generation !== m.generation) continue;
+ if (m.intent === 'pull' && !run.pulled) continue;
+ if (m.intent === 'full' && !run.full) continue;
+ if (m.intent === 'freshness' && m.wanted_head !== null && m.wanted_head !== lastCommit(sourceId)) continue;
+ markers.delete(key(sourceId, m.intent));
+ }
+ return due([sourceId]);
+ },
+ readStates: async (ids) => ids.flatMap(id => states.has(id) ? [states.get(id)!] : []),
+ writeState: async (sourceId, p: StatePatch) => {
+ const row = states.get(sourceId) ?? empty(sourceId);
+ row.state = p.state;
+ row.reason = p.reason ?? null;
+ row.first_due_at = p.firstDue === 'clear' ? null : row.first_due_at ?? at();
+ if (p.attempts !== undefined) row.attempts = p.attempts;
+ row.next_retry_at = p.nextRetryInMs ? new Date((opts.leases?.now() ?? Date.now()) + p.nextRetryInMs).toISOString() : null;
+ if (p.error !== undefined) { row.last_error_code = p.error?.code ?? null; row.last_error = p.error?.message ?? null; row.trace_path = p.error?.tracePath ?? null; }
+ states.set(sourceId, row);
+ writes.push({ kind: 'state', sourceId, detail: `${p.state}${p.reason ? `:${p.reason}` : ''}` });
+ },
+ writeCoverage: async (sourceId, c) => {
+ const row = states.get(sourceId) ?? empty(sourceId);
+ row.observed_head = c.head; row.detection_mode = c.mode; row.owner_host_id = c.ownerHostId; row.owner_kind = c.ownerKind; row.owner_pid = c.ownerPid;
+ states.set(sourceId, row);
+ writes.push({ kind: 'coverage', sourceId, detail: `${c.head}|${c.mode}|${c.ownerKind}` });
+ },
+ };
+}
diff --git a/test/serve-head-watcher.test.ts b/test/serve-head-watcher.test.ts
index 2102c2485e..0793563320 100644
--- a/test/serve-head-watcher.test.ts
+++ b/test/serve-head-watcher.test.ts
@@ -1,27 +1,34 @@
/**
- * #6858 ask 6 (option C): the serve's on-commit HEAD watcher (src/core/serve-head-watcher.ts), driven through its
- * seams with a fake clock: no timers fire on their own, each test calls `tick()`. What it protects:
+ * The serve's on-commit watcher (src/core/serve-head-watcher.ts), now the serve adapter over the commit notifier
+ * (src/core/commit-notifier.ts, GBRA-133 PR 2a), driven through its seams with a fake clock: no timers fire on their own,
+ * each test calls `tick()` and asserts the recorded decisions, never wall-clock time. What it protects:
* - `sync.on_commit` off: no git call and no sync, and flipping it on takes effect at the next flag read;
- * - a burst of HEAD moves inside the debounce starts one sync, at the last HEAD;
- * - a commit during the watcher's own sync starts exactly one follow-up once that sync ends;
+ * - an idle poll is one git call and no write; a quiet HEAD move starts on the leading edge;
+ * - a commit during the notifier's own sync starts exactly one follow-up, at the last HEAD, after the quiet window;
* - while another sync runs or another process holds the drain lease, the move waits and fires afterwards;
- * - a resumable stop is resumed up to MAX_RESUMES times, then left to the next move;
- * - a source whose drain lease is held is skipped, so another due source still starts (no starvation);
+ * - lost wakes are gone: a refused or failed start, an error run and a resumable stop without progress keep the source
+ * due with capped backoff (5 s, 15 s, 1 min, 5 min, then notifier_stalled); a resumable stop with progress resumes;
+ * - a blocked run waits for the operator until HEAD moves; a checkout mid-rebase or with index.lock is not started;
+ * - a source whose drain lease is held does not starve another due source; fair order under the host cap;
* - errors never leave the loop and are logged once per distinct message; stop() halts polling, and a stop that lands
* while discovery is awaiting leaves no watcher open and no git call behind; its promise settles the in-flight step.
*/
import { describe, expect, test } from 'bun:test';
import type { BrainEngine } from '../src/core/engine.ts';
-import { MAX_RESUMES, HEAD_FLAG_EVERY_MS, startServeHeadWatcher, type OnCommitJobStatus, type ServeHeadWatcherOptions } from '../src/core/serve-head-watcher.ts';
+import { HEAD_FLAG_EVERY_MS, startServeHeadWatcher, type OnCommitJobStatus, type ServeHeadWatcherOptions, type WatchedSource } from '../src/core/serve-head-watcher.ts';
+import { RETRY_BACKOFF_MS } from '../src/core/commit-notifier.ts';
+import { memoryNotifierStore } from './helpers/notifier-memory-store.ts';
const sha = (c: string) => c.repeat(40);
const A = sha('a'), B = sha('b'), C = sha('c'), D = sha('d');
+const QUIET = 400;
function harness(over: Partial<ServeHeadWatcherOptions> = {}, init: { head?: string; dbCommit?: string | null; flag?: boolean } = {}) {
const s = { t: 1_000_000, head: init.head ?? A, dbCommit: init.dbCommit === undefined ? A : init.dbCommit, flag: init.flag ?? true, running: false, held: false,
- git: 0, flagReads: 0, starts: [] as Array<{ id: string; jobId: string }>, jobs: new Map<string, OnCommitJobStatus>(), lines: [] as string[], intervalCleared: false };
+ git: 0, flagReads: 0, starts: [] as Array<{ id: string; jobId: string; intent: string }>, jobs: new Map<string, OnCommitJobStatus>(), lines: [] as string[], intervalCleared: false };
+ const store = memoryNotifierStore({ lastCommit: () => s.dbCommit });
const w = startServeHeadWatcher({} as BrainEngine, {
- log: line => s.lines.push(line), pollMs: 3000, debounceMs: 3000,
+ log: line => s.lines.push(line), pollMs: 3000, debounceMs: QUIET, hostId: 'host-example', store,
now: () => s.t,
setInterval: () => 'interval', clearInterval: () => { s.intervalCleared = true; },
setTimeout: () => 'timer', clearTimeout: () => {},
@@ -31,15 +38,16 @@ function harness(over: Partial<ServeHeadWatcherOptions> = {}, init: { head?: str
revParse: async () => { s.git++; return s.head; },
syncRunning: () => s.running,
drainHeld: async () => s.held,
- startSync: async (id) => { const jobId = `job-${s.starts.length + 1}`; s.starts.push({ id, jobId }); s.jobs.set(jobId, { state: 'running' }); return { jobId }; },
+ startSync: async (id, req) => { const jobId = `job-${s.starts.length + 1}`; s.starts.push({ id, jobId, intent: req.intent }); s.jobs.set(jobId, { state: 'running' }); return { jobId }; },
jobStatus: (jobId) => s.jobs.get(jobId) ?? null,
...over,
});
const finish = (jobId: string, status: OnCommitJobStatus = { state: 'done', outcome: 'synced' }, synced?: string) => { s.jobs.set(jobId, status); if (synced) s.dbCommit = synced; };
- return { w, s, finish, advance: (ms: number) => { s.t += ms; } };
+ const decisions = (kind?: string) => w.decisions.filter(d => !kind || d.decision === kind);
+ return { w, s, store, finish, decisions, advance: (ms: number) => { s.t += ms; } };
}
-describe('serve HEAD watcher', () => {
+describe('serve HEAD watcher (commit notifier)', () => {
test('flag off: no git call and no sync; flipping it on takes effect at the next flag read without a restart', async () => {
const h = harness({}, { flag: false, head: B });
for (let i = 0; i < 5; i++) { await h.w.tick(); h.advance(10_000); }
@@ -61,46 +69,47 @@ describe('serve HEAD watcher', () => {
h.advance(10_000);
await h.w.tick();
expect(h.s.git).toBe(git);
- expect(h.s.starts).toEqual([]);
});
- test('a HEAD equal to the last synced commit starts nothing; an idle poll is one git call', async () => {
+ test('a HEAD equal to the last synced commit starts nothing; an idle poll is one git call and writes nothing after the first observation', async () => {
const h = harness();
for (let i = 0; i < 4; i++) { await h.w.tick(); h.advance(3000); }
expect(h.s.git).toBe(4);
expect(h.s.starts).toEqual([]);
+ expect(h.store.writes.map(w => w.kind)).toEqual(['coverage']);
});
- test('a burst of HEAD moves inside the debounce starts one sync, at the last HEAD', async () => {
+ test('leading edge: a quiet HEAD move starts at once, with no fixed debounce', async () => {
const h = harness();
await h.w.tick();
h.s.head = B; await h.w.tick();
- h.advance(1000); h.s.head = C; await h.w.tick();
- h.advance(1000); h.s.head = D; await h.w.tick();
- h.advance(2000); await h.w.tick();
- expect(h.s.starts).toEqual([]);
- h.advance(1000); await h.w.tick();
expect(h.s.starts.map(x => x.id)).toEqual(['acme-example']);
- expect(h.s.lines.some(l => l.includes(`HEAD moved to ${D.slice(0, 8)}`))).toBe(true);
- h.advance(3000); await h.w.tick();
- expect(h.s.starts).toHaveLength(1);
+ expect(h.decisions('start')).toHaveLength(1);
+ expect(h.decisions('defer_window')).toEqual([]);
+ expect(h.s.lines.some(l => l.includes(`HEAD moved to ${B.slice(0, 8)}`))).toBe(true);
});
- test('a commit during the running sync starts exactly one follow-up after it ends', async () => {
+ test('a burst of commits during the running sync starts exactly one follow-up, at the last HEAD, after the trailing window', async () => {
const h = harness();
await h.w.tick();
h.s.head = B; await h.w.tick();
- h.advance(3000); await h.w.tick();
expect(h.s.starts).toHaveLength(1);
- h.s.head = C; h.advance(1000); await h.w.tick();
- h.advance(5000); await h.w.tick();
+ h.s.head = C; h.advance(100); await h.w.tick();
+ h.s.head = D; h.advance(100); await h.w.tick();
expect(h.s.starts).toHaveLength(1);
h.finish('job-1', { state: 'done', outcome: 'synced' }, B);
- h.advance(3000); await h.w.tick();
+ h.advance(100); await h.w.tick();
+ expect(h.decisions('follow_up')).toHaveLength(1);
+ expect(h.decisions('defer_window').at(-1)?.waitMs).toBe(QUIET - 300);
+ expect(h.s.starts).toHaveLength(1);
+ h.advance(QUIET); await h.w.tick();
expect(h.s.starts).toHaveLength(2);
- h.finish('job-2', { state: 'done', outcome: 'synced' }, C);
+ expect(h.s.lines.some(l => l.includes(`HEAD moved to ${D.slice(0, 8)}`))).toBe(true);
+ h.finish('job-2', { state: 'done', outcome: 'synced' }, D);
for (let i = 0; i < 5; i++) { h.advance(3000); await h.w.tick(); }
expect(h.s.starts).toHaveLength(2);
+ expect(h.decisions('converged')).toHaveLength(1);
+ expect(h.store.states.get('acme-example')).toMatchObject({ state: 'idle', first_due_at: null });
});
test('while another sync runs or another process holds the drain lease, the move waits and fires afterwards', async () => {
@@ -112,6 +121,7 @@ describe('serve HEAD watcher', () => {
h.s.running = false; h.s.held = true;
h.advance(3000); await h.w.tick();
expect(h.s.starts).toEqual([]);
+ expect(h.decisions('defer_drain_lease').length).toBeGreaterThan(0);
h.s.held = false;
h.advance(3000); await h.w.tick();
expect(h.s.starts).toHaveLength(1);
@@ -127,26 +137,73 @@ describe('serve HEAD watcher', () => {
expect(h.s.starts).toEqual([]);
});
- test('a resumable stop is not yet searchable, not a failure: resumed up to MAX_RESUMES times, then left to the next move', async () => {
+ test('a resumable stop that advanced is resumed, without a cap; one that did not advance backs off like a failure', async () => {
const h = harness();
await h.w.tick();
- h.s.head = B; await h.w.tick();
- for (let i = 0; i < MAX_RESUMES + 3; i++) {
- h.advance(3000); await h.w.tick();
- const last = h.s.starts.at(-1);
- if (last && h.s.jobs.get(last.jobId)?.state === 'running') h.finish(last.jobId, { state: 'done', outcome: 'resumable', reason: 'deadline' });
- h.advance(10); await h.w.tick();
+ h.s.head = D; await h.w.tick();
+ for (const synced of [B, C]) {
+ h.finish(h.s.starts.at(-1)!.jobId, { state: 'done', outcome: 'resumable', reason: 'deadline' }, synced);
+ h.advance(QUIET); await h.w.tick();
+ h.advance(QUIET); await h.w.tick();
}
- expect(h.s.starts).toHaveLength(1 + MAX_RESUMES);
- expect(h.s.lines.filter(l => l.includes('not yet searchable'))).toHaveLength(MAX_RESUMES);
- expect(h.s.lines.some(l => l.includes(`still resumable after ${MAX_RESUMES} passes`))).toBe(true);
- expect(h.s.lines.some(l => /failed/.test(l))).toBe(false);
+ expect(h.decisions('resume')).toHaveLength(2);
+ expect(h.s.starts).toHaveLength(3);
+ h.finish(h.s.starts.at(-1)!.jobId, { state: 'done', outcome: 'resumable', reason: 'deadline' });
+ h.advance(QUIET); await h.w.tick();
+ expect(h.decisions('retry').map(d => d.waitMs)).toEqual([RETRY_BACKOFF_MS[0]]);
+ expect(h.store.states.get('acme-example')?.state).toBe('retry');
+ h.advance(RETRY_BACKOFF_MS[0]); await h.w.tick();
+ expect(h.s.starts).toHaveLength(4);
+ });
+
+ test('lost wake: a refused start keeps the source due and retries at 5 s, 15 s, 1 min and 5 min, then reports notifier_stalled', async () => {
+ let starts = 0;
+ const h = harness({ startSync: async () => { starts++; return { refused: 'permission_denied' }; } });
+ await h.w.tick();
+ h.s.head = B; await h.w.tick();
+ for (const wait of [...RETRY_BACKOFF_MS, RETRY_BACKOFF_MS.at(-1)!]) { h.advance(wait); await h.w.tick(); }
+ expect(starts).toBe(6);
+ expect([...h.decisions('retry'), ...h.decisions('stalled')].map(d => d.waitMs)).toEqual([...RETRY_BACKOFF_MS, ...RETRY_BACKOFF_MS.slice(-1), ...RETRY_BACKOFF_MS.slice(-1)]);
+ expect(h.decisions('stalled').length).toBeGreaterThan(0);
+ const row = h.store.states.get('acme-example')!;
+ expect(row).toMatchObject({ state: 'retry', reason: 'notifier_stalled', last_error_code: 'notifier_stalled' });
+ expect(row.first_due_at).not.toBeNull();
+ expect(h.s.lines.filter(l => l.includes('notifier_stalled'))).toHaveLength(1);
+ expect(h.s.lines.some(l => l.includes('gbrain sync --source acme-example --no-pull'))).toBe(true);
+ });
+
+ test('lost wake: a failed or blocked run keeps the source; failed retries, blocked waits for the operator until HEAD moves', async () => {
+ const h = harness();
+ await h.w.tick();
+ h.s.head = B; await h.w.tick();
+ h.finish('job-1', { state: 'error', error: 'connection reset' });
+ h.advance(1); await h.w.tick();
+ expect(h.decisions('retry').map(d => d.detail)).toEqual(['sync_failed']);
+ h.advance(RETRY_BACKOFF_MS[0]); await h.w.tick();
+ expect(h.s.starts).toHaveLength(2);
+ h.finish('job-2', { state: 'done', outcome: 'blocked', reason: 'needs_human' });
+ h.advance(1); await h.w.tick();
+ expect(h.store.states.get('acme-example')).toMatchObject({ state: 'operator_blocked', reason: 'needs_human' });
+ for (let i = 0; i < 3; i++) { h.advance(300_000); await h.w.tick(); }
+ expect(h.s.starts).toHaveLength(2);
h.s.head = C; h.advance(3000); await h.w.tick();
+ expect(h.s.starts).toHaveLength(3);
+ });
+
+ test('quiet predicate: a checkout mid-rebase or holding index.lock is not started until it is quiet', async () => {
+ let quiet = false;
+ const h = harness({ quiet: () => quiet });
+ await h.w.tick();
+ h.s.head = B; await h.w.tick();
h.advance(3000); await h.w.tick();
- expect(h.s.starts).toHaveLength(2 + MAX_RESUMES);
+ expect(h.s.starts).toEqual([]);
+ expect(h.decisions('defer_git_busy').length).toBeGreaterThan(0);
+ quiet = true;
+ h.advance(3000); await h.w.tick();
+ expect(h.s.starts).toHaveLength(1);
});
- test('errors never leave the loop and are logged once per distinct message; a failed start waits for the next move', async () => {
+ test('errors never leave the loop and are logged once per distinct message; a failed start is retried', async () => {
let failGit = true;
let failStart = true;
let listFails = 1;
@@ -163,32 +220,17 @@ describe('serve HEAD watcher', () => {
expect(h.s.lines.filter(l => l.includes('not a git repository'))).toHaveLength(1);
failGit = false;
h.s.head = B; await h.w.tick();
- h.advance(3000); await h.w.tick();
- h.advance(3000); await h.w.tick();
expect(h.s.lines.filter(l => l.includes('writer_lock_unavailable'))).toHaveLength(1);
failStart = false;
- h.advance(3000); await h.w.tick();
- expect(h.s.lines.some(l => l.includes('job-ok'))).toBe(false);
- h.s.head = C; h.advance(1); await h.w.tick();
- h.advance(3000); await h.w.tick();
+ h.advance(RETRY_BACKOFF_MS[0]); await h.w.tick();
expect(h.s.lines.some(l => l.includes('job-ok'))).toBe(true);
});
- test('a refused start is logged once and not retried until HEAD moves', async () => {
- let starts = 0;
- const h = harness({ startSync: async () => { starts++; return { refused: 'permission_denied' }; } });
- await h.w.tick();
- h.s.head = B; await h.w.tick();
- for (let i = 0; i < 4; i++) { h.advance(3000); await h.w.tick(); }
- expect(starts).toBe(1);
- expect(h.s.lines.filter(l => l.includes('refused the sync: permission_denied'))).toHaveLength(1);
- });
-
test('stop() halts polling', async () => {
const h = harness();
await h.w.tick();
const git = h.s.git;
- h.w.stop();
+ await h.w.stop();
expect(h.s.intervalCleared).toBe(true);
h.s.head = B; h.advance(10_000);
await h.w.tick();
@@ -207,11 +249,29 @@ describe('serve HEAD watcher', () => {
for (let i = 0; i < 3; i++) { await h.w.tick(); h.advance(3000); }
expect(starts).toEqual(['alice-example']);
held.delete('acme-example');
- h.finish('job-alice-example');
+ h.finish('job-alice-example', { state: 'done', outcome: 'synced' });
await h.w.tick();
expect(starts).toEqual(['alice-example', 'acme-example']);
});
+ test('fair order under the host cap: the source started least recently goes first, so a busy source never starves another', async () => {
+ const starts: string[] = [];
+ const commits = new Map<string, string>([['acme-example', A], ['alice-example', A]]);
+ const h = harness({
+ listSources: async () => ['acme-example', 'alice-example'].map(sourceId => ({ sourceId, root: `/brains/${sourceId}`, gitDir: null, lastCommit: A })),
+ revParse: async (root) => root.endsWith('acme-example') ? h.s.head : C,
+ lastCommit: async (id) => commits.get(id) ?? null,
+ startSync: async (id) => { starts.push(id); h.s.jobs.set(`job-${starts.length}`, { state: 'running' }); return { jobId: `job-${starts.length}` }; },
+ }, { head: B });
+ await h.w.tick();
+ expect(starts).toEqual(['acme-example']);
+ expect(h.decisions('defer_cap').map(d => d.source)).toEqual(['alice-example']);
+ h.s.head = D;
+ h.finish('job-1', { state: 'done', outcome: 'synced' }); commits.set('acme-example', B);
+ h.advance(QUIET); await h.w.tick();
+ expect(starts).toEqual(['acme-example', 'alice-example']);
+ });
+
test('a source whose last_commit already covers HEAD is skipped for the next due one', async () => {
const starts: string[] = [];
const h = harness({
@@ -227,9 +287,9 @@ describe('serve HEAD watcher', () => {
});
test('stop() while discovery awaits: no watcher stays open, no git call runs, and stop() settles the in-flight step', async () => {
- let release!: (rows: Array<{ sourceId: string; root: string; gitDir: string | null; lastCommit: string | null }>) => void;
+ let release!: (rows: WatchedSource[]) => void;
let entered!: () => void;
- const listed = new Promise<Parameters<typeof release>[0]>(resolve => { release = resolve; });
+ const listed = new Promise<WatchedSource[]>(resolve => { release = resolve; });
const entry = new Promise<void>(resolve => { entered = resolve; });
let open = 0;
const h = harness({