pi-spine 2.1.0 → 2.3.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 (49) hide show
  1. package/bin/spine-batch.mjs +74 -5
  2. package/bin/spine-cli/verify.mjs +2 -18
  3. package/package.json +1 -1
  4. package/src/batch/attached-runner-promote.mjs +370 -0
  5. package/src/batch/attached-runner-reconcile.mjs +291 -0
  6. package/src/batch/attached-runner.mjs +24 -634
  7. package/src/batch/batch-guards.mjs +69 -0
  8. package/src/batch/contract-exec.mjs +483 -0
  9. package/src/batch/contract-parse.mjs +243 -0
  10. package/src/batch/contract-verify.mjs +32 -707
  11. package/src/batch/detached-diagnostics.mjs +255 -0
  12. package/src/batch/detached-run.mjs +326 -0
  13. package/src/batch/detached-start.mjs +18 -894
  14. package/src/batch/detached-wait.mjs +346 -0
  15. package/src/batch/engine-lanes/merge.mjs +25 -0
  16. package/src/batch/engine.mjs +8 -67
  17. package/src/batch/integrate-git.mjs +21 -0
  18. package/src/batch/integrate.mjs +5 -15
  19. package/src/batch/journal-rebuild-structural.mjs +352 -0
  20. package/src/batch/journal-rebuild.mjs +94 -347
  21. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  22. package/src/batch/lane-dirty-check-git.mjs +298 -0
  23. package/src/batch/lane-dirty-check.mjs +31 -297
  24. package/src/batch/reconcile-batch.mjs +483 -0
  25. package/src/batch/reconcile-classify.mjs +433 -0
  26. package/src/batch/reconcile-diagnosis.mjs +459 -0
  27. package/src/batch/reconcile-light-cache.mjs +61 -0
  28. package/src/batch/reconcile-orphan.mjs +198 -0
  29. package/src/batch/reconcile.mjs +19 -1693
  30. package/src/batch/resume-multi-lanes.mjs +44 -149
  31. package/src/batch/resume-multi-queue.mjs +159 -0
  32. package/src/batch/resume-single-validate.mjs +25 -0
  33. package/src/batch/resume.mjs +3 -20
  34. package/src/batch/review-artifacts.mjs +419 -0
  35. package/src/batch/review-step-run.mjs +383 -0
  36. package/src/batch/review-step.mjs +451 -0
  37. package/src/batch/review.mjs +32 -1199
  38. package/src/batch/salvage-batch-list.mjs +291 -0
  39. package/src/batch/salvage-batch.mjs +417 -0
  40. package/src/batch/sequence-plan.mjs +234 -0
  41. package/src/batch/sequence-run.mjs +418 -0
  42. package/src/batch/sequence-wait.mjs +167 -0
  43. package/src/batch/sequence.mjs +22 -783
  44. package/src/batch/state-guards.mjs +284 -0
  45. package/src/batch/state-io.mjs +135 -0
  46. package/src/batch/state.mjs +27 -396
  47. package/src/batch/worker-heartbeat.mjs +375 -0
  48. package/src/batch/worker-host.mjs +50 -541
  49. package/src/batch/worker-spawn.mjs +315 -0
@@ -0,0 +1,255 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Detached batch failure diagnostics — log tails, worker paths, formatted output (SP-580).
4
+ * Leaf module: no imports from detached-start, reconcile, or post-merge-limbo.
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import {
10
+ DETACHED_ENGINE_LOG_REL,
11
+ detachedEngineLogPath,
12
+ } from "./detached-spawn.mjs";
13
+ import { readLastTaskFailedEvent } from "./journal.mjs";
14
+
15
+ export const FAILURE_LOG_TAIL_LINES = 20;
16
+
17
+ const DETACHED_ENGINE_LOG_HEADER_RE = /^--- detached batch engine /;
18
+
19
+ /**
20
+ * @param {string} filePath
21
+ * @param {number} [lineCount]
22
+ * @returns {string|null}
23
+ */
24
+ function readLogTailLines(filePath, lineCount = FAILURE_LOG_TAIL_LINES) {
25
+ if (!fs.existsSync(filePath)) return null;
26
+ const content = fs.readFileSync(filePath, "utf-8");
27
+ const lines = content.split("\n");
28
+ if (lines.at(-1) === "") lines.pop();
29
+ if (lines.length === 0) return null;
30
+ return lines.slice(-lineCount).join("\n");
31
+ }
32
+
33
+ /**
34
+ * Read tail of detached engine log, scoped to the current (last) batch session.
35
+ * The append-only log contains headers like `--- detached batch engine <ISO> argv=... ---`
36
+ * separating sessions. Without filtering, stale entries from previous batches are shown.
37
+ *
38
+ * @param {string} filePath
39
+ * @param {number} [lineCount]
40
+ * @returns {string|null}
41
+ */
42
+ export function readCurrentBatchLogTail(filePath, lineCount = FAILURE_LOG_TAIL_LINES) {
43
+ if (!fs.existsSync(filePath)) return null;
44
+ const content = fs.readFileSync(filePath, "utf-8");
45
+ const lines = content.split("\n");
46
+ if (lines.at(-1) === "") lines.pop();
47
+ if (lines.length === 0) return null;
48
+
49
+ let lastHeaderIdx = -1;
50
+ for (let i = lines.length - 1; i >= 0; i--) {
51
+ if (DETACHED_ENGINE_LOG_HEADER_RE.test(lines[i])) {
52
+ lastHeaderIdx = i;
53
+ break;
54
+ }
55
+ }
56
+
57
+ const sessionLines = lastHeaderIdx >= 0 ? lines.slice(lastHeaderIdx) : lines;
58
+ if (sessionLines.length === 0) return null;
59
+ return sessionLines.slice(-lineCount).join("\n");
60
+ }
61
+
62
+ /**
63
+ * @param {string} projectRoot
64
+ * @param {string} batchId
65
+ * @param {string|null|undefined} taskId
66
+ * @returns {string|null}
67
+ */
68
+ function findWorkerOutputLogPath(projectRoot, batchId, taskId) {
69
+ const lanesDir = path.join(projectRoot, ".spine", "runtime", batchId, "lanes");
70
+ if (!fs.existsSync(lanesDir)) return null;
71
+
72
+ /** @type {string|null} */
73
+ let newestPath = null;
74
+ /** @type {number} */
75
+ let newestMtime = 0;
76
+
77
+ for (const laneDir of fs.readdirSync(lanesDir)) {
78
+ if (!laneDir.startsWith("lane-")) continue;
79
+ const lanePath = path.join(lanesDir, laneDir);
80
+ for (const name of fs.readdirSync(lanePath)) {
81
+ if (!name.startsWith("worker-output-") || !name.endsWith(".log")) continue;
82
+ if (taskId && name !== `worker-output-${taskId}.log`) continue;
83
+ const candidate = path.join(lanePath, name);
84
+ const mtime = fs.statSync(candidate).mtimeMs;
85
+ if (mtime >= newestMtime) {
86
+ newestMtime = mtime;
87
+ newestPath = candidate;
88
+ }
89
+ }
90
+ }
91
+
92
+ return newestPath;
93
+ }
94
+
95
+ /**
96
+ * @param {object} event
97
+ */
98
+ function summarizeTaskFailedEvent(event) {
99
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
100
+ /** @type {string[]} */
101
+ const parts = [];
102
+ if (event.taskId) parts.push(`task ${event.taskId}`);
103
+ if (payload.classification) parts.push(String(payload.classification));
104
+ if (payload.error) parts.push(String(payload.error).slice(0, 120));
105
+ if (payload.output) parts.push(String(payload.output).slice(0, 120));
106
+ if (payload.reason) parts.push(String(payload.reason));
107
+ return parts.join(" — ") || JSON.stringify(payload).slice(0, 160);
108
+ }
109
+
110
+ /**
111
+ * @param {object} params
112
+ * @param {string} params.projectRoot
113
+ * @param {string|null|undefined} [params.batchId]
114
+ * @param {string|null|undefined} [params.taskId]
115
+ * @param {string|null|undefined} [params.logPath]
116
+ */
117
+ export function collectDetachedFailureDiagnostics({ projectRoot, batchId, taskId, logPath }) {
118
+ /** @type {Record<string, unknown>} */
119
+ const diagnostics = {};
120
+
121
+ if (batchId) {
122
+ const failedEvent = readLastTaskFailedEvent(projectRoot, batchId);
123
+ if (failedEvent) {
124
+ diagnostics.taskFailedEvent = failedEvent;
125
+ diagnostics.taskFailedSummary = summarizeTaskFailedEvent(failedEvent);
126
+ }
127
+ }
128
+
129
+ if (batchId) {
130
+ const workerLogPath = findWorkerOutputLogPath(projectRoot, batchId, taskId ?? null);
131
+ if (workerLogPath) {
132
+ const tail = readLogTailLines(workerLogPath);
133
+ if (tail) {
134
+ diagnostics.workerLogPath = path.relative(projectRoot, workerLogPath);
135
+ diagnostics.workerLogTail = tail;
136
+ }
137
+ }
138
+ }
139
+
140
+ const engineLogPath = logPath
141
+ ? path.isAbsolute(logPath)
142
+ ? logPath
143
+ : path.join(projectRoot, logPath)
144
+ : detachedEngineLogPath(projectRoot);
145
+ const engineTail = readCurrentBatchLogTail(engineLogPath);
146
+ if (engineTail) {
147
+ diagnostics.engineLogPath = path.isAbsolute(logPath ?? "")
148
+ ? logPath
149
+ : logPath ?? DETACHED_ENGINE_LOG_REL;
150
+ diagnostics.engineLogTail = engineTail;
151
+ }
152
+
153
+ return diagnostics;
154
+ }
155
+
156
+ /**
157
+ * @param {Record<string, unknown>} payload
158
+ * @param {object} params
159
+ * @param {string} params.projectRoot
160
+ * @param {string|null|undefined} [params.batchId]
161
+ * @param {string|null|undefined} [params.taskId]
162
+ * @param {string|null|undefined} [params.logPath]
163
+ */
164
+ export function attachDetachedFailureDiagnostics(payload, { projectRoot, batchId, taskId, logPath }) {
165
+ const diagnostics = collectDetachedFailureDiagnostics({ projectRoot, batchId, taskId, logPath });
166
+ if (diagnostics.taskFailedSummary) payload.taskFailedSummary = diagnostics.taskFailedSummary;
167
+ if (diagnostics.workerLogTail) {
168
+ payload.workerLogPath = diagnostics.workerLogPath;
169
+ payload.workerLogTail = diagnostics.workerLogTail;
170
+ }
171
+ if (diagnostics.engineLogTail) {
172
+ payload.engineLogPath = diagnostics.engineLogPath;
173
+ payload.engineLogTail = diagnostics.engineLogTail;
174
+ }
175
+ return payload;
176
+ }
177
+
178
+ /**
179
+ * @param {object} result
180
+ * @param {boolean} [json]
181
+ */
182
+ export function formatDetachedEngineOutput(result, json = false) {
183
+ if (json) {
184
+ return `${JSON.stringify(result, null, 2)}\n`;
185
+ }
186
+
187
+ const operation = result.operation ?? "start";
188
+ const operationLabel = operation === "resume" ? "resume" : "start";
189
+
190
+ if (!result.ok) {
191
+ const lines = [
192
+ "",
193
+ `Detached batch ${operationLabel} failed`,
194
+ "",
195
+ result.output ?? result.error ?? "Unknown error",
196
+ ];
197
+ if (result.taskFailedSummary) {
198
+ lines.push("", " Last task.failed:", ` ${result.taskFailedSummary}`);
199
+ }
200
+ if (result.workerLogTail) {
201
+ lines.push(
202
+ "",
203
+ ` Worker log tail${result.workerLogPath ? ` (${result.workerLogPath})` : ""}:`,
204
+ ...result.workerLogTail.split("\n").map((line) => ` ${line}`),
205
+ );
206
+ }
207
+ if (result.engineLogTail) {
208
+ lines.push(
209
+ "",
210
+ ` Detached engine log tail${result.engineLogPath ? ` (${result.engineLogPath})` : ""}:`,
211
+ ...result.engineLogTail.split("\n").map((line) => ` ${line}`),
212
+ );
213
+ }
214
+ if (result.logPath) {
215
+ lines.push("", ` Log: ${result.logPath}`);
216
+ }
217
+ if (result.suggestedCommand) {
218
+ lines.push("", ` → ${result.suggestedCommand}`);
219
+ }
220
+ lines.push("", " Run with --attached for foreground errors.", "");
221
+ return lines.join("\n");
222
+ }
223
+
224
+ /** @type {string} */
225
+ let headline;
226
+ if (result.status === "resume_completed" || result.status === "start_completed") {
227
+ headline =
228
+ operationLabel === "resume"
229
+ ? "Batch resume completed."
230
+ : "Batch start completed.";
231
+ } else if (result.status === "engine_started") {
232
+ headline =
233
+ operationLabel === "resume"
234
+ ? "Batch engine resuming in the background (engine started; resume not yet confirmed)."
235
+ : "Batch engine starting in the background (engine started; batch not yet confirmed).";
236
+ } else {
237
+ headline = `Batch engine ${operationLabel === "resume" ? "resuming" : "starting"} in the background.`;
238
+ }
239
+
240
+ const lines = ["", headline, ""];
241
+ if (result.status) lines.push(` Status: ${result.status}`);
242
+ if (result.scope) lines.push(` Scope: ${result.scope}`);
243
+ if (result.batchId) lines.push(` Batch: ${result.batchId}`);
244
+ if (result.taskId) lines.push(` Task: ${result.taskId}`);
245
+ if (result.phase) lines.push(` Phase: ${result.phase}`);
246
+ if (result.enginePid) lines.push(` Engine PID: ${result.enginePid}`);
247
+ if (result.logPath) lines.push(` Log: ${result.logPath}`);
248
+ lines.push("", ` → ${result.suggestedCommand ?? "spine status --diagnose"}`, "");
249
+ return lines.join("\n");
250
+ }
251
+
252
+ /** @deprecated use formatDetachedEngineOutput */
253
+ export function formatDetachedBatchStartOutput(result, json = false) {
254
+ return formatDetachedEngineOutput(result, json);
255
+ }
@@ -0,0 +1,326 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Detached batch start/resume entrypoints — orchestrates spawn + wait (SP-598).
4
+ */
5
+
6
+ import {
7
+ buildAttachedBatchResumeArgv,
8
+ buildAttachedBatchStartArgv,
9
+ spawnDetachedBatchEngine,
10
+ } from "./detached-spawn.mjs";
11
+ import {
12
+ attachDetachedFailureDiagnostics,
13
+ formatDetachedEngineOutput,
14
+ } from "./detached-diagnostics.mjs";
15
+ import { maybeSpawnSupervisorOnDetachedStart } from "./supervisor-spawn.mjs";
16
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
17
+ import { validateResumeBatch } from "./resume.mjs";
18
+ import { enforceAttachedEngineSingleOwner, finalizeResumePostMergeLimbo } from "./attached-runner.mjs";
19
+ import { loadSpineBatchState } from "./state.mjs";
20
+ import {
21
+ persistDetachedEnginePid,
22
+ prepareDetachedResumeEngineHandoff,
23
+ resolveDetachedWaitTimeoutMs,
24
+ runDetachedStartPreflight,
25
+ waitForDetachedBatchResume,
26
+ waitForDetachedBatchStart,
27
+ } from "./detached-wait.mjs";
28
+
29
+ /**
30
+ * @param {object} params
31
+ * @param {string} params.projectRoot
32
+ * @param {string} params.spineBin
33
+ * @param {string} params.scope
34
+ * @param {boolean} [params.skipPreflight]
35
+ * @param {boolean} [params.forceSuperseded]
36
+ * @param {number|null} [params.waveFilter]
37
+ * @param {boolean} [params.waitTerminal]
38
+ * @param {boolean} [params.json]
39
+ */
40
+ export async function startBatchDetached({
41
+ projectRoot,
42
+ spineBin,
43
+ scope,
44
+ skipPreflight = false,
45
+ forceSuperseded = false,
46
+ waveFilter = null,
47
+ waitTerminal = false,
48
+ json = false,
49
+ }) {
50
+ const preflight = runDetachedStartPreflight({ projectRoot, skipPreflight });
51
+ if (!preflight.ok) {
52
+ const payload = {
53
+ ok: false,
54
+ detached: true,
55
+ operation: "start",
56
+ error: preflight.error,
57
+ output: preflight.output,
58
+ };
59
+ return {
60
+ ok: false,
61
+ exitCode: preflight.exitCode ?? 1,
62
+ output: formatDetachedEngineOutput(payload, json),
63
+ result: payload,
64
+ };
65
+ }
66
+
67
+ const before = loadSpineBatchState(projectRoot);
68
+ const previousBatchId = before.raw?.batchId ?? null;
69
+ const engineLock = enforceAttachedEngineSingleOwner({ projectRoot, force: false, operation: "start" });
70
+ if (!engineLock.ok) {
71
+ const payload = {
72
+ ok: false,
73
+ detached: true,
74
+ operation: "start",
75
+ batchId: engineLock.batchId,
76
+ error: engineLock.error,
77
+ output: engineLock.output,
78
+ enginePid: engineLock.enginePid,
79
+ suggestedCommand: "spine batch resume --attached --force",
80
+ };
81
+ return {
82
+ ok: false,
83
+ exitCode: engineLock.exitCode ?? 1,
84
+ output: formatDetachedEngineOutput(payload, json),
85
+ result: payload,
86
+ };
87
+ }
88
+ const argv = buildAttachedBatchStartArgv({
89
+ scope,
90
+ skipPreflight: true,
91
+ forceSuperseded,
92
+ waveFilter,
93
+ });
94
+ const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });
95
+ persistDetachedEnginePid(projectRoot, enginePid);
96
+ const wait = await waitForDetachedBatchStart({ projectRoot, previousBatchId, waitTerminal });
97
+
98
+ if (!wait.ok) {
99
+ /** @type {Record<string, unknown>} */
100
+ const payload = {
101
+ ok: false,
102
+ detached: true,
103
+ operation: "start",
104
+ scope,
105
+ enginePid,
106
+ logPath,
107
+ error: wait.error,
108
+ batchId: wait.batchId ?? null,
109
+ lastError: wait.lastError ?? null,
110
+ output:
111
+ wait.error === "timeout_waiting_for_batch"
112
+ ? "Engine may still be running or orphaned — run `spine status --diagnose`."
113
+ : `Batch engine exited before running (phase=${wait.phase ?? "unknown"}).`,
114
+ suggestedCommand: "spine status --diagnose",
115
+ };
116
+ attachDetachedFailureDiagnostics(payload, {
117
+ projectRoot,
118
+ batchId: wait.batchId ?? null,
119
+ logPath,
120
+ });
121
+ return {
122
+ ok: false,
123
+ exitCode: 1,
124
+ output: formatDetachedEngineOutput(payload, json),
125
+ result: payload,
126
+ };
127
+ }
128
+
129
+ const configResult = loadSpineConfig(projectRoot);
130
+ const supervisorSpawn = maybeSpawnSupervisorOnDetachedStart({
131
+ projectRoot,
132
+ batchId: wait.batchId,
133
+ config: configResult.config ?? {},
134
+ });
135
+
136
+ const payload = {
137
+ ok: true,
138
+ detached: true,
139
+ operation: "start",
140
+ status: wait.status ?? "engine_started",
141
+ batchId: wait.batchId,
142
+ phase: wait.phase,
143
+ scope,
144
+ enginePid,
145
+ logPath,
146
+ suggestedCommand: "spine status --diagnose",
147
+ supervisorSpawned: supervisorSpawn.spawned === true,
148
+ supervisorPid: supervisorSpawn.supervisorPid ?? null,
149
+ };
150
+ return {
151
+ ok: true,
152
+ exitCode: 0,
153
+ output: formatDetachedEngineOutput(payload, json),
154
+ result: payload,
155
+ };
156
+ }
157
+
158
+ /**
159
+ * @param {object} params
160
+ * @param {string} params.projectRoot
161
+ * @param {string} params.spineBin
162
+ * @param {boolean} [params.force]
163
+ * @param {boolean} [params.waitTerminal]
164
+ * @param {boolean} [params.json]
165
+ */
166
+ export async function resumeBatchDetached({
167
+ projectRoot,
168
+ spineBin,
169
+ force = false,
170
+ waitTerminal = false,
171
+ json = false,
172
+ }) {
173
+ const engineLock = enforceAttachedEngineSingleOwner({ projectRoot, force, operation: "resume" });
174
+ if (!engineLock.ok) {
175
+ const payload = {
176
+ ok: false,
177
+ detached: true,
178
+ operation: "resume",
179
+ batchId: engineLock.batchId,
180
+ error: engineLock.error,
181
+ output: engineLock.output,
182
+ enginePid: engineLock.enginePid,
183
+ suggestedCommand:
184
+ engineLock.error === "concurrent_resume_blocked"
185
+ ? "spine status --diagnose"
186
+ : "spine batch resume --attached --force",
187
+ };
188
+ return {
189
+ ok: false,
190
+ exitCode: engineLock.exitCode ?? 1,
191
+ output: formatDetachedEngineOutput(payload, json),
192
+ result: payload,
193
+ };
194
+ }
195
+ const releaseResumeLock = engineLock.releaseResumeLock;
196
+
197
+ const resumeCheck = validateResumeBatch({ projectRoot, force });
198
+ if (!resumeCheck.ok) {
199
+ releaseResumeLock?.();
200
+ const payload = {
201
+ ok: false,
202
+ detached: true,
203
+ operation: "resume",
204
+ error: resumeCheck.error,
205
+ output: resumeCheck.output,
206
+ batchId: resumeCheck.batchId,
207
+ taskId: resumeCheck.taskId,
208
+ };
209
+ return {
210
+ ok: false,
211
+ exitCode: resumeCheck.exitCode ?? 1,
212
+ output: formatDetachedEngineOutput(payload, json),
213
+ result: payload,
214
+ };
215
+ }
216
+
217
+ const { batchId, updatedAt, taskId } = resumeCheck;
218
+
219
+ if (resumeCheck.postMergeLimbo) {
220
+ const loaded = loadSpineBatchState(projectRoot);
221
+ const state = loaded.raw;
222
+ const finalizeResult = finalizeResumePostMergeLimbo({
223
+ projectRoot,
224
+ state,
225
+ batchId,
226
+ orchBranch: state.orchBranch,
227
+ fromPhase: String(state.phase ?? "running"),
228
+ resumeForced: force,
229
+ });
230
+ releaseResumeLock?.();
231
+ if (!finalizeResult?.ok) {
232
+ const payload = {
233
+ ok: false,
234
+ detached: true,
235
+ operation: "resume",
236
+ batchId,
237
+ taskId,
238
+ error: "post_merge_limbo_finalize_failed",
239
+ output: finalizeResult?.output ?? "Failed to finalize post-merge limbo.\n",
240
+ };
241
+ return {
242
+ ok: false,
243
+ exitCode: 1,
244
+ output: formatDetachedEngineOutput(payload, json),
245
+ result: payload,
246
+ };
247
+ }
248
+
249
+ const payload = {
250
+ ok: true,
251
+ detached: true,
252
+ operation: "resume",
253
+ status: "resume_completed",
254
+ batchId,
255
+ taskId,
256
+ phase: "completed",
257
+ output: finalizeResult.output,
258
+ };
259
+ return {
260
+ ok: true,
261
+ exitCode: 0,
262
+ output: formatDetachedEngineOutput(payload, json),
263
+ result: payload,
264
+ };
265
+ }
266
+
267
+ prepareDetachedResumeEngineHandoff(projectRoot);
268
+ const argv = buildAttachedBatchResumeArgv({ force });
269
+ const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });
270
+ releaseResumeLock?.();
271
+ const waitTimeoutMs = resolveDetachedWaitTimeoutMs(waitTerminal);
272
+ const wait = await waitForDetachedBatchResume({
273
+ projectRoot,
274
+ batchId,
275
+ updatedAtBefore: updatedAt,
276
+ taskId,
277
+ waitTerminal,
278
+ timeoutMs: waitTimeoutMs,
279
+ });
280
+
281
+ if (!wait.ok) {
282
+ /** @type {Record<string, unknown>} */
283
+ const payload = {
284
+ ok: false,
285
+ detached: true,
286
+ operation: "resume",
287
+ batchId,
288
+ taskId,
289
+ enginePid,
290
+ logPath,
291
+ error: wait.error,
292
+ lastError: wait.lastError ?? null,
293
+ output:
294
+ wait.error === "timeout_waiting_for_resume"
295
+ ? "Engine may still be running or orphaned — run `spine status --diagnose`."
296
+ : `Batch resume failed (phase=${wait.phase ?? "unknown"}).`,
297
+ suggestedCommand: "spine status --diagnose",
298
+ };
299
+ attachDetachedFailureDiagnostics(payload, { projectRoot, batchId, taskId, logPath });
300
+ return {
301
+ ok: false,
302
+ exitCode: 1,
303
+ output: formatDetachedEngineOutput(payload, json),
304
+ result: payload,
305
+ };
306
+ }
307
+
308
+ const payload = {
309
+ ok: true,
310
+ detached: true,
311
+ operation: "resume",
312
+ status: wait.status ?? "engine_started",
313
+ batchId: wait.batchId,
314
+ taskId,
315
+ phase: wait.phase,
316
+ enginePid,
317
+ logPath,
318
+ suggestedCommand: "spine status --diagnose",
319
+ };
320
+ return {
321
+ ok: true,
322
+ exitCode: 0,
323
+ output: formatDetachedEngineOutput(payload, json),
324
+ result: payload,
325
+ };
326
+ }