pi-spine 1.0.2 → 1.2.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 (129) hide show
  1. package/README.md +61 -489
  2. package/bin/get-version.mjs +1 -13
  3. package/bin/spine-batch.mjs +162 -51
  4. package/bin/spine-cli/batch.mjs +3 -3
  5. package/bin/spine-cli/lane-logs.mjs +24 -0
  6. package/bin/spine-cli/scenarios.mjs +298 -0
  7. package/bin/spine-cli/wait.mjs +30 -0
  8. package/bin/spine-cli/watch.mjs +27 -0
  9. package/bin/spine-config.mjs +1 -212
  10. package/bin/spine-doctor.mjs +2 -418
  11. package/bin/spine-init.mjs +1 -398
  12. package/bin/spine-issue.mjs +196 -0
  13. package/bin/spine-journal.mjs +1 -0
  14. package/bin/spine-preflight.mjs +1 -700
  15. package/bin/spine-review-step.mjs +6 -4
  16. package/bin/spine-run.mjs +30 -0
  17. package/bin/spine-status.mjs +19 -1
  18. package/bin/spine-tasks.mjs +112 -13
  19. package/bin/spine-worker-runner.mjs +24 -14
  20. package/bin/spine.mjs +52 -2
  21. package/extensions/spine/worker-tools.ts +14 -12
  22. package/package.json +5 -2
  23. package/skills/create-spine-tasks/SKILL.md +135 -6
  24. package/skills/create-spine-tasks/references/clarify-template.md +73 -0
  25. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  26. package/skills/create-spine-tasks/references/prompt-template.md +2 -0
  27. package/skills/create-spine-tasks/references/requirements-checklist-template.md +94 -0
  28. package/src/batch/abort.mjs +3 -12
  29. package/src/batch/agent-session-worker.mjs +45 -5
  30. package/src/batch/attached-engine-handoff.mjs +188 -0
  31. package/src/batch/attached-runner.mjs +312 -0
  32. package/src/batch/contract-prelanded.mjs +180 -0
  33. package/src/batch/contract-verify.mjs +140 -2
  34. package/src/batch/detached-start.mjs +105 -7
  35. package/src/batch/diagnosis-alternatives.mjs +46 -0
  36. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  37. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  38. package/src/batch/diagnosis-stub.mjs +109 -0
  39. package/src/batch/diagnosis-task-done.mjs +110 -0
  40. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  41. package/src/batch/diagnosis.mjs +174 -62
  42. package/src/batch/engine-lanes/merge.mjs +168 -77
  43. package/src/batch/engine-lanes/queue.mjs +4 -1
  44. package/src/batch/engine-lanes/review.mjs +32 -74
  45. package/src/batch/engine-lanes/watch.mjs +29 -0
  46. package/src/batch/engine-lanes.mjs +1 -0
  47. package/src/batch/engine-scope.mjs +42 -5
  48. package/src/batch/engine.mjs +115 -68
  49. package/src/batch/evidence.mjs +81 -17
  50. package/src/batch/gate.mjs +46 -17
  51. package/src/batch/git-helpers.mjs +96 -0
  52. package/src/batch/heartbeat.mjs +73 -7
  53. package/src/batch/integrate.mjs +3 -5
  54. package/src/batch/journal.mjs +25 -0
  55. package/src/batch/lane-commit.mjs +90 -5
  56. package/src/batch/lifecycle.mjs +131 -4
  57. package/src/batch/macro-phase.mjs +226 -0
  58. package/src/batch/merge/adoption-doc-merge.mjs +243 -0
  59. package/src/batch/merge/wave-merge-state.mjs +108 -0
  60. package/src/batch/metrics.mjs +74 -5
  61. package/src/batch/orphan-detect.mjs +74 -0
  62. package/src/batch/pause.mjs +223 -0
  63. package/src/batch/post-merge-limbo.mjs +345 -17
  64. package/src/batch/reconcile.mjs +473 -50
  65. package/src/batch/resume-common.mjs +6 -2
  66. package/src/batch/resume-engine.mjs +58 -1
  67. package/src/batch/resume-lane-reviews.mjs +16 -0
  68. package/src/batch/resume-multi-lanes.mjs +56 -1
  69. package/src/batch/resume-multi-validate.mjs +148 -8
  70. package/src/batch/resume-multi.mjs +45 -44
  71. package/src/batch/resume.mjs +64 -47
  72. package/src/batch/retry.mjs +56 -5
  73. package/src/batch/review-shared.mjs +196 -0
  74. package/src/batch/review-spawn.mjs +326 -0
  75. package/src/batch/review.mjs +178 -212
  76. package/src/batch/rules-manifest-drift.mjs +157 -0
  77. package/src/batch/salvage.mjs +2 -1
  78. package/src/batch/sequence.mjs +454 -0
  79. package/src/batch/state.mjs +18 -3
  80. package/src/batch/status-json.mjs +67 -0
  81. package/src/batch/task-stall-budget.mjs +94 -10
  82. package/src/batch/worker-host.mjs +185 -37
  83. package/src/batch/worker-output.mjs +196 -3
  84. package/src/batch/worktree.mjs +10 -0
  85. package/src/cli/handoff.mjs +1 -1
  86. package/src/cli/issue-draft.mjs +180 -0
  87. package/src/cli/journal-follow.mjs +239 -0
  88. package/src/cli/lane-logs.mjs +291 -0
  89. package/src/cli/rules.mjs +1 -1
  90. package/src/cli/sequence.mjs +108 -0
  91. package/src/cli/settings-set.mjs +3 -22
  92. package/src/cli/settings-slash.mjs +27 -5
  93. package/src/cli/wait.mjs +187 -0
  94. package/src/cli/watch.mjs +160 -0
  95. package/src/config/agent-model-resolve.mjs +48 -0
  96. package/src/config/cursor-rules/discover.mjs +3 -21
  97. package/src/config/defaults.mjs +7 -1
  98. package/src/config/settings-fields.mjs +48 -0
  99. package/src/config/spine-config-load.mjs +221 -0
  100. package/src/config/spine-init-constants.mjs +424 -0
  101. package/src/config/spine-preflight-lib.mjs +1180 -0
  102. package/src/dashboard/lane-throughput.mjs +351 -0
  103. package/src/dashboard/public/dashboard.css +25 -1
  104. package/src/dashboard/public/dashboard.js +224 -40
  105. package/src/dashboard/public/index.html +15 -9
  106. package/src/dashboard/server.mjs +4 -0
  107. package/src/dashboard/snapshot.mjs +387 -6
  108. package/src/dashboard/view.mjs +170 -15
  109. package/src/doctor/agent-model-inherit.mjs +61 -6
  110. package/src/doctor/run-doctor-checks.mjs +483 -0
  111. package/src/doctor/sequence-safety.mjs +57 -0
  112. package/src/doctor/stale-path.mjs +22 -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/migrate/taskplane-config.mjs +1 -1
  117. package/src/planner/file-scope.mjs +246 -0
  118. package/src/planner/format-plan.mjs +9 -7
  119. package/src/planner/index.mjs +6 -2
  120. package/src/planner/pending.mjs +92 -1
  121. package/src/planner/wave-scope.mjs +136 -0
  122. package/src/planner/waves.mjs +133 -0
  123. package/src/tasks/analyze/index.mjs +453 -0
  124. package/src/tasks/packet/index.mjs +1 -0
  125. package/src/tasks/packet/parse-prompt.mjs +42 -1
  126. package/src/tasks/packet/validate-prompt.mjs +124 -0
  127. package/src/util/command-exists.mjs +19 -0
  128. package/templates/docs/constitution.md +61 -0
  129. package/templates/spine-config.json +9 -2
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Attached engine post-merge SIGTERM survival (SP-316, GitHub #21).
3
+ *
4
+ * When parent shell/tooling sends SIGTERM after the last merge but before the land
5
+ * loop opens the integrate gate, finalize in-process or spawn a detached resume engine.
6
+ */
7
+
8
+ import path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import {
11
+ buildAttachedBatchResumeArgv,
12
+ spawnDetachedBatchEngine,
13
+ } from "./detached-start.mjs";
14
+ import { loadGateRecord } from "./gate.mjs";
15
+ import { appendJournalEvent } from "./journal.mjs";
16
+ import {
17
+ finalizeBatchForIntegrate,
18
+ isPostMergeLimbo,
19
+ tryFinalizePostMergeLimbo,
20
+ } from "./post-merge-limbo.mjs";
21
+ import {
22
+ clearBatchEnginePid,
23
+ loadSpineBatchState,
24
+ recordBatchEnginePid,
25
+ saveSpineBatchState,
26
+ } from "./state.mjs";
27
+
28
+ const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
29
+
30
+ /** @type {boolean} */
31
+ let shutdownHandlerInstalled = false;
32
+
33
+ /** @type {boolean} */
34
+ let shutdownHandoffInFlight = false;
35
+
36
+ /**
37
+ * @param {string} [spineBin]
38
+ */
39
+ export function resolveDefaultSpineBin(spineBin) {
40
+ if (spineBin && path.isAbsolute(spineBin)) return spineBin;
41
+ if (spineBin) return path.resolve(spineBin);
42
+ return path.join(PACKAGE_ROOT, "bin", "spine.mjs");
43
+ }
44
+
45
+ /**
46
+ * @param {object} params
47
+ * @param {string} params.projectRoot
48
+ * @param {object} params.state
49
+ * @param {string} params.batchId
50
+ */
51
+ function postMergeLimboGateMissing({ projectRoot, state, batchId }) {
52
+ if (String(state.phase ?? "") === "completed") return false;
53
+ if (!isPostMergeLimbo(state)) return false;
54
+ return loadGateRecord(projectRoot, batchId) == null;
55
+ }
56
+
57
+ /**
58
+ * Finalize post-merge limbo in-process when eligible.
59
+ *
60
+ * @param {object} params
61
+ * @param {string} params.projectRoot
62
+ * @param {object} params.state
63
+ * @param {string} params.batchId
64
+ * @param {string} params.orchBranch
65
+ */
66
+ export function finalizeAttachedPostMergeLimbo({ projectRoot, state, batchId, orchBranch }) {
67
+ if (!postMergeLimboGateMissing({ projectRoot, state, batchId })) {
68
+ return null;
69
+ }
70
+ return tryFinalizePostMergeLimbo({
71
+ projectRoot,
72
+ state,
73
+ batchId,
74
+ orchBranch,
75
+ resumed: false,
76
+ });
77
+ }
78
+
79
+ /**
80
+ * @param {object} params
81
+ * @param {string} params.projectRoot
82
+ * @param {string} [params.spineBin]
83
+ * @param {string} [params.signal]
84
+ */
85
+ export function attemptPostMergeLandLoopHandoff({
86
+ projectRoot,
87
+ spineBin,
88
+ signal = "SIGTERM",
89
+ }) {
90
+ if (shutdownHandoffInFlight) {
91
+ return { handled: false, reason: "handoff_in_flight" };
92
+ }
93
+ shutdownHandoffInFlight = true;
94
+
95
+ const loaded = loadSpineBatchState(projectRoot);
96
+ if (!loaded.raw) {
97
+ shutdownHandoffInFlight = false;
98
+ return { handled: false, reason: "no_active_batch" };
99
+ }
100
+
101
+ const state = loaded.raw;
102
+ const batchId = String(state.batchId ?? "");
103
+ const orchBranch = String(state.orchBranch ?? "");
104
+
105
+ if (String(state.phase ?? "") === "completed" || loadGateRecord(projectRoot, batchId)) {
106
+ shutdownHandoffInFlight = false;
107
+ return { handled: true, action: "already_finalized", batchId };
108
+ }
109
+
110
+ if (!isPostMergeLimbo(state)) {
111
+ shutdownHandoffInFlight = false;
112
+ return { handled: false, reason: "not_post_merge_limbo", batchId };
113
+ }
114
+
115
+ const finalizeResult = finalizeAttachedPostMergeLimbo({
116
+ projectRoot,
117
+ state,
118
+ batchId,
119
+ orchBranch,
120
+ });
121
+ if (finalizeResult?.ok) {
122
+ clearBatchEnginePid(state);
123
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
124
+ appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
125
+ signal,
126
+ action: "finalized_in_process",
127
+ });
128
+ shutdownHandoffInFlight = false;
129
+ return {
130
+ handled: true,
131
+ action: "finalized_in_process",
132
+ batchId,
133
+ result: finalizeResult,
134
+ };
135
+ }
136
+
137
+ const resolvedSpineBin = resolveDefaultSpineBin(spineBin);
138
+ const argv = buildAttachedBatchResumeArgv({ force: false });
139
+ const { enginePid, logPath } = spawnDetachedBatchEngine({
140
+ projectRoot,
141
+ spineBin: resolvedSpineBin,
142
+ argv,
143
+ });
144
+
145
+ const fresh = loadSpineBatchState(projectRoot);
146
+ if (fresh.raw && enginePid) {
147
+ recordBatchEnginePid(fresh.raw, enginePid);
148
+ saveSpineBatchState(projectRoot, fresh.raw, { bypassWriteGuard: true });
149
+ }
150
+
151
+ appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
152
+ signal,
153
+ action: "detached_resume_spawned",
154
+ enginePid,
155
+ logPath,
156
+ });
157
+
158
+ shutdownHandoffInFlight = false;
159
+ return {
160
+ handled: true,
161
+ action: "detached_resume_spawned",
162
+ batchId,
163
+ enginePid,
164
+ logPath,
165
+ };
166
+ }
167
+
168
+ /**
169
+ * Install SIGTERM/SIGINT handlers for attached batch engines.
170
+ *
171
+ * @param {object} params
172
+ * @param {string} params.projectRoot
173
+ * @param {string} [params.spineBin]
174
+ */
175
+ export function installAttachedEngineShutdownHandlers({ projectRoot, spineBin }) {
176
+ if (shutdownHandlerInstalled) return;
177
+ shutdownHandlerInstalled = true;
178
+
179
+ const onShutdown = (signal) => {
180
+ const handoff = attemptPostMergeLandLoopHandoff({ projectRoot, spineBin, signal });
181
+ if (handoff.handled) {
182
+ process.exit(0);
183
+ }
184
+ };
185
+
186
+ process.once("SIGTERM", () => onShutdown("SIGTERM"));
187
+ process.once("SIGINT", () => onShutdown("SIGINT"));
188
+ }
@@ -0,0 +1,312 @@
1
+ /**
2
+ * Attached batch foreground runner — milestones, integrate handoff, CLI exit (SP-343, GitHub #34).
3
+ * Post-merge limbo resume fast path (SP-348, GitHub #39).
4
+ */
5
+
6
+ import {
7
+ finalizeAttachedLandLoopBeforeExit,
8
+ finalizeResumedBatchForIntegrate,
9
+ isPostMergeLimbo,
10
+ } from "./post-merge-limbo.mjs";
11
+ import { detectPostMergeLimboForResume } from "./resume-multi-validate.mjs";
12
+ import { terminateStaleDetachedEngine } from "./resume-engine.mjs";
13
+ import { reconcileBatch } from "./reconcile.mjs";
14
+ import { readJournalEvents } from "./journal.mjs";
15
+ import { enforceOperatorPauseOnDisk } from "./pause.mjs";
16
+ import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
17
+
18
+ /** Journal types surfaced on attached stdout during the land loop. */
19
+ export const ATTACHED_LAND_LOOP_MILESTONE_TYPES = new Set([
20
+ "batch.started",
21
+ "task.started",
22
+ "task.completed",
23
+ "task.failed",
24
+ "batch.merge_started",
25
+ "batch.merge_completed",
26
+ "batch.merge_blocked",
27
+ "gate.opened",
28
+ "gate.evidence_collecting",
29
+ "gate.evidence_completed",
30
+ "gate.evidence_failed",
31
+ "batch.land_loop_finalized",
32
+ "batch.completed",
33
+ ]);
34
+
35
+ const ATTACHED_MILESTONE_POLL_MS = 200;
36
+
37
+ /** @type {boolean} */
38
+ let attachedExitHandlersInstalled = false;
39
+
40
+ /**
41
+ * Install journal-aware SIGTERM/SIGINT handlers before attached engine exit (SP-378).
42
+ *
43
+ * @param {object} params
44
+ * @param {string} params.projectRoot
45
+ * @param {string} [params.spineBin]
46
+ */
47
+ export function installAttachedExitFinalizeHandlers({ projectRoot, spineBin }) {
48
+ if (attachedExitHandlersInstalled) return;
49
+ attachedExitHandlersInstalled = true;
50
+
51
+ const onShutdown = (signal) => {
52
+ const handoff = finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal });
53
+ if (handoff.handled) {
54
+ process.exit(0);
55
+ }
56
+ };
57
+
58
+ process.once("SIGTERM", () => onShutdown("SIGTERM"));
59
+ process.once("SIGINT", () => onShutdown("SIGINT"));
60
+ }
61
+
62
+ /**
63
+ * @param {number} ms
64
+ */
65
+ function sleep(ms) {
66
+ return new Promise((resolve) => setTimeout(resolve, ms));
67
+ }
68
+
69
+ /**
70
+ * @param {object} event
71
+ */
72
+ function milestoneEventKey(event) {
73
+ if (typeof event.eventId === "string" && event.eventId) {
74
+ return event.eventId;
75
+ }
76
+ const taskId = typeof event.taskId === "string" ? event.taskId : "";
77
+ const timestamp = typeof event.timestamp === "string" ? event.timestamp : String(event.timestamp ?? "");
78
+ return `${event.type ?? "unknown"}:${timestamp}:${taskId}`;
79
+ }
80
+
81
+ /**
82
+ * @param {object} event
83
+ * @returns {string}
84
+ */
85
+ export function formatAttachedMilestoneLine(event) {
86
+ const type = String(event.type ?? "unknown");
87
+ const taskId = typeof event.taskId === "string" && event.taskId ? ` ${event.taskId}` : "";
88
+ const payload =
89
+ event.payload && typeof event.payload === "object" ? /** @type {Record<string, unknown>} */ (event.payload) : {};
90
+ const waveIndex = payload.waveIndex;
91
+ const waveSuffix =
92
+ typeof waveIndex === "number" &&
93
+ (type === "batch.merge_started" || type === "batch.merge_completed" || type === "batch.merge_blocked")
94
+ ? ` wave=${waveIndex}`
95
+ : "";
96
+ return `[spine] ${type}${taskId}${waveSuffix}\n`;
97
+ }
98
+
99
+ /**
100
+ * @param {object} params
101
+ * @param {string} params.projectRoot
102
+ * @param {(line: string) => void} [params.write]
103
+ * @returns {Promise<{ stop: () => Promise<void> }>}
104
+ */
105
+ export async function startAttachedMilestoneReporter({ projectRoot, write = (line) => process.stdout.write(line) }) {
106
+ /** @type {Set<string>} */
107
+ const printed = new Set();
108
+ let batchId = null;
109
+ let stopped = false;
110
+
111
+ const loop = async () => {
112
+ while (!stopped) {
113
+ enforceOperatorPauseOnDisk(projectRoot);
114
+ if (!batchId) {
115
+ const loaded = loadSpineBatchState(projectRoot);
116
+ batchId = loaded.raw?.batchId ? String(loaded.raw.batchId) : null;
117
+ }
118
+ if (batchId) {
119
+ const events = readJournalEvents(projectRoot, batchId);
120
+ for (const event of events) {
121
+ const key = milestoneEventKey(event);
122
+ if (printed.has(key)) continue;
123
+ if (!ATTACHED_LAND_LOOP_MILESTONE_TYPES.has(String(event.type ?? ""))) continue;
124
+ printed.add(key);
125
+ write(formatAttachedMilestoneLine(event));
126
+ }
127
+ }
128
+ await sleep(ATTACHED_MILESTONE_POLL_MS);
129
+ }
130
+ };
131
+
132
+ const loopPromise = loop();
133
+
134
+ return {
135
+ stop: async () => {
136
+ stopped = true;
137
+ await loopPromise;
138
+ if (batchId) {
139
+ const events = readJournalEvents(projectRoot, batchId);
140
+ for (const event of events) {
141
+ const key = milestoneEventKey(event);
142
+ if (printed.has(key)) continue;
143
+ if (!ATTACHED_LAND_LOOP_MILESTONE_TYPES.has(String(event.type ?? ""))) continue;
144
+ printed.add(key);
145
+ write(formatAttachedMilestoneLine(event));
146
+ }
147
+ }
148
+ },
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Run an attached foreground engine while streaming land-loop journal milestones to stdout.
154
+ *
155
+ * @param {object} params
156
+ * @param {string} params.projectRoot
157
+ * @param {() => Promise<object>} params.runEngine
158
+ * @param {(line: string) => void} [params.write]
159
+ */
160
+ export async function runAttachedBatchEngine({ projectRoot, runEngine, write, spineBin }) {
161
+ installAttachedExitFinalizeHandlers({ projectRoot, spineBin });
162
+ const reporter = await startAttachedMilestoneReporter({ projectRoot, write });
163
+ try {
164
+ const result = await runEngine();
165
+ const handoff = finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal: "exit" });
166
+ if (handoff.handled && handoff.action === "finalized_in_process" && handoff.result) {
167
+ return handoff.result;
168
+ }
169
+ return result;
170
+ } finally {
171
+ await reporter.stop();
172
+ }
173
+ }
174
+
175
+ /**
176
+ * @param {object} result
177
+ * @param {import("./reconcile.mjs").ReconciliationResult} reconciliation
178
+ */
179
+ function resolveAttachedBatchExitCode(result, reconciliation) {
180
+ if (reconciliation.phase === "merge_blocked") {
181
+ return result.exitCode ?? 1;
182
+ }
183
+ return result.exitCode ?? (result.ok ? 0 : 1);
184
+ }
185
+
186
+ /**
187
+ * @param {object} params
188
+ * @param {string} params.projectRoot
189
+ * @param {"start"|"resume"} params.operation
190
+ * @param {object} params.result
191
+ * @param {boolean} [params.json]
192
+ */
193
+ export function formatAttachedBatchCliResult({ projectRoot, operation, result, json = false }) {
194
+ const reconciliation = reconcileBatch({ projectRoot });
195
+ const mergeBlocked = reconciliation.phase === "merge_blocked";
196
+
197
+ if (json) {
198
+ return {
199
+ exitCode: resolveAttachedBatchExitCode(result, reconciliation),
200
+ output: `${JSON.stringify({ ...result, reconciliation }, null, 2)}\n`,
201
+ };
202
+ }
203
+
204
+ const operationLabel = operation === "resume" ? "resumed" : "started";
205
+ const headline = result.ok
206
+ ? `Batch ${operationLabel}`
207
+ : mergeBlocked && reconciliation.headline
208
+ ? reconciliation.headline
209
+ : operation === "resume"
210
+ ? "Batch resume failed"
211
+ : "Batch start failed";
212
+
213
+ /** @type {string[]} */
214
+ const lines = ["", headline, ""];
215
+
216
+ if (result.output) {
217
+ lines.push(result.output.trimEnd());
218
+ } else if (result.error && !mergeBlocked) {
219
+ lines.push(String(result.error));
220
+ }
221
+
222
+ if (reconciliation.headline && reconciliation.headline !== headline) {
223
+ lines.push("", reconciliation.headline);
224
+ }
225
+ if (reconciliation.suggestedCommand) {
226
+ lines.push("", ` → ${reconciliation.suggestedCommand}`);
227
+ }
228
+ if (reconciliation.alternatives?.length) {
229
+ lines.push("", " Alternatives:");
230
+ for (const alt of reconciliation.alternatives) {
231
+ lines.push(` • ${alt}`);
232
+ }
233
+ }
234
+
235
+ if (result.batchId) {
236
+ lines.push("", ` Batch: ${result.batchId}`);
237
+ }
238
+ if (result.taskId) {
239
+ lines.push(` Task: ${result.taskId}`);
240
+ }
241
+
242
+ lines.push("");
243
+ return {
244
+ exitCode: resolveAttachedBatchExitCode(result, reconciliation),
245
+ output: lines.join("\n"),
246
+ };
247
+ }
248
+
249
+ /**
250
+ * Write attached CLI output and exit so the foreground process does not linger after batch.completed.
251
+ *
252
+ * @param {{ exitCode?: number, output?: string }} cli
253
+ * @param {object} [options]
254
+ * @param {boolean} [options.deferExit]
255
+ */
256
+ export function finishAttachedBatchCli(cli, { deferExit = false, projectRoot, spineBin } = {}) {
257
+ const exitCode = cli.exitCode ?? 1;
258
+ if (cli.output) {
259
+ process.stdout.write(cli.output);
260
+ }
261
+ if (deferExit) {
262
+ return;
263
+ }
264
+ if (projectRoot) {
265
+ finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal: "cli_exit" });
266
+ }
267
+ process.exit(exitCode);
268
+ }
269
+
270
+ /**
271
+ * Finalize post-merge limbo during resume without re-running workers.
272
+ *
273
+ * @param {object} params
274
+ * @param {string} params.projectRoot
275
+ * @param {object} params.state
276
+ * @param {string} params.batchId
277
+ * @param {string} params.orchBranch
278
+ * @param {string} [params.fromPhase]
279
+ * @param {boolean} [params.resumeForced]
280
+ * @returns {ReturnType<typeof finalizeResumedBatchForIntegrate>|null}
281
+ */
282
+ export function finalizeResumePostMergeLimbo({
283
+ projectRoot,
284
+ state,
285
+ batchId,
286
+ orchBranch,
287
+ fromPhase = "running",
288
+ resumeForced = false,
289
+ }) {
290
+ if (String(state.phase ?? "") === "completed") {
291
+ return null;
292
+ }
293
+ if (!detectPostMergeLimboForResume({ projectRoot, state }) && !isPostMergeLimbo(state)) {
294
+ return null;
295
+ }
296
+
297
+ terminateStaleDetachedEngine({
298
+ projectRoot,
299
+ state,
300
+ batchId,
301
+ fromPhase,
302
+ });
303
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
304
+
305
+ return finalizeResumedBatchForIntegrate({
306
+ projectRoot,
307
+ state,
308
+ batchId,
309
+ orchBranch,
310
+ resumeForced,
311
+ });
312
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Pre-landed fileScopeMustChange satisfaction (issue #56, SP-373).
3
+ */
4
+
5
+ import path from "node:path";
6
+ import { execFileSync } from "node:child_process";
7
+ import micromatch from "micromatch";
8
+ import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
9
+
10
+ /**
11
+ * @param {string} file
12
+ * @param {string} pattern
13
+ */
14
+ function matchesPattern(file, pattern) {
15
+ return micromatch.isMatch(file, pattern, { dot: true });
16
+ }
17
+
18
+ /**
19
+ * @param {string} worktreePath
20
+ * @param {string} relPath
21
+ */
22
+ function gitFirstCommitTouchingPath(worktreePath, relPath) {
23
+ try {
24
+ const output = execFileSync("git", ["log", "--reverse", "--format=%H", "--", relPath], {
25
+ cwd: worktreePath,
26
+ encoding: "utf-8",
27
+ stdio: ["ignore", "pipe", "pipe"],
28
+ timeout: 10_000,
29
+ }).trim();
30
+ return output.split(/\r?\n/).map((line) => line.trim()).find(Boolean) ?? null;
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * @param {string} worktreePath
38
+ * @param {string} sinceCommit
39
+ * @param {string} baseRef
40
+ * @param {string} pattern
41
+ */
42
+ function listPathsChangedSinceCommit(worktreePath, sinceCommit, baseRef, pattern) {
43
+ try {
44
+ const output = execFileSync(
45
+ "git",
46
+ ["diff", "--name-only", `${sinceCommit}..${baseRef}`, "--", pattern],
47
+ {
48
+ cwd: worktreePath,
49
+ encoding: "utf-8",
50
+ stdio: ["ignore", "pipe", "pipe"],
51
+ timeout: 10_000,
52
+ },
53
+ );
54
+ return output
55
+ .split(/\r?\n/)
56
+ .map((line) => line.trim())
57
+ .filter(Boolean);
58
+ } catch {
59
+ return [];
60
+ }
61
+ }
62
+
63
+ /**
64
+ * @param {string} worktreePath
65
+ * @param {string[]} changedFiles
66
+ * @param {object} [config]
67
+ * @returns {string | null}
68
+ */
69
+ export function resolvePromptRelPath(worktreePath, changedFiles, config = {}) {
70
+ if (typeof config.promptRelPath === "string" && config.promptRelPath.trim()) {
71
+ return config.promptRelPath.replace(/\\/g, "/");
72
+ }
73
+ if (typeof config.taskFolder === "string" && config.taskFolder.trim()) {
74
+ const rel = path.relative(worktreePath, config.taskFolder).replace(/\\/g, "/");
75
+ if (rel && !rel.startsWith("..")) {
76
+ return `${rel}/PROMPT.md`;
77
+ }
78
+ }
79
+
80
+ const tasksRoot = String(config.paths?.tasksRoot ?? DEFAULT_TASKS_ROOT).replace(/\\/g, "/");
81
+ /** @type {Set<string>} */
82
+ const taskDirs = new Set();
83
+ for (const file of changedFiles) {
84
+ const normalized = String(file).replace(/\\/g, "/");
85
+ const match = normalized.match(new RegExp(`^${tasksRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/([^/]+)/`));
86
+ if (match?.[1]) {
87
+ taskDirs.add(match[1]);
88
+ }
89
+ }
90
+ if (taskDirs.size === 1) {
91
+ return `${tasksRoot}/${[...taskDirs][0]}/PROMPT.md`;
92
+ }
93
+ return null;
94
+ }
95
+
96
+ /**
97
+ * @param {string} worktreePath
98
+ * @param {string} pattern
99
+ * @param {string | null} promptRelPath
100
+ * @param {string} baseRef
101
+ */
102
+ export function isFileScopePatternPrelanded(worktreePath, pattern, promptRelPath, baseRef = "main") {
103
+ if (!promptRelPath) {
104
+ return false;
105
+ }
106
+ const introCommit = gitFirstCommitTouchingPath(worktreePath, promptRelPath);
107
+ if (!introCommit) {
108
+ return false;
109
+ }
110
+ const changedPaths = listPathsChangedSinceCommit(worktreePath, introCommit, baseRef, pattern);
111
+ return changedPaths.some((filePath) => matchesPattern(filePath, pattern));
112
+ }
113
+
114
+ /**
115
+ * @param {string[]} changedFiles
116
+ * @param {string} [tasksRoot]
117
+ */
118
+ export function hasSpineTaskDeliveryChanges(changedFiles, tasksRoot = DEFAULT_TASKS_ROOT) {
119
+ const prefix = `${String(tasksRoot).replace(/\\/g, "/")}/`;
120
+ return changedFiles.some((file) => String(file).replace(/\\/g, "/").startsWith(prefix));
121
+ }
122
+
123
+ /**
124
+ * @param {string} worktreePath
125
+ * @param {string} pattern
126
+ * @param {string[]} changedFiles
127
+ * @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
128
+ * @param {object} config
129
+ * @param {string} baseBranch
130
+ * @param {{ testCommandOk: boolean }} delivery
131
+ * @param {(worktreePath: string, artifactPath: string) => boolean} artifactExists
132
+ */
133
+ export function isPrelandedFileScopeSatisfied(
134
+ worktreePath,
135
+ pattern,
136
+ changedFiles,
137
+ parsedContract,
138
+ config,
139
+ baseBranch,
140
+ delivery,
141
+ artifactExists,
142
+ ) {
143
+ const matchedInLane = changedFiles.some((file) => matchesPattern(file, pattern));
144
+ if (matchedInLane) {
145
+ return false;
146
+ }
147
+ const promptRelPath = resolvePromptRelPath(worktreePath, changedFiles, config);
148
+ if (!isFileScopePatternPrelanded(worktreePath, pattern, promptRelPath, baseBranch)) {
149
+ return false;
150
+ }
151
+ if (parsedContract.testCommand && !delivery.testCommandOk) {
152
+ return false;
153
+ }
154
+ for (const artifactPath of parsedContract.artifactsMustExist ?? []) {
155
+ if (!artifactExists(worktreePath, artifactPath)) {
156
+ return false;
157
+ }
158
+ }
159
+ return true;
160
+ }
161
+
162
+ /**
163
+ * @param {string} worktreePath
164
+ * @param {string} pattern
165
+ * @param {string[]} changedFiles
166
+ * @param {object} config
167
+ * @param {string} baseBranch
168
+ */
169
+ export function isStubPrelandedFileScopeSatisfied(worktreePath, pattern, changedFiles, config, baseBranch) {
170
+ const tasksRoot = config.paths?.tasksRoot ?? DEFAULT_TASKS_ROOT;
171
+ if (!hasSpineTaskDeliveryChanges(changedFiles, tasksRoot)) {
172
+ return false;
173
+ }
174
+ return isFileScopePatternPrelanded(
175
+ worktreePath,
176
+ pattern,
177
+ resolvePromptRelPath(worktreePath, changedFiles, config),
178
+ baseBranch,
179
+ );
180
+ }