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,388 @@
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 { isProcessAlive } from "../process/liveness.mjs";
13
+ import { terminateStaleDetachedEngine } from "./resume-engine.mjs";
14
+ import { reconcileBatch } from "./reconcile.mjs";
15
+ import { readJournalEventsCached } from "./journal.mjs";
16
+ import { enforceOperatorPauseOnDisk } from "./pause.mjs";
17
+ import { loadSpineBatchState, readBatchEnginePid, saveSpineBatchState } from "./state.mjs";
18
+
19
+ /** Journal types surfaced on attached stdout during the land loop. */
20
+ export const ATTACHED_LAND_LOOP_MILESTONE_TYPES = new Set([
21
+ "batch.started",
22
+ "task.started",
23
+ "task.completed",
24
+ "task.failed",
25
+ "batch.merge_started",
26
+ "batch.merge_completed",
27
+ "batch.merge_blocked",
28
+ "gate.opened",
29
+ "gate.evidence_collecting",
30
+ "gate.evidence_completed",
31
+ "gate.evidence_failed",
32
+ "batch.land_loop_finalized",
33
+ "batch.completed",
34
+ ]);
35
+
36
+ const ATTACHED_MILESTONE_POLL_MS = 200;
37
+
38
+ /** @type {boolean} */
39
+ let attachedExitHandlersInstalled = false;
40
+
41
+ /**
42
+ * Install journal-aware SIGTERM/SIGINT handlers before attached engine exit (SP-378).
43
+ *
44
+ * @param {object} params
45
+ * @param {string} params.projectRoot
46
+ * @param {string} [params.spineBin]
47
+ */
48
+ export function installAttachedExitFinalizeHandlers({ projectRoot, spineBin }) {
49
+ if (attachedExitHandlersInstalled) return;
50
+ attachedExitHandlersInstalled = true;
51
+
52
+ const onShutdown = (signal) => {
53
+ const handoff = finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal });
54
+ if (handoff.handled) {
55
+ process.exit(0);
56
+ }
57
+ };
58
+
59
+ process.once("SIGTERM", () => onShutdown("SIGTERM"));
60
+ process.once("SIGINT", () => onShutdown("SIGINT"));
61
+ }
62
+
63
+ /**
64
+ * @param {number} ms
65
+ */
66
+ function sleep(ms) {
67
+ return new Promise((resolve) => setTimeout(resolve, ms));
68
+ }
69
+
70
+ /**
71
+ * @param {object} event
72
+ */
73
+ function milestoneEventKey(event) {
74
+ if (typeof event.eventId === "string" && event.eventId) {
75
+ return event.eventId;
76
+ }
77
+ const taskId = typeof event.taskId === "string" ? event.taskId : "";
78
+ const timestamp = typeof event.timestamp === "string" ? event.timestamp : String(event.timestamp ?? "");
79
+ return `${event.type ?? "unknown"}:${timestamp}:${taskId}`;
80
+ }
81
+
82
+ /**
83
+ * @param {object} event
84
+ * @returns {string}
85
+ */
86
+ export function formatAttachedMilestoneLine(event) {
87
+ const type = String(event.type ?? "unknown");
88
+ const taskId = typeof event.taskId === "string" && event.taskId ? ` ${event.taskId}` : "";
89
+ const payload =
90
+ event.payload && typeof event.payload === "object" ? /** @type {Record<string, unknown>} */ (event.payload) : {};
91
+ const waveIndex = payload.waveIndex;
92
+ const waveSuffix =
93
+ typeof waveIndex === "number" &&
94
+ (type === "batch.merge_started" || type === "batch.merge_completed" || type === "batch.merge_blocked")
95
+ ? ` wave=${waveIndex}`
96
+ : "";
97
+ return `[spine] ${type}${taskId}${waveSuffix}\n`;
98
+ }
99
+
100
+ /**
101
+ * @param {object} params
102
+ * @param {string} params.projectRoot
103
+ * @param {(line: string) => void} [params.write]
104
+ * @returns {Promise<{ stop: () => Promise<void> }>}
105
+ */
106
+ export async function startAttachedMilestoneReporter({ projectRoot, write = (line) => process.stdout.write(line) }) {
107
+ /** @type {Set<string>} */
108
+ const printed = new Set();
109
+ let batchId = null;
110
+ let stopped = false;
111
+
112
+ const loop = async () => {
113
+ while (!stopped) {
114
+ enforceOperatorPauseOnDisk(projectRoot);
115
+ if (!batchId) {
116
+ const loaded = loadSpineBatchState(projectRoot);
117
+ batchId = loaded.raw?.batchId ? String(loaded.raw.batchId) : null;
118
+ }
119
+ if (batchId) {
120
+ const events = readJournalEventsCached(projectRoot, batchId);
121
+ for (const event of events) {
122
+ const key = milestoneEventKey(event);
123
+ if (printed.has(key)) continue;
124
+ if (!ATTACHED_LAND_LOOP_MILESTONE_TYPES.has(String(event.type ?? ""))) continue;
125
+ printed.add(key);
126
+ write(formatAttachedMilestoneLine(event));
127
+ }
128
+ }
129
+ await sleep(ATTACHED_MILESTONE_POLL_MS);
130
+ }
131
+ };
132
+
133
+ const loopPromise = loop();
134
+
135
+ return {
136
+ stop: async () => {
137
+ stopped = true;
138
+ await loopPromise;
139
+ if (batchId) {
140
+ const events = readJournalEventsCached(projectRoot, batchId);
141
+ for (const event of events) {
142
+ const key = milestoneEventKey(event);
143
+ if (printed.has(key)) continue;
144
+ if (!ATTACHED_LAND_LOOP_MILESTONE_TYPES.has(String(event.type ?? ""))) continue;
145
+ printed.add(key);
146
+ write(formatAttachedMilestoneLine(event));
147
+ }
148
+ }
149
+ },
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Reject a second attached engine when resilience.enginePid is alive (SP-434, GitHub #89).
155
+ *
156
+ * @param {object} params
157
+ * @param {string} params.projectRoot
158
+ * @param {boolean} [params.force] Orphan-terminate prior engine before handoff
159
+ * @param {"start"|"resume"} [params.operation]
160
+ */
161
+ export function enforceAttachedEngineSingleOwner({ projectRoot, force = false, operation = "resume" }) {
162
+ const loaded = loadSpineBatchState(projectRoot);
163
+ const state = loaded.raw;
164
+ if (!state) {
165
+ return { ok: true };
166
+ }
167
+
168
+ const batchId = String(state.batchId ?? "");
169
+ const enginePid = readBatchEnginePid(state);
170
+ if (enginePid == null || enginePid === process.pid || !isProcessAlive(enginePid)) {
171
+ return { ok: true };
172
+ }
173
+
174
+ const fromPhase = String(state.phase ?? "");
175
+ if (force) {
176
+ const terminateResult = terminateStaleDetachedEngine({
177
+ projectRoot,
178
+ state,
179
+ batchId,
180
+ fromPhase,
181
+ allowRunningOrphanTerminate: true,
182
+ });
183
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
184
+ return {
185
+ ok: true,
186
+ handoff: true,
187
+ terminated: terminateResult.terminated,
188
+ stalePid: terminateResult.stalePid ?? enginePid,
189
+ };
190
+ }
191
+
192
+ const operationLabel = operation === "start" ? "start" : "resume";
193
+ const output =
194
+ `Attached batch engine already running (PID ${enginePid}, batch ${batchId}).\n` +
195
+ `Stop the existing engine or run spine batch ${operationLabel} --attached --force to orphan it first.\n`;
196
+ return {
197
+ ok: false,
198
+ exitCode: 1,
199
+ error: "attached_engine_already_running",
200
+ output,
201
+ batchId,
202
+ enginePid,
203
+ };
204
+ }
205
+
206
+ /**
207
+ * Run an attached foreground engine while streaming land-loop journal milestones to stdout.
208
+ *
209
+ * @param {object} params
210
+ * @param {string} params.projectRoot
211
+ * @param {() => Promise<object>} params.runEngine
212
+ * @param {(line: string) => void} [params.write]
213
+ * @param {boolean} [params.force]
214
+ * @param {"start"|"resume"} [params.operation]
215
+ */
216
+ export async function runAttachedBatchEngine({
217
+ projectRoot,
218
+ runEngine,
219
+ write,
220
+ spineBin,
221
+ force = false,
222
+ operation = "resume",
223
+ }) {
224
+ if (operation === "start") {
225
+ const lock = enforceAttachedEngineSingleOwner({ projectRoot, force: false, operation: "start" });
226
+ if (!lock.ok) {
227
+ return {
228
+ ok: false,
229
+ exitCode: lock.exitCode ?? 1,
230
+ error: lock.error,
231
+ output: lock.output,
232
+ batchId: lock.batchId,
233
+ };
234
+ }
235
+ }
236
+
237
+ installAttachedExitFinalizeHandlers({ projectRoot, spineBin });
238
+ const reporter = await startAttachedMilestoneReporter({ projectRoot, write });
239
+ try {
240
+ const result = await runEngine();
241
+ const handoff = finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal: "exit" });
242
+ if (handoff.handled && handoff.action === "finalized_in_process" && handoff.result) {
243
+ return handoff.result;
244
+ }
245
+ return result;
246
+ } finally {
247
+ await reporter.stop();
248
+ }
249
+ }
250
+
251
+ /**
252
+ * @param {object} result
253
+ * @param {import("./reconcile.mjs").ReconciliationResult} reconciliation
254
+ */
255
+ function resolveAttachedBatchExitCode(result, reconciliation) {
256
+ if (reconciliation.phase === "merge_blocked") {
257
+ return result.exitCode ?? 1;
258
+ }
259
+ return result.exitCode ?? (result.ok ? 0 : 1);
260
+ }
261
+
262
+ /**
263
+ * @param {object} params
264
+ * @param {string} params.projectRoot
265
+ * @param {"start"|"resume"} params.operation
266
+ * @param {object} params.result
267
+ * @param {boolean} [params.json]
268
+ */
269
+ export function formatAttachedBatchCliResult({ projectRoot, operation, result, json = false }) {
270
+ const reconciliation = reconcileBatch({ projectRoot });
271
+ const mergeBlocked = reconciliation.phase === "merge_blocked";
272
+
273
+ if (json) {
274
+ return {
275
+ exitCode: resolveAttachedBatchExitCode(result, reconciliation),
276
+ output: `${JSON.stringify({ ...result, reconciliation }, null, 2)}\n`,
277
+ };
278
+ }
279
+
280
+ const operationLabel = operation === "resume" ? "resumed" : "started";
281
+ const headline = result.ok
282
+ ? `Batch ${operationLabel}`
283
+ : mergeBlocked && reconciliation.headline
284
+ ? reconciliation.headline
285
+ : operation === "resume"
286
+ ? "Batch resume failed"
287
+ : "Batch start failed";
288
+
289
+ /** @type {string[]} */
290
+ const lines = ["", headline, ""];
291
+
292
+ if (result.output) {
293
+ lines.push(result.output.trimEnd());
294
+ } else if (result.error && !mergeBlocked) {
295
+ lines.push(String(result.error));
296
+ }
297
+
298
+ if (reconciliation.headline && reconciliation.headline !== headline) {
299
+ lines.push("", reconciliation.headline);
300
+ }
301
+ if (reconciliation.suggestedCommand) {
302
+ lines.push("", ` → ${reconciliation.suggestedCommand}`);
303
+ }
304
+ if (reconciliation.alternatives?.length) {
305
+ lines.push("", " Alternatives:");
306
+ for (const alt of reconciliation.alternatives) {
307
+ lines.push(` • ${alt}`);
308
+ }
309
+ }
310
+
311
+ if (result.batchId) {
312
+ lines.push("", ` Batch: ${result.batchId}`);
313
+ }
314
+ if (result.taskId) {
315
+ lines.push(` Task: ${result.taskId}`);
316
+ }
317
+
318
+ lines.push("");
319
+ return {
320
+ exitCode: resolveAttachedBatchExitCode(result, reconciliation),
321
+ output: lines.join("\n"),
322
+ };
323
+ }
324
+
325
+ /**
326
+ * Write attached CLI output and exit so the foreground process does not linger after batch.completed.
327
+ *
328
+ * @param {{ exitCode?: number, output?: string }} cli
329
+ * @param {object} [options]
330
+ * @param {boolean} [options.deferExit]
331
+ */
332
+ export function finishAttachedBatchCli(cli, { deferExit = false, projectRoot, spineBin } = {}) {
333
+ const exitCode = cli.exitCode ?? 1;
334
+ if (cli.output) {
335
+ process.stdout.write(cli.output);
336
+ }
337
+ if (deferExit) {
338
+ return;
339
+ }
340
+ if (projectRoot) {
341
+ finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal: "cli_exit" });
342
+ }
343
+ process.exit(exitCode);
344
+ }
345
+
346
+ /**
347
+ * Finalize post-merge limbo during resume without re-running workers.
348
+ *
349
+ * @param {object} params
350
+ * @param {string} params.projectRoot
351
+ * @param {object} params.state
352
+ * @param {string} params.batchId
353
+ * @param {string} params.orchBranch
354
+ * @param {string} [params.fromPhase]
355
+ * @param {boolean} [params.resumeForced]
356
+ * @returns {ReturnType<typeof finalizeResumedBatchForIntegrate>|null}
357
+ */
358
+ export function finalizeResumePostMergeLimbo({
359
+ projectRoot,
360
+ state,
361
+ batchId,
362
+ orchBranch,
363
+ fromPhase = "running",
364
+ resumeForced = false,
365
+ }) {
366
+ if (String(state.phase ?? "") === "completed") {
367
+ return null;
368
+ }
369
+ if (!detectPostMergeLimboForResume({ projectRoot, state }) && !isPostMergeLimbo(state)) {
370
+ return null;
371
+ }
372
+
373
+ terminateStaleDetachedEngine({
374
+ projectRoot,
375
+ state,
376
+ batchId,
377
+ fromPhase,
378
+ });
379
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
380
+
381
+ return finalizeResumedBatchForIntegrate({
382
+ projectRoot,
383
+ state,
384
+ batchId,
385
+ orchBranch,
386
+ resumeForced,
387
+ });
388
+ }
@@ -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
+ }
@@ -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
+ }