pi-better-background-tasks 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +131 -4
  2. package/package.json +3 -1
  3. package/src/adapter-contract.ts +16 -2
  4. package/src/batch.ts +108 -0
  5. package/src/delivery-observer.ts +42 -0
  6. package/src/goal-provider.ts +72 -5
  7. package/src/index.ts +39 -0
  8. package/src/navigator-provider.ts +175 -6
  9. package/src/observed-waits.ts +3677 -0
  10. package/src/output.ts +22 -2
  11. package/src/process.ts +100 -1
  12. package/src/runtime.ts +189 -10
  13. package/src/sandbox.ts +276 -2
  14. package/src/shared-callback-batcher.ts +18 -1
  15. package/src/shared-execution-policy.ts +2 -0
  16. package/src/shared-failure-observations.ts +78 -24
  17. package/src/shared-log-utils.ts +277 -31
  18. package/src/shared-operation-coordinator/index.ts +113 -0
  19. package/src/shared-operation-coordinator/src/errors.ts +75 -0
  20. package/src/shared-operation-coordinator/src/operations.ts +376 -0
  21. package/src/shared-operation-coordinator/src/outbox.ts +431 -0
  22. package/src/shared-operation-coordinator/src/rows.ts +439 -0
  23. package/src/shared-operation-coordinator/src/schema.ts +244 -0
  24. package/src/shared-operation-coordinator/src/sqlite.ts +239 -0
  25. package/src/shared-operation-coordinator/src/store.ts +397 -0
  26. package/src/shared-operation-coordinator/src/types.ts +648 -0
  27. package/src/shared-operation-coordinator/src/validate.ts +239 -0
  28. package/src/shared-operation-coordinator/src/waits.ts +1378 -0
  29. package/src/stall.ts +4 -1
  30. package/src/supervisor/README.md +111 -0
  31. package/src/supervisor/emit-runner.mjs +101 -0
  32. package/src/supervisor/generated/conditions.mjs +96 -0
  33. package/src/supervisor/generated/identity.mjs +95 -0
  34. package/src/supervisor/generated/process-identity.mjs +43 -0
  35. package/src/supervisor/generated/process.mjs +514 -0
  36. package/src/supervisor/generated/runner.mjs +872 -0
  37. package/src/supervisor/generated/store.mjs +605 -0
  38. package/src/supervisor/generated/types.mjs +50 -0
  39. package/src/supervisor/identity.ts +99 -0
  40. package/src/supervisor/index.ts +37 -0
  41. package/src/supervisor/invocation.ts +44 -0
  42. package/src/supervisor/runner.ts +982 -0
  43. package/src/supervisor/store.ts +649 -0
  44. package/src/supervisor/supervisor.ts +730 -0
  45. package/src/supervisor/types.ts +384 -0
  46. package/src/tools.ts +410 -12
  47. package/src/types.ts +41 -1
package/src/output.ts CHANGED
@@ -224,7 +224,20 @@ function formatDecision(meta: BackgroundTaskMeta): string | undefined {
224
224
  lines.push(formatCondition(result.matchedCondition, result.matchedValue));
225
225
  }
226
226
  if (meta.lastExitCode !== undefined || meta.lastSignal) {
227
- lines.push(`exit=${meta.lastExitCode ?? "null"}${meta.lastSignal ? ` signal=${meta.lastSignal}` : ""}`);
227
+ // A gated task's exit can be a failing step's code rather than the last command's (#619).
228
+ const gate = meta.stepGateFailure ? " (step gate)" : "";
229
+ lines.push(`exit=${meta.lastExitCode ?? "null"}${meta.lastSignal ? ` signal=${meta.lastSignal}` : ""}${gate}`);
230
+ }
231
+ if (meta.stepGateFailure) {
232
+ // "stopped at that step" is the usual errexit case; a differing shell exit means the
233
+ // command disabled errexit and the gate's EXIT override or the command decided the exit.
234
+ const gate = meta.stepGateFailure;
235
+ const ending = gate.shellExitCode === null
236
+ ? "the shell exit is unknown"
237
+ : gate.shellExitCode === gate.stepExitCode
238
+ ? "the shell stopped at that step"
239
+ : `the shell's own exit was ${gate.shellExitCode}`;
240
+ lines.push(`step gate: ${oneLine(gate.command || "a chained step", 120)} exited ${gate.stepExitCode}; ${ending}`);
228
241
  }
229
242
  if (result.reason && !result.matchedCondition) lines.push(oneLine(result.reason, 240));
230
243
  if (meta.error && meta.error !== meta.stopError && meta.error !== result.reason) {
@@ -288,6 +301,11 @@ function formatProcessDiagnostics(diagnostics: TaskProcessDiagnostics | undefine
288
301
  return `process diagnostics: ${facts}\nA snapshot cannot prove useful work or a hang.`;
289
302
  }
290
303
 
304
+ function formatStepGate(meta: BackgroundTaskMeta): string | undefined {
305
+ if (!meta.requireSuccessfulSteps) return undefined;
306
+ return "step gate: on; the command runs under bash errexit, so its first unhandled failing step ends the task.";
307
+ }
308
+
291
309
  function formatLaunchSandbox(meta: BackgroundTaskMeta): string | undefined {
292
310
  const sandbox = meta.sandbox;
293
311
  if (!sandbox) return "sandbox: unknown; launch-time policy was not recorded.";
@@ -330,6 +348,8 @@ function contentRevision(meta: BackgroundTaskMeta, stall?: StallObservation): st
330
348
  meta.lastProgressAt ?? null,
331
349
  meta.lastExitCode ?? null,
332
350
  meta.lastSignal ?? null,
351
+ meta.requireSuccessfulSteps ?? null,
352
+ meta.stepGateFailure ?? null,
333
353
  meta.error ?? null,
334
354
  meta.stopError ?? null,
335
355
  meta.logGeneration ?? 0,
@@ -493,7 +513,7 @@ export function formatLaunch(meta: BackgroundTaskMeta, firstCheck?: FirstWatchCh
493
513
  identity: `Started background ${meta.kind} ${label}. Status: ${meta.status}.`,
494
514
  failure: incidentSection(meta.id, {}),
495
515
  decision: formatDecision(meta),
496
- diagnostics: [formatLaunchSandbox(meta), ...remoteLines, ...(checkText ? [checkText] : [])].filter(Boolean).join("\n") || undefined,
516
+ diagnostics: [formatLaunchSandbox(meta), formatStepGate(meta), ...remoteLines, ...(checkText ? [checkText] : [])].filter(Boolean).join("\n") || undefined,
497
517
  progress: withLog ? logLine : undefined,
498
518
  },
499
519
  gaps: taskGaps(meta),
package/src/process.ts CHANGED
@@ -2,7 +2,7 @@ import { spawn, spawnSync } from "node:child_process";
2
2
  import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import type { ChildProcess } from "node:child_process";
5
- import type { CommandResult, CommandSpec } from "./types.js";
5
+ import type { CommandResult, CommandSpec, StepGateFailure } from "./types.js";
6
6
 
7
7
  /** Known Git for Windows locations; `bash -lc` needs a real bash, not the WSL shim. */
8
8
  const WINDOWS_BASH_CANDIDATES = [
@@ -75,6 +75,105 @@ export function bashSingleQuote(value: string): string {
75
75
  return `'${value.replace(/'/g, "'\\''")}'`;
76
76
  }
77
77
 
78
+ /**
79
+ * Env var carrying the operator's own command into a gated launch (#619).
80
+ *
81
+ * The gate script `eval`s this value instead of concatenating it, so a command
82
+ * containing quotes, heredocs, or multiple lines is parsed exactly as bash would
83
+ * parse it alone. The value is also kept out of the spawned argv.
84
+ */
85
+ export const STEP_GATE_COMMAND_ENV = "PI_BG_STEP_GATE_COMMAND";
86
+
87
+ /** Longest failing-step text recorded in task metadata; the log keeps it whole. */
88
+ export const STEP_GATE_COMMAND_CHARS = 160;
89
+
90
+ /**
91
+ * Bash script that runs an opt-in step gate around the operator's command (#619).
92
+ *
93
+ * The gate is a bash `errexit` contract, not shell parsing: `set -e` ends the
94
+ * command at the first unhandled failing step with that step's exit code, so a
95
+ * later command — in the same list, a function, a subshell, or a command
96
+ * substitution — can no longer turn a red gate green. A failure the command
97
+ * handles itself (`|| true`, `if`/`while`/`until` conditions, `!`, `&&`/`||`
98
+ * lists) is not a gate failure, and a discarded process-substitution status is
99
+ * not one either. `set -E` lets the ERR trap name a failure inside a shell
100
+ * function (functions run in the main shell); the trap records only main-shell
101
+ * failures (`BASH_SUBSHELL` 0), so a status bash itself discards is never claimed
102
+ * as the verdict — an unhandled command substitution still fails its assignment
103
+ * in the main shell. The EXIT trap writes the verdict to stderr, where the
104
+ * harness reads it back, and forces a failing step's code when the command
105
+ * disabled errexit and would have exited 0.
106
+ *
107
+ * Exposed for tests and reuse.
108
+ */
109
+ export function stepGateScript(id: string): string {
110
+ return [
111
+ "# Step gate (#619) from pi-better-background-tasks: bash errexit ends the command at its first unhandled failing step.",
112
+ "set -E",
113
+ "set -e",
114
+ `__pi_step_gate_id=${bashSingleQuote(id)}`,
115
+ "__pi_step_gate_first=0",
116
+ "__pi_step_gate_command=",
117
+ "__pi_step_gate_record() {",
118
+ " __pi_step_gate_status=$?",
119
+ " if [ \"${BASH_SUBSHELL:-0}\" -eq 0 ] && [ \"${__pi_step_gate_first:-0}\" -eq 0 ] && [ \"$__pi_step_gate_status\" -ne 0 ]; then",
120
+ " __pi_step_gate_first=$__pi_step_gate_status",
121
+ " __pi_step_gate_command=${BASH_COMMAND:-}",
122
+ " fi",
123
+ " return 0",
124
+ "}",
125
+ "__pi_step_gate_finish() {",
126
+ " __pi_step_gate_status=$?",
127
+ " if [ \"${__pi_step_gate_first:-0}\" -ne 0 ]; then",
128
+ " __pi_step_gate_text=${__pi_step_gate_command//$'\\n'/ }",
129
+ " printf '\\n--- step gate [%s]: first failing step exit=%s; shell exit=%s: %s ---\\n' \"$__pi_step_gate_id\" \"$__pi_step_gate_first\" \"$__pi_step_gate_status\" \"$__pi_step_gate_text\" >&2",
130
+ " if [ \"$__pi_step_gate_status\" -eq 0 ]; then exit \"$__pi_step_gate_first\"; fi",
131
+ " fi",
132
+ " exit \"$__pi_step_gate_status\"",
133
+ "}",
134
+ "trap '__pi_step_gate_record' ERR",
135
+ "trap '__pi_step_gate_finish' EXIT",
136
+ `if [ -z "\${${STEP_GATE_COMMAND_ENV}:-}" ]; then`,
137
+ " printf '\\n--- step gate [%s]: the gated command was not provided; nothing ran ---\\n' \"$__pi_step_gate_id\" >&2",
138
+ " exit 125",
139
+ "fi",
140
+ `eval "\${${STEP_GATE_COMMAND_ENV}}"`,
141
+ ].join("\n");
142
+ }
143
+
144
+ /**
145
+ * Read the gate's verdict marker from a task log (#619). Bash writes it as the last
146
+ * line of stderr, so log retention cannot turn a red gate green; a missing marker
147
+ * only costs the failing command's name, never the verdict carried by the exit code.
148
+ *
149
+ * Exposed for tests and reuse.
150
+ */
151
+ export function parseStepGateFailure(logText: string, id: string): StepGateFailure | undefined {
152
+ const marker = `--- step gate [${id}]: first failing step exit=`;
153
+ let found: StepGateFailure | undefined;
154
+ for (const rawLine of logText.split("\n")) {
155
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
156
+ if (!line.startsWith(marker) || !line.endsWith(" ---")) continue;
157
+ const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
158
+ if (!match) continue;
159
+ const stepExitCode = Number(match[1]);
160
+ const shellExitCode = Number(match[2]);
161
+ if (!Number.isInteger(stepExitCode) || stepExitCode === 0) continue;
162
+ // The marker is the newest evidence, and the shell writes only the first failing step.
163
+ found = {
164
+ stepExitCode,
165
+ shellExitCode: Number.isInteger(shellExitCode) ? shellExitCode : null,
166
+ command: boundedStepCommand(match[3]),
167
+ };
168
+ }
169
+ return found;
170
+ }
171
+
172
+ function boundedStepCommand(value: string): string {
173
+ const oneLine = value.replace(/\s+/g, " ").trim();
174
+ return oneLine.length > STEP_GATE_COMMAND_CHARS ? `${oneLine.slice(0, STEP_GATE_COMMAND_CHARS - 1)}…` : oneLine;
175
+ }
176
+
78
177
  /**
79
178
  * On Windows, numeric fds above 2 are unusable as child stdio: Node spawns the
80
179
  * process, but its output handles end up broken, every write fails, and shell
package/src/runtime.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { statSync } from "node:fs";
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync, statSync } from "node:fs";
2
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
4
  import { appendLine, appendTaskOutput, appendWatchResult, retainLogTail, resolveMaxLogBytes } from "./logs.js";
4
5
  import { evaluateCondition, validateCondition } from "./conditions.js";
5
- import { processExists, runCommandOnce, spawnCommand, stopProcessGroup } from "./process.js";
6
+ import { parseStepGateFailure, processExists, runCommandOnce, spawnCommand, STEP_GATE_COMMAND_ENV, stepGateScript, stopProcessGroup } from "./process.js";
6
7
  import { currentProcessStartToken, readProcessStartToken } from "./process-identity.js";
7
8
  import { DEFAULT_TMUX_BOOTSTRAP_TIMEOUT_MS, expandSshRemoteTaskPreset } from "./remote-task-preset.js";
8
9
  import type { RemoteRunner, ResolvedSshRemoteTask } from "./remote-task-preset.js";
@@ -22,6 +23,7 @@ import type {
22
23
  FirstWatchCheck,
23
24
  RemoteTaskParams,
24
25
  SshConnectionParams,
26
+ StepGateFailure,
25
27
  TerminalResult,
26
28
  } from "./types.js";
27
29
  import { observeTaskStallAttention } from "./stall-attention.js";
@@ -167,9 +169,23 @@ export interface TaskIntentParams {
167
169
 
168
170
  export interface SpawnTaskParams extends CommandSpec, TaskIntentParams {
169
171
  name?: string;
172
+ /**
173
+ * Batch identity assigned by the batch launcher, never declared by a caller.
174
+ * Absent for a single spawn; carried into the persisted metadata so batch
175
+ * membership survives a reload instead of living only in the launch result.
176
+ */
177
+ batchId?: string;
178
+ /** Batch label from the same launch, when the operator gave one. */
179
+ batchName?: string;
170
180
  callback?: boolean;
171
181
  timeout_seconds?: number;
172
182
  max_log_bytes?: number;
183
+ /**
184
+ * Opt-in step gate (#619): run the command under bash errexit, so the first
185
+ * unhandled failing step ends the task with that step's exit code and a later
186
+ * command cannot mask it.
187
+ */
188
+ require_successful_steps?: boolean;
173
189
  ssh?: SshConnectionParams;
174
190
  remote?: RemoteTaskParams;
175
191
  }
@@ -182,6 +198,12 @@ export interface WatchTaskParams extends CommandSpec, TaskIntentParams {
182
198
  max_log_bytes?: number;
183
199
  success_when: Condition;
184
200
  failure_when?: Condition;
201
+ /**
202
+ * Rejected (#619): a watch check is one polled command whose own exit code is the
203
+ * outcome, so the step gate cannot apply. Accepted in the shared schema only where
204
+ * the same wrapper also spawns.
205
+ */
206
+ require_successful_steps?: boolean;
185
207
  /** Consecutive blind checks before the watch is flagged (#359). Default 3; 0 turns it off. */
186
208
  blind_checks?: number;
187
209
  ssh?: SshConnectionParams;
@@ -190,6 +212,12 @@ export interface WatchTaskParams extends CommandSpec, TaskIntentParams {
190
212
 
191
213
  export interface TaskRuntimeDependencies {
192
214
  remoteRunner?: RemoteRunner;
215
+ /**
216
+ * Embedding/test seam for a local watch's poll command. Production polls run
217
+ * the persisted command through `runCommandOnce`; a remote watch keeps using
218
+ * its SSH runner instead.
219
+ */
220
+ watchPollRunner?: WatchPollRunner;
193
221
  }
194
222
 
195
223
  /**
@@ -201,6 +229,46 @@ function withCommandPolicy(meta: BackgroundTaskMeta, seconds: number | undefined
201
229
  return seconds === undefined ? meta : { ...meta, commandTimeoutSeconds: seconds };
202
230
  }
203
231
 
232
+ /**
233
+ * The step gate applies to a shell command only (#619). A direct argv launch already
234
+ * reports the real exit code, and a structured SSH command runs under remote
235
+ * semantics the local gate cannot observe, so both are refused rather than silently
236
+ * ignored: a gate that quietly does nothing is the masking bug it exists to fix.
237
+ */
238
+ function stepGateRefusal(params: SpawnTaskParams): string | undefined {
239
+ if (params.require_successful_steps !== true) return undefined;
240
+ if (params.shell === false) {
241
+ return "Invalid step gate: require_successful_steps needs a shell command; argv with shell:false already reports the real exit code. The task was not started.";
242
+ }
243
+ if (!params.command || params.command.trim().length === 0) {
244
+ return "Invalid step gate: require_successful_steps needs a non-empty shell command. The task was not started.";
245
+ }
246
+ if (params.ssh) {
247
+ return "Invalid step gate: require_successful_steps is local-only and cannot observe a structured ssh command. The task was not started.";
248
+ }
249
+ return undefined;
250
+ }
251
+
252
+ /** Read the gate verdict bash wrote at the end of the task log (#619). */
253
+ function readStepGateFailure(meta: BackgroundTaskMeta): StepGateFailure | undefined {
254
+ try {
255
+ return parseStepGateFailure(readFileSync(meta.logPath, "utf8"), meta.id);
256
+ } catch {
257
+ // A swept temp dir or an unreadable log costs the reason, never the verdict.
258
+ return undefined;
259
+ }
260
+ }
261
+
262
+ /**
263
+ * The command actually spawned for a gated task: bash runs the gate script and
264
+ * `eval`s the operator's own command from `STEP_GATE_COMMAND_ENV`. Meta keeps the
265
+ * operator's command verbatim, so status, log, and recovery never show the wrapper.
266
+ */
267
+ function withStepGate(spec: CommandSpec, id: string, gated: boolean): CommandSpec {
268
+ if (!gated) return spec;
269
+ return { ...spec, command: stepGateScript(id), env: { ...spec.env, [STEP_GATE_COMMAND_ENV]: spec.command! } };
270
+ }
271
+
204
272
  function persistedCommandCapSeconds(meta: BackgroundTaskMeta): number | undefined {
205
273
  const value = meta.commandTimeoutSeconds;
206
274
  return isCommandTimeoutSeconds(value) ? value : undefined;
@@ -231,6 +299,10 @@ export function spawnTask(
231
299
  // Resolved before any task directory, log, or metadata exists so a blocked
232
300
  // launch leaves nothing behind. Structured SSH must also honor launch restrictions.
233
301
  const intent = readTaskIntent(params);
302
+ // A gate that could only be silently ignored is refused before any task state exists (#619).
303
+ const stepGateRefused = stepGateRefusal(params);
304
+ if (stepGateRefused) throw new Error(stepGateRefused);
305
+ const stepGated = params.require_successful_steps === true;
234
306
  const cwd = params.cwd ?? defaultCwd;
235
307
  const sandboxPlan = resolveForegroundSandboxPlan(pi, !!params.ssh, params);
236
308
  // The application/shell switches apply before any task state exists, so a
@@ -253,7 +325,8 @@ export function spawnTask(
253
325
  remote: params.remote,
254
326
  }, dependencies.remoteRunner)
255
327
  : undefined;
256
- const commandSpec: CommandSpec = remoteTask?.commandSpec ?? { ...params, cwd, shell: params.shell ?? true };
328
+ const operatorSpec: CommandSpec = remoteTask?.commandSpec ?? { ...params, cwd, shell: params.shell ?? true };
329
+ const commandSpec = withStepGate(operatorSpec, id, stepGated);
257
330
  const sandboxNotices: string[] = [];
258
331
  const launchSpec = remoteTask
259
332
  ? commandSpec
@@ -281,6 +354,8 @@ export function spawnTask(
281
354
  const meta = withCommandPolicy({
282
355
  id,
283
356
  name: params.name,
357
+ batchId: params.batchId,
358
+ batchName: params.batchName,
284
359
  kind: "process",
285
360
  status: "running",
286
361
  startedAt: now,
@@ -292,6 +367,7 @@ export function spawnTask(
292
367
  command: params.command,
293
368
  argv: commandSpec.argv,
294
369
  shell: commandSpec.shell,
370
+ ...(stepGated ? { requireSuccessfulSteps: true } : {}),
295
371
  cwd,
296
372
  env: params.env,
297
373
  launchArgv: launchArgvOf(commandSpec, launchSpec),
@@ -321,8 +397,17 @@ export function spawnTask(
321
397
  if (!latest) return;
322
398
  enforceLogRetention(latest);
323
399
  if (isTerminalStatus(latest.status)) return;
324
- if (exitCode !== 0) recordExitFailure(latest, "execution", `Process exited with code ${exitCode ?? "unknown"}${signal ? ` (${signal})` : ""}`, exitCode, "close", { at: Date.now() });
325
- else {
400
+ // The gate's own marker names the failing step (#619). It never decides the
401
+ // verdict: bash errexit already exits with that step's code (and the gate's EXIT
402
+ // trap forces it when a command disabled errexit), so a missing marker loses the
403
+ // reason, not the failure.
404
+ const stepGateFailure = latest.requireSuccessfulSteps ? readStepGateFailure(latest) : undefined;
405
+ const detail = `Process exited with code ${exitCode ?? "unknown"}${signal ? ` (${signal})` : ""}`;
406
+ if (exitCode !== 0) {
407
+ recordExitFailure(latest, "execution", stepGateFailure
408
+ ? `${detail}; step gate: ${stepGateFailure.command || "a chained step"} exited ${stepGateFailure.stepExitCode}`
409
+ : detail, exitCode, "close", { at: Date.now() });
410
+ } else {
326
411
  recoverFailure(latest, "execution", "close");
327
412
  recoverDeclaredOperation(latest);
328
413
  }
@@ -330,6 +415,7 @@ export function spawnTask(
330
415
  latest.endedAt = Date.now();
331
416
  latest.lastExitCode = exitCode;
332
417
  latest.lastSignal = signal;
418
+ if (stepGateFailure) latest.stepGateFailure = stepGateFailure;
333
419
  latest.result = { exitCode, signal };
334
420
  writeMeta(latest);
335
421
  void notifyTerminal(pi, latest, getActiveSession);
@@ -527,6 +613,9 @@ export function startWatchTask(
527
613
  const error = condition && validateCondition(condition);
528
614
  if (error) throw new Error(`${name}: ${error}`);
529
615
  }
616
+ if (params.require_successful_steps === true) {
617
+ throw new Error("Invalid step gate: require_successful_steps is for a spawned shell command; a watch poll reports its own exit code as the outcome. The task was not started.");
618
+ }
530
619
  const blindChecks = readBlindChecks(params.blind_checks);
531
620
  const intent = readTaskIntent(params);
532
621
  const cwd = params.cwd ?? defaultCwd;
@@ -591,7 +680,7 @@ export function startWatchTask(
591
680
  firstCheckWaiters.set(id, { promise: firstCheck, resolve: resolveFirst });
592
681
  scheduleWatch(pi, id, 0, getActiveSession, remoteTask
593
682
  ? (timeoutMs) => remoteTask.runOnce(undefined, timeoutMs)
594
- : undefined);
683
+ : dependencies.watchPollRunner);
595
684
  return meta;
596
685
  }
597
686
 
@@ -642,7 +731,7 @@ export function resumeRunningTask(
642
731
  if (meta.kind === "command_watch") {
643
732
  scheduleWatch(pi, meta.id, 0, getActiveSession, remoteTask
644
733
  ? (timeoutMs) => remoteTask.runOnce(undefined, timeoutMs)
645
- : undefined);
734
+ : dependencies.watchPollRunner);
646
735
  return meta;
647
736
  }
648
737
 
@@ -912,10 +1001,10 @@ async function pollWatch(
912
1001
  applyCaptureOverflow(latest, result);
913
1002
  enforceLogRetention(latest);
914
1003
  latest.lastCheckedAt = Date.now();
915
- latest.lastProgressAt = latest.lastCheckedAt;
916
1004
  latest.lastExitCode = result.exitCode;
917
1005
  latest.lastSignal = result.signal;
918
1006
  latest.lastState = extractLastState(result);
1007
+ observeWatchOutcome(latest, result);
919
1008
 
920
1009
  const pollKey = result.startedAt;
921
1010
  if (result.timedOut) {
@@ -1386,7 +1475,10 @@ function enforceLogRetention(meta: BackgroundTaskMeta): void {
1386
1475
  const log = statSync(meta.logPath);
1387
1476
  const mtimeMs = Math.trunc(log.mtimeMs);
1388
1477
  const maintenance = meta.logMaintenance?.mtimeMs === mtimeMs && meta.logMaintenance.size === log.size;
1389
- if (!maintenance && mtimeMs > (meta.lastProgressAt ?? meta.startedAt)) {
1478
+ // A watch's log only records its own polls, so its mtime is poll activity and
1479
+ // never evidence that the watch's observed outcome moved. Spawned processes
1480
+ // keep taking real log writes as progress.
1481
+ if (meta.kind !== "command_watch" && !maintenance && mtimeMs > (meta.lastProgressAt ?? meta.startedAt)) {
1390
1482
  meta.lastProgressAt = mtimeMs;
1391
1483
  writeMeta(meta);
1392
1484
  }
@@ -1428,4 +1520,91 @@ function extractLastState(result: { stdout: string }): unknown {
1428
1520
  } catch {
1429
1521
  return result.stdout.slice(0, 4000);
1430
1522
  }
1431
- }
1523
+ }
1524
+
1525
+ /** Version tag of the watch outcome fingerprint. A value from another version is adopted, never compared. */
1526
+ const WATCH_FINGERPRINT_VERSION = "v1";
1527
+ /** OSC and CSI control sequences are display markup, not content. */
1528
+ const TERMINAL_ESCAPE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]/g;
1529
+
1530
+ /**
1531
+ * Text as the terminal would settle it. Redraw frames and control sequences are
1532
+ * display churn: repainting the same visible line is not a new observation.
1533
+ */
1534
+ function settledTerminalText(text: string): string {
1535
+ return text
1536
+ .replace(TERMINAL_ESCAPE, "")
1537
+ .split("\n")
1538
+ .map((line) => {
1539
+ // A CR immediately before LF ends the line; any other CR overwrites it in place.
1540
+ const body = line.endsWith("\r") ? line.slice(0, -1) : line;
1541
+ return (body.split("\r").at(-1) ?? "").replace(/[ \t]+$/, "");
1542
+ })
1543
+ .join("\n")
1544
+ .replace(/\n+$/, "");
1545
+ }
1546
+
1547
+ /** Objects compare by content regardless of key order, so reordered keys are not progress. */
1548
+ function canonicalJsonText(value: unknown): string {
1549
+ if (Array.isArray(value)) return `[${value.map(canonicalJsonText).join(",")}]`;
1550
+ if (value && typeof value === "object") {
1551
+ const record = value as Record<string, unknown>;
1552
+ const entries = Object.keys(record).sort()
1553
+ .map((key) => `${JSON.stringify(key)}:${canonicalJsonText(record[key])}`);
1554
+ return `{${entries.join(",")}}`;
1555
+ }
1556
+ return JSON.stringify(value) ?? "null";
1557
+ }
1558
+
1559
+ /** stdout compares as JSON content when it parses, and as settled text otherwise. */
1560
+ function canonicalWatchStdout(stdout: string): string {
1561
+ const settled = settledTerminalText(stdout);
1562
+ try {
1563
+ return `json:${canonicalJsonText(JSON.parse(settled))}`;
1564
+ } catch {
1565
+ return `text:${settled}`;
1566
+ }
1567
+ }
1568
+
1569
+ /**
1570
+ * What a poll observed, independent of when it ran. Exit status, signal, error,
1571
+ * stdout content, and stderr content are included; poll metadata (start time,
1572
+ * end time, duration, check count) is deliberately not, so it can never hide a
1573
+ * watch that reports the same outcome forever. Watch stdout may carry its own
1574
+ * timestamps: projecting meaningful fields is the caller's job, not this
1575
+ * fingerprint's guess.
1576
+ */
1577
+ function watchOutcomeFingerprint(result: CommandResult): string {
1578
+ // A runner may report why the check itself could not run; that is part of the
1579
+ // observed outcome, not poll metadata.
1580
+ const reported = (result as CommandResult & { error?: unknown }).error;
1581
+ const error = typeof reported === "string" ? settledTerminalText(reported) : null;
1582
+ const payload = JSON.stringify([
1583
+ result.exitCode,
1584
+ result.signal ?? null,
1585
+ result.timedOut === true,
1586
+ error,
1587
+ canonicalWatchStdout(result.stdout),
1588
+ settledTerminalText(result.stderr),
1589
+ ]);
1590
+ return `${WATCH_FINGERPRINT_VERSION}:${createHash("sha256").update(payload).digest("hex")}`;
1591
+ }
1592
+
1593
+ /**
1594
+ * A watch's state clock advances only when its observed outcome changes. The
1595
+ * poll itself is activity (`lastCheckedAt`), not progress, so a stationary
1596
+ * watch still becomes quiet and then a suspected stall while it keeps polling.
1597
+ * A record with no current fingerprint is adopted without moving the clock, so
1598
+ * an upgrade or reload cannot keep resetting that silence.
1599
+ */
1600
+ function observeWatchOutcome(meta: BackgroundTaskMeta, result: CommandResult): void {
1601
+ const fingerprint = watchOutcomeFingerprint(result);
1602
+ const prior = meta.watchFingerprint;
1603
+ meta.watchFingerprint = fingerprint;
1604
+ const comparable = typeof prior === "string" && prior.startsWith(`${WATCH_FINGERPRINT_VERSION}:`);
1605
+ if (!comparable) {
1606
+ if (meta.lastProgressAt === undefined) meta.lastProgressAt = meta.startedAt;
1607
+ return;
1608
+ }
1609
+ if (prior !== fingerprint) meta.lastProgressAt = meta.lastCheckedAt ?? Date.now();
1610
+ }