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
@@ -5,29 +5,50 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { execFileSync } from "node:child_process";
8
- import { loadSpineConfig } from "../../bin/spine-config.mjs";
8
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
+ import { PACKAGE_ROOT } from "../config/spine-init-constants.mjs";
9
10
  import { resolveTasksRootPath } from "../config/env-overrides.mjs";
11
+ import { buildStalePathDoctorCheck } from "../doctor/stale-path.mjs";
12
+ import { loadGateRecord } from "./gate.mjs";
13
+ import { deriveMacroPhase, macroPhaseLabel } from "./macro-phase.mjs";
10
14
  import {
11
15
  buildDiagnosisOutput,
16
+ classifyTaskDoneSemantics,
12
17
  inferLaunchFailureFromWorkerOutputTail,
13
18
  inferLaunchFailureKind,
19
+ inferMergeGitignoredFailure,
14
20
  } from "./diagnosis.mjs";
15
- import { workerOutputLogPath } from "./worker-output.mjs";
21
+ import { summarizeMergeFailures } from "./diagnosis-merge-failure.mjs";
22
+ import { inferWorkerDoneMissingFailure } from "./diagnosis-worker-done-missing.mjs";
23
+ import {
24
+ findStubMarkedSucceededTask,
25
+ inferStubExitReasonForTask,
26
+ } from "./diagnosis-stub.mjs";
27
+ import { workerOutputLogPath, workerOutputLogRef } from "./worker-output.mjs";
16
28
  import { detectOrphanRunning, journalEventsSinceResume } from "./orphan-detect.mjs";
17
29
  import { isPostMergeLimbo } from "./post-merge-limbo.mjs";
18
30
  import { computePendingTasks } from "./resume-multi.mjs";
31
+ import { computeStatusProgress } from "./status-json.mjs";
19
32
  import {
20
33
  detectBatchStateDrift,
21
34
  rebuildBatchStateFromJournal,
22
35
  } from "./journal-rebuild.mjs";
23
- import { extractJournalDiagnosisHints, journalPath, readJournalEvents } from "./journal.mjs";
36
+ import { appendJournalEvent, extractJournalDiagnosisHints, findPlanReviewNestedSpawnBlockedFailure, journalPath, readJournalEvents } from "./journal.mjs";
24
37
  import { findLatestSalvageInspection } from "./salvage.mjs";
25
38
  import { countCommitsAhead } from "./lane-commit.mjs";
39
+ import { isProcessAlive } from "../process/liveness.mjs";
26
40
  import {
27
41
  loadBatchStateFile,
28
42
  parseBatchState,
29
43
  resolveBatchStatePath,
30
44
  } from "./batch-state-io.mjs";
45
+ import {
46
+ clearBatchEnginePid,
47
+ readBatchEnginePid,
48
+ recomputeTaskCounters,
49
+ saveSpineBatchState,
50
+ updateSegmentForTask,
51
+ } from "./state.mjs";
31
52
 
32
53
  export { loadBatchStateFile, parseBatchState, resolveBatchStatePath } from "./batch-state-io.mjs";
33
54
 
@@ -41,7 +62,8 @@ const RUNNING_PHASES = new Set(["planning", "running", "executing", "merging"]);
41
62
  * @property {string|null} taskFolder
42
63
  * @property {boolean} doneFileFound
43
64
  * @property {string} classification
44
- * @property {boolean} [doneOnDisk]
65
+ * @property {boolean} doneOnMain
66
+ * @property {boolean} doneInLane
45
67
  */
46
68
 
47
69
  /**
@@ -72,7 +94,12 @@ const RUNNING_PHASES = new Set(["planning", "running", "executing", "merging"]);
72
94
  * @property {string|null} [batchId]
73
95
  * @property {string|null} [batchStatePath]
74
96
  * @property {string|null} [phase]
97
+ * @property {import("./macro-phase.mjs").MacroPhase} [macroPhase]
98
+ * @property {string} [macroPhaseLabel]
75
99
  * @property {object} [signals]
100
+ * @property {number} [pendingTasks]
101
+ * @property {number} [currentWaveIndex]
102
+ * @property {number} [waveCount]
76
103
  */
77
104
 
78
105
  /**
@@ -87,50 +114,20 @@ export function resolveTasksRoot(projectRoot, configResult) {
87
114
  return resolveTasksRootPath(projectRoot, loaded.config);
88
115
  }
89
116
 
90
- /**
91
- * @param {string} tasksRoot
92
- * @param {string} taskId
93
- * @param {string|null} taskFolder
94
- */
95
- function resolveTaskFolder(tasksRoot, taskId, taskFolder) {
96
- if (taskFolder) {
97
- const direct = path.join(tasksRoot, taskFolder);
98
- if (fs.existsSync(direct)) return direct;
99
- }
100
-
101
- if (!tasksRoot || !fs.existsSync(tasksRoot)) return null;
102
-
103
- const match = fs
104
- .readdirSync(tasksRoot, { withFileTypes: true })
105
- .filter((entry) => entry.isDirectory() && entry.name.startsWith(`${taskId}-`))
106
- .map((entry) => path.join(tasksRoot, entry.name))[0];
107
-
108
- return match ?? null;
109
- }
110
-
111
117
  /**
112
118
  * @param {NormalizedBatchState} batch
113
119
  * @param {string|null} tasksRoot
120
+ * @param {string} [projectRoot]
114
121
  */
115
- export function classifyTasks(batch, tasksRoot) {
116
- return batch.tasks.map((task) => {
117
- const folderPath =
118
- tasksRoot && task.taskId
119
- ? resolveTaskFolder(tasksRoot, task.taskId, task.taskFolder)
120
- : null;
121
- const doneOnDisk = folderPath ? fs.existsSync(path.join(folderPath, ".DONE")) : false;
122
-
123
- let classification = task.classification;
124
- if (doneOnDisk || task.doneFileFound) {
125
- classification = "terminal-success";
126
- }
127
-
128
- return {
129
- ...task,
130
- doneOnDisk,
131
- classification,
132
- };
133
- });
122
+ export function classifyTasks(batch, tasksRoot, projectRoot = "") {
123
+ return batch.tasks.map((task) =>
124
+ classifyTaskDoneSemantics(task, {
125
+ tasksRoot,
126
+ projectRoot,
127
+ batchId: batch.batchId,
128
+ lanes: batch.lanes,
129
+ }),
130
+ );
134
131
  }
135
132
 
136
133
  /**
@@ -321,8 +318,16 @@ function resolveFailedExitReason(rawTasks, failedTaskId) {
321
318
  * @returns {{ exitReason: string|null, launchFailureKind: string|null }}
322
319
  */
323
320
  function deriveFailureContext(failedTaskId, exitReason, signals) {
324
- const resolvedExitReason =
321
+ let resolvedExitReason =
325
322
  exitReason ?? resolveFailedExitReason(signals.raw?.tasks, failedTaskId);
323
+ if (failedTaskId && signals.tasksRoot) {
324
+ const taskFolder =
325
+ signals.tasks?.find((entry) => entry.taskId === failedTaskId)?.taskFolder ?? null;
326
+ const stubReason = inferStubExitReasonForTask(signals.tasksRoot, failedTaskId, taskFolder);
327
+ if (stubReason) {
328
+ resolvedExitReason = stubReason;
329
+ }
330
+ }
326
331
  const launchFailureKind = inferLaunchFailureKind({
327
332
  exitReason: resolvedExitReason,
328
333
  journalEvents: signals.journalEvents,
@@ -364,6 +369,53 @@ function enrichLaunchFailureFromWorkerOutput(projectRoot, batchId, failedTaskId,
364
369
  return inferLaunchFailureFromWorkerOutputTail(tail) ?? launchFailureKind;
365
370
  }
366
371
 
372
+ /**
373
+ * @param {string} projectRoot
374
+ * @param {string} batchId
375
+ * @param {string|null} failedTaskId
376
+ * @param {Array<{ taskId: string, laneNumber?: number|null }>} tasks
377
+ * @param {object|null} doneMissingHint
378
+ * @returns {{ workerOutputLogRef: string|null, workerOutputLogPath: string|null, workerOutputTail: string|null, workerOutputSnippet: string|null, changedFileCount: number|null }}
379
+ */
380
+ function enrichWorkerDoneMissingContext(
381
+ projectRoot,
382
+ batchId,
383
+ failedTaskId,
384
+ tasks,
385
+ doneMissingHint,
386
+ ) {
387
+ const task = tasks.find((entry) => entry.taskId === failedTaskId);
388
+ const laneNumber = task?.laneNumber;
389
+ const logRef =
390
+ doneMissingHint?.workerOutputLogRef ??
391
+ (failedTaskId && laneNumber != null
392
+ ? workerOutputLogRef(batchId, laneNumber, failedTaskId)
393
+ : null);
394
+ const logPath =
395
+ doneMissingHint?.workerOutputLogPath ??
396
+ (failedTaskId && laneNumber != null
397
+ ? workerOutputLogPath(projectRoot, batchId, laneNumber, failedTaskId)
398
+ : null);
399
+ const tailFromDisk = logPath ? readWorkerOutputLogTail(logPath) : null;
400
+ const outputText = [doneMissingHint?.output, tailFromDisk].filter(Boolean).join("\n");
401
+ const snippet = outputText
402
+ ? outputText
403
+ .split("\n")
404
+ .filter(Boolean)
405
+ .slice(-3)
406
+ .join(" | ")
407
+ : null;
408
+
409
+ return {
410
+ workerOutputLogRef: logRef,
411
+ workerOutputLogPath: logPath,
412
+ workerOutputTail: tailFromDisk,
413
+ workerOutputSnippet: snippet,
414
+ changedFileCount:
415
+ doneMissingHint?.changedFileCount != null ? doneMissingHint.changedFileCount : null,
416
+ };
417
+ }
418
+
367
419
  /**
368
420
  * @param {Array<{ taskId: string, classification: string, laneNumber?: number|null }>} tasks
369
421
  * @param {string|null} failedTaskId
@@ -382,6 +434,40 @@ function hasGhostRunningCluster(tasks, failedTaskId) {
382
434
  );
383
435
  }
384
436
 
437
+ /**
438
+ * @param {object[]} journalEvents
439
+ * @param {string|null} failedTaskId
440
+ * @returns {string[]}
441
+ */
442
+ function extractGitignoredPathsFromJournal(journalEvents, failedTaskId) {
443
+ if (!Array.isArray(journalEvents)) return [];
444
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
445
+ const event = journalEvents[index];
446
+ if (event.type !== "task.failed") continue;
447
+ const eventTaskId = event.taskId ?? event.payload?.taskId;
448
+ if (failedTaskId && eventTaskId && eventTaskId !== failedTaskId) continue;
449
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
450
+ if (Array.isArray(payload.gitignoredPaths)) {
451
+ return payload.gitignoredPaths.filter((entry) => typeof entry === "string");
452
+ }
453
+ }
454
+ return [];
455
+ }
456
+
457
+ /**
458
+ * @param {Record<string, unknown>|null|undefined} raw
459
+ * @param {string} batchId
460
+ * @param {string} taskId
461
+ * @returns {string|null}
462
+ */
463
+ function laneTaskBranchForDiagnosis(raw, batchId, taskId) {
464
+ const tasks = raw?.tasks;
465
+ if (!Array.isArray(tasks)) return null;
466
+ const task = tasks.find((entry) => entry?.taskId === taskId);
467
+ if (!task || task.laneNumber == null) return null;
468
+ return `task/spine-lane-${task.laneNumber}-${batchId}`;
469
+ }
470
+
385
471
  /**
386
472
  * @param {string} diagnosis
387
473
  * @param {string|null} failedTaskId
@@ -398,6 +484,22 @@ function withFailureContext(diagnosis, failedTaskId, signals, exitReason = null)
398
484
  };
399
485
  }
400
486
 
487
+ /**
488
+ * @param {object[]} journalEvents
489
+ * @param {Record<string, unknown>|null|undefined} raw
490
+ * @param {string|null} taskId
491
+ */
492
+ function journalIndicatesResumeRulesStall(journalEvents, raw, taskId) {
493
+ const scoped = journalEventsSinceResume(journalEvents, raw);
494
+ const hasRulesSelected = scoped.some((event) => {
495
+ if (event.type !== "worker.rules_selected") return false;
496
+ const eventTaskId = event.taskId ?? event.payload?.taskId;
497
+ return !taskId || !eventTaskId || eventTaskId === taskId;
498
+ });
499
+ const hasBatchResumed = scoped.some((event) => event.type === "batch.resumed");
500
+ return hasRulesSelected && hasBatchResumed;
501
+ }
502
+
401
503
  /**
402
504
  * @param {object} signals
403
505
  */
@@ -441,6 +543,16 @@ export function deriveDiagnosis(signals) {
441
543
 
442
544
  if (orphanRunning) {
443
545
  if (orphanRunning.kind === "lane" && orphanRunning.taskId) {
546
+ const enginePid = readBatchEnginePid(signals.raw);
547
+ const engineDead = enginePid == null || !isProcessAlive(enginePid);
548
+ const resumeRulesStall = journalIndicatesResumeRulesStall(
549
+ signals.journalEvents ?? [],
550
+ signals.raw,
551
+ orphanRunning.taskId,
552
+ );
553
+ if (engineDead && resumeRulesStall) {
554
+ return withFailureContext("engine_orphaned", orphanRunning.taskId, signals);
555
+ }
444
556
  return withFailureContext("worker_orphaned", orphanRunning.taskId, signals);
445
557
  }
446
558
  return withFailureContext("engine_orphaned", orphanRunning.taskId ?? null, signals);
@@ -490,6 +602,13 @@ export function deriveDiagnosis(signals) {
490
602
  "needs_replan",
491
603
  );
492
604
  }
605
+ const doneMissing = inferWorkerDoneMissingFailure({
606
+ journalEvents: signals.journalEvents,
607
+ failedTaskId,
608
+ });
609
+ if (doneMissing) {
610
+ return withFailureContext("worker_done_missing", failedTaskId, signals);
611
+ }
493
612
  return withFailureContext("needs_retry", failedTaskId, signals);
494
613
  }
495
614
 
@@ -510,6 +629,19 @@ export function deriveDiagnosis(signals) {
510
629
  return withFailureContext("needs_integrate", null, signals);
511
630
  }
512
631
 
632
+ if (phase === "merge_blocked") {
633
+ return withFailureContext("failed", null, signals);
634
+ }
635
+
636
+ if (
637
+ phase === "merging" &&
638
+ endedAt != null &&
639
+ Array.isArray(signals.raw?.mergeResults) &&
640
+ signals.raw.mergeResults.some((entry) => String(entry?.status ?? "").toLowerCase() === "failed")
641
+ ) {
642
+ return withFailureContext("failed", null, signals);
643
+ }
644
+
513
645
  if (phase === "merging" || (allTasksTerminalSuccess && mergeResultsEmpty && git.orchBranchExists && !git.orchMergedToBase)) {
514
646
  if (allTasksTerminalSuccess && git.orchBranchExists && !git.orchMergedToBase && !mergeResultsEmpty) {
515
647
  return withFailureContext("needs_integrate", null, signals);
@@ -521,6 +653,15 @@ export function deriveDiagnosis(signals) {
521
653
  return withFailureContext("needs_integrate", null, signals);
522
654
  }
523
655
 
656
+ if (
657
+ phase === "failed" &&
658
+ !hasFailedTasks &&
659
+ !hasSegmentDrift &&
660
+ hasPendingTasks
661
+ ) {
662
+ return withFailureContext("needs_retry", null, signals);
663
+ }
664
+
524
665
  if (phase === "failed" || (failedTasks > 0 && !hasPendingTasks && !hasRunningTasks)) {
525
666
  return withFailureContext("failed", failedTaskId, signals);
526
667
  }
@@ -562,7 +703,9 @@ export function reconcileBatch(ctx) {
562
703
  batchId: null,
563
704
  batchStatePath: null,
564
705
  phase: null,
565
- signals: { idle: true },
706
+ macroPhase: "idle",
707
+ macroPhaseLabel: macroPhaseLabel("idle"),
708
+ signals: { idle: true, macroPhase: "idle" },
566
709
  };
567
710
  }
568
711
 
@@ -575,7 +718,9 @@ export function reconcileBatch(ctx) {
575
718
  batchId: null,
576
719
  batchStatePath: loaded.path,
577
720
  phase: null,
578
- signals: { parseError: loaded.parseError },
721
+ macroPhase: "failed",
722
+ macroPhaseLabel: macroPhaseLabel("failed"),
723
+ signals: { parseError: loaded.parseError, macroPhase: "failed" },
579
724
  };
580
725
  }
581
726
 
@@ -588,12 +733,14 @@ export function reconcileBatch(ctx) {
588
733
  batchId: null,
589
734
  batchStatePath: loaded.path,
590
735
  phase: null,
591
- signals: { unreadable: true },
736
+ macroPhase: "failed",
737
+ macroPhaseLabel: macroPhaseLabel("failed"),
738
+ signals: { unreadable: true, macroPhase: "failed" },
592
739
  };
593
740
  }
594
741
 
595
742
  const tasksRoot = resolveTasksRoot(projectRoot);
596
- const classifiedTasks = classifyTasks(batch, tasksRoot);
743
+ const classifiedTasks = classifyTasks(batch, tasksRoot, projectRoot);
597
744
  const git = inspectGitState({
598
745
  projectRoot,
599
746
  batchId: batch.batchId,
@@ -631,6 +778,7 @@ export function reconcileBatch(ctx) {
631
778
  mergeResultsEmpty: batch.mergeResults.length === 0,
632
779
  git,
633
780
  tasks: classifiedTasks,
781
+ tasksRoot,
634
782
  segments: batch.segments,
635
783
  lanes: batch.lanes,
636
784
  raw: batch.raw,
@@ -666,7 +814,36 @@ export function reconcileBatch(ctx) {
666
814
  const pendingTaskCount = computePendingTasks(batch.raw ?? {}).length;
667
815
  signals.pendingTaskCount = pendingTaskCount;
668
816
 
669
- const { diagnosis, failedTaskId, exitReason, launchFailureKind } = deriveDiagnosis(signals);
817
+ let { diagnosis, failedTaskId, exitReason, launchFailureKind } = deriveDiagnosis(signals);
818
+ const stubSucceededTaskId = findStubMarkedSucceededTask(tasksRoot, classifiedTasks);
819
+ if (
820
+ stubSucceededTaskId &&
821
+ (diagnosis === "completed" ||
822
+ diagnosis === "needs_integrate" ||
823
+ diagnosis === "limbo_stale" ||
824
+ diagnosis === "completed_manual")
825
+ ) {
826
+ diagnosis = "needs_retry";
827
+ failedTaskId = stubSucceededTaskId;
828
+ exitReason = "stub";
829
+ }
830
+ const doneMissingHint =
831
+ diagnosis === "worker_done_missing"
832
+ ? inferWorkerDoneMissingFailure({
833
+ journalEvents,
834
+ failedTaskId,
835
+ })
836
+ : null;
837
+ const doneMissingContext =
838
+ diagnosis === "worker_done_missing"
839
+ ? enrichWorkerDoneMissingContext(
840
+ projectRoot,
841
+ batch.batchId,
842
+ failedTaskId,
843
+ classifiedTasks,
844
+ doneMissingHint,
845
+ )
846
+ : null;
670
847
  const resolvedLaunchFailureKind =
671
848
  diagnosis === "worker_orphaned"
672
849
  ? enrichLaunchFailureFromWorkerOutput(
@@ -688,6 +865,52 @@ export function reconcileBatch(ctx) {
688
865
  ? `spine batch retry ${signals.orphanRunning.taskId}`
689
866
  : null;
690
867
 
868
+ const gateRecord = batch.batchId ? loadGateRecord(projectRoot, batch.batchId) : null;
869
+ const integrateGateOpen = signals.postMergeLimbo === true && Boolean(gateRecord);
870
+
871
+ const macroPhase = deriveMacroPhase({
872
+ diagnosis,
873
+ batchPhase: batch.phase,
874
+ gateRecord,
875
+ postMergeLimbo: signals.postMergeLimbo === true,
876
+ journalEvents,
877
+ mergeResults: batch.mergeResults,
878
+ });
879
+ const resolvedMacroPhaseLabel = macroPhaseLabel(macroPhase);
880
+ if (ctx.verbose) {
881
+ signals.macroPhase = macroPhase;
882
+ }
883
+
884
+ const stalePathCheck = buildStalePathDoctorCheck({
885
+ packageRoot: PACKAGE_ROOT,
886
+ runningSpinePath: path.join(PACKAGE_ROOT, "bin", "spine.mjs"),
887
+ });
888
+ const stalePathSpine = stalePathCheck.warning === true;
889
+ const planReviewNestedSpawnBlocked =
890
+ diagnosis === "worker_orphaned" &&
891
+ findPlanReviewNestedSpawnBlockedFailure(journalEvents, failedTaskId);
892
+
893
+ const mergeGitignoredFailure = inferMergeGitignoredFailure({
894
+ exitReason,
895
+ failureClass: batch.raw?.mergeResults?.find((entry) => entry?.failureClass)?.failureClass ?? null,
896
+ lastError: batch.raw?.lastError ?? null,
897
+ journalEvents,
898
+ });
899
+ const mergeFailureSummary = summarizeMergeFailures(
900
+ batch.mergeResults,
901
+ batch.raw?.lastError ?? null,
902
+ );
903
+ signals.mergeFailed = mergeFailureSummary.mergeFailed;
904
+ signals.failedMerges = mergeFailureSummary.failedMerges;
905
+ signals.failedWaveIndex = mergeFailureSummary.failedWaveIndex;
906
+ signals.failedLane = mergeFailureSummary.failedLane;
907
+ signals.lastError = mergeFailureSummary.lastError;
908
+ const gitignoredPaths = extractGitignoredPathsFromJournal(journalEvents, failedTaskId);
909
+ const taskBranch =
910
+ failedTaskId != null
911
+ ? laneTaskBranchForDiagnosis(batch.raw, batch.batchId, failedTaskId)
912
+ : null;
913
+
691
914
  const output = buildDiagnosisOutput(diagnosis, {
692
915
  batchId: batch.batchId,
693
916
  phase: batch.phase,
@@ -701,6 +924,19 @@ export function reconcileBatch(ctx) {
701
924
  salvageRetryCommand,
702
925
  ghostRunningCluster,
703
926
  postMergeLimbo: signals.postMergeLimbo === true,
927
+ integrateGateOpen,
928
+ stalePathSpine,
929
+ planReviewNestedSpawnBlocked,
930
+ mergeGitignoredFailure,
931
+ mergeFailed: mergeFailureSummary.mergeFailed,
932
+ failedWaveIndex: mergeFailureSummary.failedWaveIndex,
933
+ failedLane: mergeFailureSummary.failedLane,
934
+ lastError: mergeFailureSummary.lastError,
935
+ succeededTasks: batch.succeededTasks,
936
+ totalTasks: batch.totalTasks,
937
+ taskBranch,
938
+ gitignoredPaths,
939
+ ...(doneMissingContext ?? {}),
704
940
  });
705
941
 
706
942
  if (diagnosis === "git_unavailable") {
@@ -709,11 +945,31 @@ export function reconcileBatch(ctx) {
709
945
  output.alternatives = ["spine status --diagnose"];
710
946
  }
711
947
 
948
+ const progress = computeStatusProgress({
949
+ batchRaw: batch.raw,
950
+ succeededTasks: batch.succeededTasks,
951
+ totalTasks: batch.totalTasks,
952
+ pendingTasks: pendingTaskCount,
953
+ });
954
+
712
955
  return {
713
956
  ...output,
714
957
  batchId: batch.batchId,
715
958
  batchStatePath: loaded.path ?? ctx.batchStatePath ?? null,
716
959
  phase: batch.phase,
960
+ macroPhase,
961
+ macroPhaseLabel: resolvedMacroPhaseLabel,
962
+ failedTasks: signals.failedTasks,
963
+ succeededTasks: batch.succeededTasks,
964
+ totalTasks: batch.totalTasks,
965
+ pendingTasks: progress?.pendingTasks,
966
+ currentWaveIndex: progress?.currentWaveIndex,
967
+ waveCount: progress?.waveCount,
968
+ mergeFailed: mergeFailureSummary.mergeFailed,
969
+ failedMerges: mergeFailureSummary.failedMerges,
970
+ failedWaveIndex: mergeFailureSummary.failedWaveIndex,
971
+ failedLane: mergeFailureSummary.failedLane,
972
+ lastError: mergeFailureSummary.lastError,
717
973
  signals: ctx.verbose ? signals : undefined,
718
974
  };
719
975
  }
@@ -727,3 +983,170 @@ export function reconcileBatch(ctx) {
727
983
  export function runReconciliationCheck(ctx) {
728
984
  return reconcileBatch(ctx);
729
985
  }
986
+
987
+ /**
988
+ * @param {unknown[]} lanes
989
+ * @param {number|null|undefined} laneNumber
990
+ */
991
+ function findLaneForOrphanReconcile(lanes, laneNumber) {
992
+ if (!Array.isArray(lanes)) return null;
993
+ if (laneNumber != null) {
994
+ const match = lanes.find((lane) => Number(lane?.laneNumber) === Number(laneNumber));
995
+ if (match) return match;
996
+ }
997
+ return lanes[0] ?? null;
998
+ }
999
+
1000
+ /**
1001
+ * Classify tasks for orphan reconcile (status-only, mirrors resume validation).
1002
+ *
1003
+ * @param {object[]} tasks
1004
+ */
1005
+ function classifyTasksForOrphanReconcile(tasks) {
1006
+ return (tasks ?? []).map((task) => {
1007
+ const status = String(task?.status ?? "").toLowerCase();
1008
+ return {
1009
+ taskId: task.taskId,
1010
+ laneNumber: task.laneNumber,
1011
+ classification: status === "running" ? "running" : status,
1012
+ };
1013
+ });
1014
+ }
1015
+
1016
+ /**
1017
+ * @param {object[]} journalEvents
1018
+ * @param {string} taskId
1019
+ * @param {string} eventType
1020
+ */
1021
+ function journalHasTaskEvent(journalEvents, taskId, eventType) {
1022
+ return journalEvents.some((event) => {
1023
+ if (String(event?.type ?? "") !== eventType) return false;
1024
+ const eventTaskId = event.taskId ?? event.payload?.taskId;
1025
+ return eventTaskId === taskId;
1026
+ });
1027
+ }
1028
+
1029
+ /**
1030
+ * Transition orphan running tasks to failed so retry/resume paths succeed (SP-315 / #20).
1031
+ *
1032
+ * @param {object} params
1033
+ * @param {string} params.projectRoot
1034
+ * @param {object} params.state
1035
+ * @returns {{ reconciled: boolean, taskId?: string|null, kind?: string, exitReason?: string }}
1036
+ */
1037
+ export function reconcileOrphanRunningState({ projectRoot, state }) {
1038
+ if (!state || typeof state !== "object") {
1039
+ return { reconciled: false };
1040
+ }
1041
+
1042
+ const batchId = String(state.batchId ?? "");
1043
+ if (!batchId) {
1044
+ return { reconciled: false };
1045
+ }
1046
+
1047
+ const classifiedTasks = classifyTasksForOrphanReconcile(state.tasks);
1048
+ const hasRunningTasks = classifiedTasks.some((task) => task.classification === "running");
1049
+ const journalEvents = readJournalEvents(projectRoot, batchId);
1050
+ const scopedJournalEvents = journalEventsSinceResume(journalEvents, state);
1051
+ const orphanRunning = detectOrphanRunning({
1052
+ phase: String(state.phase ?? ""),
1053
+ hasRunningTasks,
1054
+ tasks: classifiedTasks,
1055
+ lanes: state.lanes ?? [],
1056
+ raw: state,
1057
+ journalEvents: scopedJournalEvents,
1058
+ });
1059
+
1060
+ if (!orphanRunning) {
1061
+ return { reconciled: false };
1062
+ }
1063
+
1064
+ const exitReason = orphanRunning.kind === "engine" ? "engine_orphaned" : "worker_orphaned";
1065
+ /** @type {string[]} */
1066
+ const taskIdsToFail =
1067
+ orphanRunning.kind === "lane" && orphanRunning.taskId
1068
+ ? [orphanRunning.taskId]
1069
+ : classifiedTasks
1070
+ .filter((task) => task.classification === "running")
1071
+ .map((task) => task.taskId)
1072
+ .filter(Boolean);
1073
+
1074
+ if (taskIdsToFail.length === 0) {
1075
+ return { reconciled: false };
1076
+ }
1077
+
1078
+ const now = Date.now();
1079
+ let changed = false;
1080
+
1081
+ for (const taskId of taskIdsToFail) {
1082
+ const task = (state.tasks ?? []).find((entry) => entry?.taskId === taskId);
1083
+ if (!task || task.status !== "running") continue;
1084
+
1085
+ task.status = "failed";
1086
+ task.endedAt = now;
1087
+ task.exitReason = exitReason;
1088
+ updateSegmentForTask(state, taskId, "failed");
1089
+ changed = true;
1090
+
1091
+ if (!journalHasTaskEvent(scopedJournalEvents, taskId, "task.failed")) {
1092
+ const lane = findLaneForOrphanReconcile(state.lanes, task.laneNumber);
1093
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
1094
+ taskId,
1095
+ laneNumber: task.laneNumber ?? null,
1096
+ laneId: lane?.laneId ?? null,
1097
+ reason: exitReason,
1098
+ reconciled: true,
1099
+ });
1100
+ }
1101
+
1102
+ if (
1103
+ orphanRunning.kind === "lane" &&
1104
+ !journalHasTaskEvent(scopedJournalEvents, taskId, "lane.died")
1105
+ ) {
1106
+ const lane = findLaneForOrphanReconcile(state.lanes, task.laneNumber);
1107
+ appendJournalEvent(projectRoot, batchId, "lane.died", {
1108
+ taskId,
1109
+ laneNumber: task.laneNumber ?? null,
1110
+ laneId: lane?.laneId ?? null,
1111
+ reason: exitReason,
1112
+ reconciled: true,
1113
+ });
1114
+ }
1115
+ }
1116
+
1117
+ for (const lane of state.lanes ?? []) {
1118
+ if (!lane || typeof lane !== "object") continue;
1119
+ const workerPid = Number(/** @type {{ workerPid?: number }} */ (lane).workerPid);
1120
+ if (Number.isFinite(workerPid) && workerPid > 0 && !isProcessAlive(workerPid)) {
1121
+ delete lane.workerPid;
1122
+ changed = true;
1123
+ }
1124
+ }
1125
+
1126
+ const enginePid = readBatchEnginePid(state);
1127
+ if (enginePid != null && !isProcessAlive(enginePid)) {
1128
+ clearBatchEnginePid(state);
1129
+ changed = true;
1130
+ }
1131
+
1132
+ if (!changed) {
1133
+ return { reconciled: false };
1134
+ }
1135
+
1136
+ recomputeTaskCounters(state);
1137
+ if (String(state.phase ?? "") === "running") {
1138
+ state.phase = "failed";
1139
+ state.endedAt = state.endedAt ?? now;
1140
+ state.lastError =
1141
+ state.lastError ?? `Orphan reconcile: ${exitReason} (task ${taskIdsToFail.join(", ")})`;
1142
+ }
1143
+
1144
+ saveSpineBatchState(projectRoot, state);
1145
+
1146
+ return {
1147
+ reconciled: true,
1148
+ taskId: orphanRunning.taskId ?? taskIdsToFail[0] ?? null,
1149
+ kind: orphanRunning.kind,
1150
+ exitReason,
1151
+ };
1152
+ }