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,445 @@
1
+ /**
2
+ * pi-spine batch engine (Phase 2 single-lane, Phase 3 multi-lane + §17.4 merge policy).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import crypto from "node:crypto";
8
+ import { discoverTasks } from "../tasks/packet/discover.mjs";
9
+ import { buildPlan } from "../planner/index.mjs";
10
+ import { runBatchPreflight, resolveTasksRoot } from "../../bin/spine-preflight.mjs";
11
+ import { loadSpineConfig } from "../../bin/spine-config.mjs";
12
+ import { openIntegrateGateAfterBatchComplete } from "./gate.mjs";
13
+ import { integrateOrchToBase } from "./integrate.mjs";
14
+ import { appendJournalEvent } from "./journal.mjs";
15
+ import {
16
+ assertNoActiveBatch,
17
+ createInitialBatchState,
18
+ generateBatchId,
19
+ recordBatchEnginePid,
20
+ saveSpineBatchState,
21
+ } from "./state.mjs";
22
+ import {
23
+ ensureOrchBranch,
24
+ provisionLaneWorktree,
25
+ removeLaneWorktrees,
26
+ runWorktreeSetupHook,
27
+ } from "./worktree.mjs";
28
+ import { resolveWorktreeSetupHook } from "../config/worktree-setup-hook.mjs";
29
+ import {
30
+ assessWaveMergeEligibility,
31
+ canStartMultiTaskBatch,
32
+ countPlanTasks,
33
+ maxLaneNumberForPlan,
34
+ resolveBatchStartScope,
35
+ shouldAutoIntegrateAfterWave,
36
+ } from "./engine-scope.mjs";
37
+ import {
38
+ buildTasksAndLanesFromPlan,
39
+ mergeWaveLanesToOrch,
40
+ runTaskOnLane,
41
+ skipTaskDoneOnDisk,
42
+ transitionPhase,
43
+ } from "./engine-lanes.mjs";
44
+
45
+ export {
46
+ assessWaveMergeEligibility,
47
+ buildTaskLaneAssignments,
48
+ canStartMultiTaskBatch,
49
+ countPlanTasks,
50
+ forceMergeWave,
51
+ formatMixedOutcomeMessage,
52
+ isExplicitBatchScope,
53
+ maxLaneNumberForPlan,
54
+ resolveBatchStartScope,
55
+ } from "./engine-scope.mjs";
56
+ export { loadTaskFileScopePaths, mergeLaneToOrch } from "./engine-lanes.mjs";
57
+
58
+ /**
59
+ * @param {object} options
60
+ * @param {string} options.projectRoot
61
+ * @param {string} [options.scope]
62
+ * @param {boolean} [options.dryRun]
63
+ * @param {boolean} [options.skipPreflight]
64
+ */
65
+ export async function startBatch({
66
+ projectRoot,
67
+ scope = "all",
68
+ dryRun = false,
69
+ skipPreflight = false,
70
+ }) {
71
+ if (!skipPreflight) {
72
+ const preflight = runBatchPreflight({ projectRoot, skipDoctor: false });
73
+ if (!preflight.ok) {
74
+ return {
75
+ ok: false,
76
+ exitCode: preflight.exitCode ?? 1,
77
+ error: "preflight_failed",
78
+ output: preflight.output,
79
+ };
80
+ }
81
+ }
82
+
83
+ assertNoActiveBatch(projectRoot);
84
+
85
+ const configResult = loadSpineConfig(projectRoot);
86
+ const config = configResult.config ?? {};
87
+ const tasksRoot = resolveTasksRoot(projectRoot, configResult);
88
+ if (!tasksRoot) {
89
+ return { ok: false, exitCode: 1, error: "tasks_root_missing" };
90
+ }
91
+
92
+ const scopeResolution = resolveBatchStartScope(scope, tasksRoot);
93
+ if (!scopeResolution.ok) {
94
+ return {
95
+ ok: false,
96
+ exitCode: 1,
97
+ error: scopeResolution.error,
98
+ output: scopeResolution.output,
99
+ };
100
+ }
101
+
102
+ const effectiveScope = scopeResolution.scope;
103
+ const policyScope = scopeResolution.policyScope ?? effectiveScope;
104
+
105
+ const plan = buildPlan({ scope: effectiveScope, config, tasksRoot });
106
+ const batchPolicy = canStartMultiTaskBatch(plan, policyScope);
107
+ if (!batchPolicy.ok) {
108
+ return {
109
+ ok: false,
110
+ exitCode: 1,
111
+ error: batchPolicy.error,
112
+ output: batchPolicy.output,
113
+ };
114
+ }
115
+
116
+ const taskIds = batchPolicy.taskIds;
117
+ const maxLaneNumber = maxLaneNumberForPlan(plan);
118
+
119
+ if (dryRun) {
120
+ return {
121
+ ok: true,
122
+ exitCode: 0,
123
+ dryRun: true,
124
+ taskIds,
125
+ plan,
126
+ output:
127
+ `Dry run: would start batch for ${taskIds.length} task(s) across ${plan.waves.length} wave(s), ` +
128
+ `up to ${maxLaneNumber} lane(s), maxParallel=${config.lanes?.maxParallel ?? 1}.\n`,
129
+ };
130
+ }
131
+
132
+ const batchId = generateBatchId();
133
+ const baseBranch = config.baseBranch ?? "main";
134
+ const orchBranch = `orch/spine-${batchId}`;
135
+
136
+ const discovered = discoverTasks(tasksRoot);
137
+ for (const taskId of taskIds) {
138
+ if (!discovered.find((entry) => entry.taskId === taskId)) {
139
+ return { ok: false, exitCode: 1, error: "task_not_found", taskId };
140
+ }
141
+ }
142
+
143
+ const { tasks, lanes } = buildTasksAndLanesFromPlan({
144
+ plan,
145
+ discovered,
146
+ projectRoot,
147
+ batchId,
148
+ maxLaneNumber,
149
+ });
150
+
151
+ let state = createInitialBatchState({
152
+ batchId,
153
+ baseBranch,
154
+ orchBranch,
155
+ wavePlan: plan.waves.map((wave) => wave.taskIds),
156
+ tasks,
157
+ lanes,
158
+ });
159
+
160
+ saveSpineBatchState(projectRoot, state);
161
+
162
+ try {
163
+ ensureOrchBranch(projectRoot, baseBranch, orchBranch);
164
+ transitionPhase(state, "running", { projectRoot, batchId });
165
+ recordBatchEnginePid(state, process.pid);
166
+ saveSpineBatchState(projectRoot, state);
167
+
168
+ for (const lane of state.lanes) {
169
+ lane.correlationId = crypto.randomUUID();
170
+ const { worktreePath: wt } = provisionLaneWorktree({
171
+ projectRoot,
172
+ batchId,
173
+ laneNumber: lane.laneNumber,
174
+ orchBranch,
175
+ });
176
+ lane.worktreePath = wt;
177
+
178
+ const setupHookPath = resolveWorktreeSetupHook(projectRoot, config);
179
+ if (setupHookPath) {
180
+ appendJournalEvent(projectRoot, batchId, "lane.setup_hook.started", {
181
+ laneNumber: lane.laneNumber,
182
+ laneId: lane.laneId,
183
+ worktreePath: wt,
184
+ hookPath: setupHookPath,
185
+ correlationId: lane.correlationId,
186
+ });
187
+ try {
188
+ const hookResult = runWorktreeSetupHook({
189
+ projectRoot,
190
+ worktreePath: wt,
191
+ batchId,
192
+ laneNumber: lane.laneNumber,
193
+ config,
194
+ });
195
+ appendJournalEvent(projectRoot, batchId, "lane.setup_hook.completed", {
196
+ laneNumber: lane.laneNumber,
197
+ laneId: lane.laneId,
198
+ worktreePath: wt,
199
+ durationMs: hookResult.durationMs,
200
+ correlationId: lane.correlationId,
201
+ });
202
+ } catch (err) {
203
+ const message = err instanceof Error ? err.message : String(err);
204
+ appendJournalEvent(projectRoot, batchId, "lane.setup_hook.failed", {
205
+ laneNumber: lane.laneNumber,
206
+ laneId: lane.laneId,
207
+ worktreePath: wt,
208
+ error: message,
209
+ correlationId: lane.correlationId,
210
+ });
211
+ throw err;
212
+ }
213
+ }
214
+
215
+ appendJournalEvent(projectRoot, batchId, "lane.provisioned", {
216
+ laneNumber: lane.laneNumber,
217
+ laneId: lane.laneId,
218
+ worktreePath: wt,
219
+ taskBranch: lane.branch,
220
+ correlationId: lane.correlationId,
221
+ });
222
+ }
223
+ saveSpineBatchState(projectRoot, state);
224
+
225
+ let batchAborted = false;
226
+
227
+ for (const wave of plan.waves) {
228
+ state.currentWaveIndex = wave.index;
229
+ saveSpineBatchState(projectRoot, state);
230
+
231
+ for (const tick of wave.ticks ?? []) {
232
+ /** @type {Map<number, { lane: object, runs: Array<{ taskId: string, run: () => Promise<{ ok: boolean, aborted?: boolean }> }> }>} */
233
+ const runsByLane = new Map();
234
+
235
+ for (let laneInTick = 0; laneInTick < (tick.lanes?.length ?? 0); laneInTick++) {
236
+ const tickTaskIds = tick.lanes[laneInTick] ?? [];
237
+ if (tickTaskIds.length === 0) continue;
238
+
239
+ const laneNumber = laneInTick + 1;
240
+ const lane = state.lanes.find((entry) => entry.laneNumber === laneNumber);
241
+ if (!lane) continue;
242
+
243
+ if (!runsByLane.has(laneNumber)) {
244
+ runsByLane.set(laneNumber, { lane, runs: [] });
245
+ }
246
+ const laneQueue = runsByLane.get(laneNumber);
247
+
248
+ for (const taskId of tickTaskIds) {
249
+ const task = state.tasks.find((entry) => entry.taskId === taskId);
250
+ const entry = discovered.find((item) => item.taskId === taskId);
251
+ if (!task || !entry) continue;
252
+
253
+ const taskFolderRel = path.relative(projectRoot, entry.folderPath);
254
+ const doneOnDisk = fs.existsSync(path.join(entry.folderPath, ".DONE"));
255
+ const laneCorrelationId = lane.correlationId ?? crypto.randomUUID();
256
+
257
+ const run = doneOnDisk
258
+ ? () =>
259
+ skipTaskDoneOnDisk({
260
+ projectRoot,
261
+ state,
262
+ batchId,
263
+ task,
264
+ lane,
265
+ taskFolderPath: entry.folderPath,
266
+ laneCorrelationId,
267
+ })
268
+ : () =>
269
+ runTaskOnLane({
270
+ projectRoot,
271
+ state,
272
+ batchId,
273
+ baseBranch,
274
+ config,
275
+ task,
276
+ lane,
277
+ taskFolderRel,
278
+ laneCorrelationId,
279
+ }).then((result) => {
280
+ if (result.aborted) batchAborted = true;
281
+ return result;
282
+ });
283
+
284
+ laneQueue.runs.push({ taskId, run });
285
+ }
286
+ }
287
+
288
+ const laneExecutions = [...runsByLane.entries()].map(async ([laneNumber, { lane, runs }]) => {
289
+ if (runs.length > 1) {
290
+ appendJournalEvent(projectRoot, batchId, "lane.tasks_serialized", {
291
+ laneNumber,
292
+ laneId: lane.laneId,
293
+ waveIndex: wave.index,
294
+ tickIndex: tick.index,
295
+ taskIds: runs.map((entry) => entry.taskId),
296
+ correlationId: lane.correlationId ?? null,
297
+ });
298
+ }
299
+
300
+ for (const { run } of runs) {
301
+ const result = await run();
302
+ if (result.aborted) {
303
+ return result;
304
+ }
305
+ }
306
+ return { ok: true };
307
+ });
308
+
309
+ await Promise.all(laneExecutions);
310
+ if (batchAborted) break;
311
+ }
312
+
313
+ if (batchAborted) {
314
+ const abortedTask = state.tasks.find((task) => task.status === "aborted");
315
+ state.endedAt = Date.now();
316
+ state.lastError = "batch aborted";
317
+ transitionPhase(state, "aborted", {
318
+ projectRoot,
319
+ batchId,
320
+ extra: { taskId: abortedTask?.taskId },
321
+ });
322
+ saveSpineBatchState(projectRoot, state);
323
+ return {
324
+ ok: false,
325
+ exitCode: 1,
326
+ batchId,
327
+ error: "aborted",
328
+ output: "Batch aborted.\n",
329
+ };
330
+ }
331
+
332
+ const mergeEligibility = assessWaveMergeEligibility(state, wave.index);
333
+ if (!mergeEligibility.ok) {
334
+ state.endedAt = Date.now();
335
+ state.lastError = mergeEligibility.message?.slice(0, 500) ?? "mixed_outcome";
336
+ transitionPhase(state, "failed", {
337
+ projectRoot,
338
+ batchId,
339
+ extra: {
340
+ waveIndex: wave.index,
341
+ failedTaskIds: mergeEligibility.failedTaskIds,
342
+ pendingTaskIds: mergeEligibility.pendingTaskIds,
343
+ reason: "mixed_outcome",
344
+ },
345
+ });
346
+ saveSpineBatchState(projectRoot, state);
347
+ appendJournalEvent(projectRoot, batchId, "batch.merge_blocked", {
348
+ waveIndex: wave.index,
349
+ failedTaskIds: mergeEligibility.failedTaskIds,
350
+ pendingTaskIds: mergeEligibility.pendingTaskIds,
351
+ });
352
+ return {
353
+ ok: false,
354
+ exitCode: 1,
355
+ batchId,
356
+ error: "mixed_outcome_merge_blocked",
357
+ failedTaskIds: mergeEligibility.failedTaskIds,
358
+ output: `${mergeEligibility.message}\n`,
359
+ };
360
+ }
361
+
362
+ const mergeResult = await mergeWaveLanesToOrch({
363
+ projectRoot,
364
+ state,
365
+ batchId,
366
+ baseBranch,
367
+ orchBranch,
368
+ waveIndex: wave.index,
369
+ });
370
+ if (!mergeResult.ok) {
371
+ state.endedAt = Date.now();
372
+ state.lastError = mergeResult.error ?? "merge failed";
373
+ transitionPhase(state, "failed", {
374
+ projectRoot,
375
+ batchId,
376
+ extra: { reason: "merge", waveIndex: wave.index },
377
+ });
378
+ saveSpineBatchState(projectRoot, state);
379
+ return {
380
+ ok: false,
381
+ exitCode: 1,
382
+ batchId,
383
+ error: "merge_failed",
384
+ output: mergeResult.error,
385
+ };
386
+ }
387
+
388
+ if (
389
+ shouldAutoIntegrateAfterWave({
390
+ config,
391
+ waveIndex: wave.index,
392
+ totalWaves: state.totalWaves,
393
+ })
394
+ ) {
395
+ const integrateResult = integrateOrchToBase({ projectRoot, batchId });
396
+ appendJournalEvent(projectRoot, batchId, "integrate.started", {
397
+ waveIndex: wave.index,
398
+ mode: "auto_between_waves",
399
+ ok: integrateResult.ok,
400
+ });
401
+ }
402
+ }
403
+
404
+ state.endedAt = Date.now();
405
+ openIntegrateGateAfterBatchComplete({
406
+ projectRoot,
407
+ batchId,
408
+ batchState: { ...state, phase: "completed" },
409
+ });
410
+ transitionPhase(state, "completed", {
411
+ projectRoot,
412
+ batchId,
413
+ extra: { taskIds, mergeCommit: state.mergeResults.at(-1)?.mergeCommit },
414
+ });
415
+ saveSpineBatchState(projectRoot, state);
416
+
417
+ const summaryTask =
418
+ taskIds.length === 1 ? taskIds[0] : `${taskIds.length} tasks (${taskIds.join(", ")})`;
419
+ return {
420
+ ok: true,
421
+ exitCode: 0,
422
+ batchId,
423
+ taskId: taskIds.length === 1 ? taskIds[0] : undefined,
424
+ taskIds,
425
+ orchBranch,
426
+ mergeCommit: state.mergeResults.at(-1)?.mergeCommit,
427
+ output:
428
+ `Batch ${batchId} completed: ${summaryTask} succeeded; merged to ${orchBranch}.\n` +
429
+ ` → spine gate status\n → spine gate approve\n → spine integrate\n → spine batch complete\n`,
430
+ };
431
+ } catch (err) {
432
+ const message = err instanceof Error ? err.message : String(err);
433
+ state.endedAt = Date.now();
434
+ state.lastError = message;
435
+ transitionPhase(state, "failed", {
436
+ projectRoot,
437
+ batchId,
438
+ extra: { error: message },
439
+ });
440
+ saveSpineBatchState(projectRoot, state);
441
+ removeLaneWorktrees(projectRoot, batchId, maxLaneNumber);
442
+ return { ok: false, exitCode: 1, batchId, error: message };
443
+ }
444
+ }
445
+
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Safe argv execution for config-derived integrate-gate evidence commands.
3
+ * Allowlisted executables only; rejects shell metacharacters (no shell: true).
4
+ */
5
+
6
+ import path from "node:path";
7
+ import { execFileSync } from "node:child_process";
8
+
9
+ /**
10
+ * Allowed first-token executables for evidence commands.
11
+ * Extend this set deliberately when adding new package-manager or runtime support.
12
+ * @type {Set<string>}
13
+ */
14
+ export const ALLOWED_EVIDENCE_EXECUTABLES = new Set(["npm", "node", "pnpm", "yarn", "npx"]);
15
+
16
+ const SHELL_METACHAR_PATTERN = /[;|&`<>]|>>|\$\(|\$\{/;
17
+
18
+ export class EvidenceCommandError extends Error {
19
+ /**
20
+ * @param {string} message
21
+ */
22
+ constructor(message) {
23
+ super(message);
24
+ this.name = "EvidenceCommandError";
25
+ }
26
+ }
27
+
28
+ /**
29
+ * @param {string} command
30
+ */
31
+ export function assertSafeEvidenceCommand(command) {
32
+ if (typeof command !== "string" || !command.trim()) {
33
+ throw new EvidenceCommandError("empty evidence command");
34
+ }
35
+
36
+ const trimmed = command.trim();
37
+ if (/[\r\n]/.test(trimmed)) {
38
+ throw new EvidenceCommandError("evidence command contains newlines");
39
+ }
40
+ if (SHELL_METACHAR_PATTERN.test(trimmed)) {
41
+ throw new EvidenceCommandError("evidence command contains shell metacharacters");
42
+ }
43
+ if (/\$/.test(trimmed)) {
44
+ throw new EvidenceCommandError("evidence command contains shell variable expansion");
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Parse a config testing command into argv without invoking a shell.
50
+ * @param {string} command
51
+ * @returns {string[]}
52
+ */
53
+ export function parseEvidenceCommandArgv(command) {
54
+ assertSafeEvidenceCommand(command);
55
+ const argv = tokenizeCommandLine(command.trim());
56
+ if (argv.length === 0) {
57
+ throw new EvidenceCommandError("empty evidence command");
58
+ }
59
+
60
+ const executable = path.basename(argv[0]);
61
+ if (!ALLOWED_EVIDENCE_EXECUTABLES.has(executable)) {
62
+ throw new EvidenceCommandError(`evidence executable not allowed: ${executable}`);
63
+ }
64
+
65
+ return argv;
66
+ }
67
+
68
+ /**
69
+ * @param {string} line
70
+ * @returns {string[]}
71
+ */
72
+ function tokenizeCommandLine(line) {
73
+ /** @type {string[]} */
74
+ const tokens = [];
75
+ let current = "";
76
+ /** @type {"'" | '"' | null} */
77
+ let quote = null;
78
+
79
+ for (let i = 0; i < line.length; i++) {
80
+ const ch = line[i];
81
+ if (quote) {
82
+ if (ch === quote) {
83
+ quote = null;
84
+ continue;
85
+ }
86
+ if (ch === "\\" && quote === '"' && i + 1 < line.length) {
87
+ i += 1;
88
+ current += line[i];
89
+ continue;
90
+ }
91
+ current += ch;
92
+ continue;
93
+ }
94
+
95
+ if (ch === "'" || ch === '"') {
96
+ quote = ch;
97
+ continue;
98
+ }
99
+
100
+ if (/\s/.test(ch)) {
101
+ if (current) {
102
+ tokens.push(current);
103
+ current = "";
104
+ }
105
+ continue;
106
+ }
107
+
108
+ current += ch;
109
+ }
110
+
111
+ if (quote) {
112
+ throw new EvidenceCommandError("unclosed quote in evidence command");
113
+ }
114
+ if (current) {
115
+ tokens.push(current);
116
+ }
117
+
118
+ return tokens;
119
+ }
120
+
121
+ /**
122
+ * @param {string} projectRoot
123
+ * @param {string} command
124
+ * @param {number} [maxBytes]
125
+ */
126
+ export function runEvidenceCommand(projectRoot, command, maxBytes = 256 * 1024) {
127
+ if (!command) return { ok: false, skipped: true, output: "" };
128
+
129
+ try {
130
+ const argv = parseEvidenceCommandArgv(command);
131
+ const output = execFileSync(argv[0], argv.slice(1), {
132
+ cwd: projectRoot,
133
+ encoding: "utf-8",
134
+ stdio: ["ignore", "pipe", "pipe"],
135
+ timeout: 10 * 60 * 1000,
136
+ maxBuffer: maxBytes,
137
+ });
138
+ return { ok: true, skipped: false, output: String(output ?? "") };
139
+ } catch (err) {
140
+ if (err instanceof EvidenceCommandError) {
141
+ return {
142
+ ok: false,
143
+ skipped: false,
144
+ output: `[rejected] ${err.message}`,
145
+ };
146
+ }
147
+
148
+ const stdout = err && typeof err === "object" && "stdout" in err ? String(err.stdout ?? "") : "";
149
+ const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr ?? "") : "";
150
+ const message = err instanceof Error ? err.message : String(err);
151
+ return {
152
+ ok: false,
153
+ skipped: false,
154
+ output: `${stdout}${stderr}\n[exit] ${message}`.trim(),
155
+ };
156
+ }
157
+ }