pi-spine 1.0.2 → 1.2.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 (129) hide show
  1. package/README.md +61 -489
  2. package/bin/get-version.mjs +1 -13
  3. package/bin/spine-batch.mjs +162 -51
  4. package/bin/spine-cli/batch.mjs +3 -3
  5. package/bin/spine-cli/lane-logs.mjs +24 -0
  6. package/bin/spine-cli/scenarios.mjs +298 -0
  7. package/bin/spine-cli/wait.mjs +30 -0
  8. package/bin/spine-cli/watch.mjs +27 -0
  9. package/bin/spine-config.mjs +1 -212
  10. package/bin/spine-doctor.mjs +2 -418
  11. package/bin/spine-init.mjs +1 -398
  12. package/bin/spine-issue.mjs +196 -0
  13. package/bin/spine-journal.mjs +1 -0
  14. package/bin/spine-preflight.mjs +1 -700
  15. package/bin/spine-review-step.mjs +6 -4
  16. package/bin/spine-run.mjs +30 -0
  17. package/bin/spine-status.mjs +19 -1
  18. package/bin/spine-tasks.mjs +112 -13
  19. package/bin/spine-worker-runner.mjs +24 -14
  20. package/bin/spine.mjs +52 -2
  21. package/extensions/spine/worker-tools.ts +14 -12
  22. package/package.json +5 -2
  23. package/skills/create-spine-tasks/SKILL.md +135 -6
  24. package/skills/create-spine-tasks/references/clarify-template.md +73 -0
  25. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  26. package/skills/create-spine-tasks/references/prompt-template.md +2 -0
  27. package/skills/create-spine-tasks/references/requirements-checklist-template.md +94 -0
  28. package/src/batch/abort.mjs +3 -12
  29. package/src/batch/agent-session-worker.mjs +45 -5
  30. package/src/batch/attached-engine-handoff.mjs +188 -0
  31. package/src/batch/attached-runner.mjs +312 -0
  32. package/src/batch/contract-prelanded.mjs +180 -0
  33. package/src/batch/contract-verify.mjs +140 -2
  34. package/src/batch/detached-start.mjs +105 -7
  35. package/src/batch/diagnosis-alternatives.mjs +46 -0
  36. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  37. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  38. package/src/batch/diagnosis-stub.mjs +109 -0
  39. package/src/batch/diagnosis-task-done.mjs +110 -0
  40. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  41. package/src/batch/diagnosis.mjs +174 -62
  42. package/src/batch/engine-lanes/merge.mjs +168 -77
  43. package/src/batch/engine-lanes/queue.mjs +4 -1
  44. package/src/batch/engine-lanes/review.mjs +32 -74
  45. package/src/batch/engine-lanes/watch.mjs +29 -0
  46. package/src/batch/engine-lanes.mjs +1 -0
  47. package/src/batch/engine-scope.mjs +42 -5
  48. package/src/batch/engine.mjs +115 -68
  49. package/src/batch/evidence.mjs +81 -17
  50. package/src/batch/gate.mjs +46 -17
  51. package/src/batch/git-helpers.mjs +96 -0
  52. package/src/batch/heartbeat.mjs +73 -7
  53. package/src/batch/integrate.mjs +3 -5
  54. package/src/batch/journal.mjs +25 -0
  55. package/src/batch/lane-commit.mjs +90 -5
  56. package/src/batch/lifecycle.mjs +131 -4
  57. package/src/batch/macro-phase.mjs +226 -0
  58. package/src/batch/merge/adoption-doc-merge.mjs +243 -0
  59. package/src/batch/merge/wave-merge-state.mjs +108 -0
  60. package/src/batch/metrics.mjs +74 -5
  61. package/src/batch/orphan-detect.mjs +74 -0
  62. package/src/batch/pause.mjs +223 -0
  63. package/src/batch/post-merge-limbo.mjs +345 -17
  64. package/src/batch/reconcile.mjs +473 -50
  65. package/src/batch/resume-common.mjs +6 -2
  66. package/src/batch/resume-engine.mjs +58 -1
  67. package/src/batch/resume-lane-reviews.mjs +16 -0
  68. package/src/batch/resume-multi-lanes.mjs +56 -1
  69. package/src/batch/resume-multi-validate.mjs +148 -8
  70. package/src/batch/resume-multi.mjs +45 -44
  71. package/src/batch/resume.mjs +64 -47
  72. package/src/batch/retry.mjs +56 -5
  73. package/src/batch/review-shared.mjs +196 -0
  74. package/src/batch/review-spawn.mjs +326 -0
  75. package/src/batch/review.mjs +178 -212
  76. package/src/batch/rules-manifest-drift.mjs +157 -0
  77. package/src/batch/salvage.mjs +2 -1
  78. package/src/batch/sequence.mjs +454 -0
  79. package/src/batch/state.mjs +18 -3
  80. package/src/batch/status-json.mjs +67 -0
  81. package/src/batch/task-stall-budget.mjs +94 -10
  82. package/src/batch/worker-host.mjs +185 -37
  83. package/src/batch/worker-output.mjs +196 -3
  84. package/src/batch/worktree.mjs +10 -0
  85. package/src/cli/handoff.mjs +1 -1
  86. package/src/cli/issue-draft.mjs +180 -0
  87. package/src/cli/journal-follow.mjs +239 -0
  88. package/src/cli/lane-logs.mjs +291 -0
  89. package/src/cli/rules.mjs +1 -1
  90. package/src/cli/sequence.mjs +108 -0
  91. package/src/cli/settings-set.mjs +3 -22
  92. package/src/cli/settings-slash.mjs +27 -5
  93. package/src/cli/wait.mjs +187 -0
  94. package/src/cli/watch.mjs +160 -0
  95. package/src/config/agent-model-resolve.mjs +48 -0
  96. package/src/config/cursor-rules/discover.mjs +3 -21
  97. package/src/config/defaults.mjs +7 -1
  98. package/src/config/settings-fields.mjs +48 -0
  99. package/src/config/spine-config-load.mjs +221 -0
  100. package/src/config/spine-init-constants.mjs +424 -0
  101. package/src/config/spine-preflight-lib.mjs +1180 -0
  102. package/src/dashboard/lane-throughput.mjs +351 -0
  103. package/src/dashboard/public/dashboard.css +25 -1
  104. package/src/dashboard/public/dashboard.js +224 -40
  105. package/src/dashboard/public/index.html +15 -9
  106. package/src/dashboard/server.mjs +4 -0
  107. package/src/dashboard/snapshot.mjs +387 -6
  108. package/src/dashboard/view.mjs +170 -15
  109. package/src/doctor/agent-model-inherit.mjs +61 -6
  110. package/src/doctor/run-doctor-checks.mjs +483 -0
  111. package/src/doctor/sequence-safety.mjs +57 -0
  112. package/src/doctor/stale-path.mjs +22 -0
  113. package/src/doctor/stale-worktrees.mjs +102 -0
  114. package/src/fixtures/scenario-registry.mjs +194 -0
  115. package/src/fs/atomic-write.mjs +49 -0
  116. package/src/migrate/taskplane-config.mjs +1 -1
  117. package/src/planner/file-scope.mjs +246 -0
  118. package/src/planner/format-plan.mjs +9 -7
  119. package/src/planner/index.mjs +6 -2
  120. package/src/planner/pending.mjs +92 -1
  121. package/src/planner/wave-scope.mjs +136 -0
  122. package/src/planner/waves.mjs +133 -0
  123. package/src/tasks/analyze/index.mjs +453 -0
  124. package/src/tasks/packet/index.mjs +1 -0
  125. package/src/tasks/packet/parse-prompt.mjs +42 -1
  126. package/src/tasks/packet/validate-prompt.mjs +124 -0
  127. package/src/util/command-exists.mjs +19 -0
  128. package/templates/docs/constitution.md +61 -0
  129. package/templates/spine-config.json +9 -2
@@ -1,10 +1,11 @@
1
+ // @ts-check
1
2
  /**
2
3
  * pi-spine worker host — spawn worker in lane worktree with heartbeat polling.
3
4
  */
4
5
 
5
6
  import fs from "node:fs";
6
7
  import path from "node:path";
7
- import { spawn, spawnSync } from "node:child_process";
8
+ import { spawn } from "node:child_process";
8
9
  import { fileURLToPath } from "node:url";
9
10
  import { readAbortSignal } from "./abort.mjs";
10
11
  import {
@@ -14,20 +15,27 @@ import {
14
15
  computeStallDeadline,
15
16
  recordCheckpointWarning,
16
17
  recordLaneHeartbeat,
18
+ recordLaneProgressSnapshot,
17
19
  recordStallWarning,
18
20
  resolveHeartbeatKind,
19
21
  shouldEmitCheckpointWarning,
22
+ shouldEmitProgressSnapshot,
23
+ buildProgressSnapshotPayload,
24
+ progressSnapshotPayloadChanged,
20
25
  } from "./heartbeat.mjs";
21
26
  import {
22
27
  resolveStallConfigForTask,
23
28
  resolveWorkerPiTimeoutMs,
24
29
  parseTaskSizeFromFolder,
25
30
  } from "./task-stall-budget.mjs";
31
+ import { parseContract } from "../tasks/packet/parse-prompt.mjs";
26
32
  import { appendJournalEvent } from "./journal.mjs";
27
33
  import { assertReviewToolAvailable } from "./review.mjs";
28
34
  import { startAgentSessionWorker } from "./agent-session-worker.mjs";
29
- import { finalizeWorkerOutput } from "./worker-output.mjs";
35
+ import { finalizeWorkerOutput, createWorkerLiveLogWriter } from "./worker-output.mjs";
36
+ import { nextStallAnchorAt } from "./engine-lanes/watch.mjs";
30
37
  import { resolveWorkerBackend } from "../config/worker-backend.mjs";
38
+ import { commandExists } from "../util/command-exists.mjs";
31
39
  import { resolvePiSpineRoot } from "../config/pi-spine-root.mjs";
32
40
  import { resolveSafeWorkerLaunchScript } from "../config/worker-launch-script.mjs";
33
41
 
@@ -38,17 +46,47 @@ const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
38
46
  const POST_DONE_KILL_BACKOFF_MS = 5_000;
39
47
 
40
48
  /**
41
- * @param {string} cmd
49
+ * Force-terminate lane worker processes tracked in batch state.
50
+ *
51
+ * @param {unknown[]} lanes
52
+ * @param {{ hard?: boolean }} [options]
53
+ * @returns {Array<{ laneNumber: number, workerPid: number, signal: NodeJS.Signals }>}
42
54
  */
43
- function commandExists(cmd) {
44
- try {
45
- spawnSync("which", [cmd], { stdio: "ignore" });
46
- return true;
47
- } catch {
48
- return false;
55
+ export function terminateLaneWorkers(lanes, { hard = true } = {}) {
56
+ const signal = hard ? "SIGKILL" : "SIGTERM";
57
+ /** @type {Array<{ laneNumber: number, workerPid: number, signal: NodeJS.Signals }>} */
58
+ const terminated = [];
59
+ for (const lane of lanes ?? []) {
60
+ if (!lane || typeof lane !== "object") continue;
61
+ const workerPid = Number(/** @type {{ workerPid?: number }} */ (lane).workerPid);
62
+ if (!Number.isFinite(workerPid) || workerPid <= 0) continue;
63
+ const laneNumber = Number(
64
+ /** @type {{ laneNumber?: number }} */ (lane).laneNumber ?? 1,
65
+ );
66
+ try {
67
+ process.kill(workerPid, signal);
68
+ terminated.push({ laneNumber, workerPid, signal });
69
+ } catch {
70
+ // process may already be gone
71
+ }
49
72
  }
73
+ return terminated;
50
74
  }
51
75
 
76
+ /** @typedef {"launching" | "pi" | "verify" | "unknown"} WorkerPhase */
77
+
78
+ /**
79
+ * @typedef {import("node:child_process").ChildProcess | {
80
+ * pid: number;
81
+ * exitCode: number | null;
82
+ * kill: (signal?: NodeJS.Signals) => boolean;
83
+ * wait?: () => Promise<{ exitCode: number; output: string }>;
84
+ * stdout?: NodeJS.ReadableStream | null;
85
+ * stderr?: NodeJS.ReadableStream | null;
86
+ * on?: import("node:events").EventEmitter["on"];
87
+ * }} WorkerChildHandle
88
+ */
89
+
52
90
  /**
53
91
  * @param {number} ms
54
92
  */
@@ -68,6 +106,16 @@ function resolveWorkerLaunchScript(projectRoot, config = {}) {
68
106
 
69
107
  /**
70
108
  * @param {object} params
109
+ * @param {string} params.taskFolder
110
+ * @param {string} params.worktreePath
111
+ * @param {string} [params.projectRoot]
112
+ * @param {string} [params.batchId]
113
+ * @param {number} [params.laneNumber]
114
+ * @param {string} [params.taskId]
115
+ * @param {string} [params.laneCorrelationId]
116
+ * @param {string[]} [params.fileScopePaths]
117
+ * @param {object} [params.config]
118
+ * @param {number} [params.piTimeoutMs]
71
119
  */
72
120
  export function buildWorkerChildEnv({
73
121
  taskFolder,
@@ -82,6 +130,7 @@ export function buildWorkerChildEnv({
82
130
  piTimeoutMs,
83
131
  }) {
84
132
  const runner = path.join(PACKAGE_ROOT, "bin", "spine-worker-runner.mjs");
133
+ /** @type {NodeJS.ProcessEnv} */
85
134
  const env = {
86
135
  ...process.env,
87
136
  SPINE_TASK_FOLDER: taskFolder,
@@ -90,6 +139,7 @@ export function buildWorkerChildEnv({
90
139
  PI_SPINE_ROOT: resolvePiSpineRoot(config, projectRoot ?? process.cwd()),
91
140
  };
92
141
  if (projectRoot) env.SPINE_PROJECT_ROOT = projectRoot;
142
+ if (worktreePath) env.SPINE_RULES_PROJECT_ROOT = worktreePath;
93
143
  if (batchId) {
94
144
  env.SPINE_BATCH_ID = batchId;
95
145
  env.SPINE_JOURNAL_ATTACH = "1";
@@ -114,6 +164,18 @@ export function buildWorkerChildEnv({
114
164
 
115
165
  /**
116
166
  * @param {object} params
167
+ * @param {string} params.worktreePath
168
+ * @param {string} params.taskFolder
169
+ * @param {boolean} params.useStub
170
+ * @param {number} params.timeoutMs
171
+ * @param {string} [params.projectRoot]
172
+ * @param {string} [params.batchId]
173
+ * @param {number} [params.laneNumber]
174
+ * @param {string} [params.taskId]
175
+ * @param {string} [params.laneCorrelationId]
176
+ * @param {string[]} [params.fileScopePaths]
177
+ * @param {object} [params.config]
178
+ * @param {number} [params.piTimeoutMs]
117
179
  */
118
180
  function spawnWorkerChild({
119
181
  worktreePath,
@@ -162,6 +224,19 @@ function spawnWorkerChild({
162
224
 
163
225
  /**
164
226
  * @param {object} params
227
+ * @param {string} params.rawOutput
228
+ * @param {string} params.classification
229
+ * @param {number} params.exitCode
230
+ * @param {string} params.mode
231
+ * @param {boolean} params.doneFound
232
+ * @param {string} [params.projectRoot]
233
+ * @param {string} [params.batchId]
234
+ * @param {number} [params.laneNumber]
235
+ * @param {string} [params.taskId]
236
+ * @param {string} [params.laneCorrelationId]
237
+ * @param {object} [params.config]
238
+ * @param {number} [params.stallDeadline]
239
+ * @param {object} [params.signals]
165
240
  */
166
241
  function buildWorkerFailureResult({
167
242
  rawOutput,
@@ -205,7 +280,8 @@ function buildWorkerFailureResult({
205
280
  }
206
281
 
207
282
  /**
208
- * @param {import("node:child_process").ChildProcess | ReturnType<typeof startAgentSessionWorker>} child
283
+ * @param {WorkerChildHandle} child
284
+ * @param {() => void} onPreflightComplete
209
285
  */
210
286
  function markChildPastPreflight(child, onPreflightComplete) {
211
287
  if (typeof child.stdout?.on === "function") {
@@ -218,6 +294,10 @@ function markChildPastPreflight(child, onPreflightComplete) {
218
294
 
219
295
  /**
220
296
  * @param {object} params
297
+ * @param {boolean} params.childPastPreflight
298
+ * @param {boolean} params.useStub
299
+ * @param {string} params.workerBackend
300
+ * @returns {WorkerPhase}
221
301
  */
222
302
  function resolveWorkerPhase({
223
303
  childPastPreflight,
@@ -232,7 +312,7 @@ function resolveWorkerPhase({
232
312
  /**
233
313
  * SIGTERM then SIGKILL when a worker stays alive after post-.DONE grace.
234
314
  *
235
- * @param {import("node:child_process").ChildProcess | ReturnType<typeof startAgentSessionWorker>} child
315
+ * @param {WorkerChildHandle} child
236
316
  * @param {Promise<{ exitCode: number; output: string }>} childDone
237
317
  */
238
318
  async function terminateHungWorkerChild(child, childDone) {
@@ -248,22 +328,27 @@ async function terminateHungWorkerChild(child, childDone) {
248
328
  }
249
329
 
250
330
  /**
251
- * @param {import("node:child_process").ChildProcess | ReturnType<typeof startAgentSessionWorker>} child
331
+ * @param {WorkerChildHandle} child
332
+ * @param {{ append: (rawChunk: string) => void } | null} [liveLogWriter]
252
333
  */
253
- function collectChildOutput(child) {
254
- if (typeof child.wait === "function") {
334
+ function collectChildOutput(child, liveLogWriter) {
335
+ if ("wait" in child && typeof child.wait === "function") {
255
336
  return child.wait();
256
337
  }
257
338
  return new Promise((resolve) => {
258
339
  let stdout = "";
259
340
  let stderr = "";
260
- child.stdout?.on("data", (chunk) => {
261
- stdout += chunk.toString();
341
+ child.stdout?.on("data", (/** @type {Buffer | string} */ chunk) => {
342
+ const text = chunk.toString();
343
+ stdout += text;
344
+ liveLogWriter?.append(text);
262
345
  });
263
- child.stderr?.on("data", (chunk) => {
264
- stderr += chunk.toString();
346
+ child.stderr?.on("data", (/** @type {Buffer | string} */ chunk) => {
347
+ const text = chunk.toString();
348
+ stderr += text;
349
+ liveLogWriter?.append(text);
265
350
  });
266
- child.on("close", (code) => {
351
+ child.on?.("close", (/** @type {number | null} */ code) => {
267
352
  resolve({ exitCode: code ?? 1, output: `${stdout}${stderr}` });
268
353
  });
269
354
  });
@@ -271,6 +356,18 @@ function collectChildOutput(child) {
271
356
 
272
357
  /**
273
358
  * @param {object} params
359
+ * @param {string} params.worktreePath
360
+ * @param {string} params.taskFolder
361
+ * @param {boolean} params.useStub
362
+ * @param {number} params.timeoutMs
363
+ * @param {number} [params.piTimeoutMs]
364
+ * @param {string} [params.projectRoot]
365
+ * @param {string} [params.batchId]
366
+ * @param {number} [params.laneNumber]
367
+ * @param {string} [params.taskId]
368
+ * @param {string} [params.laneCorrelationId]
369
+ * @param {string[]} [params.fileScopePaths]
370
+ * @param {object} [params.config]
274
371
  * @param {object} [params.workerBackendDeps]
275
372
  */
276
373
  function spawnWorkerHandle({
@@ -301,14 +398,14 @@ function spawnWorkerHandle({
301
398
 
302
399
  if (!useStub && resolveWorkerBackend(config) === "agentSession") {
303
400
  return startAgentSessionWorker(
304
- {
401
+ /** @type {{ worktreePath: string; taskFolder: string; config?: object; taskFileScope?: string[]; journal?: import("../config/worker-context.mjs").WorkerRulesJournalContext; projectRoot?: string }} */ ({
305
402
  worktreePath,
306
403
  taskFolder,
307
404
  config,
308
405
  taskFileScope: fileScopePaths,
309
406
  journal,
310
407
  projectRoot,
311
- },
408
+ }),
312
409
  workerBackendDeps ?? {},
313
410
  );
314
411
  }
@@ -342,6 +439,7 @@ function spawnWorkerHandle({
342
439
  * @param {object} [params.config]
343
440
  * @param {(timestamp: number) => void} [params.onHeartbeat]
344
441
  * @param {(pid: number) => void} [params.onWorkerPid]
442
+ * @param {string[]} [params.fileScopePaths]
345
443
  * @param {number} [params.timeoutMs]
346
444
  * @param {object} [params.workerBackendDeps] Test-only injectables for agentSession backend
347
445
  */
@@ -401,11 +499,18 @@ export async function runWorker({
401
499
  }
402
500
 
403
501
  const taskSize = parseTaskSizeFromFolder(taskFolder);
404
- const stallConfig = resolveStallConfigForTask({ config, taskSize });
405
- const piTimeoutMs = resolveWorkerPiTimeoutMs({ config, taskSize });
502
+ const promptPath = path.join(taskFolder, "PROMPT.md");
503
+ const contract = fs.existsSync(promptPath)
504
+ ? parseContract(fs.readFileSync(promptPath, "utf-8"))
505
+ : { stallTimeoutMinutes: null, extendGraceOnFileScope: null };
506
+ const stallConfig = resolveStallConfigForTask({ config, taskSize, contract });
507
+ const piTimeoutMs = resolveWorkerPiTimeoutMs({ config, taskSize, contract });
406
508
  const startedAt = Date.now();
509
+ let stallAnchorAt = startedAt;
407
510
  let lastCheckpointAt = startedAt;
408
511
  let lastHeartbeatAt = 0;
512
+ let lastProgressSnapshotAt = 0;
513
+ let lastSnapshotPayload = null;
409
514
  let lastSignals = null;
410
515
  let activitySinceCheckpoint = false;
411
516
  let checkpointWarningSent = false;
@@ -428,13 +533,22 @@ export async function runWorker({
428
533
  config,
429
534
  workerBackendDeps,
430
535
  });
536
+ const workerChild = /** @type {WorkerChildHandle} */ (child);
431
537
  let childPastPreflight = !useLaunchScript;
538
+ /** @type {WorkerPhase} */
432
539
  let workerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
433
- markChildPastPreflight(child, () => {
540
+ markChildPastPreflight(workerChild, () => {
434
541
  childPastPreflight = true;
435
542
  });
436
- onWorkerPid?.(child.pid ?? 0);
437
- const childDone = collectChildOutput(child);
543
+ onWorkerPid?.(workerChild.pid ?? 0);
544
+ const liveLogWriter = createWorkerLiveLogWriter({
545
+ projectRoot,
546
+ batchId,
547
+ laneNumber,
548
+ taskId,
549
+ config,
550
+ });
551
+ const childDone = collectChildOutput(workerChild, liveLogWriter);
438
552
 
439
553
  while (true) {
440
554
  const doneOnDisk = fs.existsSync(donePath);
@@ -448,7 +562,7 @@ export async function runWorker({
448
562
  const abortSignal = readAbortSignal(projectRoot, batchId);
449
563
  if (abortSignal) {
450
564
  const hard = Boolean(abortSignal.hard);
451
- child.kill(hard ? "SIGKILL" : "SIGTERM");
565
+ workerChild.kill(hard ? "SIGKILL" : "SIGTERM");
452
566
  const { output } = await childDone;
453
567
  return buildWorkerFailureResult({
454
568
  rawOutput: output,
@@ -467,7 +581,7 @@ export async function runWorker({
467
581
  }
468
582
 
469
583
  if (doneOnDisk) {
470
- if (child.exitCode !== null) {
584
+ if (workerChild.exitCode !== null) {
471
585
  break;
472
586
  }
473
587
  const graceElapsed = now - (postDoneStartedAt ?? now);
@@ -479,18 +593,18 @@ export async function runWorker({
479
593
  correlationId: laneCorrelationId,
480
594
  graceElapsedMs: graceElapsed,
481
595
  postDoneGraceMs: stallConfig.postDoneGraceMs,
482
- childPid: child.pid ?? null,
596
+ childPid: workerChild.pid ?? null,
483
597
  });
484
598
  }
485
599
  postDoneTerminated = true;
486
- await terminateHungWorkerChild(child, childDone);
600
+ await terminateHungWorkerChild(workerChild, childDone);
487
601
  break;
488
602
  }
489
603
  await sleep(Math.min(stallConfig.pollIntervalMs, 5_000));
490
604
  continue;
491
605
  }
492
606
 
493
- const signals = collectProgressSignals({
607
+ const signals = collectProgressSignals(/** @type {any} */ ({
494
608
  worktreePath,
495
609
  taskFolder,
496
610
  laneBranch,
@@ -499,13 +613,15 @@ export async function runWorker({
499
613
  projectRoot && batchId
500
614
  ? { projectRoot, batchId, laneNumber, taskId }
501
615
  : undefined,
502
- });
616
+ }));
503
617
  const nextWorkerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
504
618
  if (nextWorkerPhase !== "launching" && workerPhase === "launching") {
619
+ stallAnchorAt = now;
505
620
  lastCheckpointAt = now;
506
621
  activitySinceCheckpoint = false;
507
622
  checkpointWarningSent = false;
508
623
  lastSignals = null;
624
+ lastSnapshotPayload = null;
509
625
  }
510
626
  workerPhase = nextWorkerPhase;
511
627
 
@@ -552,17 +668,42 @@ export async function runWorker({
552
668
 
553
669
  lastSignals = signals;
554
670
 
671
+ if (
672
+ projectRoot &&
673
+ batchId &&
674
+ shouldEmitProgressSnapshot({
675
+ now,
676
+ lastEmittedAt: lastProgressSnapshotAt,
677
+ intervalMs: stallConfig.progressSnapshotIntervalMs,
678
+ })
679
+ ) {
680
+ const snapshotPayload = buildProgressSnapshotPayload(signals, workerPhase);
681
+ if (progressSnapshotPayloadChanged(lastSnapshotPayload, snapshotPayload)) {
682
+ recordLaneProgressSnapshot({
683
+ projectRoot,
684
+ batchId,
685
+ laneNumber,
686
+ taskId,
687
+ signals,
688
+ correlationId: laneCorrelationId,
689
+ workerPhase,
690
+ });
691
+ lastSnapshotPayload = snapshotPayload;
692
+ }
693
+ lastProgressSnapshotAt = now;
694
+ }
695
+
555
696
  if (
556
697
  projectRoot &&
557
698
  batchId &&
558
699
  now - lastHeartbeatAt >= stallConfig.heartbeatIntervalMs
559
700
  ) {
560
- const heartbeatKind = resolveHeartbeatKind({
701
+ const heartbeatKind = resolveHeartbeatKind(/** @type {any} */ ({
561
702
  workerPhase,
562
703
  checkpointChanged,
563
704
  activityChanged,
564
- });
565
- recordLaneHeartbeat({
705
+ }));
706
+ recordLaneHeartbeat(/** @type {any} */ ({
566
707
  projectRoot,
567
708
  batchId,
568
709
  laneNumber,
@@ -571,6 +712,12 @@ export async function runWorker({
571
712
  correlationId: laneCorrelationId,
572
713
  workerPhase,
573
714
  heartbeatKind,
715
+ }));
716
+ stallAnchorAt = nextStallAnchorAt({
717
+ stallAnchorAt,
718
+ now,
719
+ workerPhase,
720
+ heartbeatKind,
574
721
  });
575
722
  onHeartbeat?.(now);
576
723
  lastHeartbeatAt = now;
@@ -579,6 +726,7 @@ export async function runWorker({
579
726
  const stallDeadline = computeStallDeadline({
580
727
  startedAt,
581
728
  lastProgressAt: lastCheckpointAt,
729
+ lastAliveAt: stallAnchorAt,
582
730
  stallConfig,
583
731
  });
584
732
 
@@ -595,7 +743,7 @@ export async function runWorker({
595
743
  });
596
744
  stallWarningSent = true;
597
745
  }
598
- child.kill("SIGTERM");
746
+ workerChild.kill("SIGTERM");
599
747
  const { output } = await childDone;
600
748
  return buildWorkerFailureResult({
601
749
  rawOutput: output,
@@ -614,7 +762,7 @@ export async function runWorker({
614
762
  });
615
763
  }
616
764
 
617
- if (child.exitCode !== null) {
765
+ if (workerChild.exitCode !== null) {
618
766
  break;
619
767
  }
620
768
 
@@ -4,9 +4,11 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
+ import { writeJsonAtomic, writeTextAtomic } from "../fs/atomic-write.mjs";
7
8
  import { appendJournalEvent } from "./journal.mjs";
8
9
 
9
10
  const DEFAULT_MAX_BYTES = 262_144;
11
+ const DEFAULT_LIVE_LOG_MAX_BYTES = 262_144;
10
12
  const DEFAULT_TAIL_LINES = 200;
11
13
  const TRUNCATION_MARKER = "\n...[worker output truncated]...\n";
12
14
 
@@ -38,10 +40,17 @@ export function resolveWorkerOutputConfig(config = {}) {
38
40
  }
39
41
  }
40
42
 
43
+ const liveMaxBytes = Number(lanes.workerLiveLogMaxBytes);
44
+
41
45
  return {
42
46
  maxBytes: Number.isFinite(maxBytes) && maxBytes > 0 ? maxBytes : DEFAULT_MAX_BYTES,
43
47
  tailLines: Number.isFinite(tailLines) && tailLines > 0 ? tailLines : DEFAULT_TAIL_LINES,
44
48
  retainOnSuccess: lanes.retainWorkerOutputOnSuccess === true,
49
+ streamWorkerOutputLive: lanes.streamWorkerOutputLive === true,
50
+ workerLiveLogMaxBytes:
51
+ Number.isFinite(liveMaxBytes) && liveMaxBytes > 0
52
+ ? liveMaxBytes
53
+ : DEFAULT_LIVE_LOG_MAX_BYTES,
45
54
  denyPatterns,
46
55
  };
47
56
  }
@@ -134,6 +143,118 @@ export function workerOutputLogRef(batchId, laneNumber, taskId) {
134
143
  );
135
144
  }
136
145
 
146
+ /**
147
+ * @param {string} projectRoot
148
+ * @param {string} batchId
149
+ * @param {number} laneNumber
150
+ * @param {string} taskId
151
+ */
152
+ export function workerLiveLogPath(projectRoot, batchId, laneNumber, taskId) {
153
+ return path.join(
154
+ projectRoot,
155
+ ".spine",
156
+ "runtime",
157
+ batchId,
158
+ "lanes",
159
+ `lane-${laneNumber}`,
160
+ `worker-live-${taskId}.log`,
161
+ );
162
+ }
163
+
164
+ /**
165
+ * @param {string} batchId
166
+ * @param {number} laneNumber
167
+ * @param {string} taskId
168
+ */
169
+ export function workerLiveLogRef(batchId, laneNumber, taskId) {
170
+ return path.join(
171
+ ".spine",
172
+ "runtime",
173
+ batchId,
174
+ "lanes",
175
+ `lane-${laneNumber}`,
176
+ `worker-live-${taskId}.log`,
177
+ );
178
+ }
179
+
180
+ /**
181
+ * Byte-cap live log content with the same truncation marker as terminal capture.
182
+ *
183
+ * @param {string} text
184
+ * @param {number} maxBytes
185
+ */
186
+ export function truncateLiveLogBytes(text, maxBytes) {
187
+ if (!text) return "";
188
+
189
+ const encoded = Buffer.from(text, "utf-8");
190
+ if (encoded.byteLength <= maxBytes) {
191
+ return text;
192
+ }
193
+
194
+ const markerBytes = Buffer.byteLength(TRUNCATION_MARKER, "utf-8");
195
+ const budget = Math.max(0, maxBytes - markerBytes);
196
+ let slice = encoded.subarray(encoded.byteLength - budget).toString("utf-8");
197
+ const newline = slice.indexOf("\n");
198
+ if (newline >= 0 && newline < slice.length - 1) {
199
+ slice = slice.slice(newline + 1);
200
+ }
201
+ return `${TRUNCATION_MARKER}${slice}`;
202
+ }
203
+
204
+ /**
205
+ * Append redacted worker output to the live log with a rolling byte cap.
206
+ *
207
+ * @param {object} params
208
+ * @param {string} params.logPath
209
+ * @param {string} params.rawChunk
210
+ * @param {ReturnType<typeof resolveWorkerOutputConfig>} params.outputConfig
211
+ */
212
+ export function appendWorkerLiveLogChunk({ logPath, rawChunk, outputConfig }) {
213
+ if (!rawChunk) return;
214
+
215
+ const redacted = redactWorkerOutput(String(rawChunk), outputConfig);
216
+ if (!redacted) return;
217
+
218
+ const prior = fs.existsSync(logPath) ? fs.readFileSync(logPath, "utf-8") : "";
219
+ const combined = `${prior}${redacted}`;
220
+ const capped = truncateLiveLogBytes(combined, outputConfig.workerLiveLogMaxBytes);
221
+ if (!capped) return;
222
+
223
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
224
+ writeTextAtomic(logPath, capped);
225
+ }
226
+
227
+ /**
228
+ * Create an append-only live log writer when `lanes.streamWorkerOutputLive` is enabled.
229
+ *
230
+ * @param {object} params
231
+ * @param {string} [params.projectRoot]
232
+ * @param {string} [params.batchId]
233
+ * @param {number} [params.laneNumber]
234
+ * @param {string} [params.taskId]
235
+ * @param {object} [params.config]
236
+ * @returns {{ append: (rawChunk: string) => void; logPath: string } | null}
237
+ */
238
+ export function createWorkerLiveLogWriter({
239
+ projectRoot,
240
+ batchId,
241
+ laneNumber,
242
+ taskId,
243
+ config = {},
244
+ }) {
245
+ const outputConfig = resolveWorkerOutputConfig(config);
246
+ if (!outputConfig.streamWorkerOutputLive) return null;
247
+ if (!projectRoot || !batchId || laneNumber == null || !taskId) return null;
248
+
249
+ const logPath = workerLiveLogPath(projectRoot, batchId, laneNumber, taskId);
250
+ return {
251
+ logPath,
252
+ append(rawChunk) {
253
+ appendWorkerLiveLogChunk({ logPath, rawChunk, outputConfig });
254
+ },
255
+ };
256
+ }
257
+
137
258
  /**
138
259
  * @param {object} params
139
260
  */
@@ -150,8 +271,7 @@ export function persistWorkerOutputLog({
150
271
  if (!captured.trim()) return null;
151
272
 
152
273
  const logPath = workerOutputLogPath(projectRoot, batchId, laneNumber, taskId);
153
- fs.mkdirSync(path.dirname(logPath), { recursive: true });
154
- fs.writeFileSync(logPath, captured, "utf-8");
274
+ writeTextAtomic(logPath, captured);
155
275
 
156
276
  return {
157
277
  logPath,
@@ -250,4 +370,77 @@ export function finalizeWorkerOutput({
250
370
  };
251
371
  }
252
372
 
253
- export { TRUNCATION_MARKER, DEFAULT_MAX_BYTES, DEFAULT_TAIL_LINES };
373
+ /**
374
+ * Parse a `.DONE` marker body. Legacy empty/text markers remain valid (SP-321).
375
+ *
376
+ * @param {string} content
377
+ */
378
+ export function parseWorkerDoneMarker(content) {
379
+ const trimmed = String(content ?? "").trim();
380
+ if (!trimmed) {
381
+ return { valid: true, legacy: true, kind: "empty" };
382
+ }
383
+
384
+ if (trimmed.startsWith("{")) {
385
+ try {
386
+ const data = JSON.parse(trimmed);
387
+ if (
388
+ typeof data?.taskId === "string" &&
389
+ data.taskId.length > 0 &&
390
+ typeof data?.completedAt === "string" &&
391
+ data.completedAt.length > 0
392
+ ) {
393
+ return {
394
+ valid: true,
395
+ legacy: false,
396
+ kind: "json",
397
+ taskId: data.taskId,
398
+ completedAt: data.completedAt,
399
+ };
400
+ }
401
+ return { valid: false, legacy: false, kind: "json_partial", reason: "missing_fields" };
402
+ } catch {
403
+ return { valid: false, legacy: false, kind: "json_partial", reason: "parse_error" };
404
+ }
405
+ }
406
+
407
+ return { valid: true, legacy: true, kind: "text" };
408
+ }
409
+
410
+ /**
411
+ * @param {string} content
412
+ */
413
+ export function isWorkerDoneMarkerValid(content) {
414
+ return parseWorkerDoneMarker(content).valid;
415
+ }
416
+
417
+ /**
418
+ * @param {string} donePath
419
+ */
420
+ export function readWorkerDoneMarker(donePath) {
421
+ if (!fs.existsSync(donePath)) {
422
+ return { present: false, valid: false };
423
+ }
424
+ const parsed = parseWorkerDoneMarker(fs.readFileSync(donePath, "utf-8"));
425
+ return { present: true, ...parsed };
426
+ }
427
+
428
+ /**
429
+ * Atomically write a structured `.DONE` marker for engine validation.
430
+ *
431
+ * @param {string} donePath
432
+ * @param {{ taskId: string }} params
433
+ */
434
+ export function writeWorkerDoneMarker(donePath, { taskId }) {
435
+ writeJsonAtomic(donePath, {
436
+ taskId,
437
+ completedAt: new Date().toISOString(),
438
+ });
439
+ }
440
+
441
+ export {
442
+ TRUNCATION_MARKER,
443
+ DEFAULT_MAX_BYTES,
444
+ DEFAULT_LIVE_LOG_MAX_BYTES,
445
+ DEFAULT_TAIL_LINES,
446
+ };