pi-spine 2.2.0 → 2.3.1

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 (56) hide show
  1. package/bin/spine-cli/verify.mjs +15 -46
  2. package/package.json +1 -1
  3. package/src/batch/attached-runner-promote.mjs +370 -0
  4. package/src/batch/attached-runner-reconcile.mjs +291 -0
  5. package/src/batch/attached-runner.mjs +24 -645
  6. package/src/batch/batch-guards.mjs +69 -0
  7. package/src/batch/contract-exec.mjs +483 -0
  8. package/src/batch/contract-parse.mjs +243 -0
  9. package/src/batch/contract-verify.mjs +32 -707
  10. package/src/batch/detached-diagnostics.mjs +255 -0
  11. package/src/batch/detached-run.mjs +326 -0
  12. package/src/batch/detached-start.mjs +18 -894
  13. package/src/batch/detached-wait.mjs +346 -0
  14. package/src/batch/diagnosis.mjs +35 -4
  15. package/src/batch/engine-lanes/orch-sync.mjs +126 -0
  16. package/src/batch/engine-lanes.mjs +69 -0
  17. package/src/batch/engine.mjs +8 -67
  18. package/src/batch/integrate-git.mjs +21 -0
  19. package/src/batch/integrate.mjs +5 -15
  20. package/src/batch/journal-rebuild-structural.mjs +352 -0
  21. package/src/batch/journal-rebuild.mjs +16 -348
  22. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  23. package/src/batch/lane-dirty-check-git.mjs +298 -0
  24. package/src/batch/lane-dirty-check.mjs +31 -297
  25. package/src/batch/reconcile-batch.mjs +495 -0
  26. package/src/batch/reconcile-classify.mjs +433 -0
  27. package/src/batch/reconcile-diagnosis.mjs +459 -0
  28. package/src/batch/reconcile-light-cache.mjs +61 -0
  29. package/src/batch/reconcile-orphan.mjs +198 -0
  30. package/src/batch/reconcile.mjs +19 -1693
  31. package/src/batch/resume-multi-lanes.mjs +6 -148
  32. package/src/batch/resume-multi-queue.mjs +159 -0
  33. package/src/batch/resume-single-validate.mjs +25 -0
  34. package/src/batch/resume.mjs +3 -20
  35. package/src/batch/review-artifacts.mjs +419 -0
  36. package/src/batch/review-step-run.mjs +383 -0
  37. package/src/batch/review-step.mjs +451 -0
  38. package/src/batch/review.mjs +32 -1199
  39. package/src/batch/salvage-batch-list.mjs +291 -0
  40. package/src/batch/salvage-batch.mjs +10 -284
  41. package/src/batch/sequence-plan.mjs +234 -0
  42. package/src/batch/sequence-run.mjs +418 -0
  43. package/src/batch/sequence-wait.mjs +167 -0
  44. package/src/batch/sequence.mjs +22 -783
  45. package/src/batch/state-guards.mjs +284 -0
  46. package/src/batch/state-io.mjs +135 -0
  47. package/src/batch/state.mjs +27 -396
  48. package/src/batch/worker-heartbeat.mjs +382 -0
  49. package/src/batch/worker-host.mjs +56 -548
  50. package/src/batch/worker-spawn.mjs +326 -0
  51. package/src/batch/worktree.mjs +68 -0
  52. package/src/config/preflight/integrate-plan.mjs +6 -1
  53. package/src/config/preflight/loc-capstone.mjs +274 -0
  54. package/src/config/spine-preflight-lib.mjs +14 -0
  55. package/src/planner/index.mjs +14 -3
  56. package/src/process/terminate-tree.mjs +154 -0
@@ -5,24 +5,6 @@
5
5
 
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
- import { spawn } from "node:child_process";
9
- import { fileURLToPath } from "node:url";
10
- import { readAbortSignal } from "./abort.mjs";
11
- import {
12
- activitySignalsChanged,
13
- checkpointSignalsChanged,
14
- collectProgressSignals,
15
- computeStallDeadline,
16
- recordCheckpointWarning,
17
- recordLaneHeartbeat,
18
- recordLaneProgressSnapshot,
19
- recordStallWarning,
20
- resolveHeartbeatKind,
21
- shouldEmitCheckpointWarning,
22
- shouldEmitProgressSnapshot,
23
- buildProgressSnapshotPayload,
24
- progressSnapshotPayloadChanged,
25
- } from "./heartbeat.mjs";
26
8
  import {
27
9
  resolveStallConfigForTask,
28
10
  resolveWorkerPiTimeoutMs,
@@ -31,23 +13,31 @@ import {
31
13
  import { parseContract } from "../tasks/packet/parse-prompt.mjs";
32
14
  import { appendJournalEvent } from "./journal.mjs";
33
15
  import { assertReviewToolAvailable } from "./review.mjs";
34
- import { startAgentSessionWorker } from "./agent-session-worker.mjs";
35
16
  import { finalizeWorkerOutput, createWorkerLiveLogWriter } from "./worker-output.mjs";
36
- import { nextStallAnchorAt } from "./engine-lanes/watch.mjs";
37
17
  import { resolveWorkerBackend } from "../config/worker-backend.mjs";
38
18
  import { commandExists } from "../util/command-exists.mjs";
39
- import { resolvePiSpineRoot } from "../config/pi-spine-root.mjs";
40
- import { resolveSafeWorkerLaunchScript } from "../config/worker-launch-script.mjs";
19
+ import {
20
+ collectChildOutput,
21
+ markChildPastPreflight,
22
+ resolveWorkerLaunchScript,
23
+ resolveWorkerPhase,
24
+ spawnWorkerHandle,
25
+ terminateHungWorkerChild,
26
+ CHILD_DONE_TIMEOUT_MS,
27
+ } from "./worker-spawn.mjs";
28
+ import {
29
+ createWorkerPollState,
30
+ pollWorkerUntilSettled,
31
+ } from "./worker-heartbeat.mjs";
32
+ import { terminateProcessTree } from "../process/terminate-tree.mjs";
41
33
 
42
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
43
- const PACKAGE_ROOT = path.resolve(__dirname, "../..");
34
+ export { buildWorkerChildEnv } from "./worker-spawn.mjs";
44
35
 
45
36
  const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
46
- const POST_DONE_KILL_BACKOFF_MS = 5_000;
47
- const CHILD_DONE_TIMEOUT_MS = 15_000;
48
37
 
49
38
  /**
50
- * Force-terminate lane worker processes tracked in batch state.
39
+ * Force-terminate lane worker process trees tracked in batch state.
40
+ * Reaps nested `pi` grandchildren, not only the tracked runner PID (SP-609 / #194).
51
41
  *
52
42
  * @param {unknown[]} lanes
53
43
  * @param {{ hard?: boolean }} [options]
@@ -64,29 +54,16 @@ export function terminateLaneWorkers(lanes, { hard = true } = {}) {
64
54
  const laneNumber = Number(
65
55
  /** @type {{ laneNumber?: number }} */ (lane).laneNumber ?? 1,
66
56
  );
67
- try {
68
- process.kill(workerPid, signal);
69
- terminated.push({ laneNumber, workerPid, signal });
70
- } catch {
71
- // process may already be gone
72
- }
57
+ const result = terminateProcessTree(workerPid, { signal });
58
+ if (result.signaled.length === 0) continue;
59
+ terminated.push({ laneNumber, workerPid, signal });
73
60
  }
74
61
  return terminated;
75
62
  }
76
63
 
77
- /** @typedef {"launching" | "pi" | "verify" | "unknown"} WorkerPhase */
64
+ /** @typedef {import("./worker-spawn.mjs").WorkerPhase} WorkerPhase */
78
65
 
79
- /**
80
- * @typedef {import("node:child_process").ChildProcess | {
81
- * pid: number;
82
- * exitCode: number | null;
83
- * kill: (signal?: NodeJS.Signals) => boolean;
84
- * wait?: () => Promise<{ exitCode: number; output: string }>;
85
- * stdout?: NodeJS.ReadableStream | null;
86
- * stderr?: NodeJS.ReadableStream | null;
87
- * on?: import("node:events").EventEmitter["on"];
88
- * }} WorkerChildHandle
89
- */
66
+ /** @typedef {import("./worker-spawn.mjs").WorkerChildHandle} WorkerChildHandle */
90
67
 
91
68
  /**
92
69
  * @param {number} ms
@@ -95,135 +72,6 @@ function sleep(ms) {
95
72
  return new Promise((resolve) => setTimeout(resolve, ms));
96
73
  }
97
74
 
98
-
99
- /**
100
- * @param {string} projectRoot
101
- * @param {object} [config]
102
- * @returns {string|null}
103
- */
104
- function resolveWorkerLaunchScript(projectRoot, config = {}) {
105
- return resolveSafeWorkerLaunchScript(projectRoot, config);
106
- }
107
-
108
- /**
109
- * @param {object} params
110
- * @param {string} params.taskFolder
111
- * @param {string} params.worktreePath
112
- * @param {string} [params.projectRoot]
113
- * @param {string} [params.batchId]
114
- * @param {number} [params.laneNumber]
115
- * @param {string} [params.taskId]
116
- * @param {string} [params.laneCorrelationId]
117
- * @param {string[]} [params.fileScopePaths]
118
- * @param {object} [params.config]
119
- * @param {number} [params.piTimeoutMs]
120
- */
121
- export function buildWorkerChildEnv({
122
- taskFolder,
123
- worktreePath,
124
- projectRoot,
125
- batchId,
126
- laneNumber,
127
- taskId,
128
- laneCorrelationId,
129
- fileScopePaths = [],
130
- config = {},
131
- piTimeoutMs,
132
- }) {
133
- const runner = path.join(PACKAGE_ROOT, "bin", "spine-worker-runner.mjs");
134
- /** @type {NodeJS.ProcessEnv} */
135
- const env = {
136
- ...process.env,
137
- SPINE_TASK_FOLDER: taskFolder,
138
- SPINE_WORKTREE: worktreePath,
139
- SPINE_WORKER_RUNNER: runner,
140
- SPINE_IS_WORKER: "1",
141
- PI_SPINE_ROOT: resolvePiSpineRoot(config, projectRoot ?? process.cwd()),
142
- };
143
- if (projectRoot) env.SPINE_PROJECT_ROOT = projectRoot;
144
- if (worktreePath) env.SPINE_RULES_PROJECT_ROOT = worktreePath;
145
- if (batchId) {
146
- env.SPINE_BATCH_ID = batchId;
147
- env.SPINE_JOURNAL_ATTACH = "1";
148
- delete env.SPINE_SUPPRESS_JOURNAL_ATTACH;
149
- }
150
- if (laneNumber != null) env.SPINE_LANE_NUMBER = String(laneNumber);
151
- if (taskId) env.SPINE_TASK_ID = taskId;
152
- if (laneCorrelationId) env.SPINE_LANE_CORRELATION_ID = laneCorrelationId;
153
- if (Array.isArray(fileScopePaths) && fileScopePaths.length > 0) {
154
- env.SPINE_TASK_FILE_SCOPE = JSON.stringify(fileScopePaths);
155
- }
156
- if (process.env.SPINE_WORKER_STUB === "1") {
157
- env.SPINE_REVIEW_STUB = "1";
158
- }
159
- if (piTimeoutMs != null && Number.isFinite(piTimeoutMs) && piTimeoutMs > 0) {
160
- env.SPINE_WORKER_PI_TIMEOUT_MS = String(
161
- process.env.SPINE_WORKER_PI_TIMEOUT_MS ?? piTimeoutMs,
162
- );
163
- }
164
- return env;
165
- }
166
-
167
- /**
168
- * @param {object} params
169
- * @param {string} params.worktreePath
170
- * @param {string} params.taskFolder
171
- * @param {boolean} params.useStub
172
- * @param {number} params.timeoutMs
173
- * @param {string} [params.projectRoot]
174
- * @param {string} [params.batchId]
175
- * @param {number} [params.laneNumber]
176
- * @param {string} [params.taskId]
177
- * @param {string} [params.laneCorrelationId]
178
- * @param {string[]} [params.fileScopePaths]
179
- * @param {object} [params.config]
180
- * @param {number} [params.piTimeoutMs]
181
- */
182
- function spawnWorkerChild({
183
- worktreePath,
184
- taskFolder,
185
- useStub,
186
- timeoutMs: _timeoutMs,
187
- projectRoot,
188
- batchId,
189
- laneNumber,
190
- taskId,
191
- laneCorrelationId,
192
- fileScopePaths = [],
193
- config = {},
194
- piTimeoutMs,
195
- }) {
196
- const runner = path.join(PACKAGE_ROOT, "bin", "spine-worker-runner.mjs");
197
- const env = buildWorkerChildEnv({
198
- taskFolder,
199
- worktreePath,
200
- projectRoot,
201
- batchId,
202
- laneNumber,
203
- taskId,
204
- laneCorrelationId,
205
- fileScopePaths,
206
- config,
207
- piTimeoutMs,
208
- });
209
- const args = useStub ? ["--stub"] : ["--pi"];
210
-
211
- const launchScript = projectRoot ? resolveWorkerLaunchScript(projectRoot, config) : null;
212
- if (launchScript) {
213
- return spawn(launchScript, [runner, ...args], {
214
- cwd: worktreePath,
215
- env,
216
- stdio: ["ignore", "pipe", "pipe"],
217
- });
218
- }
219
-
220
- return spawn(process.execPath, [runner, ...args], {
221
- cwd: worktreePath,
222
- env,
223
- stdio: ["ignore", "pipe", "pipe"],
224
- });
225
- }
226
-
227
75
  /**
228
76
  * @param {object} params
229
77
  * @param {string} params.rawOutput
@@ -281,153 +129,6 @@ function buildWorkerFailureResult({
281
129
  };
282
130
  }
283
131
 
284
- /**
285
- * @param {WorkerChildHandle} child
286
- * @param {() => void} onPreflightComplete
287
- */
288
- function markChildPastPreflight(child, onPreflightComplete) {
289
- if (typeof child.stdout?.on === "function") {
290
- child.stdout.on("data", onPreflightComplete);
291
- }
292
- if (typeof child.stderr?.on === "function") {
293
- child.stderr.on("data", onPreflightComplete);
294
- }
295
- }
296
-
297
- /**
298
- * @param {object} params
299
- * @param {boolean} params.childPastPreflight
300
- * @param {boolean} params.useStub
301
- * @param {string} params.workerBackend
302
- * @returns {WorkerPhase}
303
- */
304
- function resolveWorkerPhase({
305
- childPastPreflight,
306
- useStub,
307
- workerBackend,
308
- }) {
309
- if (!childPastPreflight) return "launching";
310
- if (useStub || workerBackend === "agentSession") return "pi";
311
- return "pi";
312
- }
313
-
314
- /**
315
- * SIGTERM then SIGKILL when a worker stays alive after post-.DONE grace.
316
- *
317
- * @param {WorkerChildHandle} child
318
- * @param {Promise<{ exitCode: number; output: string }>} childDone
319
- */
320
- async function terminateHungWorkerChild(child, childDone) {
321
- child.kill("SIGTERM");
322
- const raced = await Promise.race([childDone, sleep(POST_DONE_KILL_BACKOFF_MS)]);
323
- if (raced && typeof raced === "object" && "exitCode" in raced) {
324
- return raced;
325
- }
326
- if (child.exitCode === null && typeof child.kill === "function") {
327
- child.kill("SIGKILL");
328
- }
329
- return childDone;
330
- }
331
-
332
- /**
333
- * @param {WorkerChildHandle} child
334
- * @param {{ append: (rawChunk: string) => void } | null} [liveLogWriter]
335
- */
336
- function collectChildOutput(child, liveLogWriter) {
337
- if ("wait" in child && typeof child.wait === "function") {
338
- return child.wait();
339
- }
340
- return new Promise((resolve) => {
341
- let stdout = "";
342
- let stderr = "";
343
- child.stdout?.on("data", (/** @type {Buffer | string} */ chunk) => {
344
- const text = chunk.toString();
345
- stdout += text;
346
- liveLogWriter?.append(text);
347
- });
348
- child.stderr?.on("data", (/** @type {Buffer | string} */ chunk) => {
349
- const text = chunk.toString();
350
- stderr += text;
351
- liveLogWriter?.append(text);
352
- });
353
- child.on?.("close", (/** @type {number | null} */ code) => {
354
- resolve({ exitCode: code ?? 1, output: `${stdout}${stderr}` });
355
- });
356
- });
357
- }
358
-
359
- /**
360
- * @param {object} params
361
- * @param {string} params.worktreePath
362
- * @param {string} params.taskFolder
363
- * @param {boolean} params.useStub
364
- * @param {number} params.timeoutMs
365
- * @param {number} [params.piTimeoutMs]
366
- * @param {string} [params.projectRoot]
367
- * @param {string} [params.batchId]
368
- * @param {number} [params.laneNumber]
369
- * @param {string} [params.taskId]
370
- * @param {string} [params.laneCorrelationId]
371
- * @param {string[]} [params.fileScopePaths]
372
- * @param {object} [params.config]
373
- * @param {object} [params.workerBackendDeps]
374
- */
375
- function spawnWorkerHandle({
376
- worktreePath,
377
- taskFolder,
378
- useStub,
379
- timeoutMs,
380
- piTimeoutMs,
381
- projectRoot,
382
- batchId,
383
- laneNumber,
384
- taskId,
385
- laneCorrelationId,
386
- fileScopePaths = [],
387
- config,
388
- workerBackendDeps,
389
- }) {
390
- const journal =
391
- projectRoot && batchId
392
- ? {
393
- projectRoot,
394
- batchId,
395
- taskId,
396
- laneNumber,
397
- correlationId: laneCorrelationId,
398
- }
399
- : undefined;
400
-
401
- if (!useStub && resolveWorkerBackend(config) === "agentSession") {
402
- return startAgentSessionWorker(
403
- /** @type {{ worktreePath: string; taskFolder: string; config?: object; taskFileScope?: string[]; journal?: import("../config/worker-context.mjs").WorkerRulesJournalContext; projectRoot?: string }} */ ({
404
- worktreePath,
405
- taskFolder,
406
- config,
407
- taskFileScope: fileScopePaths,
408
- journal,
409
- projectRoot,
410
- }),
411
- workerBackendDeps ?? {},
412
- );
413
- }
414
-
415
- return spawnWorkerChild({
416
- worktreePath,
417
- taskFolder,
418
- useStub,
419
- timeoutMs,
420
- piTimeoutMs,
421
- projectRoot,
422
- batchId,
423
- laneNumber,
424
- taskId,
425
- laneCorrelationId,
426
- fileScopePaths,
427
- config,
428
- });
429
- }
430
-
431
132
  /**
432
133
  * @param {object} params
433
134
  * @param {string} params.worktreePath
@@ -508,17 +209,6 @@ export async function runWorker({
508
209
  const stallConfig = resolveStallConfigForTask({ config, taskSize, contract });
509
210
  const piTimeoutMs = resolveWorkerPiTimeoutMs({ config, taskSize, contract });
510
211
  const startedAt = Date.now();
511
- let stallAnchorAt = startedAt;
512
- let lastCheckpointAt = startedAt;
513
- let lastHeartbeatAt = 0;
514
- let lastProgressSnapshotAt = 0;
515
- let lastSnapshotPayload = null;
516
- let lastSignals = null;
517
- let activitySinceCheckpoint = false;
518
- let checkpointWarningSent = false;
519
- let stallWarningSent = false;
520
- let postDoneStartedAt = null;
521
- let postDoneTerminated = false;
522
212
 
523
213
  const child = spawnWorkerHandle({
524
214
  worktreePath,
@@ -538,7 +228,7 @@ export async function runWorker({
538
228
  const workerChild = /** @type {WorkerChildHandle} */ (child);
539
229
  let childPastPreflight = !useLaunchScript;
540
230
  /** @type {WorkerPhase} */
541
- let workerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
231
+ const initialWorkerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
542
232
  markChildPastPreflight(workerChild, () => {
543
233
  childPastPreflight = true;
544
234
  });
@@ -552,230 +242,48 @@ export async function runWorker({
552
242
  });
553
243
  const childDone = collectChildOutput(workerChild, liveLogWriter);
554
244
 
555
- while (true) {
556
- const doneOnDisk = fs.existsSync(donePath);
557
- const now = Date.now();
558
-
559
- if (doneOnDisk && postDoneStartedAt === null) {
560
- postDoneStartedAt = now;
561
- }
562
-
563
- if (projectRoot && batchId) {
564
- const abortSignal = readAbortSignal(projectRoot, batchId);
565
- if (abortSignal) {
566
- const hard = Boolean(abortSignal.hard);
567
- workerChild.kill(hard ? "SIGKILL" : "SIGTERM");
568
- const { output } = await childDone;
569
- return buildWorkerFailureResult({
570
- rawOutput: output,
571
- classification: "aborted",
572
- exitCode: hard ? 137 : 130,
573
- mode: workerMode,
574
- doneFound: fs.existsSync(donePath),
575
- projectRoot,
576
- batchId,
577
- laneNumber,
578
- taskId,
579
- laneCorrelationId,
580
- config,
581
- });
582
- }
583
- }
584
-
585
- if (doneOnDisk) {
586
- if (workerChild.exitCode !== null) {
587
- break;
588
- }
589
- const graceElapsed = now - (postDoneStartedAt ?? now);
590
- if (graceElapsed >= stallConfig.postDoneGraceMs) {
591
- if (projectRoot && batchId) {
592
- appendJournalEvent(projectRoot, batchId, "worker.post_done_terminated", {
593
- laneNumber,
594
- taskId,
595
- correlationId: laneCorrelationId,
596
- graceElapsedMs: graceElapsed,
597
- postDoneGraceMs: stallConfig.postDoneGraceMs,
598
- childPid: workerChild.pid ?? null,
599
- });
600
- }
601
- postDoneTerminated = true;
602
- await terminateHungWorkerChild(workerChild, childDone);
603
- break;
604
- }
605
- await sleep(Math.min(stallConfig.pollIntervalMs, 5_000));
606
- continue;
607
- }
608
-
609
- const signals = collectProgressSignals(
610
- /** @type {Parameters<typeof collectProgressSignals>[0]} */ ({
611
- worktreePath,
612
- taskFolder,
613
- laneBranch,
614
- fileScopePaths,
615
- journalContext:
616
- projectRoot && batchId
617
- ? { projectRoot, batchId, laneNumber, taskId }
618
- : undefined,
619
- }),
620
- );
621
- const nextWorkerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
622
- if (nextWorkerPhase !== "launching" && workerPhase === "launching") {
623
- stallAnchorAt = now;
624
- lastCheckpointAt = now;
625
- activitySinceCheckpoint = false;
626
- checkpointWarningSent = false;
627
- lastSignals = null;
628
- lastSnapshotPayload = null;
629
- }
630
- workerPhase = nextWorkerPhase;
631
-
632
- const checkpointChanged =
633
- workerPhase !== "launching" && checkpointSignalsChanged(lastSignals, signals);
634
- const activityChanged =
635
- workerPhase !== "launching" && activitySignalsChanged(lastSignals, signals);
636
-
637
- if (checkpointChanged) {
638
- lastCheckpointAt = now;
639
- activitySinceCheckpoint = false;
640
- checkpointWarningSent = false;
641
- } else if (activityChanged) {
642
- activitySinceCheckpoint = true;
643
- if (stallConfig.extendGraceOnFileScope) {
644
- lastCheckpointAt = now;
645
- }
646
- }
647
-
648
- if (
649
- projectRoot &&
650
- batchId &&
651
- !checkpointWarningSent &&
652
- shouldEmitCheckpointWarning({
653
- now,
654
- lastCheckpointAt,
655
- signals,
656
- stallConfig,
657
- activitySinceCheckpoint,
658
- workerPhase,
659
- })
660
- ) {
661
- recordCheckpointWarning({
662
- projectRoot,
663
- batchId,
664
- laneNumber,
665
- taskId,
666
- signals,
667
- lastCheckpointAt,
668
- correlationId: laneCorrelationId,
669
- });
670
- checkpointWarningSent = true;
671
- }
672
-
673
- lastSignals = signals;
674
-
675
- if (
676
- projectRoot &&
677
- batchId &&
678
- shouldEmitProgressSnapshot({
679
- now,
680
- lastEmittedAt: lastProgressSnapshotAt,
681
- intervalMs: stallConfig.progressSnapshotIntervalMs,
682
- })
683
- ) {
684
- const snapshotPayload = buildProgressSnapshotPayload(signals, workerPhase);
685
- if (progressSnapshotPayloadChanged(lastSnapshotPayload, snapshotPayload)) {
686
- recordLaneProgressSnapshot({
687
- projectRoot,
688
- batchId,
689
- laneNumber,
690
- taskId,
691
- signals,
692
- correlationId: laneCorrelationId,
693
- workerPhase,
694
- });
695
- lastSnapshotPayload = snapshotPayload;
696
- }
697
- lastProgressSnapshotAt = now;
698
- }
699
-
700
- if (
701
- projectRoot &&
702
- batchId &&
703
- now - lastHeartbeatAt >= stallConfig.heartbeatIntervalMs
704
- ) {
705
- const heartbeatKind = resolveHeartbeatKind(
706
- /** @type {Parameters<typeof resolveHeartbeatKind>[0]} */ ({
707
- workerPhase,
708
- checkpointChanged,
709
- activityChanged,
710
- }),
711
- );
712
- recordLaneHeartbeat(
713
- /** @type {Parameters<typeof recordLaneHeartbeat>[0]} */ ({
714
- projectRoot,
715
- batchId,
716
- laneNumber,
717
- taskId,
718
- signals,
719
- correlationId: laneCorrelationId,
720
- workerPhase,
721
- heartbeatKind,
722
- }),
723
- );
724
- stallAnchorAt = nextStallAnchorAt({
725
- stallAnchorAt,
726
- now,
727
- workerPhase,
728
- heartbeatKind,
729
- });
730
- onHeartbeat?.(now);
731
- lastHeartbeatAt = now;
732
- }
733
-
734
- const stallDeadline = computeStallDeadline({
735
- startedAt,
736
- lastProgressAt: lastCheckpointAt,
737
- lastAliveAt: stallAnchorAt,
738
- stallConfig,
739
- });
740
-
741
- if (now >= stallDeadline) {
742
- if (!stallWarningSent && projectRoot && batchId) {
743
- recordStallWarning({
744
- projectRoot,
745
- batchId,
746
- laneNumber,
747
- taskId,
748
- signals,
749
- stallDeadline,
750
- correlationId: laneCorrelationId,
751
- });
752
- stallWarningSent = true;
753
- }
754
- const { output } = await terminateHungWorkerChild(workerChild, childDone);
755
- return buildWorkerFailureResult({
756
- rawOutput: output,
757
- classification: "stall_timeout",
758
- exitCode: 124,
759
- mode: workerMode,
760
- doneFound: fs.existsSync(donePath),
245
+ const pollState = createWorkerPollState(startedAt, initialWorkerPhase);
246
+ const pollOutcome = await pollWorkerUntilSettled({
247
+ donePath,
248
+ workerChild,
249
+ childDone,
250
+ stallConfig,
251
+ startedAt,
252
+ pollState,
253
+ worktreePath,
254
+ taskFolder,
255
+ laneBranch,
256
+ fileScopePaths,
257
+ projectRoot,
258
+ batchId,
259
+ laneNumber,
260
+ taskId,
261
+ laneCorrelationId,
262
+ useStub,
263
+ workerBackend,
264
+ childPastPreflight,
265
+ onHeartbeat,
266
+ workerMode,
267
+ buildFailureResult: (
268
+ /** @type {Pick<Parameters<typeof buildWorkerFailureResult>[0], "rawOutput" | "classification" | "exitCode" | "mode" | "doneFound" | "stallDeadline" | "signals">} */ partial,
269
+ ) =>
270
+ buildWorkerFailureResult({
271
+ ...partial,
761
272
  projectRoot,
762
273
  batchId,
763
274
  laneNumber,
764
275
  taskId,
765
276
  laneCorrelationId,
766
277
  config,
767
- stallDeadline,
768
- signals,
769
- });
770
- }
771
-
772
- if (workerChild.exitCode !== null) {
773
- break;
774
- }
278
+ }),
279
+ });
775
280
 
776
- await sleep(Math.min(stallConfig.pollIntervalMs, 5_000));
281
+ if (pollOutcome.kind === "failure") {
282
+ return pollOutcome.result;
777
283
  }
778
284
 
285
+ const postDoneTerminated = pollOutcome.postDoneTerminated;
286
+
779
287
  const childResult = await Promise.race([childDone, sleep(CHILD_DONE_TIMEOUT_MS).then(() => null)]);
780
288
  let exitCode, output;
781
289
  if (childResult) {