pi-spine 2.2.0 → 2.3.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/bin/spine-cli/verify.mjs +2 -19
  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/engine.mjs +8 -67
  15. package/src/batch/integrate-git.mjs +21 -0
  16. package/src/batch/integrate.mjs +5 -15
  17. package/src/batch/journal-rebuild-structural.mjs +352 -0
  18. package/src/batch/journal-rebuild.mjs +16 -348
  19. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  20. package/src/batch/lane-dirty-check-git.mjs +298 -0
  21. package/src/batch/lane-dirty-check.mjs +31 -297
  22. package/src/batch/reconcile-batch.mjs +483 -0
  23. package/src/batch/reconcile-classify.mjs +433 -0
  24. package/src/batch/reconcile-diagnosis.mjs +459 -0
  25. package/src/batch/reconcile-light-cache.mjs +61 -0
  26. package/src/batch/reconcile-orphan.mjs +198 -0
  27. package/src/batch/reconcile.mjs +19 -1693
  28. package/src/batch/resume-multi-lanes.mjs +6 -148
  29. package/src/batch/resume-multi-queue.mjs +159 -0
  30. package/src/batch/resume-single-validate.mjs +25 -0
  31. package/src/batch/resume.mjs +3 -20
  32. package/src/batch/review-artifacts.mjs +419 -0
  33. package/src/batch/review-step-run.mjs +383 -0
  34. package/src/batch/review-step.mjs +451 -0
  35. package/src/batch/review.mjs +32 -1199
  36. package/src/batch/salvage-batch-list.mjs +291 -0
  37. package/src/batch/salvage-batch.mjs +10 -284
  38. package/src/batch/sequence-plan.mjs +234 -0
  39. package/src/batch/sequence-run.mjs +418 -0
  40. package/src/batch/sequence-wait.mjs +167 -0
  41. package/src/batch/sequence.mjs +22 -783
  42. package/src/batch/state-guards.mjs +284 -0
  43. package/src/batch/state-io.mjs +135 -0
  44. package/src/batch/state.mjs +27 -396
  45. package/src/batch/worker-heartbeat.mjs +375 -0
  46. package/src/batch/worker-host.mjs +50 -541
  47. package/src/batch/worker-spawn.mjs +315 -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,20 +13,26 @@ 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";
41
32
 
42
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
43
- const PACKAGE_ROOT = path.resolve(__dirname, "../..");
33
+ export { buildWorkerChildEnv } from "./worker-spawn.mjs";
44
34
 
45
35
  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
36
 
49
37
  /**
50
38
  * Force-terminate lane worker processes tracked in batch state.
@@ -74,19 +62,9 @@ export function terminateLaneWorkers(lanes, { hard = true } = {}) {
74
62
  return terminated;
75
63
  }
76
64
 
77
- /** @typedef {"launching" | "pi" | "verify" | "unknown"} WorkerPhase */
65
+ /** @typedef {import("./worker-spawn.mjs").WorkerPhase} WorkerPhase */
78
66
 
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
- */
67
+ /** @typedef {import("./worker-spawn.mjs").WorkerChildHandle} WorkerChildHandle */
90
68
 
91
69
  /**
92
70
  * @param {number} ms
@@ -95,135 +73,6 @@ function sleep(ms) {
95
73
  return new Promise((resolve) => setTimeout(resolve, ms));
96
74
  }
97
75
 
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
76
  /**
228
77
  * @param {object} params
229
78
  * @param {string} params.rawOutput
@@ -281,153 +130,6 @@ function buildWorkerFailureResult({
281
130
  };
282
131
  }
283
132
 
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
133
  /**
432
134
  * @param {object} params
433
135
  * @param {string} params.worktreePath
@@ -508,17 +210,6 @@ export async function runWorker({
508
210
  const stallConfig = resolveStallConfigForTask({ config, taskSize, contract });
509
211
  const piTimeoutMs = resolveWorkerPiTimeoutMs({ config, taskSize, contract });
510
212
  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
213
 
523
214
  const child = spawnWorkerHandle({
524
215
  worktreePath,
@@ -538,7 +229,7 @@ export async function runWorker({
538
229
  const workerChild = /** @type {WorkerChildHandle} */ (child);
539
230
  let childPastPreflight = !useLaunchScript;
540
231
  /** @type {WorkerPhase} */
541
- let workerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
232
+ const initialWorkerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
542
233
  markChildPastPreflight(workerChild, () => {
543
234
  childPastPreflight = true;
544
235
  });
@@ -552,230 +243,48 @@ export async function runWorker({
552
243
  });
553
244
  const childDone = collectChildOutput(workerChild, liveLogWriter);
554
245
 
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),
246
+ const pollState = createWorkerPollState(startedAt, initialWorkerPhase);
247
+ const pollOutcome = await pollWorkerUntilSettled({
248
+ donePath,
249
+ workerChild,
250
+ childDone,
251
+ stallConfig,
252
+ startedAt,
253
+ pollState,
254
+ worktreePath,
255
+ taskFolder,
256
+ laneBranch,
257
+ fileScopePaths,
258
+ projectRoot,
259
+ batchId,
260
+ laneNumber,
261
+ taskId,
262
+ laneCorrelationId,
263
+ useStub,
264
+ workerBackend,
265
+ childPastPreflight,
266
+ onHeartbeat,
267
+ workerMode,
268
+ buildFailureResult: (
269
+ /** @type {Pick<Parameters<typeof buildWorkerFailureResult>[0], "rawOutput" | "classification" | "exitCode" | "mode" | "doneFound" | "stallDeadline" | "signals">} */ partial,
270
+ ) =>
271
+ buildWorkerFailureResult({
272
+ ...partial,
761
273
  projectRoot,
762
274
  batchId,
763
275
  laneNumber,
764
276
  taskId,
765
277
  laneCorrelationId,
766
278
  config,
767
- stallDeadline,
768
- signals,
769
- });
770
- }
771
-
772
- if (workerChild.exitCode !== null) {
773
- break;
774
- }
279
+ }),
280
+ });
775
281
 
776
- await sleep(Math.min(stallConfig.pollIntervalMs, 5_000));
282
+ if (pollOutcome.kind === "failure") {
283
+ return pollOutcome.result;
777
284
  }
778
285
 
286
+ const postDoneTerminated = pollOutcome.postDoneTerminated;
287
+
779
288
  const childResult = await Promise.race([childDone, sleep(CHILD_DONE_TIMEOUT_MS).then(() => null)]);
780
289
  let exitCode, output;
781
290
  if (childResult) {