pi-spine 1.2.0 → 1.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 (60) hide show
  1. package/README.md +4 -4
  2. package/bin/spine-cli/verify.mjs +3 -0
  3. package/bin/spine-plan.mjs +49 -1
  4. package/bin/spine-worker-runner.mjs +136 -4
  5. package/package.json +1 -1
  6. package/skills/create-spine-tasks/SKILL.md +7 -2
  7. package/skills/create-spine-tasks/references/contract-template.md +95 -3
  8. package/src/batch/attached-runner.mjs +81 -5
  9. package/src/batch/contract-stub-delivery.mjs +110 -0
  10. package/src/batch/contract-task-start.mjs +204 -0
  11. package/src/batch/contract-verify.mjs +55 -8
  12. package/src/batch/detached-start.mjs +72 -2
  13. package/src/batch/diagnosis-launch-failure.mjs +114 -0
  14. package/src/batch/diagnosis-primary-failure.mjs +89 -0
  15. package/src/batch/diagnosis-tail-state.mjs +57 -0
  16. package/src/batch/diagnosis.mjs +22 -113
  17. package/src/batch/engine-lanes/commit.mjs +145 -0
  18. package/src/batch/engine-lanes/review.mjs +67 -87
  19. package/src/batch/engine-lanes.mjs +21 -79
  20. package/src/batch/engine.mjs +46 -0
  21. package/src/batch/heartbeat.mjs +2 -2
  22. package/src/batch/integrate-assert.mjs +69 -0
  23. package/src/batch/integrate-worktree.mjs +354 -0
  24. package/src/batch/integrate.mjs +195 -102
  25. package/src/batch/journal-rebuild.mjs +48 -2
  26. package/src/batch/journal.mjs +63 -0
  27. package/src/batch/lane-dirty-check.mjs +437 -0
  28. package/src/batch/limbo-detect.mjs +34 -0
  29. package/src/batch/macro-phase.mjs +76 -0
  30. package/src/batch/metrics.mjs +2 -0
  31. package/src/batch/pause.mjs +18 -7
  32. package/src/batch/post-merge-limbo.mjs +3 -28
  33. package/src/batch/reconcile.mjs +79 -9
  34. package/src/batch/resume-common.mjs +27 -0
  35. package/src/batch/resume-multi-lanes.mjs +11 -0
  36. package/src/batch/resume-multi.mjs +2 -0
  37. package/src/batch/resume.mjs +8 -1
  38. package/src/batch/retry.mjs +41 -10
  39. package/src/batch/rules-manifest-drift.mjs +43 -2
  40. package/src/batch/sequence-state.mjs +290 -0
  41. package/src/batch/sequence.mjs +113 -51
  42. package/src/batch/state.mjs +16 -0
  43. package/src/batch/worker-host.mjs +1 -0
  44. package/src/cli/sequence.mjs +14 -1
  45. package/src/cli/settings-set.mjs +33 -3
  46. package/src/config/model-id.mjs +103 -0
  47. package/src/config/spine-init-constants.mjs +1 -0
  48. package/src/config/spine-preflight-lib.mjs +23 -1
  49. package/src/dashboard/public/dashboard.js +14 -3
  50. package/src/dashboard/running-tail-state.mjs +31 -0
  51. package/src/dashboard/server.mjs +4 -0
  52. package/src/dashboard/snapshot.mjs +260 -28
  53. package/src/dashboard/view.mjs +112 -2
  54. package/src/doctor/agent-models.mjs +53 -0
  55. package/src/doctor/batch-size-guidance.mjs +30 -2
  56. package/src/doctor/pi-extension-conflict.mjs +169 -0
  57. package/src/doctor/run-doctor-checks.mjs +6 -0
  58. package/src/planner/scope.mjs +5 -1
  59. package/src/tasks/packet/parse-prompt.mjs +31 -1
  60. package/src/tasks/packet/validate-contract.mjs +108 -0
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Stub delivery-only fileScopeMustChange detection (GitHub #67, SP-407).
3
+ */
4
+
5
+ import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
6
+
7
+ /** Repo roots that indicate implementation scope, not stub delivery. */
8
+ const IMPLEMENTATION_ROOT_PREFIXES = [
9
+ "src/",
10
+ "bin/",
11
+ "tests/",
12
+ "scripts/",
13
+ "docs/",
14
+ ".github/",
15
+ ];
16
+
17
+ /** Exact repo-root files that indicate implementation scope. */
18
+ const IMPLEMENTATION_ROOT_FILES = new Set([
19
+ "package.json",
20
+ "package-lock.json",
21
+ "eslint.config.js",
22
+ ]);
23
+
24
+ /**
25
+ * @param {string} pattern
26
+ */
27
+ function normalizePattern(pattern) {
28
+ return String(pattern ?? "").replace(/\\/g, "/").trim();
29
+ }
30
+
31
+ /**
32
+ * @param {string} tasksRoot
33
+ */
34
+ function escapeRegex(tasksRoot) {
35
+ return normalizePattern(tasksRoot).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
36
+ }
37
+
38
+ /**
39
+ * @param {string} pattern
40
+ */
41
+ export function isImplementationScopePattern(pattern) {
42
+ const normalized = normalizePattern(pattern);
43
+ if (!normalized) {
44
+ return false;
45
+ }
46
+ if (IMPLEMENTATION_ROOT_FILES.has(normalized)) {
47
+ return true;
48
+ }
49
+ for (const prefix of IMPLEMENTATION_ROOT_PREFIXES) {
50
+ if (normalized === prefix.slice(0, -1) || normalized.startsWith(prefix)) {
51
+ return true;
52
+ }
53
+ }
54
+ return false;
55
+ }
56
+
57
+ /**
58
+ * True when a contract path pattern targets only stub delivery artifacts.
59
+ *
60
+ * @param {string} pattern
61
+ * @param {string} [tasksRoot]
62
+ */
63
+ export function isDeliveryArtifactPath(pattern, tasksRoot = DEFAULT_TASKS_ROOT) {
64
+ const normalized = normalizePattern(pattern);
65
+ if (!normalized) {
66
+ return false;
67
+ }
68
+ if (isImplementationScopePattern(normalized)) {
69
+ return false;
70
+ }
71
+
72
+ const root = escapeRegex(tasksRoot);
73
+
74
+ if (new RegExp(`^${root}/\\*/STATUS\\.md$`).test(normalized)) {
75
+ return true;
76
+ }
77
+ if (new RegExp(`^${root}/[^/]+/STATUS\\.md$`).test(normalized)) {
78
+ return true;
79
+ }
80
+ if (new RegExp(`^${root}/\\*/\\.DONE$`).test(normalized)) {
81
+ return true;
82
+ }
83
+ if (new RegExp(`^${root}/[^/]+/\\.DONE$`).test(normalized)) {
84
+ return true;
85
+ }
86
+ if (normalized === ".DONE") {
87
+ return true;
88
+ }
89
+ if (new RegExp(`^${root}/[^/]+/\\*\\*$`).test(normalized)) {
90
+ return true;
91
+ }
92
+ if (new RegExp(`^${root}/[^/]+/.+`).test(normalized) && !normalized.includes("..")) {
93
+ return true;
94
+ }
95
+
96
+ return false;
97
+ }
98
+
99
+ /**
100
+ * True when every fileScopeMustChange pattern is stub delivery-only.
101
+ *
102
+ * @param {string[]} patterns
103
+ * @param {string} [tasksRoot]
104
+ */
105
+ export function isStubDeliveryOnlyScope(patterns, tasksRoot = DEFAULT_TASKS_ROOT) {
106
+ if (!Array.isArray(patterns) || patterns.length === 0) {
107
+ return false;
108
+ }
109
+ return patterns.every((pattern) => isDeliveryArtifactPath(pattern, tasksRoot));
110
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Resolve lane branch HEAD at task.started for scoped contract verify (issue #62, SP-415).
3
+ */
4
+
5
+ import { execFileSync } from "node:child_process";
6
+
7
+ const PAYLOAD_COMMIT_KEYS = ["taskStartCommit", "startCommit", "commitSha", "headCommit", "laneBranchHead"];
8
+
9
+ /**
10
+ * @param {object} event
11
+ * @returns {string|null}
12
+ */
13
+ function readEventCommitSha(event) {
14
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
15
+ for (const key of PAYLOAD_COMMIT_KEYS) {
16
+ const value = payload[key];
17
+ if (typeof value === "string" && value.trim()) {
18
+ return value.trim();
19
+ }
20
+ }
21
+ return null;
22
+ }
23
+
24
+ /**
25
+ * @param {object} event
26
+ * @returns {string|null}
27
+ */
28
+ function readEventLaneId(event) {
29
+ if (typeof event.laneId === "string" && event.laneId) {
30
+ return event.laneId;
31
+ }
32
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
33
+ if (typeof payload.laneId === "string" && payload.laneId) {
34
+ return payload.laneId;
35
+ }
36
+ if (payload.laneNumber != null) {
37
+ return `lane-${payload.laneNumber}`;
38
+ }
39
+ return null;
40
+ }
41
+
42
+ /**
43
+ * @param {object} event
44
+ * @returns {string|null}
45
+ */
46
+ function readEventTaskId(event) {
47
+ if (typeof event.taskId === "string" && event.taskId) {
48
+ return event.taskId;
49
+ }
50
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
51
+ if (typeof payload.taskId === "string" && payload.taskId) {
52
+ return payload.taskId;
53
+ }
54
+ return null;
55
+ }
56
+
57
+ /**
58
+ * @param {object} event
59
+ * @returns {string|null}
60
+ */
61
+ function readEventTimestampIso(event) {
62
+ if (!event || typeof event !== "object") {
63
+ return null;
64
+ }
65
+ const ts = event.timestamp;
66
+ if (typeof ts === "string" && ts.trim()) {
67
+ return ts.trim();
68
+ }
69
+ if (typeof ts === "number" && Number.isFinite(ts)) {
70
+ return new Date(ts).toISOString();
71
+ }
72
+ return null;
73
+ }
74
+
75
+ /**
76
+ * @param {string|null|undefined} eventLaneId
77
+ * @param {string|null|undefined} requestedLaneId
78
+ */
79
+ function lanesMatch(eventLaneId, requestedLaneId) {
80
+ if (!requestedLaneId) {
81
+ return true;
82
+ }
83
+ return eventLaneId === requestedLaneId;
84
+ }
85
+
86
+ /**
87
+ * @param {object} event
88
+ * @param {string|null|undefined} batchId
89
+ */
90
+ function batchMatches(event, batchId) {
91
+ if (!batchId) {
92
+ return true;
93
+ }
94
+ return String(event.batchId ?? "") === batchId;
95
+ }
96
+
97
+ /**
98
+ * @param {object[]} journal
99
+ * @param {string|null|undefined} laneId
100
+ * @param {number} beforeIndex
101
+ * @returns {string|null}
102
+ */
103
+ function resolvePriorLaneCommit(journal, laneId, beforeIndex) {
104
+ for (let index = beforeIndex - 1; index >= 0; index -= 1) {
105
+ const event = journal[index];
106
+ if (String(event?.type ?? "") !== "lane.committed") {
107
+ continue;
108
+ }
109
+ if (!lanesMatch(readEventLaneId(event), laneId)) {
110
+ continue;
111
+ }
112
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
113
+ const sha = payload.commitSha ?? payload.mergeCommit;
114
+ if (typeof sha === "string" && sha.trim()) {
115
+ return sha.trim();
116
+ }
117
+ }
118
+ return null;
119
+ }
120
+
121
+ /**
122
+ * @param {string} worktreePath
123
+ * @param {string} timestampIso
124
+ * @returns {string|null}
125
+ */
126
+ function resolveHeadAtTimestamp(worktreePath, timestampIso) {
127
+ try {
128
+ const output = execFileSync("git", ["rev-list", "-1", `--before=${timestampIso}`, "HEAD"], {
129
+ cwd: worktreePath,
130
+ encoding: "utf-8",
131
+ stdio: ["ignore", "pipe", "pipe"],
132
+ timeout: 30_000,
133
+ }).trim();
134
+ return output || null;
135
+ } catch {
136
+ return null;
137
+ }
138
+ }
139
+
140
+ /**
141
+ * @param {object[]} journal
142
+ * @param {string} taskId
143
+ * @param {string|null|undefined} laneId
144
+ * @param {string|null|undefined} batchId
145
+ * @returns {{ event: object, index: number } | null}
146
+ */
147
+ function findLastTaskStarted(journal, taskId, laneId, batchId) {
148
+ let match = null;
149
+ for (let index = 0; index < journal.length; index += 1) {
150
+ const event = journal[index];
151
+ if (String(event?.type ?? "") !== "task.started") {
152
+ continue;
153
+ }
154
+ if (readEventTaskId(event) !== taskId) {
155
+ continue;
156
+ }
157
+ if (!lanesMatch(readEventLaneId(event), laneId)) {
158
+ continue;
159
+ }
160
+ if (!batchMatches(event, batchId)) {
161
+ continue;
162
+ }
163
+ match = { event, index };
164
+ }
165
+ return match;
166
+ }
167
+
168
+ /**
169
+ * Resolve parent commit SHA at task.started for per-task scoped contract verify.
170
+ * Returns null when unavailable so callers fall back to main...HEAD diff.
171
+ *
172
+ * @param {{ journal: object[], taskId: string, laneId?: string|null, batchId?: string|null, worktreePath?: string|null }} options
173
+ * @returns {string|null}
174
+ */
175
+ export function resolveTaskStartCommit({ journal, taskId, laneId, batchId, worktreePath }) {
176
+ if (!Array.isArray(journal) || !taskId) {
177
+ return null;
178
+ }
179
+
180
+ const started = findLastTaskStarted(journal, taskId, laneId, batchId);
181
+ if (!started) {
182
+ return null;
183
+ }
184
+
185
+ const payloadCommit = readEventCommitSha(started.event);
186
+ if (payloadCommit) {
187
+ return payloadCommit;
188
+ }
189
+
190
+ const eventLaneId = readEventLaneId(started.event);
191
+ const priorLaneCommit = resolvePriorLaneCommit(journal, eventLaneId, started.index);
192
+ if (priorLaneCommit) {
193
+ return priorLaneCommit;
194
+ }
195
+
196
+ if (typeof worktreePath === "string" && worktreePath.trim()) {
197
+ const timestampIso = readEventTimestampIso(started.event);
198
+ if (timestampIso) {
199
+ return resolveHeadAtTimestamp(worktreePath.trim(), timestampIso);
200
+ }
201
+ }
202
+
203
+ return null;
204
+ }
@@ -15,6 +15,9 @@ import {
15
15
 
16
16
  export { resolvePromptRelPath, isFileScopePatternPrelanded, hasSpineTaskDeliveryChanges } from "./contract-prelanded.mjs";
17
17
 
18
+ /** Default stdout/stderr capture limit for contract testCommand (issue #86). */
19
+ export const CONTRACT_TEST_COMMAND_MAX_BUFFER = 10 * 1024 * 1024;
20
+
18
21
  /**
19
22
  * @param {string} taskId
20
23
  * @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
@@ -193,10 +196,15 @@ export function verifyStubFileScopeMustChange(
193
196
  /**
194
197
  * @param {string} worktreePath
195
198
  * @param {string} [baseBranch]
199
+ * @param {string} [sinceCommit] When set, diff `sinceCommit..HEAD` instead of `baseBranch...HEAD`.
196
200
  */
197
- export function listChangedFiles(worktreePath, baseBranch = "main") {
201
+ export function listChangedFiles(worktreePath, baseBranch = "main", sinceCommit = undefined) {
202
+ const scopedSince = String(sinceCommit ?? "").trim();
203
+ const diffRange =
204
+ scopedSince.length > 0 ? `${scopedSince}..HEAD` : `${baseBranch}...HEAD`;
205
+
198
206
  try {
199
- const output = execFileSync("git", ["diff", "--name-only", `${baseBranch}...HEAD`], {
207
+ const output = execFileSync("git", ["diff", "--name-only", diffRange], {
200
208
  cwd: worktreePath,
201
209
  encoding: "utf-8",
202
210
  stdio: ["ignore", "pipe", "pipe"],
@@ -207,6 +215,9 @@ export function listChangedFiles(worktreePath, baseBranch = "main") {
207
215
  .map((line) => line.trim())
208
216
  .filter(Boolean);
209
217
  } catch {
218
+ if (scopedSince.length > 0) {
219
+ return [];
220
+ }
210
221
  try {
211
222
  const output = execFileSync("git", ["diff", "--name-only", "HEAD"], {
212
223
  cwd: worktreePath,
@@ -232,16 +243,32 @@ export function matchesContractPattern(file, pattern) {
232
243
  return micromatch.isMatch(file, pattern, { dot: true });
233
244
  }
234
245
 
246
+ /**
247
+ * @param {number} byteCount
248
+ */
249
+ function formatMaxBufferLabel(byteCount) {
250
+ const mib = byteCount / (1024 * 1024);
251
+ if (mib >= 1 && Number.isInteger(mib)) {
252
+ return `${mib}MB`;
253
+ }
254
+ if (byteCount >= 1024) {
255
+ return `${Math.round(byteCount / 1024)}KB`;
256
+ }
257
+ return `${byteCount}B`;
258
+ }
259
+
235
260
  /**
236
261
  * @param {string} worktreePath
237
262
  * @param {string} command
263
+ * @param {{ maxBuffer?: number }} [options]
238
264
  */
239
- function runContractTestCommand(worktreePath, command) {
265
+ export function runContractTestCommand(worktreePath, command, options = {}) {
240
266
  const trimmed = String(command ?? "").trim();
241
267
  if (!trimmed || trimmed === "true") {
242
268
  return { ok: true, exitCode: 0, output: "" };
243
269
  }
244
270
 
271
+ const maxBuffer = options.maxBuffer ?? CONTRACT_TEST_COMMAND_MAX_BUFFER;
245
272
  const shell = process.env.SHELL || (process.platform === "win32" ? "cmd.exe" : "/bin/sh");
246
273
  const shellFlag = process.platform === "win32" ? "/c" : "-c";
247
274
  const result = spawnSync(shell, [shellFlag, trimmed], {
@@ -249,13 +276,25 @@ function runContractTestCommand(worktreePath, command) {
249
276
  encoding: "utf-8",
250
277
  stdio: ["ignore", "pipe", "pipe"],
251
278
  timeout: 10 * 60 * 1000,
252
- maxBuffer: 256 * 1024,
279
+ maxBuffer,
253
280
  });
254
281
 
255
- const exitCode = Number(result.status ?? 1);
256
282
  const stdout = String(result.stdout ?? "");
257
283
  const stderr = String(result.stderr ?? "");
258
284
  const output = `${stdout}\n${stderr}`;
285
+
286
+ if (result.error?.code === "ENOBUFS") {
287
+ const limitLabel = formatMaxBufferLabel(maxBuffer);
288
+ return {
289
+ ok: false,
290
+ exitCode: Number(result.status ?? 255),
291
+ output,
292
+ bufferOverflow: true,
293
+ summary: `testCommand output exceeded maxBuffer (${limitLabel}); use a scoped testCommand instead of full-suite commands. Command: ${trimmed}`,
294
+ };
295
+ }
296
+
297
+ const exitCode = Number(result.status ?? 1);
259
298
  if (exitCode === 0) {
260
299
  return { ok: true, exitCode: 0, output };
261
300
  }
@@ -342,18 +381,24 @@ function findArtifactMatch(worktreePath, artifactPattern) {
342
381
  * @param {string} worktreePath
343
382
  * @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
344
383
  * @param {object} [config]
384
+ * @param {string} [config.baseBranch]
385
+ * @param {string} [config.sinceCommit] When set, scope file-scope checks to `sinceCommit..HEAD` (serialized lanes).
386
+ * @param {string} [config.taskStartCommit] Alias for `sinceCommit` (SP-415 journal resolution).
345
387
  * @returns {{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }> }}
346
388
  */
347
389
  export function verifyContract(worktreePath, parsedContract, config = {}) {
348
390
  /** @type {Array<{ field: string, ok: boolean, message: string }>} */
349
391
  const checks = [];
350
392
  const baseBranch = config?.baseBranch ?? "main";
351
- const changedFiles = listChangedFiles(worktreePath, baseBranch);
393
+ const sinceCommit = config?.sinceCommit ?? config?.taskStartCommit ?? undefined;
394
+ const changedFiles = listChangedFiles(worktreePath, baseBranch, sinceCommit);
352
395
 
353
396
  let testCommandOutput = "";
354
397
  let testCommandOk = true;
355
398
  if (parsedContract.testCommand) {
356
- const result = runContractTestCommand(worktreePath, parsedContract.testCommand);
399
+ const result = runContractTestCommand(worktreePath, parsedContract.testCommand, {
400
+ maxBuffer: config?.contractTestMaxBuffer,
401
+ });
357
402
  testCommandOutput = result.output;
358
403
  testCommandOk = result.ok;
359
404
  checks.push({
@@ -361,7 +406,9 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
361
406
  ok: result.ok,
362
407
  message: result.ok
363
408
  ? "testCommand passed"
364
- : `Contract testCommand failed (exit ${result.exitCode}): ${result.summary || "(no output)"}`,
409
+ : result.bufferOverflow
410
+ ? `Contract ${result.summary}`
411
+ : `Contract testCommand failed (exit ${result.exitCode}): ${result.summary || "(no output)"}`,
365
412
  });
366
413
  }
367
414
 
@@ -13,7 +13,7 @@ import { validateResumeBatch } from "./resume.mjs";
13
13
  import { assessRunningPhaseResumeEligibility } from "./resume-multi-validate.mjs";
14
14
  import { readLastTaskFailedEvent } from "./journal.mjs";
15
15
  import { prepareOrphanResumeHandoff } from "./resume-engine.mjs";
16
- import { finalizeResumePostMergeLimbo } from "./attached-runner.mjs";
16
+ import { enforceAttachedEngineSingleOwner, finalizeResumePostMergeLimbo } from "./attached-runner.mjs";
17
17
  import {
18
18
  ACTIVE_PHASES,
19
19
  loadSpineBatchState,
@@ -87,6 +87,37 @@ function readLogTailLines(filePath, lineCount = FAILURE_LOG_TAIL_LINES) {
87
87
  return lines.slice(-lineCount).join("\n");
88
88
  }
89
89
 
90
+ const DETACHED_ENGINE_LOG_HEADER_RE = /^--- detached batch engine /;
91
+
92
+ /**
93
+ * Read tail of detached engine log, scoped to the current (last) batch session.
94
+ * The append-only log contains headers like `--- detached batch engine <ISO> argv=... ---`
95
+ * separating sessions. Without filtering, stale entries from previous batches are shown.
96
+ *
97
+ * @param {string} filePath
98
+ * @param {number} [lineCount]
99
+ * @returns {string|null}
100
+ */
101
+ export function readCurrentBatchLogTail(filePath, lineCount = FAILURE_LOG_TAIL_LINES) {
102
+ if (!fs.existsSync(filePath)) return null;
103
+ const content = fs.readFileSync(filePath, "utf-8");
104
+ const lines = content.split("\n");
105
+ if (lines.at(-1) === "") lines.pop();
106
+ if (lines.length === 0) return null;
107
+
108
+ let lastHeaderIdx = -1;
109
+ for (let i = lines.length - 1; i >= 0; i--) {
110
+ if (DETACHED_ENGINE_LOG_HEADER_RE.test(lines[i])) {
111
+ lastHeaderIdx = i;
112
+ break;
113
+ }
114
+ }
115
+
116
+ const sessionLines = lastHeaderIdx >= 0 ? lines.slice(lastHeaderIdx) : lines;
117
+ if (sessionLines.length === 0) return null;
118
+ return sessionLines.slice(-lineCount).join("\n");
119
+ }
120
+
90
121
  /**
91
122
  * @param {string} projectRoot
92
123
  * @param {string} batchId
@@ -170,7 +201,7 @@ export function collectDetachedFailureDiagnostics({ projectRoot, batchId, taskId
170
201
  ? logPath
171
202
  : path.join(projectRoot, logPath)
172
203
  : detachedEngineLogPath(projectRoot);
173
- const engineTail = readLogTailLines(engineLogPath);
204
+ const engineTail = readCurrentBatchLogTail(engineLogPath);
174
205
  if (engineTail) {
175
206
  diagnostics.engineLogPath = path.isAbsolute(logPath ?? "")
176
207
  ? logPath
@@ -671,6 +702,25 @@ export async function startBatchDetached({
671
702
 
672
703
  const before = loadSpineBatchState(projectRoot);
673
704
  const previousBatchId = before.raw?.batchId ?? null;
705
+ const engineLock = enforceAttachedEngineSingleOwner({ projectRoot, force: false, operation: "start" });
706
+ if (!engineLock.ok) {
707
+ const payload = {
708
+ ok: false,
709
+ detached: true,
710
+ operation: "start",
711
+ batchId: engineLock.batchId,
712
+ error: engineLock.error,
713
+ output: engineLock.output,
714
+ enginePid: engineLock.enginePid,
715
+ suggestedCommand: "spine batch resume --attached --force",
716
+ };
717
+ return {
718
+ ok: false,
719
+ exitCode: engineLock.exitCode ?? 1,
720
+ output: formatDetachedEngineOutput(payload, json),
721
+ result: payload,
722
+ };
723
+ }
674
724
  const argv = buildAttachedBatchStartArgv({
675
725
  scope,
676
726
  skipPreflight: true,
@@ -747,6 +797,26 @@ export async function resumeBatchDetached({
747
797
  waitTerminal = false,
748
798
  json = false,
749
799
  }) {
800
+ const engineLock = enforceAttachedEngineSingleOwner({ projectRoot, force, operation: "resume" });
801
+ if (!engineLock.ok) {
802
+ const payload = {
803
+ ok: false,
804
+ detached: true,
805
+ operation: "resume",
806
+ batchId: engineLock.batchId,
807
+ error: engineLock.error,
808
+ output: engineLock.output,
809
+ enginePid: engineLock.enginePid,
810
+ suggestedCommand: "spine batch resume --attached --force",
811
+ };
812
+ return {
813
+ ok: false,
814
+ exitCode: engineLock.exitCode ?? 1,
815
+ output: formatDetachedEngineOutput(payload, json),
816
+ result: payload,
817
+ };
818
+ }
819
+
750
820
  const resumeCheck = validateResumeBatch({ projectRoot, force });
751
821
  if (!resumeCheck.ok) {
752
822
  const payload = {
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Worker launch failure inference for diagnosis headlines (SP-105, SP-421).
3
+ */
4
+ import { isPrimaryTaskFailureExitReason } from "./diagnosis-primary-failure.mjs";
5
+
6
+ /**
7
+ * @param {string} haystack
8
+ * @param {object} [hints]
9
+ * @param {boolean} [hints.launchingPhase]
10
+ * @returns {string|null}
11
+ */
12
+ function classifyLaunchFailureHaystack(haystack, hints = {}) {
13
+ const normalized = haystack.toLowerCase();
14
+
15
+ if (
16
+ normalized.includes("dirtyworktree") ||
17
+ normalized.includes("gitignoreddirtyworktree") ||
18
+ normalized.includes("lane_commit_failed")
19
+ ) {
20
+ return null;
21
+ }
22
+
23
+ if (hints.launchingPhase) {
24
+ if (normalized.includes("pi_spine_root") || normalized.includes("config_pi_spine_root")) {
25
+ return "pi_spine_root";
26
+ }
27
+ return "launch_failed";
28
+ }
29
+
30
+ if (normalized.includes("pi_spine_root") || normalized.includes("config_pi_spine_root")) {
31
+ return "pi_spine_root";
32
+ }
33
+
34
+ if (
35
+ normalized.includes("not a git repository") ||
36
+ normalized.includes("worktree") ||
37
+ normalized.includes("worktreeunhealthy")
38
+ ) {
39
+ return "worktree_unhealthy";
40
+ }
41
+
42
+ return null;
43
+ }
44
+
45
+ /**
46
+ * @param {object|null} failedEvent
47
+ * @param {string|null} exitReason
48
+ * @returns {string|null}
49
+ */
50
+ function classifyLaunchFailureFromEvent(failedEvent, exitReason) {
51
+ const payload = failedEvent?.payload && typeof failedEvent.payload === "object" ? failedEvent.payload : {};
52
+ const haystack = [
53
+ exitReason,
54
+ payload.classification,
55
+ payload.output,
56
+ payload.exitReason,
57
+ ].filter(Boolean).join("\n");
58
+
59
+ return classifyLaunchFailureHaystack(haystack, {
60
+ launchingPhase:
61
+ payload.workerPhase === "launching" || payload.classification === "launch_failed",
62
+ });
63
+ }
64
+
65
+ /**
66
+ * @param {string|null|undefined} outputText
67
+ * @returns {string|null}
68
+ */
69
+ export function inferLaunchFailureFromWorkerOutputTail(outputText) {
70
+ if (!outputText || !String(outputText).trim()) return null;
71
+ return classifyLaunchFailureHaystack(String(outputText));
72
+ }
73
+
74
+ /**
75
+ * @param {object} ctx
76
+ * @param {string|null} [ctx.exitReason]
77
+ * @param {object[]} [ctx.journalEvents]
78
+ * @param {string|null} [ctx.failedTaskId]
79
+ * @returns {string|null}
80
+ */
81
+ export function inferLaunchFailureKind(ctx = {}) {
82
+ const { exitReason, journalEvents, failedTaskId } = ctx;
83
+ if (isPrimaryTaskFailureExitReason(exitReason)) {
84
+ return null;
85
+ }
86
+ if (exitReason === "launch_failed" || exitReason === "worker_launch_failed") {
87
+ return "launch_failed";
88
+ }
89
+
90
+ const kinds = [];
91
+ if (Array.isArray(journalEvents)) {
92
+ const taskFailedEvents = journalEvents.filter((event) => event.type === "task.failed");
93
+ const prioritized = failedTaskId
94
+ ? [
95
+ ...taskFailedEvents.filter(
96
+ (event) => (event.taskId ?? event.payload?.taskId) === failedTaskId,
97
+ ),
98
+ ...taskFailedEvents.filter(
99
+ (event) => (event.taskId ?? event.payload?.taskId) !== failedTaskId,
100
+ ),
101
+ ]
102
+ : taskFailedEvents;
103
+
104
+ for (const failedEvent of prioritized) {
105
+ const kind = classifyLaunchFailureFromEvent(failedEvent, exitReason);
106
+ if (kind) kinds.push(kind);
107
+ }
108
+ }
109
+
110
+ if (kinds.includes("pi_spine_root")) return "pi_spine_root";
111
+ if (kinds.includes("launch_failed")) return "launch_failed";
112
+ if (kinds.includes("worktree_unhealthy")) return "worktree_unhealthy";
113
+ return null;
114
+ }