Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): the default sync deadline never stops a run that is still importing
garrytan120fcfe2ffa1
diff --git a/src/cli.ts b/src/cli.tsindex 8aa3e2f47e..6d88fa4273 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2439,16 +2439,10 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promis});if (res) {const { installProcessWatchdog } = await import('./core/process-watchdog.ts');- syncWatchdog = installProcessWatchdog({- deadlineMs: res.deadlineMs,- graceMs: res.graceMs,- label: 'sync-watchdog',- heartbeatMs: 60_000,- });- process.stderr.write(- `[sync-watchdog] hard deadline armed: ${Math.round(res.deadlineMs / 1000)}s ` +- `+ ${Math.round(res.graceMs / 1000)}s grace (${res.reason}); disable with --no-hard-deadline\n`,- );+ const { syncWatchdogPlan } = await import('./core/sync-reconcile.ts');+ const plan = syncWatchdogPlan(args, res);+ syncWatchdog = installProcessWatchdog(plan.watchdog);+ process.stderr.write(plan.armedLine);}} catch (e) {// A bad --hard-deadline value throws here (same posture as --timeout).diff --git a/src/core/forward-progress.ts b/src/core/forward-progress.tsnew file mode 100644index 0000000000..0852f49ae7--- /dev/null+++ b/src/core/forward-progress.ts@@ -0,0 +1,38 @@+/**+ * Process-wide forward-progress signal.+ *+ * A long-running command proves it is still doing useful work by calling+ * `noteForwardProgress()` whenever a unit of work completes (the shared+ * progress reporter calls it on every `tick`). Deadlines that must never kill+ * a run that is still progressing (the sync hard deadline, the serve boot+ * deadline) subscribe with `onForwardProgress` and extend themselves while+ * the signal keeps arriving. Heartbeats are NOT progress: a timer firing says+ * the event loop is alive, not that work is finishing.+ *+ * Zero imports on purpose: `progress.ts` (zero-dependency) and the watchdogs+ * both depend on it.+ */++type ForwardProgressListener = () => void;++const listeners = new Set<ForwardProgressListener>();+let lastProgressAt = 0;++/** Record that a unit of work just completed. Cheap enough to call per item. */+export function noteForwardProgress(): void {+ lastProgressAt = Date.now();+ for (const listener of listeners) {+ try { listener(); } catch { /* a listener must never break the work loop */ }+ }+}++/** Subscribe to forward-progress notes; returns the unsubscribe function. */+export function onForwardProgress(listener: ForwardProgressListener): () => void {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+}++/** Wall-clock ms of the most recent progress note in this process (0 = none yet). */+export function lastForwardProgressAt(): number {+ return lastProgressAt;+}diff --git a/src/core/process-watchdog.ts b/src/core/process-watchdog.tsindex 6f482abf36..237faf1827 100644--- a/src/core/process-watchdog.ts+++ b/src/core/process-watchdog.ts@@ -37,6 +37,7 @@import { Worker } from 'node:worker_threads';// Zero-import teardown-budget leaf — safe edge, no cycle (it imports nothing).import { MAX_TIMER_DELAY_MS } from './background-work.ts';+import { lastForwardProgressAt, onForwardProgress } from './forward-progress.ts';export type WatchdogAction = 'wait' | 'sigterm' | 'sigkill';@@ -53,6 +54,27 @@ export function watchdogDecision(elapsedMs: number, deadlineMs: number, graceMs:return 'wait';}+export type ProgressDeadlineAction = 'wait' | 'extend' | 'stop';++/**+ * Pure decision for a progress-aware deadline (mirrored in WORKER_SRC — keep+ * them in lockstep). A run that is still making forward progress is never+ * stopped: once the deadline passes, the deadline extends for as long as the+ * last progress note is younger than `windowMs`, and stops the run only after+ * a full window with no progress. `windowMs <= 0` keeps the plain wall-clock+ * deadline.+ * elapsed < deadline -> 'wait'+ * deadline passed, progress within window -> 'extend'+ * deadline passed, no progress for window -> 'stop' (SIGTERM, then SIGKILL after grace)+ */+export function progressDeadlineDecision(+ elapsedMs: number, deadlineMs: number, sinceProgressMs: number, windowMs: number,+): ProgressDeadlineAction {+ if (elapsedMs < deadlineMs) return 'wait';+ if (windowMs > 0 && sinceProgressMs < windowMs) return 'extend';+ return 'stop';+}+export interface ProcessWatchdogOpts {/** Wall-clock ms after which SIGTERM is sent. Must be > 0 or the watchdog is a no-op. */deadlineMs: number;@@ -64,6 +86,20 @@ export interface ProcessWatchdogOpts {heartbeatMs?: number;/** Injectable warn sink (tests). Default writes to process.stderr. */onWarn?: (msg: string) => void;+ /**+ * Progress-aware mode: past the deadline, keep the run alive while+ * `noteForwardProgress()` (src/core/forward-progress.ts) fired within this+ * many ms; stop only after a full window without progress. 0 = off (plain+ * wall-clock deadline). The window starts at install, so a run that has not+ * reported progress yet still gets one window.+ */+ progressWindowMs?: number;+ /**+ * Written to stdout (fd 1) when the watchdog stops the run, so the agent+ * operating the command sees why it stopped and how to resume, not only a+ * stderr line and an exit status.+ */+ stopNotice?: string;}export interface WatchdogHandle {@@ -120,27 +156,53 @@ const INERT: WatchdogHandle = { dispose() {}, get active() { return false; } };* so it can't break the string literal or inject log lines.*/const WORKER_SRC = `-const { workerData } = require('node:worker_threads');+const { parentPort, workerData } = require('node:worker_threads');const { writeSync } = require('node:fs');-const { deadlineMs, graceMs, label, heartbeatMs } = workerData;+const { deadlineMs, graceMs, label, heartbeatMs, progressWindowMs, stopNotice } = workerData;const t0 = Date.now();+let lastProgress = t0;+let extended = false;function w(m) { try { writeSync(2, '[' + label + '] ' + m + '\\n'); } catch (e) {} }+if (progressWindowMs > 0 && parentPort) parentPort.on('message', () => { lastProgress = Date.now(); });if (heartbeatMs > 0) {const hb = setInterval(() => {const elapsed = Math.round((Date.now() - t0) / 1000);+ if (extended) {+ w('parent alive ' + elapsed + 's elapsed, past the deadline and still progressing (last progress ' + Math.round((Date.now() - lastProgress) / 1000) + 's ago); stops after ' + Math.round(progressWindowMs / 1000) + 's without progress');+ return;+ }const killIn = Math.round((deadlineMs + graceMs - (Date.now() - t0)) / 1000);- w('parent alive ' + elapsed + 's elapsed, hard-kill in ~' + killIn + 's');+ w('parent alive ' + elapsed + 's elapsed, ' + (progressWindowMs > 0 ? 'deadline' : 'hard-kill') + ' in ~' + killIn + 's');}, heartbeatMs);if (typeof hb.unref === 'function') hb.unref();}-setTimeout(() => {- w('deadline reached (' + Math.round(deadlineMs/1000) + 's) — sending SIGTERM for graceful shutdown');+function stop() {+ if (progressWindowMs > 0) {+ w('deadline reached (' + Math.round(deadlineMs/1000) + 's) and no progress for ' + Math.round((Date.now() - lastProgress) / 1000) + 's — sending SIGTERM for graceful shutdown');+ } else {+ w('deadline reached (' + Math.round(deadlineMs/1000) + 's) — sending SIGTERM for graceful shutdown');+ }+ if (stopNotice) { try { writeSync(1, stopNotice + '\\n'); } catch (e) {} }try { process.kill(process.pid, 'SIGTERM'); } catch (e) {}-}, deadlineMs);-setTimeout(() => {- w('grace expired — sending SIGKILL (event loop was starved; this is the orphan-pileup backstop)');- try { process.kill(process.pid, 'SIGKILL'); } catch (e) {}-}, deadlineMs + graceMs);+ setTimeout(() => {+ w('grace expired — sending SIGKILL (event loop was starved; this is the orphan-pileup backstop)');+ try { process.kill(process.pid, 'SIGKILL'); } catch (e) {}+ }, graceMs);+}+function check() {+ const now = Date.now();+ const since = now - lastProgress;+ // mirrors progressDeadlineDecision+ if (now - t0 < deadlineMs) { setTimeout(check, deadlineMs - (now - t0)); return; }+ if (progressWindowMs > 0 && since < progressWindowMs) {+ if (!extended) w('deadline reached (' + Math.round(deadlineMs/1000) + 's) but the run is still progressing (last progress ' + Math.round(since / 1000) + 's ago) — extending; it stops after ' + Math.round(progressWindowMs / 1000) + 's without progress');+ extended = true;+ setTimeout(check, progressWindowMs - since);+ return;+ }+ stop();+}+setTimeout(check, deadlineMs);`;/**@@ -159,23 +221,37 @@ export function installProcessWatchdog(opts: ProcessWatchdogOpts): WatchdogHandl// Sanitize label to a safe charset (defends the inline worker string + log lines).const label = (opts.label ?? 'watchdog').replace(/[^A-Za-z0-9_.:-]/g, '').slice(0, 40) || 'watchdog';const heartbeatMs = Math.max(0, Math.floor(opts.heartbeatMs ?? 0));+ const progressWindowMs = Math.min(MAX_WATCHDOG_TIMER_MS, Math.max(0, Math.floor(Number.isFinite(opts.progressWindowMs) ? opts.progressWindowMs! : 0)));+ const stopNotice = opts.stopNotice ?? '';if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) return INERT;try {const worker = new Worker(WORKER_SRC, {eval: true,- workerData: { deadlineMs, graceMs, label, heartbeatMs },+ workerData: { deadlineMs, graceMs, label, heartbeatMs, progressWindowMs, stopNotice },});// Don't let the watchdog keep the process alive past clean completion.(worker as unknown as { unref?: () => void }).unref?.();// A worker-side error must never crash the host; log and move on.worker.on('error', (err) => warn(`[${label}] watchdog worker error: ${err instanceof Error ? err.message : String(err)}`));+ // Progress notes are forwarded at most once per throttle interval: a+ // per-file postMessage on a 50k-file import is needless cross-thread+ // traffic when the worker only compares against a window of minutes.+ const throttleMs = Math.max(10, Math.min(1000, Math.floor(progressWindowMs / 4)));+ let lastPost = 0;+ const unsubscribe = progressWindowMs > 0 ? onForwardProgress(() => {+ const now = Date.now();+ if (now - lastPost < throttleMs) return;+ lastPost = now;+ try { worker.postMessage(1); } catch { /* worker gone */ }+ }) : () => {};let disposed = false;return {dispose() {if (disposed) return;disposed = true;+ unsubscribe();void worker.terminate();},get active() { return !disposed; },@@ -187,17 +263,32 @@ export function installProcessWatchdog(opts: ProcessWatchdogOpts): WatchdogHandl`falling back to an in-process timer that will NOT fire if the event loop is starved.`,);let killed = false;- const term = setTimeout(() => { try { process.kill(process.pid, 'SIGTERM'); } catch { /* */ } }, deadlineMs);- const kill = setTimeout(() => { killed = true; try { process.kill(process.pid, 'SIGKILL'); } catch { /* */ } }, deadlineMs + graceMs);+ const t0 = Date.now();+ let kill: ReturnType<typeof setTimeout> | undefined;+ let term: ReturnType<typeof setTimeout>;+ const check = () => {+ const now = Date.now();+ const since = now - Math.max(t0, lastForwardProgressAt());+ const action = progressDeadlineDecision(now - t0, deadlineMs, since, progressWindowMs);+ if (action !== 'stop') {+ term = setTimeout(check, action === 'wait' ? deadlineMs - (now - t0) : progressWindowMs - since);+ (term as unknown as { unref?: () => void }).unref?.();+ return;+ }+ if (stopNotice) { try { process.stdout.write(stopNotice + '\n'); } catch { /* */ } }+ try { process.kill(process.pid, 'SIGTERM'); } catch { /* */ }+ kill = setTimeout(() => { killed = true; try { process.kill(process.pid, 'SIGKILL'); } catch { /* */ } }, graceMs);+ (kill as unknown as { unref?: () => void }).unref?.();+ };+ term = setTimeout(check, deadlineMs);(term as unknown as { unref?: () => void }).unref?.();- (kill as unknown as { unref?: () => void }).unref?.();let disposed = false;return {dispose() {if (disposed || killed) return;disposed = true;clearTimeout(term);- clearTimeout(kill);+ if (kill) clearTimeout(kill);},get active() { return !disposed; },};diff --git a/src/core/progress.ts b/src/core/progress.tsindex 8a40490c9b..f87e4cee5e 100644--- a/src/core/progress.ts+++ b/src/core/progress.ts@@ -26,6 +26,8 @@* See docs/progress-events.md for the full reference.*/+import { noteForwardProgress } from './forward-progress.ts';+export type ProgressMode = 'auto' | 'human' | 'json' | 'quiet';export interface ProgressOptions {@@ -284,6 +286,7 @@ class Reporter implements ReporterInternal {const s = this.state;if (!s) return;s.done += n;+ noteForwardProgress();if (this.renderMode === 'quiet') return;diff --git a/src/core/sync-reconcile.ts b/src/core/sync-reconcile.tsindex 1a2889ddfb..bce6ce2fa3 100644--- a/src/core/sync-reconcile.ts+++ b/src/core/sync-reconcile.ts@@ -122,6 +122,13 @@ export interface HardDeadlineResolution {graceMs: number;/** Where the deadline came from (for the armed-log line + tests). */reason: string;+ /**+ * Progress-aware window (ms). Set for the default and env deadlines: past+ * the deadline the run continues while it keeps importing, and stops only+ * after this long without progress. Absent for the explicit `--hard-deadline`+ * and `--timeout` flags, which stay strict wall-clock caps.+ */+ progressWindowMs?: number;}/**@@ -152,7 +159,8 @@ export function resolveStallAbortSeconds(* flag, or an explicit opt-out / 0).** Precedence: --no-hard-deadline > --hard-deadline > --timeout(non-all) > env >- * non-TTY default (3600s) > none.+ * non-TTY default (3600s) > none. The env and default deadlines are+ * progress-aware (`progressWindowMs`); the explicit flags are strict.*/export function resolveSyncHardDeadline(args: string[],@@ -181,17 +189,64 @@ export function resolveSyncHardDeadline(if (sec && sec > 0) return mk(sec, 'flag:--timeout');}+ // A large first sync legitimately outlives the default hour, so these two+ // deadlines never stop a run that is still importing: past the deadline they+ // extend while progress keeps arriving, for up to one stall window between+ // progress notes (the same window the in-band stall watchdog uses).+ const stallSec = resolveStallAbortSeconds(env);+ const progressAware = (res: HardDeadlineResolution | null): HardDeadlineResolution | null =>+ res && { ...res, progressWindowMs: (stallSec > 0 ? stallSec : DEFAULT_SYNC_STALL_ABORT_SEC) * 1000 };+const envRaw = env.GBRAIN_SYNC_MAX_RUNTIME_SECONDS;if (envRaw !== undefined && envRaw !== '') {const n = Number(envRaw);- if (Number.isFinite(n)) return mk(n, 'env:GBRAIN_SYNC_MAX_RUNTIME_SECONDS'); // n<=0 disables+ if (Number.isFinite(n)) return progressAware(mk(n, 'env:GBRAIN_SYNC_MAX_RUNTIME_SECONDS')); // n<=0 disables}- if (!opts.isTty) return mk(opts.defaultNonTtySec ?? 3600, 'default:non-tty');+ if (!opts.isTty) return progressAware(mk(opts.defaultNonTtySec ?? 3600, 'default:non-tty'));return null;}+/**+ * The `gbrain sync` watchdog installation for a resolved deadline: the+ * `installProcessWatchdog` options (progress window and stop notice included)+ * and the stderr line announcing it.+ */+export function syncWatchdogPlan(args: string[], res: HardDeadlineResolution): {+ watchdog: { deadlineMs: number; graceMs: number; label: string; heartbeatMs: number; progressWindowMs?: number; stopNotice: string };+ armedLine: string;+} {+ return {+ watchdog: { deadlineMs: res.deadlineMs, graceMs: res.graceMs, label: 'sync-watchdog', heartbeatMs: 60_000,+ progressWindowMs: res.progressWindowMs, stopNotice: syncDeadlineStopNotice(args, res) },+ armedLine: `[sync-watchdog] hard deadline armed: ${Math.round(res.deadlineMs / 1000)}s + ${Math.round(res.graceMs / 1000)}s grace (${res.reason})` ++ (res.progressWindowMs ? `; extends while the sync keeps progressing (stops after ${Math.round(res.progressWindowMs / 1000)}s without progress)` : '') ++ '; disable with --no-hard-deadline\n',+ };+}++/**+ * The stdout notice the sync watchdog prints when it stops a run, so the agent+ * sees why the sync ended and the exact command that resumes it (a SIGTERMed+ * process prints no summary of its own). One JSON object under `--json`.+ */+export function syncDeadlineStopNotice(args: string[], res: HardDeadlineResolution): string {+ const deadlineSec = Math.round(res.deadlineMs / 1000);+ const windowSec = res.progressWindowMs ? Math.round(res.progressWindowMs / 1000) : null;+ const resume = ['gbrain', 'sync', ...args].map(a => /^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`).join(' ');+ const cause = windowSec+ ? `the ${deadlineSec}s sync deadline (${res.reason}) passed and the run made no progress for ${windowSec}s`+ : `the ${deadlineSec}s sync deadline (${res.reason}) passed`;+ const fix = 'Pages imported before the stop are kept and a rerun skips them. Resume with: ' + resume ++ '. If the stop was wrong for this brain, rerun with --hard-deadline <seconds> or --no-hard-deadline.';+ if (args.includes('--json')) {+ return JSON.stringify({ status: 'stopped', code: 'sync_deadline_stop', reason: res.reason, deadline_seconds: deadlineSec,+ progress_window_seconds: windowSec, cause, resume_command: resume, fix });+ }+ return `gbrain sync stopped (code=sync_deadline_stop): ${cause}. ${fix}`;+}+/*** Compose 1..N AbortSignals into one (CQ2). Undefined inputs are dropped; the* result aborts when ANY input aborts. Returns a single signal directly (nodiff --git a/test/fixtures/watchdog-harness.ts b/test/fixtures/watchdog-harness.tsindex 198e58c338..a9f2dc25f3 100644--- a/test/fixtures/watchdog-harness.ts+++ b/test/fixtures/watchdog-harness.ts@@ -22,9 +22,20 @@* stall-dispose — install, dispose immediately, then genuinely starve past* stall+grace. A disposed watchdog must never kill.*+ * Progress-aware deadline modes (large-brain sync, F4d) — argv[5] is the+ * progress window in ms:+ * progress-with — install a progress-aware watchdog, then keep reporting+ * forward progress (noteForwardProgress every 25ms) for+ * 4x the deadline. Must NOT be stopped; prints COMPLETED.+ * progress-stalls — report progress for half the deadline, then idle (loop+ * responsive, no progress). Must be SIGTERMed one window+ * after the last progress note, after printing the+ * STOP-NOTICE stop notice on stdout.+ ** Safety net: the busy loop self-exits after 8s so a failed test kill can't hang CI.*/import { installProcessWatchdog, installLoopStallWatchdog } from '../../src/core/process-watchdog.ts';+import { noteForwardProgress } from '../../src/core/forward-progress.ts';const mode = process.argv[2] ?? 'starve-with';const deadlineMs = Number(process.argv[3] ?? 300);@@ -73,6 +84,19 @@ if (mode.startsWith('stall-')) {process.exit(0);}+if (mode.startsWith('progress-')) {+ const progressWindowMs = Number(process.argv[5] ?? 400);+ installProcessWatchdog({ deadlineMs, graceMs, label: 'test-wd', progressWindowMs, stopNotice: 'STOP-NOTICE' });+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));+ const t0 = Date.now();+ const progressFor = mode === 'progress-with' ? deadlineMs * 4 : deadlineMs / 2;+ while (Date.now() - t0 < progressFor) { noteForwardProgress(); await sleep(25); }+ if (mode === 'progress-with') { process.stdout.write('COMPLETED\n'); process.exit(0); }+ while (Date.now() - t0 < 8000) await sleep(25);+ process.stdout.write('SURVIVED\n');+ process.exit(0);+}+if (mode === 'starve-with' || mode === 'clean-dispose') {const handle = installProcessWatchdog({ deadlineMs, graceMs, label: 'test-wd' });if (mode === 'clean-dispose') {diff --git a/test/large-brain-ceilings.serial.test.ts b/test/large-brain-ceilings.serial.test.tsnew file mode 100644index 0000000000..0a036f9696--- /dev/null+++ b/test/large-brain-ceilings.serial.test.ts@@ -0,0 +1,62 @@+/**+ * Large-brain ceilings (Foundations 1, F4d), at the CLI boundary where a+ * 52,028-document brain hit them.+ *+ * Protects:+ * - `gbrain sync` under a non-TTY caller: the default and env deadlines no+ * longer kill a run that is still importing. A sync whose work outlasts+ * its deadline window completes and imports every file.+ * Fails when: the sync watchdog goes back to a plain wall-clock kill (the+ * child exits 143 after the 1 s deadline with files missing).+ * Why new: test/process-watchdog.serial.test.ts drives the watchdog through a+ * harness; it does not run the real CLI command the operator runs.+ * Seam: none. Deadlines are shortened through the documented env knob, not by+ * waiting an hour.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';+import { writeLargeWorktree } from './helpers/large-worktree.ts';++const KEYS = { OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined };++function commitWorktree(root: string, files: number): void {+ writeLargeWorktree(root, files);+ const git = (args: string[]) => execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=t', ...args], { cwd: root, stdio: 'ignore' });+ git(['init', '--quiet']);+ git(['add', '-A']);+ git(['commit', '--quiet', '-m', 'fixture']);+}++let dir: string;+beforeAll(() => { dir = mkdtempSync(join(tmpdir(), 'gbrain-large-ceilings-')); });+afterAll(() => rmSync(dir, { recursive: true, force: true }));++async function freshBrain(name: string): Promise<string> {+ const home = join(dir, name, 'home');+ const init = await runCli(['init', '--pglite', '--no-embedding'], { home, env: KEYS, timeoutMs: 120_000 });+ expect(init.exitCode).toBe(0);+ return home;+}++describe('large-brain ceilings (CLI)', () => {+ test('a sync that outlasts its deadline window keeps going while it imports, and completes', async () => {+ const home = await freshBrain('sync');+ const repo = join(dir, 'sync', 'repo');+ commitWorktree(repo, 150);+ expect((await runCli(['sources', 'add', 'notes', '--path', repo], { home, env: KEYS, timeoutMs: 120_000 })).exitCode).toBe(0);++ const sync = await runCli(['sync', '--source', 'notes', '--no-pull'], {+ home, timeoutMs: 180_000,+ env: { ...KEYS, GBRAIN_SYNC_MAX_RUNTIME_SECONDS: '1', GBRAIN_SYNC_STALL_ABORT_SECONDS: '60' },+ });+ expect(sync.stderr).toContain('extends while the sync keeps progressing');+ expect(sync.stderr).toContain('still progressing');+ expect(sync.stdout).not.toContain('sync_deadline_stop');+ expect(sync.exitCode).toBe(0);+ expect(sync.stdout).toContain('150 file(s) imported');+ }, 300_000);+});diff --git a/test/process-watchdog.serial.test.ts b/test/process-watchdog.serial.test.tsindex 6e7b7e1ba5..04ba7eeb6d 100644--- a/test/process-watchdog.serial.test.ts+++ b/test/process-watchdog.serial.test.ts@@ -18,8 +18,9 @@ async function runHarness(deadlineMs: number,graceMs: number,hardCapMs: number,+ progressWindowMs?: number,): Promise<{ exitCode: number | null; signalled: boolean; elapsedMs: number; stdout: string; stderr: string; killedByTest: boolean }> {- const proc = Bun.spawn(['bun', HARNESS, mode, String(deadlineMs), String(graceMs)], {+ const proc = Bun.spawn(['bun', HARNESS, mode, String(deadlineMs), String(graceMs), ...(progressWindowMs === undefined ? [] : [String(progressWindowMs)])], {stdout: 'pipe',stderr: 'pipe',});@@ -67,6 +68,31 @@ describe('process-watchdog integration (Bun-pinned)', () => {}, 15000);});+// Large-brain ceiling (F4d): a 52k-document sync outlived the default hour+// while still importing and was killed mid-run. The progress-aware deadline+// extends while noteForwardProgress keeps arriving and stops the run only+// after a full window without progress.+describe('progress-aware deadline integration (Bun-pinned)', () => {+ test('a run that keeps progressing past the deadline is never stopped', async () => {+ const r = await runHarness('progress-with', 300, 150, 6000, 400);+ expect(r.killedByTest).toBe(false);+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toContain('COMPLETED');+ expect(r.stdout).not.toContain('STOP-NOTICE');+ expect(r.stderr).toContain('still progressing');+ }, 15000);++ test('a run that stops progressing is stopped one window later, with the stop notice on stdout', async () => {+ const r = await runHarness('progress-stalls', 300, 150, 6000, 400);+ expect(r.killedByTest).toBe(false);+ expect(r.signalled).toBe(true);+ expect(r.stdout).toContain('STOP-NOTICE');+ expect(r.stdout).not.toContain('SURVIVED');+ expect(r.stderr).toContain('no progress for');+ expect(r.elapsedMs).toBeLessThan(4000);+ }, 15000);+});+describe('loop-stall watchdog integration (Bun-pinned, #4281)', () => {test('starved loop with a SIGTERM listener is SIGTERMed then SIGKILLed around stall+grace', async () => {// stall 300 + grace 250 = ~550ms expected death (plus worker boot). Thediff --git a/test/process-watchdog.test.ts b/test/process-watchdog.test.tsindex 080dcff2ef..ad4d0dca79 100644--- a/test/process-watchdog.test.ts+++ b/test/process-watchdog.test.ts@@ -6,6 +6,7 @@import { describe, test, expect } from 'bun:test';import {watchdogDecision,+ progressDeadlineDecision,installProcessWatchdog,clampWatchdogTimers,MAX_WATCHDOG_TIMER_MS,@@ -303,3 +304,21 @@ describe('installLoopStallWatchdog (handle contract)', () => {h.dispose();});});++describe('progressDeadlineDecision (large-brain ceiling: never stop a progressing run)', () => {+ test('waits before the deadline whatever the progress age', () => {+ expect(progressDeadlineDecision(999, 1000, 10_000, 500)).toBe('wait');+ });++ test('past the deadline, recent progress extends', () => {+ expect(progressDeadlineDecision(5000, 1000, 499, 500)).toBe('extend');+ });++ test('past the deadline, a full window without progress stops (inclusive)', () => {+ expect(progressDeadlineDecision(5000, 1000, 500, 500)).toBe('stop');+ });++ test('a zero window keeps the strict wall-clock deadline', () => {+ expect(progressDeadlineDecision(1000, 1000, 0, 0)).toBe('stop');+ });+});diff --git a/test/sync-hard-deadline.test.ts b/test/sync-hard-deadline.test.tsindex 33716c455b..333308db33 100644--- a/test/sync-hard-deadline.test.ts+++ b/test/sync-hard-deadline.test.ts@@ -10,6 +10,7 @@ import {DEFAULT_SYNC_STALL_ABORT_SEC,HARD_DEADLINE_GRACE_SEC,} from '../src/commands/sync.ts';+import { syncDeadlineStopNotice } from '../src/core/sync-reconcile.ts';const GRACE_MS = HARD_DEADLINE_GRACE_SEC * 1000;@@ -68,7 +69,7 @@ describe('resolveSyncHardDeadline', () => {test('env GBRAIN_SYNC_MAX_RUNTIME_SECONDS sets the deadline', () => {const r = resolveSyncHardDeadline([], { isTty: true, env: { GBRAIN_SYNC_MAX_RUNTIME_SECONDS: '900' } });- expect(r).toEqual({ deadlineMs: 900_000, graceMs: GRACE_MS, reason: 'env:GBRAIN_SYNC_MAX_RUNTIME_SECONDS' });+ expect(r).toEqual({ deadlineMs: 900_000, graceMs: GRACE_MS, reason: 'env:GBRAIN_SYNC_MAX_RUNTIME_SECONDS', progressWindowMs: 900_000 });});test('env 0 disables (overrides the non-TTY default)', () => {@@ -78,7 +79,7 @@ describe('resolveSyncHardDeadline', () => {test('non-TTY default is 3600s', () => {const r = resolveSyncHardDeadline([], { isTty: false });- expect(r).toEqual({ deadlineMs: 3_600_000, graceMs: GRACE_MS, reason: 'default:non-tty' });+ expect(r).toEqual({ deadlineMs: 3_600_000, graceMs: GRACE_MS, reason: 'default:non-tty', progressWindowMs: 900_000 });});test('TTY interactive with no flag/env arms nothing', () => {@@ -91,6 +92,40 @@ describe('resolveSyncHardDeadline', () => {});});+// F4d: the default and env deadlines must never stop a sync that is still+// importing; the explicit flags stay strict wall-clock caps.+describe('progress-aware sync deadline (large-brain ceiling)', () => {+ test('default and env deadlines carry the stall window as their progress window', () => {+ expect(resolveSyncHardDeadline([], { isTty: false, env: { GBRAIN_SYNC_STALL_ABORT_SECONDS: '120' } })?.progressWindowMs).toBe(120_000);+ expect(resolveSyncHardDeadline([], { isTty: true, env: { GBRAIN_SYNC_MAX_RUNTIME_SECONDS: '60', GBRAIN_SYNC_STALL_ABORT_SECONDS: '30' } })?.progressWindowMs).toBe(30_000);+ });++ test('a disabled stall watchdog still leaves a default progress window, never a hair trigger', () => {+ expect(resolveSyncHardDeadline([], { isTty: false, env: { GBRAIN_SYNC_STALL_ABORT_SECONDS: '0' } })?.progressWindowMs)+ .toBe(DEFAULT_SYNC_STALL_ABORT_SEC * 1000);+ });++ test('--hard-deadline and --timeout stay strict (no progress window)', () => {+ expect(resolveSyncHardDeadline(['--hard-deadline', '120'], { isTty: false })?.progressWindowMs).toBeUndefined();+ expect(resolveSyncHardDeadline(['--source', 'x', '--timeout', '60'], { isTty: false })?.progressWindowMs).toBeUndefined();+ });++ test('the stop notice names the cause, the code and the exact resume command', () => {+ const res = resolveSyncHardDeadline([], { isTty: false })!;+ const line = syncDeadlineStopNotice(['--source', 'notes', '--no-pull'], res);+ expect(line).toContain('code=sync_deadline_stop');+ expect(line).toContain('the 3600s sync deadline (default:non-tty) passed and the run made no progress for 900s');+ expect(line).toContain('Resume with: gbrain sync --source notes --no-pull.');+ });++ test('under --json the stop notice is one parseable object', () => {+ const res = resolveSyncHardDeadline(['--hard-deadline', '60'], { isTty: false })!;+ const notice = JSON.parse(syncDeadlineStopNotice(['--hard-deadline', '60', '--json'], res));+ expect(notice).toMatchObject({ status: 'stopped', code: 'sync_deadline_stop', deadline_seconds: 60, progress_window_seconds: null,+ resume_command: 'gbrain sync --hard-deadline 60 --json' });+ });+});+describe('composeAbortSignals', () => {test('all-undefined returns undefined', () => {expect(composeAbortSignals(undefined, undefined)).toBeUndefined();