pi-spine 1.0.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 (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +563 -0
  3. package/bin/get-version.mjs +35 -0
  4. package/bin/spine-batch.mjs +425 -0
  5. package/bin/spine-cli/batch.mjs +47 -0
  6. package/bin/spine-cli/gate.mjs +10 -0
  7. package/bin/spine-cli/integrate.mjs +10 -0
  8. package/bin/spine-cli/plan.mjs +12 -0
  9. package/bin/spine-cli/shared.mjs +73 -0
  10. package/bin/spine-cli/status.mjs +18 -0
  11. package/bin/spine-cli/verify.mjs +199 -0
  12. package/bin/spine-config.mjs +212 -0
  13. package/bin/spine-dashboard.mjs +178 -0
  14. package/bin/spine-deps.mjs +69 -0
  15. package/bin/spine-doctor.mjs +468 -0
  16. package/bin/spine-gate.mjs +137 -0
  17. package/bin/spine-init.mjs +398 -0
  18. package/bin/spine-integrate.mjs +77 -0
  19. package/bin/spine-journal.mjs +198 -0
  20. package/bin/spine-migrate-from-taskplane.mjs +136 -0
  21. package/bin/spine-plan.mjs +83 -0
  22. package/bin/spine-preflight.mjs +700 -0
  23. package/bin/spine-report-progress.d.mts +28 -0
  24. package/bin/spine-report-progress.mjs +126 -0
  25. package/bin/spine-review-step.d.mts +24 -0
  26. package/bin/spine-review-step.mjs +124 -0
  27. package/bin/spine-rules.mjs +35 -0
  28. package/bin/spine-settings.mjs +186 -0
  29. package/bin/spine-state.mjs +110 -0
  30. package/bin/spine-status.mjs +79 -0
  31. package/bin/spine-tasks.mjs +293 -0
  32. package/bin/spine-worker-runner.mjs +314 -0
  33. package/bin/spine.mjs +404 -0
  34. package/extensions/spine/settings-slash.ts +20 -0
  35. package/extensions/spine/slash-commands.ts +806 -0
  36. package/extensions/spine/worker-tools.ts +279 -0
  37. package/extensions/spine-orchestrator.ts +12 -0
  38. package/package.json +72 -0
  39. package/skills/.gitkeep +0 -0
  40. package/skills/create-spine-tasks/SKILL.md +375 -0
  41. package/skills/create-spine-tasks/references/context-template.md +25 -0
  42. package/skills/create-spine-tasks/references/contract-template.md +98 -0
  43. package/skills/create-spine-tasks/references/explore-template.md +63 -0
  44. package/skills/create-spine-tasks/references/prompt-template.md +276 -0
  45. package/src/batch/abort.mjs +272 -0
  46. package/src/batch/agent-session-worker.mjs +297 -0
  47. package/src/batch/batch-state-io.mjs +53 -0
  48. package/src/batch/contract-verify.mjs +310 -0
  49. package/src/batch/detached-start.mjs +778 -0
  50. package/src/batch/diagnosis.mjs +378 -0
  51. package/src/batch/engine-lanes/merge.mjs +632 -0
  52. package/src/batch/engine-lanes/queue.mjs +208 -0
  53. package/src/batch/engine-lanes/review.mjs +970 -0
  54. package/src/batch/engine-lanes.mjs +388 -0
  55. package/src/batch/engine-scope.mjs +251 -0
  56. package/src/batch/engine.mjs +445 -0
  57. package/src/batch/evidence-command.mjs +157 -0
  58. package/src/batch/evidence.mjs +203 -0
  59. package/src/batch/gate.mjs +359 -0
  60. package/src/batch/git-commit-env.mjs +46 -0
  61. package/src/batch/git-exec.mjs +26 -0
  62. package/src/batch/heartbeat.mjs +430 -0
  63. package/src/batch/integrate.mjs +414 -0
  64. package/src/batch/journal-rebuild.mjs +388 -0
  65. package/src/batch/journal.mjs +373 -0
  66. package/src/batch/lane-commit.mjs +153 -0
  67. package/src/batch/lifecycle.mjs +364 -0
  68. package/src/batch/metrics.mjs +265 -0
  69. package/src/batch/orphan-detect.mjs +210 -0
  70. package/src/batch/post-merge-limbo.mjs +80 -0
  71. package/src/batch/postmortem.mjs +296 -0
  72. package/src/batch/readers/spine-state.mjs +95 -0
  73. package/src/batch/readers/taskplane-state.mjs +136 -0
  74. package/src/batch/reconcile.mjs +729 -0
  75. package/src/batch/resume-common.mjs +104 -0
  76. package/src/batch/resume-engine.mjs +66 -0
  77. package/src/batch/resume-multi-lanes.mjs +479 -0
  78. package/src/batch/resume-multi-validate.mjs +187 -0
  79. package/src/batch/resume-multi.mjs +254 -0
  80. package/src/batch/resume.mjs +475 -0
  81. package/src/batch/retry.mjs +257 -0
  82. package/src/batch/review-scope.mjs +136 -0
  83. package/src/batch/review.mjs +1045 -0
  84. package/src/batch/salvage.mjs +332 -0
  85. package/src/batch/state.mjs +680 -0
  86. package/src/batch/task-stall-budget.mjs +88 -0
  87. package/src/batch/worker-host.mjs +683 -0
  88. package/src/batch/worker-output.mjs +253 -0
  89. package/src/batch/worker-prompt.mjs +84 -0
  90. package/src/batch/worktree.mjs +290 -0
  91. package/src/cli/deps.mjs +141 -0
  92. package/src/cli/handoff.mjs +364 -0
  93. package/src/cli/rules.mjs +429 -0
  94. package/src/cli/settings-set.mjs +171 -0
  95. package/src/cli/settings-show.mjs +140 -0
  96. package/src/cli/settings-slash.mjs +107 -0
  97. package/src/config/contract.mjs +56 -0
  98. package/src/config/cursor-rules/discover.mjs +416 -0
  99. package/src/config/cursor-rules/index.mjs +39 -0
  100. package/src/config/cursor-rules/match-globs.mjs +132 -0
  101. package/src/config/cursor-rules/parse-frontmatter.mjs +222 -0
  102. package/src/config/cursor-rules/priority.mjs +26 -0
  103. package/src/config/cursor-rules/profile.mjs +403 -0
  104. package/src/config/cursor-rules/select.mjs +259 -0
  105. package/src/config/defaults.mjs +36 -0
  106. package/src/config/env-overrides.mjs +207 -0
  107. package/src/config/merge-defaults.mjs +47 -0
  108. package/src/config/pi-spine-root.mjs +93 -0
  109. package/src/config/reviewer-context.mjs +243 -0
  110. package/src/config/settings-fields.mjs +265 -0
  111. package/src/config/worker-backend.mjs +116 -0
  112. package/src/config/worker-context.mjs +402 -0
  113. package/src/config/worker-launch-script.mjs +130 -0
  114. package/src/config/worktree-setup-hook.mjs +122 -0
  115. package/src/dashboard/public/dashboard.css +77 -0
  116. package/src/dashboard/public/dashboard.js +349 -0
  117. package/src/dashboard/public/index.html +80 -0
  118. package/src/dashboard/server.mjs +155 -0
  119. package/src/dashboard/snapshot.mjs +414 -0
  120. package/src/dashboard/sse.mjs +15 -0
  121. package/src/dashboard/view.mjs +292 -0
  122. package/src/doctor/agent-model-inherit.mjs +101 -0
  123. package/src/doctor/batch-size-guidance.mjs +72 -0
  124. package/src/doctor/coexistence.mjs +312 -0
  125. package/src/doctor/rules-manifest.mjs +133 -0
  126. package/src/doctor/stale-path.mjs +156 -0
  127. package/src/doctor/stall-config.mjs +108 -0
  128. package/src/doctor/suggest-max-parallel.mjs +53 -0
  129. package/src/doctor/task-packet-size.mjs +110 -0
  130. package/src/doctor/worktree-health.mjs +71 -0
  131. package/src/migrate/taskplane-config.mjs +116 -0
  132. package/src/planner/cycles.mjs +63 -0
  133. package/src/planner/format-plan.mjs +132 -0
  134. package/src/planner/graph.mjs +99 -0
  135. package/src/planner/index.mjs +125 -0
  136. package/src/planner/lanes.mjs +111 -0
  137. package/src/planner/pending.mjs +39 -0
  138. package/src/planner/scope.mjs +142 -0
  139. package/src/process/liveness.mjs +21 -0
  140. package/src/tasks/packet/discover.mjs +40 -0
  141. package/src/tasks/packet/index.mjs +81 -0
  142. package/src/tasks/packet/merge-deps.mjs +79 -0
  143. package/src/tasks/packet/parse-prompt.mjs +445 -0
  144. package/src/tasks/packet/parse-status.mjs +118 -0
  145. package/src/tasks/packet/validate-contract.mjs +115 -0
  146. package/src/tasks/packet/validate-prompt.mjs +99 -0
  147. package/src/worker-tools/report-progress.d.mts +18 -0
  148. package/src/worker-tools/report-progress.mjs +59 -0
  149. package/src/worker-tools/request-gate.d.mts +17 -0
  150. package/src/worker-tools/request-gate.mjs +54 -0
  151. package/templates/agents/reviewer.md +123 -0
  152. package/templates/agents/supervisor.md +59 -0
  153. package/templates/agents/worker.md +122 -0
  154. package/templates/rules-profile.json +27 -0
  155. package/templates/spine-config.json +64 -0
  156. package/templates/tasks/CONTEXT.md +30 -0
@@ -0,0 +1,683 @@
1
+ /**
2
+ * pi-spine worker host — spawn worker in lane worktree with heartbeat polling.
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { spawn, spawnSync } from "node:child_process";
8
+ import { fileURLToPath } from "node:url";
9
+ import { readAbortSignal } from "./abort.mjs";
10
+ import {
11
+ activitySignalsChanged,
12
+ checkpointSignalsChanged,
13
+ collectProgressSignals,
14
+ computeStallDeadline,
15
+ recordCheckpointWarning,
16
+ recordLaneHeartbeat,
17
+ recordStallWarning,
18
+ resolveHeartbeatKind,
19
+ shouldEmitCheckpointWarning,
20
+ } from "./heartbeat.mjs";
21
+ import {
22
+ resolveStallConfigForTask,
23
+ resolveWorkerPiTimeoutMs,
24
+ parseTaskSizeFromFolder,
25
+ } from "./task-stall-budget.mjs";
26
+ import { appendJournalEvent } from "./journal.mjs";
27
+ import { assertReviewToolAvailable } from "./review.mjs";
28
+ import { startAgentSessionWorker } from "./agent-session-worker.mjs";
29
+ import { finalizeWorkerOutput } from "./worker-output.mjs";
30
+ import { resolveWorkerBackend } from "../config/worker-backend.mjs";
31
+ import { resolvePiSpineRoot } from "../config/pi-spine-root.mjs";
32
+ import { resolveSafeWorkerLaunchScript } from "../config/worker-launch-script.mjs";
33
+
34
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
35
+ const PACKAGE_ROOT = path.resolve(__dirname, "../..");
36
+
37
+ const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
38
+ const POST_DONE_KILL_BACKOFF_MS = 5_000;
39
+
40
+ /**
41
+ * @param {string} cmd
42
+ */
43
+ function commandExists(cmd) {
44
+ try {
45
+ spawnSync("which", [cmd], { stdio: "ignore" });
46
+ return true;
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * @param {number} ms
54
+ */
55
+ function sleep(ms) {
56
+ return new Promise((resolve) => setTimeout(resolve, ms));
57
+ }
58
+
59
+
60
+ /**
61
+ * @param {string} projectRoot
62
+ * @param {object} [config]
63
+ * @returns {string|null}
64
+ */
65
+ function resolveWorkerLaunchScript(projectRoot, config = {}) {
66
+ return resolveSafeWorkerLaunchScript(projectRoot, config);
67
+ }
68
+
69
+ /**
70
+ * @param {object} params
71
+ */
72
+ export function buildWorkerChildEnv({
73
+ taskFolder,
74
+ worktreePath,
75
+ projectRoot,
76
+ batchId,
77
+ laneNumber,
78
+ taskId,
79
+ laneCorrelationId,
80
+ fileScopePaths = [],
81
+ config = {},
82
+ piTimeoutMs,
83
+ }) {
84
+ const runner = path.join(PACKAGE_ROOT, "bin", "spine-worker-runner.mjs");
85
+ const env = {
86
+ ...process.env,
87
+ SPINE_TASK_FOLDER: taskFolder,
88
+ SPINE_WORKTREE: worktreePath,
89
+ SPINE_WORKER_RUNNER: runner,
90
+ PI_SPINE_ROOT: resolvePiSpineRoot(config, projectRoot ?? process.cwd()),
91
+ };
92
+ if (projectRoot) env.SPINE_PROJECT_ROOT = projectRoot;
93
+ if (batchId) {
94
+ env.SPINE_BATCH_ID = batchId;
95
+ env.SPINE_JOURNAL_ATTACH = "1";
96
+ delete env.SPINE_SUPPRESS_JOURNAL_ATTACH;
97
+ }
98
+ if (laneNumber != null) env.SPINE_LANE_NUMBER = String(laneNumber);
99
+ if (taskId) env.SPINE_TASK_ID = taskId;
100
+ if (laneCorrelationId) env.SPINE_LANE_CORRELATION_ID = laneCorrelationId;
101
+ if (Array.isArray(fileScopePaths) && fileScopePaths.length > 0) {
102
+ env.SPINE_TASK_FILE_SCOPE = JSON.stringify(fileScopePaths);
103
+ }
104
+ if (process.env.SPINE_WORKER_STUB === "1") {
105
+ env.SPINE_REVIEW_STUB = "1";
106
+ }
107
+ if (piTimeoutMs != null && Number.isFinite(piTimeoutMs) && piTimeoutMs > 0) {
108
+ env.SPINE_WORKER_PI_TIMEOUT_MS = String(
109
+ process.env.SPINE_WORKER_PI_TIMEOUT_MS ?? piTimeoutMs,
110
+ );
111
+ }
112
+ return env;
113
+ }
114
+
115
+ /**
116
+ * @param {object} params
117
+ */
118
+ function spawnWorkerChild({
119
+ worktreePath,
120
+ taskFolder,
121
+ useStub,
122
+ timeoutMs,
123
+ projectRoot,
124
+ batchId,
125
+ laneNumber,
126
+ taskId,
127
+ laneCorrelationId,
128
+ fileScopePaths = [],
129
+ config = {},
130
+ piTimeoutMs,
131
+ }) {
132
+ const runner = path.join(PACKAGE_ROOT, "bin", "spine-worker-runner.mjs");
133
+ const env = buildWorkerChildEnv({
134
+ taskFolder,
135
+ worktreePath,
136
+ projectRoot,
137
+ batchId,
138
+ laneNumber,
139
+ taskId,
140
+ laneCorrelationId,
141
+ fileScopePaths,
142
+ config,
143
+ piTimeoutMs,
144
+ });
145
+ const args = useStub ? ["--stub"] : ["--pi"];
146
+
147
+ const launchScript = projectRoot ? resolveWorkerLaunchScript(projectRoot, config) : null;
148
+ if (launchScript) {
149
+ return spawn(launchScript, [runner, ...args], {
150
+ cwd: worktreePath,
151
+ env,
152
+ stdio: ["ignore", "pipe", "pipe"],
153
+ });
154
+ }
155
+
156
+ return spawn(process.execPath, [runner, ...args], {
157
+ cwd: worktreePath,
158
+ env,
159
+ stdio: ["ignore", "pipe", "pipe"],
160
+ });
161
+ }
162
+
163
+ /**
164
+ * @param {object} params
165
+ */
166
+ function buildWorkerFailureResult({
167
+ rawOutput,
168
+ classification,
169
+ exitCode,
170
+ mode,
171
+ doneFound,
172
+ projectRoot,
173
+ batchId,
174
+ laneNumber,
175
+ taskId,
176
+ laneCorrelationId,
177
+ config,
178
+ stallDeadline,
179
+ signals,
180
+ }) {
181
+ const finalized = finalizeWorkerOutput({
182
+ rawOutput,
183
+ classification,
184
+ ok: false,
185
+ projectRoot,
186
+ batchId,
187
+ laneNumber,
188
+ taskId,
189
+ correlationId: laneCorrelationId,
190
+ exitCode,
191
+ stallDeadline,
192
+ signals,
193
+ config,
194
+ });
195
+ return {
196
+ ok: false,
197
+ exitCode,
198
+ mode,
199
+ output: finalized.output,
200
+ workerOutputLogPath: finalized.logPath,
201
+ workerOutputLogRef: finalized.logRef,
202
+ classification,
203
+ doneFound,
204
+ };
205
+ }
206
+
207
+ /**
208
+ * @param {import("node:child_process").ChildProcess | ReturnType<typeof startAgentSessionWorker>} child
209
+ */
210
+ function markChildPastPreflight(child, onPreflightComplete) {
211
+ if (typeof child.stdout?.on === "function") {
212
+ child.stdout.on("data", onPreflightComplete);
213
+ }
214
+ if (typeof child.stderr?.on === "function") {
215
+ child.stderr.on("data", onPreflightComplete);
216
+ }
217
+ }
218
+
219
+ /**
220
+ * @param {object} params
221
+ */
222
+ function resolveWorkerPhase({
223
+ childPastPreflight,
224
+ useStub,
225
+ workerBackend,
226
+ }) {
227
+ if (!childPastPreflight) return "launching";
228
+ if (useStub || workerBackend === "agentSession") return "pi";
229
+ return "pi";
230
+ }
231
+
232
+ /**
233
+ * SIGTERM then SIGKILL when a worker stays alive after post-.DONE grace.
234
+ *
235
+ * @param {import("node:child_process").ChildProcess | ReturnType<typeof startAgentSessionWorker>} child
236
+ * @param {Promise<{ exitCode: number; output: string }>} childDone
237
+ */
238
+ async function terminateHungWorkerChild(child, childDone) {
239
+ child.kill("SIGTERM");
240
+ const raced = await Promise.race([childDone, sleep(POST_DONE_KILL_BACKOFF_MS)]);
241
+ if (raced && typeof raced === "object" && "exitCode" in raced) {
242
+ return raced;
243
+ }
244
+ if (child.exitCode === null && typeof child.kill === "function") {
245
+ child.kill("SIGKILL");
246
+ }
247
+ return childDone;
248
+ }
249
+
250
+ /**
251
+ * @param {import("node:child_process").ChildProcess | ReturnType<typeof startAgentSessionWorker>} child
252
+ */
253
+ function collectChildOutput(child) {
254
+ if (typeof child.wait === "function") {
255
+ return child.wait();
256
+ }
257
+ return new Promise((resolve) => {
258
+ let stdout = "";
259
+ let stderr = "";
260
+ child.stdout?.on("data", (chunk) => {
261
+ stdout += chunk.toString();
262
+ });
263
+ child.stderr?.on("data", (chunk) => {
264
+ stderr += chunk.toString();
265
+ });
266
+ child.on("close", (code) => {
267
+ resolve({ exitCode: code ?? 1, output: `${stdout}${stderr}` });
268
+ });
269
+ });
270
+ }
271
+
272
+ /**
273
+ * @param {object} params
274
+ * @param {object} [params.workerBackendDeps]
275
+ */
276
+ function spawnWorkerHandle({
277
+ worktreePath,
278
+ taskFolder,
279
+ useStub,
280
+ timeoutMs,
281
+ piTimeoutMs,
282
+ projectRoot,
283
+ batchId,
284
+ laneNumber,
285
+ taskId,
286
+ laneCorrelationId,
287
+ fileScopePaths = [],
288
+ config,
289
+ workerBackendDeps,
290
+ }) {
291
+ const journal =
292
+ projectRoot && batchId
293
+ ? {
294
+ projectRoot,
295
+ batchId,
296
+ taskId,
297
+ laneNumber,
298
+ correlationId: laneCorrelationId,
299
+ }
300
+ : undefined;
301
+
302
+ if (!useStub && resolveWorkerBackend(config) === "agentSession") {
303
+ return startAgentSessionWorker(
304
+ {
305
+ worktreePath,
306
+ taskFolder,
307
+ config,
308
+ taskFileScope: fileScopePaths,
309
+ journal,
310
+ projectRoot,
311
+ },
312
+ workerBackendDeps ?? {},
313
+ );
314
+ }
315
+
316
+ return spawnWorkerChild({
317
+ worktreePath,
318
+ taskFolder,
319
+ useStub,
320
+ timeoutMs,
321
+ piTimeoutMs,
322
+ projectRoot,
323
+ batchId,
324
+ laneNumber,
325
+ taskId,
326
+ laneCorrelationId,
327
+ fileScopePaths,
328
+ config,
329
+ });
330
+ }
331
+
332
+ /**
333
+ * @param {object} params
334
+ * @param {string} params.worktreePath
335
+ * @param {string} params.taskFolder
336
+ * @param {string} [params.projectRoot]
337
+ * @param {string} [params.batchId]
338
+ * @param {number} [params.laneNumber]
339
+ * @param {string} [params.taskId]
340
+ * @param {string} [params.laneBranch]
341
+ * @param {string} [params.laneCorrelationId]
342
+ * @param {object} [params.config]
343
+ * @param {(timestamp: number) => void} [params.onHeartbeat]
344
+ * @param {(pid: number) => void} [params.onWorkerPid]
345
+ * @param {number} [params.timeoutMs]
346
+ * @param {object} [params.workerBackendDeps] Test-only injectables for agentSession backend
347
+ */
348
+ export async function runWorker({
349
+ worktreePath,
350
+ taskFolder,
351
+ projectRoot,
352
+ batchId,
353
+ laneNumber = 1,
354
+ taskId,
355
+ laneBranch,
356
+ laneCorrelationId,
357
+ config = {},
358
+ onHeartbeat,
359
+ onWorkerPid,
360
+ fileScopePaths = [],
361
+ timeoutMs = DEFAULT_TIMEOUT_MS,
362
+ workerBackendDeps = {},
363
+ }) {
364
+ const donePath = path.join(taskFolder, ".DONE");
365
+ if (fs.existsSync(donePath)) {
366
+ return { ok: true, exitCode: 0, mode: "already-done" };
367
+ }
368
+
369
+ const useStub =
370
+ process.env.SPINE_WORKER_STUB === "1" ||
371
+ process.env.SPINE_WORKER_STUB === "true" ||
372
+ (!commandExists("pi") && resolveWorkerBackend(config) !== "agentSession");
373
+
374
+ const workerBackend = useStub ? "subprocess" : resolveWorkerBackend(config);
375
+ const workerMode = useStub ? "stub" : workerBackend === "agentSession" ? "agentSession" : "pi";
376
+ const useLaunchScript = Boolean(
377
+ projectRoot ? resolveWorkerLaunchScript(projectRoot, config) : null,
378
+ );
379
+
380
+ const reviewCheck = assertReviewToolAvailable({ taskFolder });
381
+ if (!reviewCheck.ok) {
382
+ if (projectRoot && batchId) {
383
+ appendJournalEvent(projectRoot, batchId, "review.failed", {
384
+ taskId,
385
+ laneNumber,
386
+ correlationId: laneCorrelationId,
387
+ reviewLevel: reviewCheck.reviewLevel,
388
+ error: reviewCheck.error,
389
+ spawnFailed: true,
390
+ phase: "preflight",
391
+ });
392
+ }
393
+ return {
394
+ ok: false,
395
+ exitCode: 1,
396
+ mode: workerMode,
397
+ output: reviewCheck.error ?? "review tool unavailable",
398
+ classification: "review_failed",
399
+ doneFound: false,
400
+ };
401
+ }
402
+
403
+ const taskSize = parseTaskSizeFromFolder(taskFolder);
404
+ const stallConfig = resolveStallConfigForTask({ config, taskSize });
405
+ const piTimeoutMs = resolveWorkerPiTimeoutMs({ config, taskSize });
406
+ const startedAt = Date.now();
407
+ let lastCheckpointAt = startedAt;
408
+ let lastHeartbeatAt = 0;
409
+ let lastSignals = null;
410
+ let activitySinceCheckpoint = false;
411
+ let checkpointWarningSent = false;
412
+ let stallWarningSent = false;
413
+ let postDoneStartedAt = null;
414
+ let postDoneTerminated = false;
415
+
416
+ const child = spawnWorkerHandle({
417
+ worktreePath,
418
+ taskFolder,
419
+ useStub,
420
+ timeoutMs: piTimeoutMs,
421
+ piTimeoutMs,
422
+ projectRoot,
423
+ batchId,
424
+ laneNumber,
425
+ taskId,
426
+ laneCorrelationId,
427
+ fileScopePaths,
428
+ config,
429
+ workerBackendDeps,
430
+ });
431
+ let childPastPreflight = !useLaunchScript;
432
+ let workerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
433
+ markChildPastPreflight(child, () => {
434
+ childPastPreflight = true;
435
+ });
436
+ onWorkerPid?.(child.pid ?? 0);
437
+ const childDone = collectChildOutput(child);
438
+
439
+ while (true) {
440
+ const doneOnDisk = fs.existsSync(donePath);
441
+ const now = Date.now();
442
+
443
+ if (doneOnDisk && postDoneStartedAt === null) {
444
+ postDoneStartedAt = now;
445
+ }
446
+
447
+ if (projectRoot && batchId) {
448
+ const abortSignal = readAbortSignal(projectRoot, batchId);
449
+ if (abortSignal) {
450
+ const hard = Boolean(abortSignal.hard);
451
+ child.kill(hard ? "SIGKILL" : "SIGTERM");
452
+ const { output } = await childDone;
453
+ return buildWorkerFailureResult({
454
+ rawOutput: output,
455
+ classification: "aborted",
456
+ exitCode: hard ? 137 : 130,
457
+ mode: workerMode,
458
+ doneFound: fs.existsSync(donePath),
459
+ projectRoot,
460
+ batchId,
461
+ laneNumber,
462
+ taskId,
463
+ laneCorrelationId,
464
+ config,
465
+ });
466
+ }
467
+ }
468
+
469
+ if (doneOnDisk) {
470
+ if (child.exitCode !== null) {
471
+ break;
472
+ }
473
+ const graceElapsed = now - (postDoneStartedAt ?? now);
474
+ if (graceElapsed >= stallConfig.postDoneGraceMs) {
475
+ if (projectRoot && batchId) {
476
+ appendJournalEvent(projectRoot, batchId, "worker.post_done_terminated", {
477
+ laneNumber,
478
+ taskId,
479
+ correlationId: laneCorrelationId,
480
+ graceElapsedMs: graceElapsed,
481
+ postDoneGraceMs: stallConfig.postDoneGraceMs,
482
+ childPid: child.pid ?? null,
483
+ });
484
+ }
485
+ postDoneTerminated = true;
486
+ await terminateHungWorkerChild(child, childDone);
487
+ break;
488
+ }
489
+ await sleep(Math.min(stallConfig.pollIntervalMs, 5_000));
490
+ continue;
491
+ }
492
+
493
+ const signals = collectProgressSignals({
494
+ worktreePath,
495
+ taskFolder,
496
+ laneBranch,
497
+ fileScopePaths,
498
+ journalContext:
499
+ projectRoot && batchId
500
+ ? { projectRoot, batchId, laneNumber, taskId }
501
+ : undefined,
502
+ });
503
+ const nextWorkerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
504
+ if (nextWorkerPhase !== "launching" && workerPhase === "launching") {
505
+ lastCheckpointAt = now;
506
+ activitySinceCheckpoint = false;
507
+ checkpointWarningSent = false;
508
+ lastSignals = null;
509
+ }
510
+ workerPhase = nextWorkerPhase;
511
+
512
+ const checkpointChanged =
513
+ workerPhase !== "launching" && checkpointSignalsChanged(lastSignals, signals);
514
+ const activityChanged =
515
+ workerPhase !== "launching" && activitySignalsChanged(lastSignals, signals);
516
+
517
+ if (checkpointChanged) {
518
+ lastCheckpointAt = now;
519
+ activitySinceCheckpoint = false;
520
+ checkpointWarningSent = false;
521
+ } else if (activityChanged) {
522
+ activitySinceCheckpoint = true;
523
+ if (stallConfig.extendGraceOnFileScope) {
524
+ lastCheckpointAt = now;
525
+ }
526
+ }
527
+
528
+ if (
529
+ projectRoot &&
530
+ batchId &&
531
+ !checkpointWarningSent &&
532
+ shouldEmitCheckpointWarning({
533
+ now,
534
+ lastCheckpointAt,
535
+ signals,
536
+ stallConfig,
537
+ activitySinceCheckpoint,
538
+ workerPhase,
539
+ })
540
+ ) {
541
+ recordCheckpointWarning({
542
+ projectRoot,
543
+ batchId,
544
+ laneNumber,
545
+ taskId,
546
+ signals,
547
+ lastCheckpointAt,
548
+ correlationId: laneCorrelationId,
549
+ });
550
+ checkpointWarningSent = true;
551
+ }
552
+
553
+ lastSignals = signals;
554
+
555
+ if (
556
+ projectRoot &&
557
+ batchId &&
558
+ now - lastHeartbeatAt >= stallConfig.heartbeatIntervalMs
559
+ ) {
560
+ const heartbeatKind = resolveHeartbeatKind({
561
+ workerPhase,
562
+ checkpointChanged,
563
+ activityChanged,
564
+ });
565
+ recordLaneHeartbeat({
566
+ projectRoot,
567
+ batchId,
568
+ laneNumber,
569
+ taskId,
570
+ signals,
571
+ correlationId: laneCorrelationId,
572
+ workerPhase,
573
+ heartbeatKind,
574
+ });
575
+ onHeartbeat?.(now);
576
+ lastHeartbeatAt = now;
577
+ }
578
+
579
+ const stallDeadline = computeStallDeadline({
580
+ startedAt,
581
+ lastProgressAt: lastCheckpointAt,
582
+ stallConfig,
583
+ });
584
+
585
+ if (now >= stallDeadline) {
586
+ if (!stallWarningSent && projectRoot && batchId) {
587
+ recordStallWarning({
588
+ projectRoot,
589
+ batchId,
590
+ laneNumber,
591
+ taskId,
592
+ signals,
593
+ stallDeadline,
594
+ correlationId: laneCorrelationId,
595
+ });
596
+ stallWarningSent = true;
597
+ }
598
+ child.kill("SIGTERM");
599
+ const { output } = await childDone;
600
+ return buildWorkerFailureResult({
601
+ rawOutput: output,
602
+ classification: "stall_timeout",
603
+ exitCode: 124,
604
+ mode: workerMode,
605
+ doneFound: fs.existsSync(donePath),
606
+ projectRoot,
607
+ batchId,
608
+ laneNumber,
609
+ taskId,
610
+ laneCorrelationId,
611
+ config,
612
+ stallDeadline,
613
+ signals,
614
+ });
615
+ }
616
+
617
+ if (child.exitCode !== null) {
618
+ break;
619
+ }
620
+
621
+ await sleep(Math.min(stallConfig.pollIntervalMs, 5_000));
622
+ }
623
+
624
+ const { exitCode, output } = await childDone;
625
+ const doneFound = fs.existsSync(donePath);
626
+ if (postDoneTerminated && !doneFound) {
627
+ return buildWorkerFailureResult({
628
+ rawOutput: output,
629
+ classification: "failed",
630
+ exitCode,
631
+ mode: workerMode,
632
+ doneFound: false,
633
+ projectRoot,
634
+ batchId,
635
+ laneNumber,
636
+ taskId,
637
+ laneCorrelationId,
638
+ config,
639
+ });
640
+ }
641
+ const ok = doneFound && (exitCode === 0 || postDoneTerminated);
642
+ let classification = ok ? "succeeded" : "failed";
643
+ if (!ok && useLaunchScript && !childPastPreflight) {
644
+ classification = "launch_failed";
645
+ return buildWorkerFailureResult({
646
+ rawOutput: output,
647
+ classification,
648
+ exitCode,
649
+ mode: workerMode,
650
+ doneFound,
651
+ projectRoot,
652
+ batchId,
653
+ laneNumber,
654
+ taskId,
655
+ laneCorrelationId,
656
+ config,
657
+ });
658
+ }
659
+
660
+ const finalized = finalizeWorkerOutput({
661
+ rawOutput: output,
662
+ classification,
663
+ ok,
664
+ projectRoot,
665
+ batchId,
666
+ laneNumber,
667
+ taskId,
668
+ correlationId: laneCorrelationId,
669
+ exitCode,
670
+ config,
671
+ });
672
+
673
+ return {
674
+ ok,
675
+ exitCode,
676
+ mode: workerMode,
677
+ output: finalized.output,
678
+ workerOutputLogPath: finalized.logPath,
679
+ workerOutputLogRef: finalized.logRef,
680
+ classification,
681
+ doneFound,
682
+ };
683
+ }