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,778 @@
1
+ /**
2
+ * Detached batch engine spawn — default for `spine batch start` and `spine batch resume`.
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { spawn } from "node:child_process";
8
+ import { loadSpineConfig } from "../../bin/spine-config.mjs";
9
+ import { runBatchPreflight } from "../../bin/spine-preflight.mjs";
10
+ import { loadGateRecord } from "./gate.mjs";
11
+ import { reconcileBatch } from "./reconcile.mjs";
12
+ import { validateResumeBatch } from "./resume.mjs";
13
+ import { readLastTaskFailedEvent } from "./journal.mjs";
14
+ import { terminateStaleDetachedEngine } from "./resume-engine.mjs";
15
+ import {
16
+ ACTIVE_PHASES,
17
+ loadSpineBatchState,
18
+ recordBatchEnginePid,
19
+ saveSpineBatchState,
20
+ TERMINAL_BATCH_PHASES,
21
+ } from "./state.mjs";
22
+
23
+ export const DETACHED_ENGINE_LOG_REL = path.join(".spine", "runtime", "detached-engine.log");
24
+
25
+ /** Diagnoses that benefit from blocking until resume engine reaches terminal phase. */
26
+ const RESUME_WAIT_TERMINAL_DIAGNOSES = new Set([
27
+ "engine_orphaned",
28
+ "worker_orphaned",
29
+ "state_drift",
30
+ ]);
31
+
32
+ /**
33
+ * Default detached resume to --wait-terminal after orphan/drift diagnoses.
34
+ *
35
+ * @param {string} projectRoot
36
+ * @param {boolean} explicitWaitTerminal
37
+ * @param {boolean} noWaitTerminal
38
+ */
39
+ export function resolveDefaultResumeWaitTerminal(
40
+ projectRoot,
41
+ explicitWaitTerminal,
42
+ noWaitTerminal = false,
43
+ ) {
44
+ if (explicitWaitTerminal) return true;
45
+ if (noWaitTerminal) return false;
46
+ const reconciliation = reconcileBatch({ projectRoot });
47
+ const diagnosis = reconciliation.diagnosis;
48
+ if (diagnosis && RESUME_WAIT_TERMINAL_DIAGNOSES.has(diagnosis)) {
49
+ return true;
50
+ }
51
+ return false;
52
+ }
53
+
54
+ /** @type {ReadonlySet<string>} */
55
+ const TERMINAL_TASK_STATUSES = new Set(["succeeded", "failed", "skipped", "aborted"]);
56
+
57
+ const FAILURE_LOG_TAIL_LINES = 20;
58
+
59
+ /**
60
+ * @param {string} filePath
61
+ * @param {number} [lineCount]
62
+ * @returns {string|null}
63
+ */
64
+ function readLogTailLines(filePath, lineCount = FAILURE_LOG_TAIL_LINES) {
65
+ if (!fs.existsSync(filePath)) return null;
66
+ const content = fs.readFileSync(filePath, "utf-8");
67
+ const lines = content.split("\n");
68
+ if (lines.at(-1) === "") lines.pop();
69
+ if (lines.length === 0) return null;
70
+ return lines.slice(-lineCount).join("\n");
71
+ }
72
+
73
+ /**
74
+ * @param {string} projectRoot
75
+ * @param {string} batchId
76
+ * @param {string|null|undefined} taskId
77
+ * @returns {string|null}
78
+ */
79
+ function findWorkerOutputLogPath(projectRoot, batchId, taskId) {
80
+ const lanesDir = path.join(projectRoot, ".spine", "runtime", batchId, "lanes");
81
+ if (!fs.existsSync(lanesDir)) return null;
82
+
83
+ /** @type {string|null} */
84
+ let newestPath = null;
85
+ /** @type {number} */
86
+ let newestMtime = 0;
87
+
88
+ for (const laneDir of fs.readdirSync(lanesDir)) {
89
+ if (!laneDir.startsWith("lane-")) continue;
90
+ const lanePath = path.join(lanesDir, laneDir);
91
+ for (const name of fs.readdirSync(lanePath)) {
92
+ if (!name.startsWith("worker-output-") || !name.endsWith(".log")) continue;
93
+ if (taskId && name !== `worker-output-${taskId}.log`) continue;
94
+ const candidate = path.join(lanePath, name);
95
+ const mtime = fs.statSync(candidate).mtimeMs;
96
+ if (mtime >= newestMtime) {
97
+ newestMtime = mtime;
98
+ newestPath = candidate;
99
+ }
100
+ }
101
+ }
102
+
103
+ return newestPath;
104
+ }
105
+
106
+ /**
107
+ * @param {object} event
108
+ */
109
+ function summarizeTaskFailedEvent(event) {
110
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
111
+ /** @type {string[]} */
112
+ const parts = [];
113
+ if (event.taskId) parts.push(`task ${event.taskId}`);
114
+ if (payload.classification) parts.push(String(payload.classification));
115
+ if (payload.error) parts.push(String(payload.error).slice(0, 120));
116
+ if (payload.output) parts.push(String(payload.output).slice(0, 120));
117
+ if (payload.reason) parts.push(String(payload.reason));
118
+ return parts.join(" — ") || JSON.stringify(payload).slice(0, 160);
119
+ }
120
+
121
+ /**
122
+ * @param {object} params
123
+ * @param {string} params.projectRoot
124
+ * @param {string|null|undefined} [params.batchId]
125
+ * @param {string|null|undefined} [params.taskId]
126
+ * @param {string|null|undefined} [params.logPath]
127
+ */
128
+ export function collectDetachedFailureDiagnostics({ projectRoot, batchId, taskId, logPath }) {
129
+ /** @type {Record<string, unknown>} */
130
+ const diagnostics = {};
131
+
132
+ if (batchId) {
133
+ const failedEvent = readLastTaskFailedEvent(projectRoot, batchId);
134
+ if (failedEvent) {
135
+ diagnostics.taskFailedEvent = failedEvent;
136
+ diagnostics.taskFailedSummary = summarizeTaskFailedEvent(failedEvent);
137
+ }
138
+ }
139
+
140
+ if (batchId) {
141
+ const workerLogPath = findWorkerOutputLogPath(projectRoot, batchId, taskId ?? null);
142
+ if (workerLogPath) {
143
+ const tail = readLogTailLines(workerLogPath);
144
+ if (tail) {
145
+ diagnostics.workerLogPath = path.relative(projectRoot, workerLogPath);
146
+ diagnostics.workerLogTail = tail;
147
+ }
148
+ }
149
+ }
150
+
151
+ const engineLogPath = logPath
152
+ ? path.isAbsolute(logPath)
153
+ ? logPath
154
+ : path.join(projectRoot, logPath)
155
+ : detachedEngineLogPath(projectRoot);
156
+ const engineTail = readLogTailLines(engineLogPath);
157
+ if (engineTail) {
158
+ diagnostics.engineLogPath = path.isAbsolute(logPath ?? "")
159
+ ? logPath
160
+ : logPath ?? DETACHED_ENGINE_LOG_REL;
161
+ diagnostics.engineLogTail = engineTail;
162
+ }
163
+
164
+ return diagnostics;
165
+ }
166
+
167
+ /**
168
+ * @param {Record<string, unknown>} payload
169
+ * @param {object} params
170
+ * @param {string} params.projectRoot
171
+ * @param {string|null|undefined} [params.batchId]
172
+ * @param {string|null|undefined} [params.taskId]
173
+ * @param {string|null|undefined} [params.logPath]
174
+ */
175
+ function attachDetachedFailureDiagnostics(payload, { projectRoot, batchId, taskId, logPath }) {
176
+ const diagnostics = collectDetachedFailureDiagnostics({ projectRoot, batchId, taskId, logPath });
177
+ if (diagnostics.taskFailedSummary) payload.taskFailedSummary = diagnostics.taskFailedSummary;
178
+ if (diagnostics.workerLogTail) {
179
+ payload.workerLogPath = diagnostics.workerLogPath;
180
+ payload.workerLogTail = diagnostics.workerLogTail;
181
+ }
182
+ if (diagnostics.engineLogTail) {
183
+ payload.engineLogPath = diagnostics.engineLogPath;
184
+ payload.engineLogTail = diagnostics.engineLogTail;
185
+ }
186
+ return payload;
187
+ }
188
+
189
+ /**
190
+ * @param {number} ms
191
+ */
192
+ function sleep(ms) {
193
+ return new Promise((resolve) => setTimeout(resolve, ms));
194
+ }
195
+
196
+ /**
197
+ * @param {object|null|undefined} raw
198
+ * @param {string|null|undefined} taskId
199
+ */
200
+ function resumedTaskReachedTerminal(raw, taskId) {
201
+ if (!taskId || !raw || !Array.isArray(raw.tasks)) return false;
202
+ const task = raw.tasks.find((entry) => entry?.taskId === taskId);
203
+ return Boolean(task && TERMINAL_TASK_STATUSES.has(String(task.status ?? "")));
204
+ }
205
+
206
+ /**
207
+ * @param {string} projectRoot
208
+ * @param {object|null|undefined} raw
209
+ */
210
+ function detachedResumeRequiresIntegrateGate(projectRoot, raw) {
211
+ if (!raw?.batchId || String(raw.phase ?? "") !== "completed") {
212
+ return false;
213
+ }
214
+ if (!raw.orchBranch) {
215
+ return false;
216
+ }
217
+ const config = loadSpineConfig(projectRoot).config ?? {};
218
+ return config.gates?.requireBeforeIntegrate === true;
219
+ }
220
+
221
+ /**
222
+ * @param {string} projectRoot
223
+ * @param {object|null|undefined} raw
224
+ */
225
+ function detachedResumeIntegrateGateReady(projectRoot, raw) {
226
+ if (!detachedResumeRequiresIntegrateGate(projectRoot, raw)) {
227
+ return true;
228
+ }
229
+ return Boolean(loadGateRecord(projectRoot, String(raw.batchId)));
230
+ }
231
+
232
+ /**
233
+ * @param {object|null|undefined} raw
234
+ * @param {string|null|undefined} taskId
235
+ * @param {number} updatedAtBefore
236
+ */
237
+ function evaluateDetachedResumeWait(raw, taskId, updatedAtBefore) {
238
+ if (!raw?.batchId) return null;
239
+ const updatedAt = Number(raw.updatedAt ?? 0);
240
+ if (updatedAt <= updatedAtBefore) return null;
241
+
242
+ if (TERMINAL_BATCH_PHASES.has(String(raw.phase ?? ""))) {
243
+ return {
244
+ ok: true,
245
+ status: "resume_completed",
246
+ batchId: raw.batchId,
247
+ phase: raw.phase,
248
+ };
249
+ }
250
+
251
+ if (resumedTaskReachedTerminal(raw, taskId)) {
252
+ return {
253
+ ok: true,
254
+ status: "resume_completed",
255
+ batchId: raw.batchId,
256
+ phase: raw.phase,
257
+ };
258
+ }
259
+
260
+ return null;
261
+ }
262
+
263
+ /**
264
+ * @param {string} projectRoot
265
+ */
266
+ export function detachedEngineLogPath(projectRoot) {
267
+ return path.join(projectRoot, DETACHED_ENGINE_LOG_REL);
268
+ }
269
+
270
+ /**
271
+ * @param {object} params
272
+ * @param {string} params.scope
273
+ * @param {boolean} [params.skipPreflight]
274
+ */
275
+ export function buildAttachedBatchStartArgv({ scope, skipPreflight = false }) {
276
+ const tokens = String(scope ?? "")
277
+ .trim()
278
+ .split(/\s+/)
279
+ .filter(Boolean);
280
+ const args = ["batch", "start", ...tokens, "--attached"];
281
+ if (skipPreflight) args.push("--skip-preflight");
282
+ return args;
283
+ }
284
+
285
+ /**
286
+ * @param {object} params
287
+ * @param {boolean} [params.force]
288
+ */
289
+ export function buildAttachedBatchResumeArgv({ force = false }) {
290
+ const args = ["batch", "resume", "--attached"];
291
+ if (force) args.push("--force");
292
+ return args;
293
+ }
294
+
295
+ /**
296
+ * @param {object} params
297
+ * @param {string} params.projectRoot
298
+ * @param {string} params.spineBin
299
+ * @param {string[]} params.argv
300
+ */
301
+ export function spawnDetachedBatchEngine({ projectRoot, spineBin, argv }) {
302
+ const logPath = detachedEngineLogPath(projectRoot);
303
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
304
+ const logFd = fs.openSync(logPath, "a");
305
+ fs.writeFileSync(
306
+ logFd,
307
+ `\n--- detached batch engine ${new Date().toISOString()} argv=${argv.join(" ")} ---\n`,
308
+ );
309
+
310
+ const child = spawn(process.execPath, [spineBin, ...argv], {
311
+ cwd: projectRoot,
312
+ detached: true,
313
+ stdio: ["ignore", logFd, logFd],
314
+ env: process.env,
315
+ });
316
+ child.unref();
317
+ fs.closeSync(logFd);
318
+
319
+ return { enginePid: child.pid ?? null, logPath: DETACHED_ENGINE_LOG_REL };
320
+ }
321
+
322
+ /**
323
+ * @param {string} projectRoot
324
+ * @param {number|null} enginePid
325
+ */
326
+ function persistDetachedEnginePid(projectRoot, enginePid) {
327
+ const pid = Number(enginePid);
328
+ if (!Number.isFinite(pid) || pid <= 0) return;
329
+ const { raw } = loadSpineBatchState(projectRoot);
330
+ if (!raw) return;
331
+ recordBatchEnginePid(raw, pid);
332
+ saveSpineBatchState(projectRoot, raw);
333
+ }
334
+
335
+ /**
336
+ * Kill a stale detached engine and persist cleared PID before spawning resume engine (SP-254).
337
+ * Resume child records its own PID after terminateStaleDetachedEngine runs in-process.
338
+ *
339
+ * @param {string} projectRoot
340
+ */
341
+ export function prepareDetachedResumeEngineHandoff(projectRoot) {
342
+ const loaded = loadSpineBatchState(projectRoot);
343
+ if (!loaded.raw) {
344
+ return { ok: false, reason: "no_active_batch" };
345
+ }
346
+
347
+ const state = loaded.raw;
348
+ const batchId = String(state.batchId ?? "");
349
+ const fromPhase = String(state.phase ?? "");
350
+ const terminateResult = terminateStaleDetachedEngine({
351
+ projectRoot,
352
+ state,
353
+ batchId,
354
+ fromPhase,
355
+ });
356
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
357
+
358
+ return { ok: true, batchId, fromPhase, terminateResult };
359
+ }
360
+
361
+ /**
362
+ * @param {object} params
363
+ * @param {string} params.projectRoot
364
+ * @param {string | null} [params.previousBatchId]
365
+ * @param {number} [params.timeoutMs]
366
+ * @param {boolean} [params.waitTerminal]
367
+ */
368
+ export async function waitForDetachedBatchStart({
369
+ projectRoot,
370
+ previousBatchId = null,
371
+ timeoutMs = 30_000,
372
+ waitTerminal = false,
373
+ }) {
374
+ const deadline = Date.now() + timeoutMs;
375
+ /** @type {string|null} */
376
+ let startedBatchId = null;
377
+
378
+ while (Date.now() < deadline) {
379
+ const { raw } = loadSpineBatchState(projectRoot);
380
+ const batchId = raw?.batchId ?? null;
381
+ if (batchId && batchId !== previousBatchId) {
382
+ if (raw.phase === "failed" || raw.phase === "aborted") {
383
+ return {
384
+ ok: false,
385
+ error: "batch_engine_failed",
386
+ batchId,
387
+ phase: raw.phase,
388
+ lastError: raw.lastError ?? null,
389
+ };
390
+ }
391
+
392
+ if (TERMINAL_BATCH_PHASES.has(String(raw.phase ?? "")) || raw.phase === "paused") {
393
+ return {
394
+ ok: true,
395
+ status: "start_completed",
396
+ batchId,
397
+ phase: raw.phase,
398
+ };
399
+ }
400
+
401
+ if (ACTIVE_PHASES.has(raw.phase)) {
402
+ startedBatchId = batchId;
403
+ if (!waitTerminal) {
404
+ return {
405
+ ok: true,
406
+ status: "engine_started",
407
+ batchId,
408
+ phase: raw.phase,
409
+ };
410
+ }
411
+ }
412
+ }
413
+ await sleep(200);
414
+ }
415
+
416
+ if (startedBatchId) {
417
+ return {
418
+ ok: false,
419
+ error: "timeout_waiting_for_batch",
420
+ batchId: startedBatchId,
421
+ status: "engine_started",
422
+ };
423
+ }
424
+
425
+ return { ok: false, error: "timeout_waiting_for_batch" };
426
+ }
427
+
428
+ /**
429
+ * @param {object} params
430
+ * @param {string} params.projectRoot
431
+ * @param {string} params.batchId
432
+ * @param {number} params.updatedAtBefore
433
+ * @param {string|null|undefined} [params.taskId]
434
+ * @param {number} [params.timeoutMs]
435
+ * @param {boolean} [params.waitTerminal]
436
+ */
437
+ export async function waitForDetachedBatchResume({
438
+ projectRoot,
439
+ batchId,
440
+ updatedAtBefore,
441
+ taskId = null,
442
+ timeoutMs = 30_000,
443
+ waitTerminal = false,
444
+ }) {
445
+ const deadline = Date.now() + timeoutMs;
446
+ /** @type {boolean} */
447
+ let engineStarted = false;
448
+
449
+ while (Date.now() < deadline) {
450
+ const { raw } = loadSpineBatchState(projectRoot);
451
+ if (raw?.batchId !== batchId) {
452
+ await sleep(200);
453
+ continue;
454
+ }
455
+
456
+ if (raw.phase === "failed" || raw.phase === "aborted") {
457
+ return {
458
+ ok: false,
459
+ error: "batch_engine_failed",
460
+ batchId,
461
+ phase: raw.phase,
462
+ lastError: raw.lastError ?? null,
463
+ };
464
+ }
465
+
466
+ const updatedAt = Number(raw.updatedAt ?? 0);
467
+ if (raw.phase === "running" && updatedAt > updatedAtBefore) {
468
+ engineStarted = true;
469
+ if (!waitTerminal) {
470
+ return {
471
+ ok: true,
472
+ status: "engine_started",
473
+ batchId,
474
+ phase: raw.phase,
475
+ };
476
+ }
477
+ }
478
+
479
+ const completed = evaluateDetachedResumeWait(raw, taskId, updatedAtBefore);
480
+ if (completed && detachedResumeIntegrateGateReady(projectRoot, raw)) {
481
+ return completed;
482
+ }
483
+
484
+ await sleep(200);
485
+ }
486
+
487
+ return {
488
+ ok: false,
489
+ error: "timeout_waiting_for_resume",
490
+ batchId,
491
+ engineStarted,
492
+ };
493
+ }
494
+
495
+ /**
496
+ * @param {object} params
497
+ * @param {string} params.projectRoot
498
+ * @param {boolean} [params.skipPreflight]
499
+ */
500
+ export function runDetachedStartPreflight({ projectRoot, skipPreflight = false }) {
501
+ if (skipPreflight) {
502
+ return { ok: true };
503
+ }
504
+ const preflight = runBatchPreflight({ projectRoot, skipDoctor: false });
505
+ if (!preflight.ok) {
506
+ return {
507
+ ok: false,
508
+ exitCode: preflight.exitCode ?? 1,
509
+ error: "preflight_failed",
510
+ output: preflight.output,
511
+ };
512
+ }
513
+ return { ok: true };
514
+ }
515
+
516
+ /**
517
+ * @param {object} result
518
+ * @param {boolean} [json]
519
+ */
520
+ export function formatDetachedEngineOutput(result, json = false) {
521
+ if (json) {
522
+ return `${JSON.stringify(result, null, 2)}\n`;
523
+ }
524
+
525
+ const operation = result.operation ?? "start";
526
+ const operationLabel = operation === "resume" ? "resume" : "start";
527
+
528
+ if (!result.ok) {
529
+ const lines = [
530
+ "",
531
+ `Detached batch ${operationLabel} failed`,
532
+ "",
533
+ result.output ?? result.error ?? "Unknown error",
534
+ ];
535
+ if (result.taskFailedSummary) {
536
+ lines.push("", " Last task.failed:", ` ${result.taskFailedSummary}`);
537
+ }
538
+ if (result.workerLogTail) {
539
+ lines.push(
540
+ "",
541
+ ` Worker log tail${result.workerLogPath ? ` (${result.workerLogPath})` : ""}:`,
542
+ ...result.workerLogTail.split("\n").map((line) => ` ${line}`),
543
+ );
544
+ }
545
+ if (result.engineLogTail) {
546
+ lines.push(
547
+ "",
548
+ ` Detached engine log tail${result.engineLogPath ? ` (${result.engineLogPath})` : ""}:`,
549
+ ...result.engineLogTail.split("\n").map((line) => ` ${line}`),
550
+ );
551
+ }
552
+ if (result.logPath) {
553
+ lines.push("", ` Log: ${result.logPath}`);
554
+ }
555
+ if (result.suggestedCommand) {
556
+ lines.push("", ` → ${result.suggestedCommand}`);
557
+ }
558
+ lines.push("", " Run with --attached for foreground errors.", "");
559
+ return lines.join("\n");
560
+ }
561
+
562
+ /** @type {string} */
563
+ let headline;
564
+ if (result.status === "resume_completed" || result.status === "start_completed") {
565
+ headline =
566
+ operationLabel === "resume"
567
+ ? "Batch resume completed."
568
+ : "Batch start completed.";
569
+ } else if (result.status === "engine_started") {
570
+ headline =
571
+ operationLabel === "resume"
572
+ ? "Batch engine resuming in the background (engine started; resume not yet confirmed)."
573
+ : "Batch engine starting in the background (engine started; batch not yet confirmed).";
574
+ } else {
575
+ headline = `Batch engine ${operationLabel === "resume" ? "resuming" : "starting"} in the background.`;
576
+ }
577
+
578
+ const lines = ["", headline, ""];
579
+ if (result.status) lines.push(` Status: ${result.status}`);
580
+ if (result.scope) lines.push(` Scope: ${result.scope}`);
581
+ if (result.batchId) lines.push(` Batch: ${result.batchId}`);
582
+ if (result.taskId) lines.push(` Task: ${result.taskId}`);
583
+ if (result.phase) lines.push(` Phase: ${result.phase}`);
584
+ if (result.enginePid) lines.push(` Engine PID: ${result.enginePid}`);
585
+ if (result.logPath) lines.push(` Log: ${result.logPath}`);
586
+ lines.push("", ` → ${result.suggestedCommand ?? "spine status --diagnose"}`, "");
587
+ return lines.join("\n");
588
+ }
589
+
590
+ /** @deprecated use formatDetachedEngineOutput */
591
+ export function formatDetachedBatchStartOutput(result, json = false) {
592
+ return formatDetachedEngineOutput(result, json);
593
+ }
594
+
595
+ /**
596
+ * @param {object} params
597
+ * @param {string} params.projectRoot
598
+ * @param {string} params.spineBin
599
+ * @param {string} params.scope
600
+ * @param {boolean} [params.skipPreflight]
601
+ * @param {boolean} [params.waitTerminal]
602
+ * @param {boolean} [params.json]
603
+ */
604
+ export async function startBatchDetached({
605
+ projectRoot,
606
+ spineBin,
607
+ scope,
608
+ skipPreflight = false,
609
+ waitTerminal = false,
610
+ json = false,
611
+ }) {
612
+ const preflight = runDetachedStartPreflight({ projectRoot, skipPreflight });
613
+ if (!preflight.ok) {
614
+ const payload = {
615
+ ok: false,
616
+ detached: true,
617
+ operation: "start",
618
+ error: preflight.error,
619
+ output: preflight.output,
620
+ };
621
+ return {
622
+ ok: false,
623
+ exitCode: preflight.exitCode ?? 1,
624
+ output: formatDetachedEngineOutput(payload, json),
625
+ result: payload,
626
+ };
627
+ }
628
+
629
+ const before = loadSpineBatchState(projectRoot);
630
+ const previousBatchId = before.raw?.batchId ?? null;
631
+ const argv = buildAttachedBatchStartArgv({ scope, skipPreflight: true });
632
+ const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });
633
+ persistDetachedEnginePid(projectRoot, enginePid);
634
+ const wait = await waitForDetachedBatchStart({ projectRoot, previousBatchId, waitTerminal });
635
+
636
+ if (!wait.ok) {
637
+ /** @type {Record<string, unknown>} */
638
+ const payload = {
639
+ ok: false,
640
+ detached: true,
641
+ operation: "start",
642
+ scope,
643
+ enginePid,
644
+ logPath,
645
+ error: wait.error,
646
+ batchId: wait.batchId ?? null,
647
+ lastError: wait.lastError ?? null,
648
+ output:
649
+ wait.error === "timeout_waiting_for_batch"
650
+ ? "Engine may still be running or orphaned — run `spine status --diagnose`."
651
+ : `Batch engine exited before running (phase=${wait.phase ?? "unknown"}).`,
652
+ suggestedCommand: "spine status --diagnose",
653
+ };
654
+ attachDetachedFailureDiagnostics(payload, {
655
+ projectRoot,
656
+ batchId: wait.batchId ?? null,
657
+ logPath,
658
+ });
659
+ return {
660
+ ok: false,
661
+ exitCode: 1,
662
+ output: formatDetachedEngineOutput(payload, json),
663
+ result: payload,
664
+ };
665
+ }
666
+
667
+ const payload = {
668
+ ok: true,
669
+ detached: true,
670
+ operation: "start",
671
+ status: wait.status ?? "engine_started",
672
+ batchId: wait.batchId,
673
+ phase: wait.phase,
674
+ scope,
675
+ enginePid,
676
+ logPath,
677
+ suggestedCommand: "spine status --diagnose",
678
+ };
679
+ return {
680
+ ok: true,
681
+ exitCode: 0,
682
+ output: formatDetachedEngineOutput(payload, json),
683
+ result: payload,
684
+ };
685
+ }
686
+
687
+ /**
688
+ * @param {object} params
689
+ * @param {string} params.projectRoot
690
+ * @param {string} params.spineBin
691
+ * @param {boolean} [params.force]
692
+ * @param {boolean} [params.waitTerminal]
693
+ * @param {boolean} [params.json]
694
+ */
695
+ export async function resumeBatchDetached({
696
+ projectRoot,
697
+ spineBin,
698
+ force = false,
699
+ waitTerminal = false,
700
+ json = false,
701
+ }) {
702
+ const resumeCheck = validateResumeBatch({ projectRoot, force });
703
+ if (!resumeCheck.ok) {
704
+ const payload = {
705
+ ok: false,
706
+ detached: true,
707
+ operation: "resume",
708
+ error: resumeCheck.error,
709
+ output: resumeCheck.output,
710
+ batchId: resumeCheck.batchId,
711
+ taskId: resumeCheck.taskId,
712
+ };
713
+ return {
714
+ ok: false,
715
+ exitCode: resumeCheck.exitCode ?? 1,
716
+ output: formatDetachedEngineOutput(payload, json),
717
+ result: payload,
718
+ };
719
+ }
720
+
721
+ const { batchId, updatedAt, taskId } = resumeCheck;
722
+ prepareDetachedResumeEngineHandoff(projectRoot);
723
+ const argv = buildAttachedBatchResumeArgv({ force });
724
+ const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });
725
+ const wait = await waitForDetachedBatchResume({
726
+ projectRoot,
727
+ batchId,
728
+ updatedAtBefore: updatedAt,
729
+ taskId,
730
+ waitTerminal,
731
+ });
732
+
733
+ if (!wait.ok) {
734
+ /** @type {Record<string, unknown>} */
735
+ const payload = {
736
+ ok: false,
737
+ detached: true,
738
+ operation: "resume",
739
+ batchId,
740
+ taskId,
741
+ enginePid,
742
+ logPath,
743
+ error: wait.error,
744
+ lastError: wait.lastError ?? null,
745
+ output:
746
+ wait.error === "timeout_waiting_for_resume"
747
+ ? "Engine may still be running or orphaned — run `spine status --diagnose`."
748
+ : `Batch resume failed (phase=${wait.phase ?? "unknown"}).`,
749
+ suggestedCommand: "spine status --diagnose",
750
+ };
751
+ attachDetachedFailureDiagnostics(payload, { projectRoot, batchId, taskId, logPath });
752
+ return {
753
+ ok: false,
754
+ exitCode: 1,
755
+ output: formatDetachedEngineOutput(payload, json),
756
+ result: payload,
757
+ };
758
+ }
759
+
760
+ const payload = {
761
+ ok: true,
762
+ detached: true,
763
+ operation: "resume",
764
+ status: wait.status ?? "engine_started",
765
+ batchId: wait.batchId,
766
+ taskId,
767
+ phase: wait.phase,
768
+ enginePid,
769
+ logPath,
770
+ suggestedCommand: "spine status --diagnose",
771
+ };
772
+ return {
773
+ ok: true,
774
+ exitCode: 0,
775
+ output: formatDetachedEngineOutput(payload, json),
776
+ result: payload,
777
+ };
778
+ }