pi-spine 1.1.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 (126) hide show
  1. package/README.md +4 -4
  2. package/bin/spine-batch.mjs +160 -53
  3. package/bin/spine-cli/batch.mjs +3 -3
  4. package/bin/spine-cli/lane-logs.mjs +24 -0
  5. package/bin/spine-cli/scenarios.mjs +298 -0
  6. package/bin/spine-cli/verify.mjs +3 -0
  7. package/bin/spine-cli/wait.mjs +30 -0
  8. package/bin/spine-cli/watch.mjs +27 -0
  9. package/bin/spine-issue.mjs +196 -0
  10. package/bin/spine-journal.mjs +1 -0
  11. package/bin/spine-plan.mjs +49 -1
  12. package/bin/spine-run.mjs +30 -0
  13. package/bin/spine-status.mjs +19 -1
  14. package/bin/spine-tasks.mjs +16 -2
  15. package/bin/spine-worker-runner.mjs +144 -12
  16. package/bin/spine.mjs +49 -1
  17. package/package.json +1 -1
  18. package/skills/create-spine-tasks/SKILL.md +7 -2
  19. package/skills/create-spine-tasks/references/contract-template.md +114 -3
  20. package/src/batch/abort.mjs +2 -11
  21. package/src/batch/agent-session-worker.mjs +45 -5
  22. package/src/batch/attached-engine-handoff.mjs +188 -0
  23. package/src/batch/attached-runner.mjs +388 -0
  24. package/src/batch/contract-prelanded.mjs +180 -0
  25. package/src/batch/contract-stub-delivery.mjs +110 -0
  26. package/src/batch/contract-task-start.mjs +204 -0
  27. package/src/batch/contract-verify.mjs +195 -10
  28. package/src/batch/detached-start.mjs +137 -3
  29. package/src/batch/diagnosis-alternatives.mjs +46 -0
  30. package/src/batch/diagnosis-launch-failure.mjs +114 -0
  31. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  32. package/src/batch/diagnosis-primary-failure.mjs +89 -0
  33. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  34. package/src/batch/diagnosis-stub.mjs +109 -0
  35. package/src/batch/diagnosis-tail-state.mjs +57 -0
  36. package/src/batch/diagnosis-task-done.mjs +110 -0
  37. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  38. package/src/batch/diagnosis.mjs +140 -164
  39. package/src/batch/engine-lanes/commit.mjs +145 -0
  40. package/src/batch/engine-lanes/merge.mjs +110 -82
  41. package/src/batch/engine-lanes/queue.mjs +4 -1
  42. package/src/batch/engine-lanes/review.mjs +67 -87
  43. package/src/batch/engine-lanes/watch.mjs +29 -0
  44. package/src/batch/engine-lanes.mjs +21 -78
  45. package/src/batch/engine-scope.mjs +11 -1
  46. package/src/batch/engine.mjs +125 -24
  47. package/src/batch/evidence.mjs +78 -15
  48. package/src/batch/gate.mjs +43 -14
  49. package/src/batch/git-helpers.mjs +96 -0
  50. package/src/batch/heartbeat.mjs +75 -9
  51. package/src/batch/integrate-assert.mjs +69 -0
  52. package/src/batch/integrate-worktree.mjs +354 -0
  53. package/src/batch/integrate.mjs +193 -102
  54. package/src/batch/journal-rebuild.mjs +48 -2
  55. package/src/batch/journal.mjs +66 -0
  56. package/src/batch/lane-commit.mjs +90 -5
  57. package/src/batch/lane-dirty-check.mjs +437 -0
  58. package/src/batch/lifecycle.mjs +130 -3
  59. package/src/batch/limbo-detect.mjs +34 -0
  60. package/src/batch/macro-phase.mjs +302 -0
  61. package/src/batch/merge/adoption-doc-merge.mjs +93 -10
  62. package/src/batch/merge/wave-merge-state.mjs +3 -0
  63. package/src/batch/metrics.mjs +76 -5
  64. package/src/batch/orphan-detect.mjs +74 -0
  65. package/src/batch/pause.mjs +234 -0
  66. package/src/batch/post-merge-limbo.mjs +259 -28
  67. package/src/batch/reconcile.mjs +508 -63
  68. package/src/batch/resume-common.mjs +32 -1
  69. package/src/batch/resume-lane-reviews.mjs +16 -0
  70. package/src/batch/resume-multi-lanes.mjs +67 -1
  71. package/src/batch/resume-multi-validate.mjs +67 -6
  72. package/src/batch/resume-multi.mjs +11 -4
  73. package/src/batch/resume.mjs +59 -45
  74. package/src/batch/retry.mjs +97 -15
  75. package/src/batch/review-spawn.mjs +8 -2
  76. package/src/batch/rules-manifest-drift.mjs +198 -0
  77. package/src/batch/salvage.mjs +2 -1
  78. package/src/batch/sequence-state.mjs +290 -0
  79. package/src/batch/sequence.mjs +516 -0
  80. package/src/batch/state.mjs +34 -3
  81. package/src/batch/status-json.mjs +67 -0
  82. package/src/batch/task-stall-budget.mjs +22 -10
  83. package/src/batch/worker-host.mjs +96 -7
  84. package/src/batch/worker-output.mjs +196 -3
  85. package/src/cli/issue-draft.mjs +180 -0
  86. package/src/cli/journal-follow.mjs +239 -0
  87. package/src/cli/lane-logs.mjs +291 -0
  88. package/src/cli/sequence.mjs +121 -0
  89. package/src/cli/settings-set.mjs +35 -24
  90. package/src/cli/wait.mjs +187 -0
  91. package/src/cli/watch.mjs +160 -0
  92. package/src/config/agent-model-resolve.mjs +48 -0
  93. package/src/config/cursor-rules/discover.mjs +3 -21
  94. package/src/config/defaults.mjs +7 -1
  95. package/src/config/model-id.mjs +103 -0
  96. package/src/config/settings-fields.mjs +48 -0
  97. package/src/config/spine-init-constants.mjs +2 -0
  98. package/src/config/spine-preflight-lib.mjs +494 -17
  99. package/src/dashboard/lane-throughput.mjs +351 -0
  100. package/src/dashboard/public/dashboard.css +25 -1
  101. package/src/dashboard/public/dashboard.js +234 -18
  102. package/src/dashboard/public/index.html +14 -2
  103. package/src/dashboard/running-tail-state.mjs +31 -0
  104. package/src/dashboard/server.mjs +8 -0
  105. package/src/dashboard/snapshot.mjs +472 -26
  106. package/src/dashboard/view.mjs +282 -19
  107. package/src/doctor/agent-model-inherit.mjs +61 -6
  108. package/src/doctor/agent-models.mjs +53 -0
  109. package/src/doctor/batch-size-guidance.mjs +30 -2
  110. package/src/doctor/pi-extension-conflict.mjs +169 -0
  111. package/src/doctor/run-doctor-checks.mjs +32 -1
  112. package/src/doctor/sequence-safety.mjs +57 -0
  113. package/src/doctor/stale-worktrees.mjs +102 -0
  114. package/src/fixtures/scenario-registry.mjs +194 -0
  115. package/src/fs/atomic-write.mjs +49 -0
  116. package/src/planner/file-scope.mjs +246 -0
  117. package/src/planner/format-plan.mjs +9 -7
  118. package/src/planner/index.mjs +6 -2
  119. package/src/planner/scope.mjs +5 -1
  120. package/src/planner/wave-scope.mjs +136 -0
  121. package/src/planner/waves.mjs +133 -0
  122. package/src/tasks/packet/index.mjs +1 -0
  123. package/src/tasks/packet/parse-prompt.mjs +73 -2
  124. package/src/tasks/packet/validate-contract.mjs +108 -0
  125. package/src/tasks/packet/validate-prompt.mjs +124 -0
  126. package/templates/spine-config.json +8 -1
@@ -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
+ }
@@ -8,6 +8,15 @@ import { execFileSync, spawnSync } from "node:child_process";
8
8
  import micromatch from "micromatch";
9
9
  import { parseAggregateLineCoverage } from "../../scripts/coverage-parse.mjs";
10
10
  import { resolveContractMode } from "../tasks/packet/validate-contract.mjs";
11
+ import {
12
+ isPrelandedFileScopeSatisfied,
13
+ isStubPrelandedFileScopeSatisfied,
14
+ } from "./contract-prelanded.mjs";
15
+
16
+ export { resolvePromptRelPath, isFileScopePatternPrelanded, hasSpineTaskDeliveryChanges } from "./contract-prelanded.mjs";
17
+
18
+ /** Default stdout/stderr capture limit for contract testCommand (issue #86). */
19
+ export const CONTRACT_TEST_COMMAND_MAX_BUFFER = 10 * 1024 * 1024;
11
20
 
12
21
  /**
13
22
  * @param {string} taskId
@@ -68,13 +77,134 @@ export function shouldRunContractVerifyForWorker(promptMarkdown, parsedContract,
68
77
  return isExitVerificationTask(promptMarkdown);
69
78
  }
70
79
 
80
+ /**
81
+ * @returns {boolean}
82
+ */
83
+ export function isStubWorkerMode() {
84
+ return process.env.SPINE_WORKER_STUB === "1" || process.env.SPINE_WORKER_STUB === "true";
85
+ }
86
+
87
+ /**
88
+ * Legacy stub workers write "Task: stub" in `.DONE` body.
89
+ *
90
+ * @param {string} doneContent
91
+ */
92
+ export function isLegacyStubDoneMarker(doneContent) {
93
+ return /Task:\s*stub/i.test(String(doneContent ?? ""));
94
+ }
95
+
96
+ /**
97
+ * @param {string} donePath
98
+ */
99
+ export function isLegacyStubDoneFile(donePath) {
100
+ if (!fs.existsSync(donePath)) {
101
+ return false;
102
+ }
103
+ return isLegacyStubDoneMarker(fs.readFileSync(donePath, "utf-8"));
104
+ }
105
+
106
+ /**
107
+ * Lane commit enforces `fileScopeMustChange` when stub mode is active or `.DONE` is legacy stub.
108
+ *
109
+ * @param {string} donePath
110
+ */
111
+ export function shouldEnforceStubContractAtLaneCommit(donePath) {
112
+ if (isStubWorkerMode()) {
113
+ return true;
114
+ }
115
+ return isLegacyStubDoneFile(donePath);
116
+ }
117
+
118
+ /**
119
+ * @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
120
+ */
121
+ export function hasReleaseCriticalContract(parsedContract) {
122
+ return (parsedContract?.fileScopeMustChange?.length ?? 0) > 0;
123
+ }
124
+
125
+ /**
126
+ * @param {string} worktreePath
127
+ */
128
+ function listUntrackedFiles(worktreePath) {
129
+ try {
130
+ const output = execFileSync("git", ["ls-files", "-o", "--exclude-standard"], {
131
+ cwd: worktreePath,
132
+ encoding: "utf-8",
133
+ stdio: ["ignore", "pipe", "pipe"],
134
+ timeout: 30_000,
135
+ });
136
+ return output
137
+ .split(/\r?\n/)
138
+ .map((line) => line.trim())
139
+ .filter(Boolean);
140
+ } catch {
141
+ return [];
142
+ }
143
+ }
144
+
145
+ /**
146
+ * @param {string} worktreePath
147
+ * @param {string} baseBranch
148
+ * @param {string[]} [pendingPaths]
149
+ */
150
+ export function listEffectiveChangedFiles(worktreePath, baseBranch = "main", pendingPaths = []) {
151
+ return [
152
+ ...new Set([
153
+ ...listChangedFiles(worktreePath, baseBranch),
154
+ ...pendingPaths,
155
+ ...listUntrackedFiles(worktreePath),
156
+ ]),
157
+ ];
158
+ }
159
+
160
+ /**
161
+ * @param {string} worktreePath
162
+ * @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
163
+ * @param {string} [baseBranch]
164
+ * @param {string[]} [pendingPaths] Uncommitted paths about to be lane-committed
165
+ * @param {object} [config]
166
+ * @returns {{ ok: boolean, failures: string[] }}
167
+ */
168
+ export function verifyStubFileScopeMustChange(
169
+ worktreePath,
170
+ parsedContract,
171
+ baseBranch = "main",
172
+ pendingPaths = [],
173
+ config = {},
174
+ ) {
175
+ const patterns = parsedContract?.fileScopeMustChange ?? [];
176
+ if (patterns.length === 0) {
177
+ return { ok: true, failures: [] };
178
+ }
179
+
180
+ const changedFiles = listEffectiveChangedFiles(worktreePath, baseBranch, pendingPaths);
181
+ /** @type {string[]} */
182
+ const failures = [];
183
+ for (const pattern of patterns) {
184
+ const matched = changedFiles.some((file) => matchesContractPattern(file, pattern));
185
+ if (matched) {
186
+ continue;
187
+ }
188
+ if (isStubPrelandedFileScopeSatisfied(worktreePath, pattern, changedFiles, config, baseBranch)) {
189
+ continue;
190
+ }
191
+ failures.push(`Contract fileScopeMustChange: no matching changes for ${pattern}`);
192
+ }
193
+ return { ok: failures.length === 0, failures };
194
+ }
195
+
71
196
  /**
72
197
  * @param {string} worktreePath
73
198
  * @param {string} [baseBranch]
199
+ * @param {string} [sinceCommit] When set, diff `sinceCommit..HEAD` instead of `baseBranch...HEAD`.
74
200
  */
75
- 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
+
76
206
  try {
77
- const output = execFileSync("git", ["diff", "--name-only", `${baseBranch}...HEAD`], {
207
+ const output = execFileSync("git", ["diff", "--name-only", diffRange], {
78
208
  cwd: worktreePath,
79
209
  encoding: "utf-8",
80
210
  stdio: ["ignore", "pipe", "pipe"],
@@ -85,6 +215,9 @@ export function listChangedFiles(worktreePath, baseBranch = "main") {
85
215
  .map((line) => line.trim())
86
216
  .filter(Boolean);
87
217
  } catch {
218
+ if (scopedSince.length > 0) {
219
+ return [];
220
+ }
88
221
  try {
89
222
  const output = execFileSync("git", ["diff", "--name-only", "HEAD"], {
90
223
  cwd: worktreePath,
@@ -110,16 +243,32 @@ export function matchesContractPattern(file, pattern) {
110
243
  return micromatch.isMatch(file, pattern, { dot: true });
111
244
  }
112
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
+
113
260
  /**
114
261
  * @param {string} worktreePath
115
262
  * @param {string} command
263
+ * @param {{ maxBuffer?: number }} [options]
116
264
  */
117
- function runContractTestCommand(worktreePath, command) {
265
+ export function runContractTestCommand(worktreePath, command, options = {}) {
118
266
  const trimmed = String(command ?? "").trim();
119
267
  if (!trimmed || trimmed === "true") {
120
268
  return { ok: true, exitCode: 0, output: "" };
121
269
  }
122
270
 
271
+ const maxBuffer = options.maxBuffer ?? CONTRACT_TEST_COMMAND_MAX_BUFFER;
123
272
  const shell = process.env.SHELL || (process.platform === "win32" ? "cmd.exe" : "/bin/sh");
124
273
  const shellFlag = process.platform === "win32" ? "/c" : "-c";
125
274
  const result = spawnSync(shell, [shellFlag, trimmed], {
@@ -127,13 +276,25 @@ function runContractTestCommand(worktreePath, command) {
127
276
  encoding: "utf-8",
128
277
  stdio: ["ignore", "pipe", "pipe"],
129
278
  timeout: 10 * 60 * 1000,
130
- maxBuffer: 256 * 1024,
279
+ maxBuffer,
131
280
  });
132
281
 
133
- const exitCode = Number(result.status ?? 1);
134
282
  const stdout = String(result.stdout ?? "");
135
283
  const stderr = String(result.stderr ?? "");
136
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);
137
298
  if (exitCode === 0) {
138
299
  return { ok: true, exitCode: 0, output };
139
300
  }
@@ -220,35 +381,59 @@ function findArtifactMatch(worktreePath, artifactPattern) {
220
381
  * @param {string} worktreePath
221
382
  * @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
222
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).
223
387
  * @returns {{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }> }}
224
388
  */
225
389
  export function verifyContract(worktreePath, parsedContract, config = {}) {
226
390
  /** @type {Array<{ field: string, ok: boolean, message: string }>} */
227
391
  const checks = [];
228
392
  const baseBranch = config?.baseBranch ?? "main";
229
- const changedFiles = listChangedFiles(worktreePath, baseBranch);
393
+ const sinceCommit = config?.sinceCommit ?? config?.taskStartCommit ?? undefined;
394
+ const changedFiles = listChangedFiles(worktreePath, baseBranch, sinceCommit);
230
395
 
231
396
  let testCommandOutput = "";
397
+ let testCommandOk = true;
232
398
  if (parsedContract.testCommand) {
233
- const result = runContractTestCommand(worktreePath, parsedContract.testCommand);
399
+ const result = runContractTestCommand(worktreePath, parsedContract.testCommand, {
400
+ maxBuffer: config?.contractTestMaxBuffer,
401
+ });
234
402
  testCommandOutput = result.output;
403
+ testCommandOk = result.ok;
235
404
  checks.push({
236
405
  field: "testCommand",
237
406
  ok: result.ok,
238
407
  message: result.ok
239
408
  ? "testCommand passed"
240
- : `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)"}`,
241
412
  });
242
413
  }
243
414
 
244
415
  for (const pattern of parsedContract.fileScopeMustChange ?? []) {
245
416
  const matched = changedFiles.some((file) => matchesContractPattern(file, pattern));
417
+ const prelanded = !matched &&
418
+ isPrelandedFileScopeSatisfied(
419
+ worktreePath,
420
+ pattern,
421
+ changedFiles,
422
+ parsedContract,
423
+ config,
424
+ baseBranch,
425
+ { testCommandOk },
426
+ (worktree, artifactPath) => findArtifactMatch(worktree, artifactPath).ok,
427
+ );
428
+ const ok = matched || prelanded;
246
429
  checks.push({
247
430
  field: "fileScopeMustChange",
248
- ok: matched,
431
+ ok,
249
432
  message: matched
250
433
  ? `fileScopeMustChange matched: ${pattern}`
251
- : `Contract fileScopeMustChange: no matching changes for ${pattern}`,
434
+ : prelanded
435
+ ? `fileScopeMustChange pre-landed on ${baseBranch}: ${pattern}`
436
+ : `Contract fileScopeMustChange: no matching changes for ${pattern}`,
252
437
  });
253
438
  }
254
439
 
@@ -13,6 +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 { enforceAttachedEngineSingleOwner, finalizeResumePostMergeLimbo } from "./attached-runner.mjs";
16
17
  import {
17
18
  ACTIVE_PHASES,
18
19
  loadSpineBatchState,
@@ -28,6 +29,7 @@ const RESUME_WAIT_TERMINAL_DIAGNOSES = new Set([
28
29
  "engine_orphaned",
29
30
  "worker_orphaned",
30
31
  "state_drift",
32
+ "needs_integrate",
31
33
  ]);
32
34
 
33
35
  /**
@@ -85,6 +87,37 @@ function readLogTailLines(filePath, lineCount = FAILURE_LOG_TAIL_LINES) {
85
87
  return lines.slice(-lineCount).join("\n");
86
88
  }
87
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
+
88
121
  /**
89
122
  * @param {string} projectRoot
90
123
  * @param {string} batchId
@@ -168,7 +201,7 @@ export function collectDetachedFailureDiagnostics({ projectRoot, batchId, taskId
168
201
  ? logPath
169
202
  : path.join(projectRoot, logPath)
170
203
  : detachedEngineLogPath(projectRoot);
171
- const engineTail = readLogTailLines(engineLogPath);
204
+ const engineTail = readCurrentBatchLogTail(engineLogPath);
172
205
  if (engineTail) {
173
206
  diagnostics.engineLogPath = path.isAbsolute(logPath ?? "")
174
207
  ? logPath
@@ -287,8 +320,14 @@ export function detachedEngineLogPath(projectRoot) {
287
320
  * @param {string} params.scope
288
321
  * @param {boolean} [params.skipPreflight]
289
322
  * @param {boolean} [params.forceSuperseded]
323
+ * @param {number|null} [params.waveFilter]
290
324
  */
291
- export function buildAttachedBatchStartArgv({ scope, skipPreflight = false, forceSuperseded = false }) {
325
+ export function buildAttachedBatchStartArgv({
326
+ scope,
327
+ skipPreflight = false,
328
+ forceSuperseded = false,
329
+ waveFilter = null,
330
+ }) {
292
331
  const tokens = String(scope ?? "")
293
332
  .trim()
294
333
  .split(/\s+/)
@@ -296,6 +335,7 @@ export function buildAttachedBatchStartArgv({ scope, skipPreflight = false, forc
296
335
  const args = ["batch", "start", ...tokens, "--attached"];
297
336
  if (skipPreflight) args.push("--skip-preflight");
298
337
  if (forceSuperseded) args.push("--force-superseded");
338
+ if (waveFilter != null) args.push("--wave", String(waveFilter));
299
339
  return args;
300
340
  }
301
341
 
@@ -629,6 +669,7 @@ export function formatDetachedBatchStartOutput(result, json = false) {
629
669
  * @param {string} params.scope
630
670
  * @param {boolean} [params.skipPreflight]
631
671
  * @param {boolean} [params.forceSuperseded]
672
+ * @param {number|null} [params.waveFilter]
632
673
  * @param {boolean} [params.waitTerminal]
633
674
  * @param {boolean} [params.json]
634
675
  */
@@ -638,6 +679,7 @@ export async function startBatchDetached({
638
679
  scope,
639
680
  skipPreflight = false,
640
681
  forceSuperseded = false,
682
+ waveFilter = null,
641
683
  waitTerminal = false,
642
684
  json = false,
643
685
  }) {
@@ -660,7 +702,31 @@ export async function startBatchDetached({
660
702
 
661
703
  const before = loadSpineBatchState(projectRoot);
662
704
  const previousBatchId = before.raw?.batchId ?? null;
663
- const argv = buildAttachedBatchStartArgv({ scope, skipPreflight: true, forceSuperseded });
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
+ }
724
+ const argv = buildAttachedBatchStartArgv({
725
+ scope,
726
+ skipPreflight: true,
727
+ forceSuperseded,
728
+ waveFilter,
729
+ });
664
730
  const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });
665
731
  persistDetachedEnginePid(projectRoot, enginePid);
666
732
  const wait = await waitForDetachedBatchStart({ projectRoot, previousBatchId, waitTerminal });
@@ -731,6 +797,26 @@ export async function resumeBatchDetached({
731
797
  waitTerminal = false,
732
798
  json = false,
733
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
+
734
820
  const resumeCheck = validateResumeBatch({ projectRoot, force });
735
821
  if (!resumeCheck.ok) {
736
822
  const payload = {
@@ -751,6 +837,54 @@ export async function resumeBatchDetached({
751
837
  }
752
838
 
753
839
  const { batchId, updatedAt, taskId } = resumeCheck;
840
+
841
+ if (resumeCheck.postMergeLimbo) {
842
+ const loaded = loadSpineBatchState(projectRoot);
843
+ const state = loaded.raw;
844
+ const finalizeResult = finalizeResumePostMergeLimbo({
845
+ projectRoot,
846
+ state,
847
+ batchId,
848
+ orchBranch: state.orchBranch,
849
+ fromPhase: String(state.phase ?? "running"),
850
+ resumeForced: force,
851
+ });
852
+ if (!finalizeResult?.ok) {
853
+ const payload = {
854
+ ok: false,
855
+ detached: true,
856
+ operation: "resume",
857
+ batchId,
858
+ taskId,
859
+ error: "post_merge_limbo_finalize_failed",
860
+ output: finalizeResult?.output ?? "Failed to finalize post-merge limbo.\n",
861
+ };
862
+ return {
863
+ ok: false,
864
+ exitCode: 1,
865
+ output: formatDetachedEngineOutput(payload, json),
866
+ result: payload,
867
+ };
868
+ }
869
+
870
+ const payload = {
871
+ ok: true,
872
+ detached: true,
873
+ operation: "resume",
874
+ status: "resume_completed",
875
+ batchId,
876
+ taskId,
877
+ phase: "completed",
878
+ output: finalizeResult.output,
879
+ };
880
+ return {
881
+ ok: true,
882
+ exitCode: 0,
883
+ output: formatDetachedEngineOutput(payload, json),
884
+ result: payload,
885
+ };
886
+ }
887
+
754
888
  prepareDetachedResumeEngineHandoff(projectRoot);
755
889
  const argv = buildAttachedBatchResumeArgv({ force });
756
890
  const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });