pi-spine 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +563 -0
  3. package/bin/get-version.mjs +35 -0
  4. package/bin/spine-batch.mjs +425 -0
  5. package/bin/spine-cli/batch.mjs +47 -0
  6. package/bin/spine-cli/gate.mjs +10 -0
  7. package/bin/spine-cli/integrate.mjs +10 -0
  8. package/bin/spine-cli/plan.mjs +12 -0
  9. package/bin/spine-cli/shared.mjs +73 -0
  10. package/bin/spine-cli/status.mjs +18 -0
  11. package/bin/spine-cli/verify.mjs +199 -0
  12. package/bin/spine-config.mjs +212 -0
  13. package/bin/spine-dashboard.mjs +178 -0
  14. package/bin/spine-deps.mjs +69 -0
  15. package/bin/spine-doctor.mjs +468 -0
  16. package/bin/spine-gate.mjs +137 -0
  17. package/bin/spine-init.mjs +398 -0
  18. package/bin/spine-integrate.mjs +77 -0
  19. package/bin/spine-journal.mjs +198 -0
  20. package/bin/spine-migrate-from-taskplane.mjs +136 -0
  21. package/bin/spine-plan.mjs +83 -0
  22. package/bin/spine-preflight.mjs +700 -0
  23. package/bin/spine-report-progress.d.mts +28 -0
  24. package/bin/spine-report-progress.mjs +126 -0
  25. package/bin/spine-review-step.d.mts +24 -0
  26. package/bin/spine-review-step.mjs +124 -0
  27. package/bin/spine-rules.mjs +35 -0
  28. package/bin/spine-settings.mjs +186 -0
  29. package/bin/spine-state.mjs +110 -0
  30. package/bin/spine-status.mjs +79 -0
  31. package/bin/spine-tasks.mjs +293 -0
  32. package/bin/spine-worker-runner.mjs +314 -0
  33. package/bin/spine.mjs +404 -0
  34. package/extensions/spine/settings-slash.ts +20 -0
  35. package/extensions/spine/slash-commands.ts +806 -0
  36. package/extensions/spine/worker-tools.ts +279 -0
  37. package/extensions/spine-orchestrator.ts +12 -0
  38. package/package.json +72 -0
  39. package/skills/.gitkeep +0 -0
  40. package/skills/create-spine-tasks/SKILL.md +375 -0
  41. package/skills/create-spine-tasks/references/context-template.md +25 -0
  42. package/skills/create-spine-tasks/references/contract-template.md +98 -0
  43. package/skills/create-spine-tasks/references/explore-template.md +63 -0
  44. package/skills/create-spine-tasks/references/prompt-template.md +276 -0
  45. package/src/batch/abort.mjs +272 -0
  46. package/src/batch/agent-session-worker.mjs +297 -0
  47. package/src/batch/batch-state-io.mjs +53 -0
  48. package/src/batch/contract-verify.mjs +310 -0
  49. package/src/batch/detached-start.mjs +778 -0
  50. package/src/batch/diagnosis.mjs +378 -0
  51. package/src/batch/engine-lanes/merge.mjs +632 -0
  52. package/src/batch/engine-lanes/queue.mjs +208 -0
  53. package/src/batch/engine-lanes/review.mjs +970 -0
  54. package/src/batch/engine-lanes.mjs +388 -0
  55. package/src/batch/engine-scope.mjs +251 -0
  56. package/src/batch/engine.mjs +445 -0
  57. package/src/batch/evidence-command.mjs +157 -0
  58. package/src/batch/evidence.mjs +203 -0
  59. package/src/batch/gate.mjs +359 -0
  60. package/src/batch/git-commit-env.mjs +46 -0
  61. package/src/batch/git-exec.mjs +26 -0
  62. package/src/batch/heartbeat.mjs +430 -0
  63. package/src/batch/integrate.mjs +414 -0
  64. package/src/batch/journal-rebuild.mjs +388 -0
  65. package/src/batch/journal.mjs +373 -0
  66. package/src/batch/lane-commit.mjs +153 -0
  67. package/src/batch/lifecycle.mjs +364 -0
  68. package/src/batch/metrics.mjs +265 -0
  69. package/src/batch/orphan-detect.mjs +210 -0
  70. package/src/batch/post-merge-limbo.mjs +80 -0
  71. package/src/batch/postmortem.mjs +296 -0
  72. package/src/batch/readers/spine-state.mjs +95 -0
  73. package/src/batch/readers/taskplane-state.mjs +136 -0
  74. package/src/batch/reconcile.mjs +729 -0
  75. package/src/batch/resume-common.mjs +104 -0
  76. package/src/batch/resume-engine.mjs +66 -0
  77. package/src/batch/resume-multi-lanes.mjs +479 -0
  78. package/src/batch/resume-multi-validate.mjs +187 -0
  79. package/src/batch/resume-multi.mjs +254 -0
  80. package/src/batch/resume.mjs +475 -0
  81. package/src/batch/retry.mjs +257 -0
  82. package/src/batch/review-scope.mjs +136 -0
  83. package/src/batch/review.mjs +1045 -0
  84. package/src/batch/salvage.mjs +332 -0
  85. package/src/batch/state.mjs +680 -0
  86. package/src/batch/task-stall-budget.mjs +88 -0
  87. package/src/batch/worker-host.mjs +683 -0
  88. package/src/batch/worker-output.mjs +253 -0
  89. package/src/batch/worker-prompt.mjs +84 -0
  90. package/src/batch/worktree.mjs +290 -0
  91. package/src/cli/deps.mjs +141 -0
  92. package/src/cli/handoff.mjs +364 -0
  93. package/src/cli/rules.mjs +429 -0
  94. package/src/cli/settings-set.mjs +171 -0
  95. package/src/cli/settings-show.mjs +140 -0
  96. package/src/cli/settings-slash.mjs +107 -0
  97. package/src/config/contract.mjs +56 -0
  98. package/src/config/cursor-rules/discover.mjs +416 -0
  99. package/src/config/cursor-rules/index.mjs +39 -0
  100. package/src/config/cursor-rules/match-globs.mjs +132 -0
  101. package/src/config/cursor-rules/parse-frontmatter.mjs +222 -0
  102. package/src/config/cursor-rules/priority.mjs +26 -0
  103. package/src/config/cursor-rules/profile.mjs +403 -0
  104. package/src/config/cursor-rules/select.mjs +259 -0
  105. package/src/config/defaults.mjs +36 -0
  106. package/src/config/env-overrides.mjs +207 -0
  107. package/src/config/merge-defaults.mjs +47 -0
  108. package/src/config/pi-spine-root.mjs +93 -0
  109. package/src/config/reviewer-context.mjs +243 -0
  110. package/src/config/settings-fields.mjs +265 -0
  111. package/src/config/worker-backend.mjs +116 -0
  112. package/src/config/worker-context.mjs +402 -0
  113. package/src/config/worker-launch-script.mjs +130 -0
  114. package/src/config/worktree-setup-hook.mjs +122 -0
  115. package/src/dashboard/public/dashboard.css +77 -0
  116. package/src/dashboard/public/dashboard.js +349 -0
  117. package/src/dashboard/public/index.html +80 -0
  118. package/src/dashboard/server.mjs +155 -0
  119. package/src/dashboard/snapshot.mjs +414 -0
  120. package/src/dashboard/sse.mjs +15 -0
  121. package/src/dashboard/view.mjs +292 -0
  122. package/src/doctor/agent-model-inherit.mjs +101 -0
  123. package/src/doctor/batch-size-guidance.mjs +72 -0
  124. package/src/doctor/coexistence.mjs +312 -0
  125. package/src/doctor/rules-manifest.mjs +133 -0
  126. package/src/doctor/stale-path.mjs +156 -0
  127. package/src/doctor/stall-config.mjs +108 -0
  128. package/src/doctor/suggest-max-parallel.mjs +53 -0
  129. package/src/doctor/task-packet-size.mjs +110 -0
  130. package/src/doctor/worktree-health.mjs +71 -0
  131. package/src/migrate/taskplane-config.mjs +116 -0
  132. package/src/planner/cycles.mjs +63 -0
  133. package/src/planner/format-plan.mjs +132 -0
  134. package/src/planner/graph.mjs +99 -0
  135. package/src/planner/index.mjs +125 -0
  136. package/src/planner/lanes.mjs +111 -0
  137. package/src/planner/pending.mjs +39 -0
  138. package/src/planner/scope.mjs +142 -0
  139. package/src/process/liveness.mjs +21 -0
  140. package/src/tasks/packet/discover.mjs +40 -0
  141. package/src/tasks/packet/index.mjs +81 -0
  142. package/src/tasks/packet/merge-deps.mjs +79 -0
  143. package/src/tasks/packet/parse-prompt.mjs +445 -0
  144. package/src/tasks/packet/parse-status.mjs +118 -0
  145. package/src/tasks/packet/validate-contract.mjs +115 -0
  146. package/src/tasks/packet/validate-prompt.mjs +99 -0
  147. package/src/worker-tools/report-progress.d.mts +18 -0
  148. package/src/worker-tools/report-progress.mjs +59 -0
  149. package/src/worker-tools/request-gate.d.mts +17 -0
  150. package/src/worker-tools/request-gate.mjs +54 -0
  151. package/templates/agents/reviewer.md +123 -0
  152. package/templates/agents/supervisor.md +59 -0
  153. package/templates/agents/worker.md +122 -0
  154. package/templates/rules-profile.json +27 -0
  155. package/templates/spine-config.json +64 -0
  156. package/templates/tasks/CONTEXT.md +30 -0
@@ -0,0 +1,388 @@
1
+ /**
2
+ * Lane task execution facade — re-exports split modules and phase transitions.
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import {
8
+ buildTasksAndLanesFromPlan,
9
+ loadTaskFileScopePaths,
10
+ recordLaneTaskMetric,
11
+ recordPromptParseFailure,
12
+ skipTaskDoneOnDisk,
13
+ } from "./engine-lanes/queue.mjs";
14
+ import { appendJournalEvent } from "./journal.mjs";
15
+ import {
16
+ commitLaneWorktree,
17
+ filterPorcelain,
18
+ gitPorcelain,
19
+ } from "./lane-commit.mjs";
20
+ import { recordTaskFailureSalvage } from "./salvage.mjs";
21
+ import {
22
+ recordTaskSucceeded,
23
+ recordTaskTransition,
24
+ recomputeTaskCounters,
25
+ saveSpineBatchState,
26
+ updateSegmentForTask,
27
+ } from "./state.mjs";
28
+ import { runWorker } from "./worker-host.mjs";
29
+ import { runCodeReviewPhase, runFinalReviewPhase } from "./engine-lanes/review.mjs";
30
+
31
+ export {
32
+ buildTasksAndLanesFromPlan,
33
+ loadTaskFileScopePaths,
34
+ skipTaskDoneOnDisk,
35
+ } from "./engine-lanes/queue.mjs";
36
+
37
+ export {
38
+ buildFinalReviewArtifactPath,
39
+ parseFinalReviewVerdict,
40
+ shouldRunCodeReview,
41
+ shouldRunFinalReview,
42
+ runEngineFinalReview,
43
+ runEngineCodeReview,
44
+ } from "./engine-lanes/review.mjs";
45
+
46
+ export {
47
+ mergeLaneToOrch,
48
+ mergeWaveLanesToOrch,
49
+ resolveRulesManifestIntegrateDrift,
50
+ tryAutoResolveMergeConflicts,
51
+ tryAutoResolveRulesManifestMergeConflict,
52
+ } from "./engine-lanes/merge.mjs";
53
+
54
+ /**
55
+ * @param {string} fromPhase
56
+ * @param {string} toPhase
57
+ */
58
+ function phaseTransitionEventType(fromPhase, toPhase) {
59
+ if (fromPhase === "planning" && toPhase === "running") return "batch.started";
60
+ if (toPhase === "completed") return "batch.completed";
61
+ if (toPhase === "failed") return "batch.failed";
62
+ if (toPhase === "aborted") return "batch.aborted";
63
+ return null;
64
+ }
65
+
66
+ /**
67
+ * @param {object} params
68
+ */
69
+ function recordPhaseTransition({ projectRoot, batchId, fromPhase, toPhase, extra = {} }) {
70
+ const type = phaseTransitionEventType(fromPhase, toPhase);
71
+ if (!type) return null;
72
+ return appendJournalEvent(projectRoot, batchId, type, {
73
+ fromPhase,
74
+ toPhase,
75
+ ...extra,
76
+ });
77
+ }
78
+
79
+ /**
80
+ * @param {object} state
81
+ * @param {string} newPhase
82
+ * @param {object} ctx
83
+ */
84
+ export function transitionPhase(state, newPhase, ctx) {
85
+ const fromPhase = state.phase;
86
+ if (fromPhase === newPhase) return;
87
+ state.phase = newPhase;
88
+ recordPhaseTransition({
89
+ projectRoot: ctx.projectRoot,
90
+ batchId: ctx.batchId,
91
+ fromPhase,
92
+ toPhase: newPhase,
93
+ ...ctx.extra,
94
+ });
95
+ }
96
+
97
+ export async function runTaskOnLane({
98
+ projectRoot,
99
+ state,
100
+ batchId,
101
+ baseBranch,
102
+ config,
103
+ task,
104
+ lane,
105
+ taskFolderRel,
106
+ laneCorrelationId,
107
+ }) {
108
+ const taskId = task.taskId;
109
+ const laneNumber = lane.laneNumber;
110
+ const wt = lane.worktreePath;
111
+ const taskBranch = lane.branch;
112
+ const taskFolderInWorktree = path.join(wt, taskFolderRel);
113
+ const scopeResult = loadTaskFileScopePaths(path.join(projectRoot, taskFolderRel));
114
+ if (!scopeResult.ok) {
115
+ return recordPromptParseFailure({
116
+ projectRoot,
117
+ state,
118
+ batchId,
119
+ task,
120
+ lane,
121
+ laneCorrelationId,
122
+ scopeResult,
123
+ config,
124
+ taskFolderPath: path.join(projectRoot, taskFolderRel),
125
+ });
126
+ }
127
+ const fileScopePaths = scopeResult.fileScopePaths;
128
+
129
+ task.status = "running";
130
+ if (!task.startedAt) task.startedAt = Date.now();
131
+ updateSegmentForTask(state, taskId, "running");
132
+ saveSpineBatchState(projectRoot, state);
133
+ appendJournalEvent(projectRoot, batchId, "task.started", {
134
+ taskId,
135
+ laneNumber,
136
+ laneId: lane.laneId,
137
+ correlationId: laneCorrelationId,
138
+ });
139
+
140
+ const workerResult = await runWorker({
141
+ worktreePath: wt,
142
+ taskFolder: taskFolderInWorktree,
143
+ projectRoot,
144
+ batchId,
145
+ laneNumber,
146
+ taskId,
147
+ laneBranch: taskBranch,
148
+ laneCorrelationId,
149
+ fileScopePaths,
150
+ config,
151
+ onHeartbeat: (timestamp) => {
152
+ lane.lastHeartbeatAt = timestamp;
153
+ saveSpineBatchState(projectRoot, state);
154
+ },
155
+ onWorkerPid: (pid) => {
156
+ if (pid > 0) {
157
+ lane.workerPid = pid;
158
+ saveSpineBatchState(projectRoot, state);
159
+ }
160
+ },
161
+ });
162
+
163
+ if (!workerResult.ok) {
164
+ const doneOnDisk = fs.existsSync(path.join(taskFolderInWorktree, ".DONE"));
165
+ const orphanSalvage =
166
+ doneOnDisk &&
167
+ (workerResult.doneFound === true || workerResult.classification === "stall_timeout");
168
+ if (orphanSalvage) {
169
+ appendJournalEvent(projectRoot, batchId, "worker.orphan_salvaged", {
170
+ taskId,
171
+ laneNumber,
172
+ laneId: lane.laneId,
173
+ correlationId: laneCorrelationId,
174
+ classification: workerResult.classification ?? "worker_failed",
175
+ doneOnDisk: true,
176
+ });
177
+ if (lane.workerPid) {
178
+ delete lane.workerPid;
179
+ saveSpineBatchState(projectRoot, state);
180
+ }
181
+ } else {
182
+ const aborted = workerResult.classification === "aborted";
183
+ appendJournalEvent(projectRoot, batchId, "lane.died", {
184
+ laneNumber,
185
+ laneId: lane.laneId,
186
+ taskId,
187
+ correlationId: laneCorrelationId,
188
+ reason: workerResult.classification ?? "worker_failed",
189
+ });
190
+ task.status = aborted ? "aborted" : "failed";
191
+ task.endedAt = Date.now();
192
+ task.exitReason = workerResult.classification ?? "worker_failed";
193
+ updateSegmentForTask(state, taskId, aborted ? "aborted" : "failed");
194
+ recomputeTaskCounters(state);
195
+ saveSpineBatchState(projectRoot, state);
196
+ if (!aborted) {
197
+ const salvageFields = recordTaskFailureSalvage({
198
+ projectRoot,
199
+ batchId,
200
+ laneNumber,
201
+ laneId: lane.laneId,
202
+ taskId,
203
+ correlationId: laneCorrelationId,
204
+ worktreePath: wt,
205
+ fileScopePaths,
206
+ taskFolder: taskFolderInWorktree,
207
+ workerResult,
208
+ config,
209
+ batchPhase: state.phase,
210
+ taskBranch,
211
+ });
212
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
213
+ taskId,
214
+ laneNumber,
215
+ laneId: lane.laneId,
216
+ correlationId: laneCorrelationId,
217
+ ...workerResult,
218
+ ...salvageFields,
219
+ });
220
+ }
221
+ recordLaneTaskMetric({
222
+ projectRoot,
223
+ batchId,
224
+ task,
225
+ config,
226
+ taskFolder: taskFolderInWorktree,
227
+ });
228
+ return { ok: false, aborted, workerResult };
229
+ }
230
+ }
231
+
232
+ if (lane.workerPid) {
233
+ delete lane.workerPid;
234
+ saveSpineBatchState(projectRoot, state);
235
+ }
236
+
237
+ appendJournalEvent(projectRoot, batchId, "lane.completed", {
238
+ laneNumber,
239
+ laneId: lane.laneId,
240
+ taskId,
241
+ correlationId: laneCorrelationId,
242
+ });
243
+
244
+ const codeReview = await runCodeReviewPhase({
245
+ projectRoot,
246
+ state,
247
+ batchId,
248
+ config,
249
+ task,
250
+ lane,
251
+ taskFolderInWorktree,
252
+ wt,
253
+ taskBranch,
254
+ laneCorrelationId,
255
+ fileScopePaths,
256
+ });
257
+ if (!codeReview.ok) {
258
+ return codeReview;
259
+ }
260
+
261
+ const finalReview = await runFinalReviewPhase({
262
+ projectRoot,
263
+ state,
264
+ batchId,
265
+ config,
266
+ task,
267
+ lane,
268
+ taskFolderInWorktree,
269
+ wt,
270
+ taskBranch,
271
+ laneCorrelationId,
272
+ fileScopePaths,
273
+ baseBranch,
274
+ });
275
+ if (!finalReview.ok) {
276
+ return finalReview;
277
+ }
278
+
279
+ if (process.env.SPINE_TEST_STRIP_DONE_BEFORE_LANE_COMMIT === "1") {
280
+ const donePath = path.join(taskFolderInWorktree, ".DONE");
281
+ if (fs.existsSync(donePath)) {
282
+ fs.unlinkSync(donePath);
283
+ }
284
+ }
285
+
286
+ const ignorePatterns = Array.isArray(config?.worktreeSetupIgnorePaths)
287
+ ? config.worktreeSetupIgnorePaths
288
+ : [];
289
+ const laneCommit = commitLaneWorktree({
290
+ worktreePath: wt,
291
+ taskBranch,
292
+ taskId,
293
+ batchId,
294
+ taskFolder: taskFolderInWorktree,
295
+ projectRoot,
296
+ });
297
+ if (!laneCommit.ok) {
298
+ task.status = "failed";
299
+ task.endedAt = Date.now();
300
+ task.exitReason = laneCommit.failureClass ?? "lane_commit_failed";
301
+ updateSegmentForTask(state, taskId, "failed");
302
+ recomputeTaskCounters(state);
303
+ saveSpineBatchState(projectRoot, state);
304
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
305
+ taskId,
306
+ laneNumber,
307
+ laneId: lane.laneId,
308
+ correlationId: laneCorrelationId,
309
+ classification: laneCommit.failureClass ?? "lane_commit_failed",
310
+ exitCode: 1,
311
+ output: laneCommit.error,
312
+ });
313
+ recordLaneTaskMetric({
314
+ projectRoot,
315
+ batchId,
316
+ task,
317
+ config,
318
+ taskFolder: taskFolderInWorktree,
319
+ });
320
+ return {
321
+ ok: false,
322
+ error: "lane_commit_failed",
323
+ output: laneCommit.error,
324
+ };
325
+ }
326
+ if (laneCommit.committed) {
327
+ appendJournalEvent(projectRoot, batchId, "lane.committed", {
328
+ taskId,
329
+ laneNumber,
330
+ commitSha: laneCommit.commitSha,
331
+ });
332
+ }
333
+
334
+ const remainingDirty = filterPorcelain(gitPorcelain(wt), ignorePatterns);
335
+ if (remainingDirty) {
336
+ const dirtyOutput =
337
+ "Lane worktree still has uncommitted changes after auto-commit — commit manually or fix worker output";
338
+ task.status = "failed";
339
+ task.endedAt = Date.now();
340
+ task.exitReason = "DirtyWorktree";
341
+ updateSegmentForTask(state, taskId, "failed");
342
+ recomputeTaskCounters(state);
343
+ saveSpineBatchState(projectRoot, state);
344
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
345
+ taskId,
346
+ laneNumber,
347
+ laneId: lane.laneId,
348
+ correlationId: laneCorrelationId,
349
+ classification: "DirtyWorktree",
350
+ exitCode: 1,
351
+ output: dirtyOutput,
352
+ });
353
+ recordLaneTaskMetric({
354
+ projectRoot,
355
+ batchId,
356
+ task,
357
+ config,
358
+ taskFolder: taskFolderInWorktree,
359
+ });
360
+ return {
361
+ ok: false,
362
+ error: "dirty_after_lane_commit",
363
+ output: dirtyOutput,
364
+ };
365
+ }
366
+
367
+ recordTaskSucceeded(state, taskId, { exitReason: "done", doneFileFound: true });
368
+ recordTaskTransition({
369
+ projectRoot,
370
+ state,
371
+ journalType: "task.completed",
372
+ journalPayload: {
373
+ taskId,
374
+ laneNumber,
375
+ laneId: lane.laneId,
376
+ correlationId: laneCorrelationId,
377
+ },
378
+ });
379
+ recordLaneTaskMetric({
380
+ projectRoot,
381
+ batchId,
382
+ task,
383
+ config,
384
+ taskFolder: taskFolderInWorktree,
385
+ });
386
+
387
+ return { ok: true, laneCommit };
388
+ }
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Batch scope resolution and wave merge policy (extracted from engine.mjs).
3
+ */
4
+
5
+ import { discoverTasks } from "../tasks/packet/discover.mjs";
6
+ import { filterPendingTaskIds } from "../planner/pending.mjs";
7
+ import { NO_PENDING_TASKS_ERROR } from "../planner/scope.mjs";
8
+ import { appendJournalEvent } from "./journal.mjs";
9
+ import {
10
+ loadSpineBatchState,
11
+ saveSpineBatchState,
12
+ } from "./state.mjs";
13
+
14
+ /**
15
+ * Whether to auto-integrate orch→base after a wave merge when more waves remain.
16
+ *
17
+ * @param {object} params
18
+ * @param {object} [params.config]
19
+ * @param {number} params.waveIndex
20
+ * @param {number} params.totalWaves
21
+ */
22
+ export function shouldAutoIntegrateAfterWave({ config = {}, waveIndex, totalWaves }) {
23
+ return Boolean(config.lanes?.autoIntegrateBetweenWaves) && waveIndex < totalWaves - 1;
24
+ }
25
+
26
+ /**
27
+ * @param {import("../planner/index.mjs").buildPlan} plan
28
+ */
29
+ export function countPlanTasks(plan) {
30
+ const ids = new Set();
31
+ for (const wave of plan.waves ?? []) {
32
+ for (const taskId of wave.taskIds ?? []) {
33
+ ids.add(taskId);
34
+ }
35
+ }
36
+ return [...ids];
37
+ }
38
+
39
+ /**
40
+ * @param {string} scope
41
+ */
42
+ export function isExplicitBatchScope(scope) {
43
+ const normalized = String(scope ?? "")
44
+ .trim()
45
+ .toLowerCase();
46
+ return Boolean(normalized) && normalized !== "all";
47
+ }
48
+
49
+ /**
50
+ * Batch start resolves bare `all` to pending-filtered IDs (plan CLI keeps full `all`).
51
+ *
52
+ * @param {string} scope
53
+ * @param {string} tasksRoot
54
+ */
55
+ export function resolveBatchStartScope(scope, tasksRoot) {
56
+ const trimmed = String(scope ?? "").trim();
57
+ const normalized = trimmed.toLowerCase();
58
+
59
+ if (!trimmed || normalized === "all") {
60
+ const discovered = discoverTasks(tasksRoot);
61
+ const pendingIds = filterPendingTaskIds(discovered, tasksRoot);
62
+ if (pendingIds.length === 0) {
63
+ return {
64
+ ok: false,
65
+ error: "no_pending_tasks",
66
+ output: `${NO_PENDING_TASKS_ERROR}\n`,
67
+ };
68
+ }
69
+ return {
70
+ ok: true,
71
+ scope: pendingIds.join(" "),
72
+ policyScope: "pending",
73
+ };
74
+ }
75
+
76
+ if (normalized === "pending") {
77
+ return { ok: true, scope: "pending", policyScope: "pending" };
78
+ }
79
+
80
+ return { ok: true, scope: trimmed, policyScope: trimmed };
81
+ }
82
+
83
+ /**
84
+ * @param {object} plan
85
+ * @param {string} scope
86
+ */
87
+ export function canStartMultiTaskBatch(plan, scope) {
88
+ const taskIds = countPlanTasks(plan);
89
+ if (taskIds.length <= 1) {
90
+ return { ok: true, taskIds };
91
+ }
92
+
93
+ const singleWave = (plan.waves?.length ?? 0) === 1;
94
+ const firstWave = plan.waves?.[0];
95
+ const virtualLaneCount = firstWave?.virtualLaneCount ?? 1;
96
+ const multiLane = virtualLaneCount > 1;
97
+ const explicit = isExplicitBatchScope(scope);
98
+
99
+ if (explicit || (singleWave && multiLane)) {
100
+ return { ok: true, taskIds };
101
+ }
102
+
103
+ return {
104
+ ok: false,
105
+ taskIds,
106
+ error: "multi_task_not_allowed",
107
+ output:
108
+ `Multi-task batches require a single wave with disjoint lanes (virtualLaneCount > 1) or an explicit scope.\n` +
109
+ `Plan selected ${taskIds.length} task(s) across ${plan.waves?.length ?? 0} wave(s); virtualLaneCount=${virtualLaneCount}.\n` +
110
+ `Use: spine batch start TP-001 TP-002 or spine plan <scope> to verify lane assignment.\n`,
111
+ };
112
+ }
113
+
114
+ /**
115
+ * @param {object} plan
116
+ */
117
+ export function maxLaneNumberForPlan(plan) {
118
+ let max = 1;
119
+ for (const wave of plan.waves ?? []) {
120
+ for (const tick of wave.ticks ?? []) {
121
+ max = Math.max(max, tick.lanes?.length ?? 0);
122
+ }
123
+ }
124
+ return max;
125
+ }
126
+
127
+ /**
128
+ * @param {object} plan
129
+ * @returns {Map<string, { laneNumber: number, waveIndex: number, tickIndex: number }>}
130
+ */
131
+ export function buildTaskLaneAssignments(plan) {
132
+ /** @type {Map<string, { laneNumber: number, waveIndex: number, tickIndex: number }>} */
133
+ const map = new Map();
134
+ for (const wave of plan.waves ?? []) {
135
+ for (const tick of wave.ticks ?? []) {
136
+ for (let laneInTick = 0; laneInTick < (tick.lanes?.length ?? 0); laneInTick++) {
137
+ const laneNumber = laneInTick + 1;
138
+ for (const taskId of tick.lanes[laneInTick] ?? []) {
139
+ map.set(taskId, {
140
+ laneNumber,
141
+ waveIndex: wave.index,
142
+ tickIndex: tick.index,
143
+ });
144
+ }
145
+ }
146
+ }
147
+ }
148
+ return map;
149
+ }
150
+
151
+ /**
152
+ * @param {object[]} failedTasks
153
+ * @param {object[]} pendingTasks
154
+ * @param {object[]} [succeededTasks]
155
+ */
156
+ export function formatMixedOutcomeMessage(failedTasks, pendingTasks, succeededTasks = []) {
157
+ const failedIds = failedTasks.map((task) => task.taskId);
158
+ const pendingIds = pendingTasks.map((task) => task.taskId);
159
+ const succeededIds = succeededTasks.map((task) => task.taskId);
160
+ const lines = ["Wave merge blocked (§17.4 mixed-outcome policy)."];
161
+
162
+ if (succeededIds.length > 0) {
163
+ lines.push(`Succeeded task(s): ${succeededIds.join(", ")}.`);
164
+ }
165
+ if (failedIds.length > 0) {
166
+ lines.push(`Failed task(s): ${failedIds.join(", ")}.`);
167
+ for (const taskId of failedIds) {
168
+ lines.push(`Retry ${taskId} next: spine batch retry ${taskId}`);
169
+ }
170
+ lines.push(`Or skip: ${failedIds.map((id) => `/spine-skip-task ${id}`).join("; ")}`);
171
+ }
172
+ if (pendingIds.length > 0) {
173
+ lines.push(`Pending/running task(s): ${pendingIds.join(", ")}.`);
174
+ }
175
+ lines.push("Do not report batch success while failures remain.");
176
+ return lines.join("\n");
177
+ }
178
+
179
+ /**
180
+ * @param {object} state
181
+ * @param {number} waveIndex
182
+ */
183
+ export function assessWaveMergeEligibility(state, waveIndex) {
184
+ const forceMerged = (state.resilience?.forceMergedWaves ?? []).includes(waveIndex);
185
+ if (forceMerged) {
186
+ return { ok: true, forceMerged: true };
187
+ }
188
+
189
+ const waveTaskIds = state.wavePlan?.[waveIndex] ?? [];
190
+ const tasks = waveTaskIds
191
+ .map((taskId) => (state.tasks ?? []).find((task) => task?.taskId === taskId))
192
+ .filter(Boolean);
193
+
194
+ const failed = tasks.filter((task) => task.status === "failed");
195
+ const pending = tasks.filter(
196
+ (task) => task.status === "pending" || task.status === "running",
197
+ );
198
+ const succeeded = tasks.filter((task) => task.status === "succeeded");
199
+
200
+ if (failed.length === 0 && pending.length === 0) {
201
+ return { ok: true };
202
+ }
203
+
204
+ return {
205
+ ok: false,
206
+ failedTaskIds: failed.map((task) => task.taskId),
207
+ pendingTaskIds: pending.map((task) => task.taskId),
208
+ succeededTaskIds: succeeded.map((task) => task.taskId),
209
+ message: formatMixedOutcomeMessage(failed, pending, succeeded),
210
+ };
211
+ }
212
+
213
+ /**
214
+ * @param {object} params
215
+ * @param {string} params.projectRoot
216
+ * @param {number} params.waveIndex
217
+ */
218
+ export function forceMergeWave({ projectRoot, waveIndex }) {
219
+ const loaded = loadSpineBatchState(projectRoot);
220
+ if (!loaded.raw) {
221
+ return { ok: false, exitCode: 1, error: "no_active_batch", output: "No active pi-spine batch.\n" };
222
+ }
223
+
224
+ const state = loaded.raw;
225
+ const phase = String(state.phase ?? "");
226
+ if (phase !== "failed" && phase !== "paused") {
227
+ return {
228
+ ok: false,
229
+ exitCode: 1,
230
+ error: "cannot_force_merge",
231
+ output: `Force-merge is allowed when batch phase is failed or paused (current: ${phase}).\n`,
232
+ batchId: state.batchId,
233
+ };
234
+ }
235
+
236
+ state.resilience = state.resilience ?? {};
237
+ state.resilience.forceMergedWaves = [...(state.resilience.forceMergedWaves ?? []), waveIndex];
238
+ saveSpineBatchState(projectRoot, state);
239
+
240
+ appendJournalEvent(projectRoot, state.batchId, "batch.force_merge_requested", {
241
+ waveIndex,
242
+ });
243
+
244
+ return {
245
+ ok: true,
246
+ exitCode: 0,
247
+ batchId: state.batchId,
248
+ waveIndex,
249
+ output: `Wave ${waveIndex} marked for force-merge. Resume with: spine batch resume --force\n`,
250
+ };
251
+ }