pi-spine 1.1.0 → 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 (102) hide show
  1. package/bin/spine-batch.mjs +160 -53
  2. package/bin/spine-cli/batch.mjs +3 -3
  3. package/bin/spine-cli/lane-logs.mjs +24 -0
  4. package/bin/spine-cli/scenarios.mjs +298 -0
  5. package/bin/spine-cli/wait.mjs +30 -0
  6. package/bin/spine-cli/watch.mjs +27 -0
  7. package/bin/spine-issue.mjs +196 -0
  8. package/bin/spine-journal.mjs +1 -0
  9. package/bin/spine-run.mjs +30 -0
  10. package/bin/spine-status.mjs +19 -1
  11. package/bin/spine-tasks.mjs +16 -2
  12. package/bin/spine-worker-runner.mjs +10 -10
  13. package/bin/spine.mjs +49 -1
  14. package/package.json +1 -1
  15. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  16. package/src/batch/abort.mjs +2 -11
  17. package/src/batch/agent-session-worker.mjs +45 -5
  18. package/src/batch/attached-engine-handoff.mjs +188 -0
  19. package/src/batch/attached-runner.mjs +312 -0
  20. package/src/batch/contract-prelanded.mjs +180 -0
  21. package/src/batch/contract-verify.mjs +140 -2
  22. package/src/batch/detached-start.mjs +66 -2
  23. package/src/batch/diagnosis-alternatives.mjs +46 -0
  24. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  25. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  26. package/src/batch/diagnosis-stub.mjs +109 -0
  27. package/src/batch/diagnosis-task-done.mjs +110 -0
  28. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  29. package/src/batch/diagnosis.mjs +135 -68
  30. package/src/batch/engine-lanes/merge.mjs +110 -82
  31. package/src/batch/engine-lanes/queue.mjs +4 -1
  32. package/src/batch/engine-lanes/watch.mjs +29 -0
  33. package/src/batch/engine-lanes.mjs +1 -0
  34. package/src/batch/engine-scope.mjs +11 -1
  35. package/src/batch/engine.mjs +79 -24
  36. package/src/batch/evidence.mjs +78 -15
  37. package/src/batch/gate.mjs +43 -14
  38. package/src/batch/git-helpers.mjs +96 -0
  39. package/src/batch/heartbeat.mjs +73 -7
  40. package/src/batch/integrate.mjs +2 -4
  41. package/src/batch/journal.mjs +3 -0
  42. package/src/batch/lane-commit.mjs +90 -5
  43. package/src/batch/lifecycle.mjs +130 -3
  44. package/src/batch/macro-phase.mjs +226 -0
  45. package/src/batch/merge/adoption-doc-merge.mjs +93 -10
  46. package/src/batch/merge/wave-merge-state.mjs +3 -0
  47. package/src/batch/metrics.mjs +74 -5
  48. package/src/batch/orphan-detect.mjs +74 -0
  49. package/src/batch/pause.mjs +223 -0
  50. package/src/batch/post-merge-limbo.mjs +264 -8
  51. package/src/batch/reconcile.mjs +429 -54
  52. package/src/batch/resume-common.mjs +5 -1
  53. package/src/batch/resume-lane-reviews.mjs +16 -0
  54. package/src/batch/resume-multi-lanes.mjs +56 -1
  55. package/src/batch/resume-multi-validate.mjs +67 -6
  56. package/src/batch/resume-multi.mjs +9 -4
  57. package/src/batch/resume.mjs +52 -45
  58. package/src/batch/retry.mjs +56 -5
  59. package/src/batch/review-spawn.mjs +8 -2
  60. package/src/batch/rules-manifest-drift.mjs +157 -0
  61. package/src/batch/salvage.mjs +2 -1
  62. package/src/batch/sequence.mjs +454 -0
  63. package/src/batch/state.mjs +18 -3
  64. package/src/batch/status-json.mjs +67 -0
  65. package/src/batch/task-stall-budget.mjs +22 -10
  66. package/src/batch/worker-host.mjs +95 -7
  67. package/src/batch/worker-output.mjs +196 -3
  68. package/src/cli/issue-draft.mjs +180 -0
  69. package/src/cli/journal-follow.mjs +239 -0
  70. package/src/cli/lane-logs.mjs +291 -0
  71. package/src/cli/sequence.mjs +108 -0
  72. package/src/cli/settings-set.mjs +2 -21
  73. package/src/cli/wait.mjs +187 -0
  74. package/src/cli/watch.mjs +160 -0
  75. package/src/config/agent-model-resolve.mjs +48 -0
  76. package/src/config/cursor-rules/discover.mjs +3 -21
  77. package/src/config/defaults.mjs +7 -1
  78. package/src/config/settings-fields.mjs +48 -0
  79. package/src/config/spine-init-constants.mjs +1 -0
  80. package/src/config/spine-preflight-lib.mjs +471 -16
  81. package/src/dashboard/lane-throughput.mjs +351 -0
  82. package/src/dashboard/public/dashboard.css +25 -1
  83. package/src/dashboard/public/dashboard.js +223 -18
  84. package/src/dashboard/public/index.html +14 -2
  85. package/src/dashboard/server.mjs +4 -0
  86. package/src/dashboard/snapshot.mjs +215 -1
  87. package/src/dashboard/view.mjs +170 -17
  88. package/src/doctor/agent-model-inherit.mjs +61 -6
  89. package/src/doctor/run-doctor-checks.mjs +26 -1
  90. package/src/doctor/sequence-safety.mjs +57 -0
  91. package/src/doctor/stale-worktrees.mjs +102 -0
  92. package/src/fixtures/scenario-registry.mjs +194 -0
  93. package/src/fs/atomic-write.mjs +49 -0
  94. package/src/planner/file-scope.mjs +246 -0
  95. package/src/planner/format-plan.mjs +9 -7
  96. package/src/planner/index.mjs +6 -2
  97. package/src/planner/wave-scope.mjs +136 -0
  98. package/src/planner/waves.mjs +133 -0
  99. package/src/tasks/packet/index.mjs +1 -0
  100. package/src/tasks/packet/parse-prompt.mjs +42 -1
  101. package/src/tasks/packet/validate-prompt.mjs +124 -0
  102. package/templates/spine-config.json +8 -1
@@ -10,20 +10,30 @@ import { PACKAGE_ROOT } from "../config/spine-init-constants.mjs";
10
10
  import { resolveTasksRootPath } from "../config/env-overrides.mjs";
11
11
  import { buildStalePathDoctorCheck } from "../doctor/stale-path.mjs";
12
12
  import { loadGateRecord } from "./gate.mjs";
13
+ import { deriveMacroPhase, macroPhaseLabel } from "./macro-phase.mjs";
13
14
  import {
14
15
  buildDiagnosisOutput,
16
+ classifyTaskDoneSemantics,
15
17
  inferLaunchFailureFromWorkerOutputTail,
16
18
  inferLaunchFailureKind,
19
+ inferMergeGitignoredFailure,
17
20
  } from "./diagnosis.mjs";
18
- 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";
19
28
  import { detectOrphanRunning, journalEventsSinceResume } from "./orphan-detect.mjs";
20
29
  import { isPostMergeLimbo } from "./post-merge-limbo.mjs";
21
30
  import { computePendingTasks } from "./resume-multi.mjs";
31
+ import { computeStatusProgress } from "./status-json.mjs";
22
32
  import {
23
33
  detectBatchStateDrift,
24
34
  rebuildBatchStateFromJournal,
25
35
  } from "./journal-rebuild.mjs";
26
- import { extractJournalDiagnosisHints, findPlanReviewNestedSpawnBlockedFailure, journalPath, readJournalEvents } from "./journal.mjs";
36
+ import { appendJournalEvent, extractJournalDiagnosisHints, findPlanReviewNestedSpawnBlockedFailure, journalPath, readJournalEvents } from "./journal.mjs";
27
37
  import { findLatestSalvageInspection } from "./salvage.mjs";
28
38
  import { countCommitsAhead } from "./lane-commit.mjs";
29
39
  import { isProcessAlive } from "../process/liveness.mjs";
@@ -32,7 +42,13 @@ import {
32
42
  parseBatchState,
33
43
  resolveBatchStatePath,
34
44
  } from "./batch-state-io.mjs";
35
- import { readBatchEnginePid } from "./state.mjs";
45
+ import {
46
+ clearBatchEnginePid,
47
+ readBatchEnginePid,
48
+ recomputeTaskCounters,
49
+ saveSpineBatchState,
50
+ updateSegmentForTask,
51
+ } from "./state.mjs";
36
52
 
37
53
  export { loadBatchStateFile, parseBatchState, resolveBatchStatePath } from "./batch-state-io.mjs";
38
54
 
@@ -46,7 +62,8 @@ const RUNNING_PHASES = new Set(["planning", "running", "executing", "merging"]);
46
62
  * @property {string|null} taskFolder
47
63
  * @property {boolean} doneFileFound
48
64
  * @property {string} classification
49
- * @property {boolean} [doneOnDisk]
65
+ * @property {boolean} doneOnMain
66
+ * @property {boolean} doneInLane
50
67
  */
51
68
 
52
69
  /**
@@ -77,7 +94,12 @@ const RUNNING_PHASES = new Set(["planning", "running", "executing", "merging"]);
77
94
  * @property {string|null} [batchId]
78
95
  * @property {string|null} [batchStatePath]
79
96
  * @property {string|null} [phase]
97
+ * @property {import("./macro-phase.mjs").MacroPhase} [macroPhase]
98
+ * @property {string} [macroPhaseLabel]
80
99
  * @property {object} [signals]
100
+ * @property {number} [pendingTasks]
101
+ * @property {number} [currentWaveIndex]
102
+ * @property {number} [waveCount]
81
103
  */
82
104
 
83
105
  /**
@@ -92,50 +114,20 @@ export function resolveTasksRoot(projectRoot, configResult) {
92
114
  return resolveTasksRootPath(projectRoot, loaded.config);
93
115
  }
94
116
 
95
- /**
96
- * @param {string} tasksRoot
97
- * @param {string} taskId
98
- * @param {string|null} taskFolder
99
- */
100
- function resolveTaskFolder(tasksRoot, taskId, taskFolder) {
101
- if (taskFolder) {
102
- const direct = path.join(tasksRoot, taskFolder);
103
- if (fs.existsSync(direct)) return direct;
104
- }
105
-
106
- if (!tasksRoot || !fs.existsSync(tasksRoot)) return null;
107
-
108
- const match = fs
109
- .readdirSync(tasksRoot, { withFileTypes: true })
110
- .filter((entry) => entry.isDirectory() && entry.name.startsWith(`${taskId}-`))
111
- .map((entry) => path.join(tasksRoot, entry.name))[0];
112
-
113
- return match ?? null;
114
- }
115
-
116
117
  /**
117
118
  * @param {NormalizedBatchState} batch
118
119
  * @param {string|null} tasksRoot
120
+ * @param {string} [projectRoot]
119
121
  */
120
- export function classifyTasks(batch, tasksRoot) {
121
- return batch.tasks.map((task) => {
122
- const folderPath =
123
- tasksRoot && task.taskId
124
- ? resolveTaskFolder(tasksRoot, task.taskId, task.taskFolder)
125
- : null;
126
- const doneOnDisk = folderPath ? fs.existsSync(path.join(folderPath, ".DONE")) : false;
127
-
128
- let classification = task.classification;
129
- if (doneOnDisk || task.doneFileFound) {
130
- classification = "terminal-success";
131
- }
132
-
133
- return {
134
- ...task,
135
- doneOnDisk,
136
- classification,
137
- };
138
- });
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
+ );
139
131
  }
140
132
 
141
133
  /**
@@ -326,8 +318,16 @@ function resolveFailedExitReason(rawTasks, failedTaskId) {
326
318
  * @returns {{ exitReason: string|null, launchFailureKind: string|null }}
327
319
  */
328
320
  function deriveFailureContext(failedTaskId, exitReason, signals) {
329
- const resolvedExitReason =
321
+ let resolvedExitReason =
330
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
+ }
331
331
  const launchFailureKind = inferLaunchFailureKind({
332
332
  exitReason: resolvedExitReason,
333
333
  journalEvents: signals.journalEvents,
@@ -369,6 +369,53 @@ function enrichLaunchFailureFromWorkerOutput(projectRoot, batchId, failedTaskId,
369
369
  return inferLaunchFailureFromWorkerOutputTail(tail) ?? launchFailureKind;
370
370
  }
371
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
+
372
419
  /**
373
420
  * @param {Array<{ taskId: string, classification: string, laneNumber?: number|null }>} tasks
374
421
  * @param {string|null} failedTaskId
@@ -387,6 +434,40 @@ function hasGhostRunningCluster(tasks, failedTaskId) {
387
434
  );
388
435
  }
389
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
+
390
471
  /**
391
472
  * @param {string} diagnosis
392
473
  * @param {string|null} failedTaskId
@@ -521,6 +602,13 @@ export function deriveDiagnosis(signals) {
521
602
  "needs_replan",
522
603
  );
523
604
  }
605
+ const doneMissing = inferWorkerDoneMissingFailure({
606
+ journalEvents: signals.journalEvents,
607
+ failedTaskId,
608
+ });
609
+ if (doneMissing) {
610
+ return withFailureContext("worker_done_missing", failedTaskId, signals);
611
+ }
524
612
  return withFailureContext("needs_retry", failedTaskId, signals);
525
613
  }
526
614
 
@@ -541,6 +629,19 @@ export function deriveDiagnosis(signals) {
541
629
  return withFailureContext("needs_integrate", null, signals);
542
630
  }
543
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
+
544
645
  if (phase === "merging" || (allTasksTerminalSuccess && mergeResultsEmpty && git.orchBranchExists && !git.orchMergedToBase)) {
545
646
  if (allTasksTerminalSuccess && git.orchBranchExists && !git.orchMergedToBase && !mergeResultsEmpty) {
546
647
  return withFailureContext("needs_integrate", null, signals);
@@ -552,6 +653,15 @@ export function deriveDiagnosis(signals) {
552
653
  return withFailureContext("needs_integrate", null, signals);
553
654
  }
554
655
 
656
+ if (
657
+ phase === "failed" &&
658
+ !hasFailedTasks &&
659
+ !hasSegmentDrift &&
660
+ hasPendingTasks
661
+ ) {
662
+ return withFailureContext("needs_retry", null, signals);
663
+ }
664
+
555
665
  if (phase === "failed" || (failedTasks > 0 && !hasPendingTasks && !hasRunningTasks)) {
556
666
  return withFailureContext("failed", failedTaskId, signals);
557
667
  }
@@ -593,7 +703,9 @@ export function reconcileBatch(ctx) {
593
703
  batchId: null,
594
704
  batchStatePath: null,
595
705
  phase: null,
596
- signals: { idle: true },
706
+ macroPhase: "idle",
707
+ macroPhaseLabel: macroPhaseLabel("idle"),
708
+ signals: { idle: true, macroPhase: "idle" },
597
709
  };
598
710
  }
599
711
 
@@ -606,7 +718,9 @@ export function reconcileBatch(ctx) {
606
718
  batchId: null,
607
719
  batchStatePath: loaded.path,
608
720
  phase: null,
609
- signals: { parseError: loaded.parseError },
721
+ macroPhase: "failed",
722
+ macroPhaseLabel: macroPhaseLabel("failed"),
723
+ signals: { parseError: loaded.parseError, macroPhase: "failed" },
610
724
  };
611
725
  }
612
726
 
@@ -619,12 +733,14 @@ export function reconcileBatch(ctx) {
619
733
  batchId: null,
620
734
  batchStatePath: loaded.path,
621
735
  phase: null,
622
- signals: { unreadable: true },
736
+ macroPhase: "failed",
737
+ macroPhaseLabel: macroPhaseLabel("failed"),
738
+ signals: { unreadable: true, macroPhase: "failed" },
623
739
  };
624
740
  }
625
741
 
626
742
  const tasksRoot = resolveTasksRoot(projectRoot);
627
- const classifiedTasks = classifyTasks(batch, tasksRoot);
743
+ const classifiedTasks = classifyTasks(batch, tasksRoot, projectRoot);
628
744
  const git = inspectGitState({
629
745
  projectRoot,
630
746
  batchId: batch.batchId,
@@ -662,6 +778,7 @@ export function reconcileBatch(ctx) {
662
778
  mergeResultsEmpty: batch.mergeResults.length === 0,
663
779
  git,
664
780
  tasks: classifiedTasks,
781
+ tasksRoot,
665
782
  segments: batch.segments,
666
783
  lanes: batch.lanes,
667
784
  raw: batch.raw,
@@ -697,7 +814,36 @@ export function reconcileBatch(ctx) {
697
814
  const pendingTaskCount = computePendingTasks(batch.raw ?? {}).length;
698
815
  signals.pendingTaskCount = pendingTaskCount;
699
816
 
700
- 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;
701
847
  const resolvedLaunchFailureKind =
702
848
  diagnosis === "worker_orphaned"
703
849
  ? enrichLaunchFailureFromWorkerOutput(
@@ -719,10 +865,21 @@ export function reconcileBatch(ctx) {
719
865
  ? `spine batch retry ${signals.orphanRunning.taskId}`
720
866
  : null;
721
867
 
722
- const integrateGateOpen =
723
- signals.postMergeLimbo === true && batch.batchId
724
- ? Boolean(loadGateRecord(projectRoot, batch.batchId))
725
- : false;
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
+ }
726
883
 
727
884
  const stalePathCheck = buildStalePathDoctorCheck({
728
885
  packageRoot: PACKAGE_ROOT,
@@ -733,6 +890,27 @@ export function reconcileBatch(ctx) {
733
890
  diagnosis === "worker_orphaned" &&
734
891
  findPlanReviewNestedSpawnBlockedFailure(journalEvents, failedTaskId);
735
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
+
736
914
  const output = buildDiagnosisOutput(diagnosis, {
737
915
  batchId: batch.batchId,
738
916
  phase: batch.phase,
@@ -749,6 +927,16 @@ export function reconcileBatch(ctx) {
749
927
  integrateGateOpen,
750
928
  stalePathSpine,
751
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 ?? {}),
752
940
  });
753
941
 
754
942
  if (diagnosis === "git_unavailable") {
@@ -757,11 +945,31 @@ export function reconcileBatch(ctx) {
757
945
  output.alternatives = ["spine status --diagnose"];
758
946
  }
759
947
 
948
+ const progress = computeStatusProgress({
949
+ batchRaw: batch.raw,
950
+ succeededTasks: batch.succeededTasks,
951
+ totalTasks: batch.totalTasks,
952
+ pendingTasks: pendingTaskCount,
953
+ });
954
+
760
955
  return {
761
956
  ...output,
762
957
  batchId: batch.batchId,
763
958
  batchStatePath: loaded.path ?? ctx.batchStatePath ?? null,
764
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,
765
973
  signals: ctx.verbose ? signals : undefined,
766
974
  };
767
975
  }
@@ -775,3 +983,170 @@ export function reconcileBatch(ctx) {
775
983
  export function runReconciliationCheck(ctx) {
776
984
  return reconcileBatch(ctx);
777
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
+ }
@@ -27,11 +27,15 @@ export function journalHasTaskCompleted(events, taskId) {
27
27
  * @param {object} params
28
28
  */
29
29
  export function taskAlreadyComplete({ taskFolder, events, task }) {
30
+ const status = String(task?.status ?? "");
31
+ if (status === "pending" || status === "failed" || status === "running") {
32
+ return false;
33
+ }
30
34
  const doneOnDisk = fs.existsSync(path.join(taskFolder, ".DONE"));
31
35
  return (
32
36
  doneOnDisk ||
33
37
  task.doneFileFound ||
34
- task.status === "succeeded" ||
38
+ status === "succeeded" ||
35
39
  journalHasTaskCompleted(events, task.taskId)
36
40
  );
37
41
  }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Resume lane review phases — mirror engine-lanes review before lane commit (SP-359).
3
+ */
4
+
5
+ import { runCodeReviewPhase, runFinalReviewPhase } from "./engine-lanes/review.mjs";
6
+
7
+ /**
8
+ * @param {object} params
9
+ */
10
+ export async function runLaneReviewPhasesBeforeCommit(params) {
11
+ const codeReview = await runCodeReviewPhase(params);
12
+ if (!codeReview.ok) {
13
+ return codeReview;
14
+ }
15
+ return runFinalReviewPhase(params);
16
+ }