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,1180 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { execFileSync } from "node:child_process";
4
+ import { loadSpineConfig } from "./spine-config-load.mjs";
5
+ import { resolveTasksRootPath } from "./env-overrides.mjs";
6
+ import { runDoctorChecks } from "../doctor/run-doctor-checks.mjs";
7
+ import { buildStalePathDoctorCheck, isStalePathSpinePreflightBlocking } from "../doctor/stale-path.mjs";
8
+ import { PACKAGE_ROOT } from "./spine-init-constants.mjs";
9
+ import { runReconciliationCheck } from "../batch/reconcile.mjs";
10
+ import { buildPlan } from "../planner/index.mjs";
11
+ import { formatPlanHuman } from "../planner/format-plan.mjs";
12
+ import { buildCoexistencePreflightCheck } from "../doctor/coexistence.mjs";
13
+ import { validatePiSpineRootConfig } from "./pi-spine-root.mjs";
14
+ import { resolveSafeWorkerLaunchScript } from "./worker-launch-script.mjs";
15
+ import { validateWorktreeSetupHookConfig } from "./worktree-setup-hook.mjs";
16
+ import {
17
+ isRulesManifestGeneratedAtOnlyDrift,
18
+ RULES_MANIFEST_REL_PATH,
19
+ } from "./cursor-rules/discover.mjs";
20
+ import { discoverTasks } from "../tasks/packet/discover.mjs";
21
+ import { NO_PENDING_TASKS_ERROR } from "../planner/scope.mjs";
22
+ import { summarizePendingScope } from "../planner/pending.mjs";
23
+ import { validatePrompt, collectStaleFileScopeMustChangeWarnings } from "../tasks/packet/validate-prompt.mjs";
24
+ import { isRunMetricsAppendOnlyDrift } from "../batch/metrics.mjs";
25
+ import { METRICS_DEFAULTS } from "./defaults.mjs";
26
+ import { parseContract, parsePrompt } from "../tasks/packet/parse-prompt.mjs";
27
+ import { hasReleaseCriticalContract, isStubWorkerMode } from "../batch/contract-verify.mjs";
28
+
29
+ const HEALTHY_ACTIVE_PHASES = new Set(["planning", "running", "paused"]);
30
+ /** High-risk paths that together block lane→orch auto-resolution (issue #37). */
31
+ export const PRD_REL_PATH = "docs/PRD.md";
32
+ export const ORCH_MULTI_FILE_MERGE_RISK_PATHS = Object.freeze([
33
+ PRD_REL_PATH,
34
+ RULES_MANIFEST_REL_PATH,
35
+ ]);
36
+ const LIMBO_DIAGNOSES = new Set(["limbo_stale", "completed_manual"]);
37
+ const DEPENDENCIES_SCHEMA_VERSION = 1;
38
+ const TASK_ID_PATTERN = /^[A-Z]{2,}-\d{3,}$/;
39
+
40
+ /**
41
+ * @param {object} ctx
42
+ * @param {string} ctx.projectRoot
43
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
44
+ */
45
+ export function resolveTasksRoot(projectRoot, configResult) {
46
+ const loaded = configResult ?? loadSpineConfig(projectRoot);
47
+ if (!loaded.config) {
48
+ return null;
49
+ }
50
+ return resolveTasksRootPath(projectRoot, loaded.config);
51
+ }
52
+
53
+ function isInsideGitRepo(dir) {
54
+ try {
55
+ execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
56
+ cwd: dir,
57
+ stdio: ["ignore", "pipe", "pipe"],
58
+ timeout: 5000,
59
+ });
60
+ return true;
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
66
+ export function taskIdFromFolder(folderName) {
67
+ const match = String(folderName).match(/^([A-Z]{2,}-\d{3,})/);
68
+ return match?.[1] ?? null;
69
+ }
70
+
71
+ export function discoverTaskFolders(tasksRootPath) {
72
+ if (!tasksRootPath || !fs.existsSync(tasksRootPath)) return [];
73
+
74
+ return fs
75
+ .readdirSync(tasksRootPath, { withFileTypes: true })
76
+ .filter((entry) => entry.isDirectory())
77
+ .map((entry) => entry.name)
78
+ .filter((name) => fs.existsSync(path.join(tasksRootPath, name, "PROMPT.md")))
79
+ .sort();
80
+ }
81
+
82
+ export function discoverTaskIds(tasksRootPath) {
83
+ return [...new Set(discoverTaskFolders(tasksRootPath).map(taskIdFromFolder).filter(Boolean))].sort();
84
+ }
85
+
86
+ function resolveBatchStatePath(projectRoot) {
87
+ const spinePath = path.join(projectRoot, ".spine", "batch-state.json");
88
+ if (fs.existsSync(spinePath)) return spinePath;
89
+
90
+ const piPath = path.join(projectRoot, ".pi", "batch-state.json");
91
+ if (fs.existsSync(piPath)) return piPath;
92
+
93
+ return null;
94
+ }
95
+
96
+ function loadBatchState(batchStatePath) {
97
+ try {
98
+ return JSON.parse(fs.readFileSync(batchStatePath, "utf-8"));
99
+ } catch (err) {
100
+ return { parseError: err.message };
101
+ }
102
+ }
103
+
104
+ function isHealthyActiveBatch(batchState) {
105
+ if (!batchState || batchState.parseError) return false;
106
+ const phase = batchState.phase ?? batchState.status;
107
+ if (phase && HEALTHY_ACTIVE_PHASES.has(String(phase))) return true;
108
+ if (batchState.endedAt == null && batchState.batchId) return true;
109
+ return false;
110
+ }
111
+
112
+ function makeCheck(id, ok, message, extra = {}) {
113
+ return { id, ok, message, ...extra };
114
+ }
115
+
116
+ /**
117
+ * @param {object} ctx
118
+ * @param {string} ctx.projectRoot
119
+ * @param {() => ReturnType<typeof runDoctorChecks>} [ctx.runDoctor]
120
+ */
121
+ export function checkDoctor(ctx) {
122
+ const runDoctor = ctx.runDoctor ?? (() => runDoctorChecks(ctx.projectRoot));
123
+ const doctor = runDoctor();
124
+ if (doctor.ok) {
125
+ return makeCheck("doctor", true, "spine doctor passed");
126
+ }
127
+
128
+ const failed = doctor.checks.filter((entry) => !entry.ok).map((entry) => entry.label);
129
+ return makeCheck("doctor", false, `spine doctor failed (${doctor.issueCount} issue(s))`, {
130
+ details: { failedChecks: failed, checks: doctor.checks },
131
+ suggestedCommand: "spine doctor",
132
+ });
133
+ }
134
+
135
+ /**
136
+ * Fail preflight when PATH `spine` is an older global build (batch 20260619T020951 / SP-308).
137
+ *
138
+ * @param {object} [_ctx]
139
+ * @param {{ stalePathCheckArgs?: object }} [options]
140
+ */
141
+ export function checkStalePathSpine(_ctx = {}, options = {}) {
142
+ const check = buildStalePathDoctorCheck({
143
+ packageRoot: PACKAGE_ROOT,
144
+ runningSpinePath: path.join(PACKAGE_ROOT, "bin", "spine.mjs"),
145
+ ...options.stalePathCheckArgs,
146
+ });
147
+ if (isStalePathSpinePreflightBlocking(check)) {
148
+ return makeCheck("stale-path-spine", false, check.detail, {
149
+ suggestedCommand:
150
+ check.suggestedCommand ?? `cd ${PACKAGE_ROOT} && npm link`,
151
+ });
152
+ }
153
+ return makeCheck("stale-path-spine", true, check.detail, check.warning ? { warning: true } : {});
154
+ }
155
+
156
+ /**
157
+ * @param {object} ctx
158
+ * @param {string} ctx.projectRoot
159
+ */
160
+ export function checkGitClean(ctx) {
161
+ if (!isInsideGitRepo(ctx.projectRoot)) {
162
+ return makeCheck("git-clean", false, "not inside a git repository", {
163
+ suggestedCommand: "git init",
164
+ });
165
+ }
166
+
167
+ let output = "";
168
+ try {
169
+ output = execFileSync("git", ["status", "--porcelain"], {
170
+ cwd: ctx.projectRoot,
171
+ encoding: "utf-8",
172
+ timeout: 5000,
173
+ });
174
+ } catch (err) {
175
+ return makeCheck("git-clean", false, `git status failed: ${err.message}`, {
176
+ suggestedCommand: "git status",
177
+ });
178
+ }
179
+
180
+ const dirtyPaths = output
181
+ .split(/\r?\n/)
182
+ .filter(Boolean)
183
+ .map((line) => line.slice(3).trim() || line.trim());
184
+
185
+ if (dirtyPaths.length === 0) {
186
+ return makeCheck("git-clean", true, "working tree clean");
187
+ }
188
+
189
+ const manifestDrift = isRulesManifestGeneratedAtOnlyDrift(ctx.projectRoot, dirtyPaths);
190
+ if (manifestDrift.ok) {
191
+ return makeCheck(
192
+ "git-clean",
193
+ true,
194
+ `working tree clean (${RULES_MANIFEST_REL_PATH} generatedAt-only drift ignored)`,
195
+ {
196
+ details: {
197
+ manifestGeneratedAtDrift: true,
198
+ manifestPath: manifestDrift.manifestPath,
199
+ },
200
+ },
201
+ );
202
+ }
203
+
204
+ const configResult = loadSpineConfig(ctx.projectRoot);
205
+ const metricsRelPath = configResult?.config?.metrics?.path ?? METRICS_DEFAULTS.path;
206
+ const metricsDrift = isRunMetricsAppendOnlyDrift(ctx.projectRoot, dirtyPaths, metricsRelPath);
207
+ if (metricsDrift.ok) {
208
+ return makeCheck(
209
+ "git-clean",
210
+ true,
211
+ `working tree clean (${metricsRelPath} append-only drift ignored)`,
212
+ {
213
+ details: {
214
+ metricsAppendOnlyDrift: true,
215
+ metricsPath: metricsDrift.metricsPath,
216
+ },
217
+ },
218
+ );
219
+ }
220
+
221
+ const listed = dirtyPaths.slice(0, 20);
222
+ const suffix =
223
+ dirtyPaths.length > listed.length ? ` (+${dirtyPaths.length - listed.length} more)` : "";
224
+
225
+ return makeCheck(
226
+ "git-clean",
227
+ false,
228
+ `working tree has ${dirtyPaths.length} uncommitted change(s)${suffix}`,
229
+ {
230
+ details: { dirtyPaths: listed, totalDirty: dirtyPaths.length },
231
+ suggestedCommand: "git status",
232
+ },
233
+ );
234
+ }
235
+
236
+ /**
237
+ * @param {object} ctx
238
+ * @param {string} ctx.projectRoot
239
+ * @param {typeof runReconciliationCheck} [ctx.runReconciliation]
240
+ */
241
+ export function checkNoActiveBatch(ctx) {
242
+ const batchStatePath = resolveBatchStatePath(ctx.projectRoot);
243
+ if (!batchStatePath) {
244
+ return makeCheck("no-active-batch", true, "no active batch state file");
245
+ }
246
+
247
+ const batchState = loadBatchState(batchStatePath);
248
+ if (batchState.parseError) {
249
+ return makeCheck("no-active-batch", false, `cannot parse batch state: ${batchState.parseError}`, {
250
+ details: { batchStatePath: path.relative(ctx.projectRoot, batchStatePath) },
251
+ suggestedCommand: "spine status --diagnose",
252
+ });
253
+ }
254
+
255
+ const reconcile = ctx.runReconciliation ?? runReconciliationCheck;
256
+ const reconciliation = reconcile({
257
+ projectRoot: ctx.projectRoot,
258
+ batchState,
259
+ batchStatePath,
260
+ });
261
+
262
+ if (LIMBO_DIAGNOSES.has(reconciliation.diagnosis)) {
263
+ return makeCheck(
264
+ "no-active-batch",
265
+ false,
266
+ reconciliation.headline ?? "stale batch requires dismissal",
267
+ {
268
+ details: {
269
+ batchStatePath: path.relative(ctx.projectRoot, batchStatePath),
270
+ diagnosis: reconciliation.diagnosis,
271
+ batchId: batchState.batchId ?? batchState.id ?? null,
272
+ headline: reconciliation.headline,
273
+ },
274
+ suggestedCommand: reconciliation.suggestedCommand ?? "spine batch dismiss",
275
+ },
276
+ );
277
+ }
278
+
279
+ if (reconciliation.diagnosis === "running") {
280
+ const batchId = batchState.batchId ?? batchState.id ?? "unknown";
281
+ return makeCheck(
282
+ "no-active-batch",
283
+ false,
284
+ reconciliation.headline ?? `batch ${batchId} is running`,
285
+ {
286
+ details: {
287
+ batchStatePath: path.relative(ctx.projectRoot, batchStatePath),
288
+ diagnosis: reconciliation.diagnosis,
289
+ batchId,
290
+ headline: reconciliation.headline,
291
+ },
292
+ suggestedCommand: reconciliation.suggestedCommand ?? "/spine-status --diagnose",
293
+ },
294
+ );
295
+ }
296
+
297
+ if (reconciliation.diagnosis === "paused") {
298
+ const batchId = batchState.batchId ?? batchState.id ?? "unknown";
299
+ return makeCheck(
300
+ "no-active-batch",
301
+ false,
302
+ reconciliation.headline ?? `batch ${batchId} is paused`,
303
+ {
304
+ details: {
305
+ batchStatePath: path.relative(ctx.projectRoot, batchStatePath),
306
+ diagnosis: reconciliation.diagnosis,
307
+ batchId,
308
+ headline: reconciliation.headline,
309
+ },
310
+ suggestedCommand: reconciliation.suggestedCommand ?? "/spine-resume --force",
311
+ },
312
+ );
313
+ }
314
+
315
+ if (isHealthyActiveBatch(batchState)) {
316
+ const batchId = batchState.batchId ?? batchState.id ?? "unknown";
317
+ const phase = batchState.phase ?? batchState.status ?? "unknown";
318
+ return makeCheck(
319
+ "no-active-batch",
320
+ false,
321
+ `healthy active batch ${batchId} (phase: ${phase})`,
322
+ {
323
+ details: {
324
+ batchStatePath: path.relative(ctx.projectRoot, batchStatePath),
325
+ batchId,
326
+ phase,
327
+ },
328
+ suggestedCommand: reconciliation.suggestedCommand ?? "spine status --diagnose",
329
+ },
330
+ );
331
+ }
332
+
333
+ return makeCheck(
334
+ "no-active-batch",
335
+ false,
336
+ reconciliation.headline ?? "batch state file present",
337
+ {
338
+ details: {
339
+ batchStatePath: path.relative(ctx.projectRoot, batchStatePath),
340
+ diagnosis: reconciliation.diagnosis,
341
+ batchId: batchState.batchId ?? batchState.id ?? null,
342
+ },
343
+ suggestedCommand: reconciliation.suggestedCommand ?? "spine status --diagnose",
344
+ },
345
+ );
346
+ }
347
+
348
+ /**
349
+ * @param {object} ctx
350
+ * @param {string} ctx.projectRoot
351
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
352
+ */
353
+ export function checkPiSpineRoot(ctx) {
354
+ const configResult = ctx.configResult ?? loadSpineConfig(ctx.projectRoot);
355
+ const config = configResult?.config;
356
+
357
+ if (!config || configResult?.error) {
358
+ return makeCheck("pi-spine-root", true, "pi-spine root check skipped (config unavailable)");
359
+ }
360
+
361
+ const launchScript = resolveSafeWorkerLaunchScript(ctx.projectRoot, config);
362
+ const overrideConfigured = Boolean(config?.development?.piSpineRoot);
363
+ if (!launchScript && !overrideConfigured) {
364
+ return makeCheck("pi-spine-root", true, "pi-spine root not required (no custom worker launch script)");
365
+ }
366
+
367
+ const validationError = validatePiSpineRootConfig(config, ctx.projectRoot);
368
+ if (validationError) {
369
+ return makeCheck("pi-spine-root", false, validationError.message, {
370
+ suggestedCommand: validationError.suggestedCommand,
371
+ });
372
+ }
373
+
374
+ return makeCheck(
375
+ "pi-spine-root",
376
+ true,
377
+ launchScript
378
+ ? "pi-spine root valid for custom worker launch script"
379
+ : "development.piSpineRoot override valid",
380
+ );
381
+ }
382
+
383
+ /**
384
+ * @param {object} ctx
385
+ * @param {string} ctx.projectRoot
386
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
387
+ */
388
+ export function checkTasksRoot(ctx) {
389
+ const configResult = ctx.configResult ?? loadSpineConfig(ctx.projectRoot);
390
+ const tasksRootPath = resolveTasksRoot(ctx.projectRoot, configResult);
391
+
392
+ if (!tasksRootPath) {
393
+ return makeCheck("tasks-root", false, "tasks root not configured", {
394
+ suggestedCommand: "spine init",
395
+ });
396
+ }
397
+
398
+ if (!fs.existsSync(tasksRootPath)) {
399
+ return makeCheck(
400
+ "tasks-root",
401
+ false,
402
+ `tasks root missing: ${path.relative(ctx.projectRoot, tasksRootPath)}`,
403
+ {
404
+ suggestedCommand: `mkdir -p ${path.relative(ctx.projectRoot, tasksRootPath)}`,
405
+ },
406
+ );
407
+ }
408
+
409
+ const taskFolders = discoverTaskFolders(tasksRootPath);
410
+ if (taskFolders.length === 0) {
411
+ return makeCheck("tasks-root", false, "no discoverable task folders (PROMPT.md)", {
412
+ details: { tasksRootPath: path.relative(ctx.projectRoot, tasksRootPath) },
413
+ suggestedCommand: "spine init",
414
+ });
415
+ }
416
+
417
+ return makeCheck(
418
+ "tasks-root",
419
+ true,
420
+ `tasks root valid (${taskFolders.length} task folder(s))`,
421
+ {
422
+ details: {
423
+ tasksRootPath: path.relative(ctx.projectRoot, tasksRootPath),
424
+ taskFolders,
425
+ },
426
+ },
427
+ );
428
+ }
429
+
430
+ /**
431
+ * @param {object} ctx
432
+ * @param {string} ctx.projectRoot
433
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
434
+ */
435
+ export function checkDependenciesJson(ctx) {
436
+ const configResult = ctx.configResult ?? loadSpineConfig(ctx.projectRoot);
437
+ const tasksRootPath = resolveTasksRoot(ctx.projectRoot, configResult);
438
+
439
+ if (!tasksRootPath) {
440
+ return makeCheck("dependencies-json", false, "tasks root not configured", {
441
+ suggestedCommand: "spine init",
442
+ });
443
+ }
444
+
445
+ const depsPath = path.join(tasksRootPath, "dependencies.json");
446
+ if (!fs.existsSync(depsPath)) {
447
+ return makeCheck(
448
+ "dependencies-json",
449
+ false,
450
+ `dependencies.json missing: ${path.relative(ctx.projectRoot, depsPath)}`,
451
+ { suggestedCommand: "spine init" },
452
+ );
453
+ }
454
+
455
+ let parsed;
456
+ try {
457
+ parsed = JSON.parse(fs.readFileSync(depsPath, "utf-8"));
458
+ } catch (err) {
459
+ return makeCheck("dependencies-json", false, `cannot parse dependencies.json: ${err.message}`, {
460
+ suggestedCommand: "spine init",
461
+ });
462
+ }
463
+
464
+ if (parsed.version !== DEPENDENCIES_SCHEMA_VERSION) {
465
+ return makeCheck(
466
+ "dependencies-json",
467
+ false,
468
+ `dependencies.json version must be ${DEPENDENCIES_SCHEMA_VERSION} (found ${parsed.version ?? "missing"})`,
469
+ { suggestedCommand: "spine init" },
470
+ );
471
+ }
472
+
473
+ if (typeof parsed.tasks !== "object" || parsed.tasks === null || Array.isArray(parsed.tasks)) {
474
+ return makeCheck("dependencies-json", false, "dependencies.json tasks must be an object", {
475
+ suggestedCommand: "spine init",
476
+ });
477
+ }
478
+
479
+ const taskIds = Object.keys(parsed.tasks);
480
+ const invalidIds = taskIds.filter((id) => !TASK_ID_PATTERN.test(id));
481
+ if (invalidIds.length > 0) {
482
+ return makeCheck(
483
+ "dependencies-json",
484
+ false,
485
+ `dependencies.json has invalid task IDs: ${invalidIds.slice(0, 5).join(", ")}`,
486
+ { details: { invalidIds }, suggestedCommand: "spine init --tasks-root taskplane-tasks" },
487
+ );
488
+ }
489
+
490
+ const discovered = new Set(discoverTaskIds(tasksRootPath));
491
+ const unknownIds = taskIds.filter((id) => !discovered.has(id));
492
+ if (unknownIds.length > 0) {
493
+ return makeCheck(
494
+ "dependencies-json",
495
+ false,
496
+ `dependencies.json references unknown task folders: ${unknownIds.slice(0, 5).join(", ")}`,
497
+ { details: { unknownIds }, suggestedCommand: "spine init --tasks-root taskplane-tasks" },
498
+ );
499
+ }
500
+
501
+ return makeCheck(
502
+ "dependencies-json",
503
+ true,
504
+ `dependencies.json valid (${taskIds.length} task(s))`,
505
+ { details: { path: path.relative(ctx.projectRoot, depsPath), taskIds } },
506
+ );
507
+ }
508
+
509
+ /**
510
+ * @param {object} ctx
511
+ * @param {string} ctx.projectRoot
512
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
513
+ */
514
+ export function checkWorktreeSetupHook(ctx) {
515
+ const configResult = ctx.configResult ?? loadSpineConfig(ctx.projectRoot);
516
+ const config = configResult?.config;
517
+ if (!config || configResult?.error) {
518
+ return makeCheck("worktree-setup-hook", true, "worktree setup hook not configured");
519
+ }
520
+
521
+ const hookError = validateWorktreeSetupHookConfig(config, ctx.projectRoot);
522
+ if (hookError) {
523
+ return makeCheck("worktree-setup-hook", false, hookError.message, {
524
+ suggestedCommand: hookError.suggestedCommand,
525
+ });
526
+ }
527
+
528
+ if (!config.worktreeSetupHook) {
529
+ return makeCheck("worktree-setup-hook", true, "worktree setup hook not configured");
530
+ }
531
+
532
+ return makeCheck("worktree-setup-hook", true, "worktree setup hook path valid");
533
+ }
534
+
535
+ /**
536
+ * @param {object} ctx
537
+ * @param {string} ctx.projectRoot
538
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
539
+ */
540
+ export function checkTasksValidate(ctx) {
541
+ const { projectRoot, configResult } = ctx;
542
+ const config = configResult?.config;
543
+
544
+ if (!config || configResult?.error) {
545
+ return makeCheck("tasks-validate", false, "cannot validate tasks without spine config", {
546
+ suggestedCommand: "spine init",
547
+ });
548
+ }
549
+
550
+ const tasksRootPath = resolveTasksRoot(projectRoot, configResult);
551
+ if (!tasksRootPath) {
552
+ return makeCheck("tasks-validate", false, "tasks root not configured", {
553
+ suggestedCommand: "spine init",
554
+ });
555
+ }
556
+
557
+ try {
558
+ const discovered = discoverTasks(tasksRootPath);
559
+ const { pendingIds } = summarizePendingScope(discovered, tasksRootPath);
560
+ if (pendingIds.length === 0) {
561
+ return makeCheck(
562
+ "tasks-validate",
563
+ true,
564
+ "no pending tasks (all discovered tasks have .DONE)",
565
+ );
566
+ }
567
+
568
+ const selectedTaskIds = new Set(pendingIds);
569
+ /** @type {string[]} */
570
+ const failures = [];
571
+
572
+ for (const discoveredTask of discovered) {
573
+ if (!selectedTaskIds.has(discoveredTask.taskId)) continue;
574
+ const promptMarkdown = fs.readFileSync(
575
+ path.join(discoveredTask.folderPath, "PROMPT.md"),
576
+ "utf-8",
577
+ );
578
+ const validation = validatePrompt(promptMarkdown, {
579
+ taskId: discoveredTask.taskId,
580
+ contract: config.contract,
581
+ });
582
+ if (!validation.ok) {
583
+ failures.push(
584
+ `${discoveredTask.taskId}: ${validation.errors[0] ?? "invalid PROMPT packet"}`,
585
+ );
586
+ }
587
+ }
588
+
589
+ if (failures.length === 0) {
590
+ return makeCheck("tasks-validate", true, "pending task PROMPT packets valid");
591
+ }
592
+
593
+ return makeCheck("tasks-validate", false, failures[0], {
594
+ suggestedCommand: "spine tasks validate pending",
595
+ details: { failures },
596
+ });
597
+ } catch (err) {
598
+ const message = err?.message ?? String(err);
599
+ if (message === NO_PENDING_TASKS_ERROR) {
600
+ return makeCheck(
601
+ "tasks-validate",
602
+ true,
603
+ "no pending tasks (all discovered tasks have .DONE)",
604
+ );
605
+ }
606
+ return makeCheck("tasks-validate", false, `tasks validate failed: ${message}`, {
607
+ suggestedCommand: "spine tasks validate pending",
608
+ });
609
+ }
610
+ }
611
+
612
+ /**
613
+ * Warn when stub workers are about to run tasks with release-critical `fileScopeMustChange` contracts.
614
+ *
615
+ * @param {object} ctx
616
+ * @param {string} ctx.projectRoot
617
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
618
+ */
619
+ export function checkStubReleaseCritical(ctx) {
620
+ if (!isStubWorkerMode()) {
621
+ return makeCheck("stub-release-critical", true, "stub worker mode not active");
622
+ }
623
+
624
+ const configResult = ctx.configResult ?? loadSpineConfig(ctx.projectRoot);
625
+ const tasksRootPath = resolveTasksRoot(ctx.projectRoot, configResult);
626
+ if (!tasksRootPath) {
627
+ return makeCheck("stub-release-critical", true, "stub release-critical check skipped (no tasks root)");
628
+ }
629
+
630
+ try {
631
+ const discovered = discoverTasks(tasksRootPath);
632
+ const { pendingIds } = summarizePendingScope(discovered, tasksRootPath);
633
+ /** @type {string[]} */
634
+ const criticalTaskIds = [];
635
+
636
+ for (const discoveredTask of discovered) {
637
+ if (!pendingIds.includes(discoveredTask.taskId)) continue;
638
+ const promptMarkdown = fs.readFileSync(
639
+ path.join(discoveredTask.folderPath, "PROMPT.md"),
640
+ "utf-8",
641
+ );
642
+ const parsedContract = parseContract(promptMarkdown);
643
+ if (hasReleaseCriticalContract(parsedContract)) {
644
+ criticalTaskIds.push(discoveredTask.taskId);
645
+ }
646
+ }
647
+
648
+ if (criticalTaskIds.length === 0) {
649
+ return makeCheck(
650
+ "stub-release-critical",
651
+ true,
652
+ "no pending tasks with fileScopeMustChange contracts",
653
+ );
654
+ }
655
+
656
+ const preview = criticalTaskIds.slice(0, 8).join(", ");
657
+ const suffix =
658
+ criticalTaskIds.length > 8 ? ` (+${criticalTaskIds.length - 8} more)` : "";
659
+ return makeCheck(
660
+ "stub-release-critical",
661
+ true,
662
+ `SPINE_WORKER_STUB=1 with ${criticalTaskIds.length} pending task(s) requiring file-scope changes (${preview}${suffix})`,
663
+ {
664
+ warning: true,
665
+ details: { taskIds: criticalTaskIds },
666
+ suggestedCommand: "unset SPINE_WORKER_STUB",
667
+ },
668
+ );
669
+ } catch (err) {
670
+ const message = err?.message ?? String(err);
671
+ return makeCheck(
672
+ "stub-release-critical",
673
+ true,
674
+ `stub release-critical check skipped: ${message}`,
675
+ );
676
+ }
677
+ }
678
+
679
+ /**
680
+ * @param {{ title?: string | null, missionText?: string, folderName?: string }} task
681
+ */
682
+ export function isMergeOriginMainTask(task) {
683
+ const haystack = `${task.title ?? ""}\n${task.missionText ?? ""}\n${task.folderName ?? ""}`.toLowerCase();
684
+ if (/merge[-_\s]+origin[-_\s]+main/.test(haystack)) {
685
+ return true;
686
+ }
687
+ return haystack.includes("origin/main") && /\bmerge\b/.test(haystack);
688
+ }
689
+
690
+ /**
691
+ * @param {string} projectRoot
692
+ * @param {string} ref
693
+ */
694
+ function gitRefExists(projectRoot, ref) {
695
+ try {
696
+ execFileSync("git", ["rev-parse", "--verify", ref], {
697
+ cwd: projectRoot,
698
+ stdio: ["ignore", "ignore", "pipe"],
699
+ timeout: 5000,
700
+ });
701
+ return true;
702
+ } catch {
703
+ return false;
704
+ }
705
+ }
706
+
707
+ /**
708
+ * @param {string} projectRoot
709
+ */
710
+ function resolveOriginMainRef(projectRoot) {
711
+ for (const ref of ["origin/main", "refs/remotes/origin/main"]) {
712
+ if (gitRefExists(projectRoot, ref)) {
713
+ return ref;
714
+ }
715
+ }
716
+ return null;
717
+ }
718
+
719
+ /**
720
+ * @param {string} projectRoot
721
+ * @param {string} ref
722
+ * @param {string} filePath
723
+ */
724
+ function pathExistsAtRef(projectRoot, ref, filePath) {
725
+ try {
726
+ execFileSync("git", ["cat-file", "-e", `${ref}:${filePath}`], {
727
+ cwd: projectRoot,
728
+ stdio: "ignore",
729
+ timeout: 5000,
730
+ });
731
+ return true;
732
+ } catch {
733
+ return false;
734
+ }
735
+ }
736
+
737
+ /**
738
+ * @param {string} projectRoot
739
+ * @param {string} refA
740
+ * @param {string} refB
741
+ * @param {string} filePath
742
+ */
743
+ function refsDifferOnPath(projectRoot, refA, refB, filePath) {
744
+ const aExists = pathExistsAtRef(projectRoot, refA, filePath);
745
+ const bExists = pathExistsAtRef(projectRoot, refB, filePath);
746
+ if (!aExists && !bExists) {
747
+ return false;
748
+ }
749
+ if (aExists !== bExists) {
750
+ return true;
751
+ }
752
+ try {
753
+ execFileSync("git", ["diff", "--quiet", refA, refB, "--", filePath], {
754
+ cwd: projectRoot,
755
+ stdio: "ignore",
756
+ timeout: 5000,
757
+ });
758
+ return false;
759
+ } catch {
760
+ return true;
761
+ }
762
+ }
763
+
764
+ /**
765
+ * @param {string} projectRoot
766
+ * @param {string} headRef
767
+ * @param {string} originMainRef
768
+ */
769
+ export function listDivergentOrchMergeRiskPaths(projectRoot, headRef, originMainRef) {
770
+ return ORCH_MULTI_FILE_MERGE_RISK_PATHS.filter((filePath) =>
771
+ refsDifferOnPath(projectRoot, headRef, originMainRef, filePath),
772
+ );
773
+ }
774
+
775
+ /**
776
+ * Predict multi-file lane→orch merge conflicts when a pending task merges origin/main.
777
+ *
778
+ * @param {object} ctx
779
+ * @param {string} ctx.projectRoot
780
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
781
+ */
782
+ export function predictOrchMergeConflictRisk(ctx) {
783
+ const { projectRoot, configResult } = ctx;
784
+ const loaded = configResult ?? loadSpineConfig(projectRoot);
785
+ const tasksRootPath = resolveTasksRoot(projectRoot, loaded);
786
+ if (!tasksRootPath) {
787
+ return { risky: false, reason: "no_tasks_root" };
788
+ }
789
+
790
+ const originMainRef = resolveOriginMainRef(projectRoot);
791
+ if (!originMainRef) {
792
+ return { risky: false, reason: "no_origin_main" };
793
+ }
794
+
795
+ const headRef = "HEAD";
796
+ if (!gitRefExists(projectRoot, headRef)) {
797
+ return { risky: false, reason: "no_head" };
798
+ }
799
+
800
+ const divergentPaths = listDivergentOrchMergeRiskPaths(projectRoot, headRef, originMainRef);
801
+ const hasPrdDivergence = divergentPaths.includes(PRD_REL_PATH);
802
+ const hasManifestDivergence = divergentPaths.includes(RULES_MANIFEST_REL_PATH);
803
+ if (!hasPrdDivergence || !hasManifestDivergence) {
804
+ return {
805
+ risky: false,
806
+ reason: "paths_not_divergent",
807
+ divergentPaths,
808
+ originMainRef,
809
+ headRef,
810
+ };
811
+ }
812
+
813
+ try {
814
+ const discovered = discoverTasks(tasksRootPath);
815
+ const { pendingIds } = summarizePendingScope(discovered, tasksRootPath);
816
+ /** @type {string[]} */
817
+ const mergeOriginTaskIds = [];
818
+
819
+ for (const discoveredTask of discovered) {
820
+ if (!pendingIds.includes(discoveredTask.taskId)) continue;
821
+ const promptMarkdown = fs.readFileSync(
822
+ path.join(discoveredTask.folderPath, "PROMPT.md"),
823
+ "utf-8",
824
+ );
825
+ const parsed = parsePrompt(promptMarkdown);
826
+ if (
827
+ isMergeOriginMainTask({
828
+ title: parsed.title,
829
+ missionText: parsed.sections.Mission ?? "",
830
+ folderName: path.basename(discoveredTask.folderPath),
831
+ })
832
+ ) {
833
+ mergeOriginTaskIds.push(discoveredTask.taskId);
834
+ }
835
+ }
836
+
837
+ if (mergeOriginTaskIds.length === 0) {
838
+ return {
839
+ risky: false,
840
+ reason: "no_merge_origin_main_task",
841
+ divergentPaths,
842
+ originMainRef,
843
+ headRef,
844
+ };
845
+ }
846
+
847
+ return {
848
+ risky: true,
849
+ mergeOriginTaskIds,
850
+ divergentPaths,
851
+ originMainRef,
852
+ headRef,
853
+ };
854
+ } catch (err) {
855
+ return {
856
+ risky: false,
857
+ reason: "error",
858
+ message: err?.message ?? String(err),
859
+ };
860
+ }
861
+ }
862
+
863
+ /**
864
+ * Warn when pending merge-origin-main tasks predict PRD + rules-manifest orch merge conflicts.
865
+ *
866
+ * @param {object} ctx
867
+ * @param {string} ctx.projectRoot
868
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
869
+ */
870
+ export function checkOrchMergeConflictWarn(ctx) {
871
+ const risk = predictOrchMergeConflictRisk(ctx);
872
+ if (!risk.risky) {
873
+ const skipMessage =
874
+ risk.reason === "no_merge_origin_main_task"
875
+ ? "no pending merge-origin-main tasks"
876
+ : risk.reason === "no_origin_main"
877
+ ? "orch merge conflict check skipped (origin/main unavailable)"
878
+ : "no predictable multi-file orch merge conflicts";
879
+ return makeCheck("orch-merge-conflict", true, skipMessage);
880
+ }
881
+
882
+ const taskPreview = risk.mergeOriginTaskIds.slice(0, 5).join(", ");
883
+ const pathList = risk.divergentPaths.join(", ");
884
+ return makeCheck(
885
+ "orch-merge-conflict",
886
+ true,
887
+ `pending merge-origin-main task(s) (${taskPreview}) with ${pathList} divergent between HEAD and ${risk.originMainRef} — wave merge may fail on multi-file conflicts`,
888
+ {
889
+ warning: true,
890
+ details: risk,
891
+ suggestedCommand:
892
+ "merge origin/main into main before batch or resolve docs/PRD.md + rules-manifest drift manually",
893
+ },
894
+ );
895
+ }
896
+
897
+ function formatOrchMergeConflictPlanWarning(risk) {
898
+ const taskPreview = risk.mergeOriginTaskIds.slice(0, 5).join(", ");
899
+ const pathList = risk.divergentPaths.join(", ");
900
+ return [
901
+ "⚠️ Orch merge risk: pending merge-origin-main task(s)",
902
+ `(${taskPreview}) with ${pathList} divergent between HEAD and ${risk.originMainRef}.`,
903
+ "Wave merge may fail when automatic resolution cannot handle PRD + manifest together.",
904
+ ].join(" ");
905
+ }
906
+
907
+ /**
908
+ * List pending tasks whose fileScopeMustChange paths already changed on main since PROMPT intro.
909
+ *
910
+ * @param {object} ctx
911
+ * @param {string} ctx.projectRoot
912
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
913
+ */
914
+ export function listPrelandedFileScopeStaleTasks(ctx) {
915
+ const configResult = ctx.configResult ?? loadSpineConfig(ctx.projectRoot);
916
+ const tasksRootPath = resolveTasksRoot(ctx.projectRoot, configResult);
917
+ if (!tasksRootPath) {
918
+ return [];
919
+ }
920
+
921
+ const discovered = discoverTasks(tasksRootPath);
922
+ const { pendingIds } = summarizePendingScope(discovered, tasksRootPath);
923
+ /** @type {Array<{ taskId: string, warnings: string[] }>} */
924
+ const staleTasks = [];
925
+
926
+ for (const discoveredTask of discovered) {
927
+ if (!pendingIds.includes(discoveredTask.taskId)) continue;
928
+ const promptPath = path.join(discoveredTask.folderPath, "PROMPT.md");
929
+ const promptMarkdown = fs.readFileSync(promptPath, "utf-8");
930
+ const parsedContract = parseContract(promptMarkdown);
931
+ const promptRelPath = path.relative(ctx.projectRoot, promptPath);
932
+ const warnings = collectStaleFileScopeMustChangeWarnings(
933
+ ctx.projectRoot,
934
+ parsedContract,
935
+ promptRelPath,
936
+ );
937
+ if (warnings.length > 0) {
938
+ staleTasks.push({ taskId: discoveredTask.taskId, warnings });
939
+ }
940
+ }
941
+
942
+ return staleTasks;
943
+ }
944
+
945
+ /**
946
+ * Warn when pending tasks have fileScopeMustChange paths already changed on main (issue #56).
947
+ *
948
+ * @param {object} ctx
949
+ * @param {string} ctx.projectRoot
950
+ * @param {ReturnType<typeof loadSpineConfig>} [ctx.configResult]
951
+ */
952
+ export function checkPrelandedFileScopeWarn(ctx) {
953
+ try {
954
+ const staleTasks = listPrelandedFileScopeStaleTasks(ctx);
955
+ if (staleTasks.length === 0) {
956
+ return makeCheck(
957
+ "prelanded-file-scope",
958
+ true,
959
+ "no pending tasks with stale fileScopeMustChange vs main",
960
+ );
961
+ }
962
+
963
+ const preview = staleTasks.map((entry) => entry.taskId).slice(0, 5).join(", ");
964
+ const suffix = staleTasks.length > 5 ? ` (+${staleTasks.length - 5} more)` : "";
965
+ return makeCheck(
966
+ "prelanded-file-scope",
967
+ true,
968
+ `${staleTasks.length} pending task(s) with fileScopeMustChange already changed on main (${preview}${suffix})`,
969
+ {
970
+ warning: true,
971
+ details: { staleTasks },
972
+ suggestedCommand:
973
+ "spine tasks validate pending --warnings-only; amend PROMPT ## Contract before batch start",
974
+ },
975
+ );
976
+ } catch (err) {
977
+ const message = err?.message ?? String(err);
978
+ return makeCheck(
979
+ "prelanded-file-scope",
980
+ true,
981
+ `prelanded file-scope check skipped: ${message}`,
982
+ );
983
+ }
984
+ }
985
+
986
+ function formatPrelandedFileScopePlanWarning(staleTasks) {
987
+ const preview = staleTasks.map((entry) => entry.taskId).slice(0, 5).join(", ");
988
+ return [
989
+ "⚠️ Pre-landed contract risk: pending task(s)",
990
+ `(${preview}) have fileScopeMustChange paths already changed on main.`,
991
+ "Amend PROMPT ## Contract before batch start or expect contract rework loops.",
992
+ ].join(" ");
993
+ }
994
+
995
+ /**
996
+ * @param {object} ctx
997
+ */
998
+ export function runPreflightPlanCheck(ctx) {
999
+ const { projectRoot, configResult } = ctx;
1000
+ const config = configResult?.config;
1001
+
1002
+ if (!config || configResult?.error) {
1003
+ const msg = configResult?.error?.message ?? 'spine-config.json not initialized';
1004
+ return {
1005
+ status: "error",
1006
+ message: `Cannot build plan: ${msg}`,
1007
+ };
1008
+ }
1009
+
1010
+ const tasksRootPath = resolveTasksRoot(projectRoot, configResult);
1011
+ if (!tasksRootPath) {
1012
+ return {
1013
+ status: "error",
1014
+ message: "Cannot build plan: tasksRoot not configured",
1015
+ };
1016
+ }
1017
+
1018
+ try {
1019
+ const discovered = discoverTasks(tasksRootPath);
1020
+ const { pendingIds, excludedCount } = summarizePendingScope(discovered, tasksRootPath);
1021
+ const orchMergeRisk = predictOrchMergeConflictRisk(ctx);
1022
+ const prelandedFileScopeTasks = listPrelandedFileScopeStaleTasks(ctx);
1023
+ if (pendingIds.length === 0) {
1024
+ const maxParallel = config.lanes?.maxParallel ?? 1;
1025
+ const lines = [
1026
+ "Spine plan — pending",
1027
+ `0 task(s) · 0 wave(s) · maxParallel ${maxParallel}`,
1028
+ `${excludedCount} excluded (.DONE on disk)`,
1029
+ ];
1030
+ if (orchMergeRisk.risky) {
1031
+ lines.push(formatOrchMergeConflictPlanWarning(orchMergeRisk));
1032
+ }
1033
+ if (prelandedFileScopeTasks.length > 0) {
1034
+ lines.push(formatPrelandedFileScopePlanWarning(prelandedFileScopeTasks));
1035
+ }
1036
+ return {
1037
+ status: "ok",
1038
+ message: lines.join("\n"),
1039
+ details: {
1040
+ waves: 0,
1041
+ pendingCount: 0,
1042
+ excludedCount,
1043
+ orchMergeConflictRisk: orchMergeRisk,
1044
+ prelandedFileScopeTasks,
1045
+ },
1046
+ };
1047
+ }
1048
+
1049
+ const plan = buildPlan({ scope: "pending", config, tasksRoot: tasksRootPath });
1050
+ const waveCount = plan.waves?.length ?? 0;
1051
+ const planText = formatPlanHuman(plan).trimEnd();
1052
+ const planWarnings = [];
1053
+ if (orchMergeRisk.risky) {
1054
+ planWarnings.push(formatOrchMergeConflictPlanWarning(orchMergeRisk));
1055
+ }
1056
+ if (prelandedFileScopeTasks.length > 0) {
1057
+ planWarnings.push(formatPrelandedFileScopePlanWarning(prelandedFileScopeTasks));
1058
+ }
1059
+ return {
1060
+ status: "ok",
1061
+ message:
1062
+ planWarnings.length > 0
1063
+ ? `${planText}\n\n${planWarnings.join("\n\n")}`
1064
+ : planText,
1065
+ details: { waves: waveCount, orchMergeConflictRisk: orchMergeRisk, prelandedFileScopeTasks },
1066
+ };
1067
+ } catch (err) {
1068
+ const msg = err?.message ?? String(err);
1069
+ if (msg === NO_PENDING_TASKS_ERROR) {
1070
+ const maxParallel = config.lanes?.maxParallel ?? 1;
1071
+ const orchMergeRisk = predictOrchMergeConflictRisk(ctx);
1072
+ const prelandedFileScopeTasks = listPrelandedFileScopeStaleTasks(ctx);
1073
+ const lines = [
1074
+ "Spine plan — pending",
1075
+ `0 task(s) · 0 wave(s) · maxParallel ${maxParallel}`,
1076
+ "All discovered tasks have .DONE on disk",
1077
+ ];
1078
+ if (orchMergeRisk.risky) {
1079
+ lines.push(formatOrchMergeConflictPlanWarning(orchMergeRisk));
1080
+ }
1081
+ if (prelandedFileScopeTasks.length > 0) {
1082
+ lines.push(formatPrelandedFileScopePlanWarning(prelandedFileScopeTasks));
1083
+ }
1084
+ return {
1085
+ status: "ok",
1086
+ message: lines.join("\n"),
1087
+ details: {
1088
+ waves: 0,
1089
+ pendingCount: 0,
1090
+ orchMergeConflictRisk: orchMergeRisk,
1091
+ prelandedFileScopeTasks,
1092
+ },
1093
+ };
1094
+ }
1095
+ return {
1096
+ status: "error",
1097
+ message: `Failed to build plan: ${msg}`,
1098
+ };
1099
+ }
1100
+ }
1101
+
1102
+ /**
1103
+ * @param {object} options
1104
+ * @param {string} options.projectRoot
1105
+ * @param {boolean} [options.skipDoctor]
1106
+ * @param {() => ReturnType<typeof runDoctorChecks>} [options.runDoctor]
1107
+ * @param {typeof runReconciliationCheck} [options.runReconciliation]
1108
+ */
1109
+ export function runBatchPreflight(options) {
1110
+ const { projectRoot, skipDoctor = false } = options;
1111
+ const ctx = { projectRoot, configResult: loadSpineConfig(projectRoot) };
1112
+ const checks = [];
1113
+
1114
+ if (!skipDoctor) {
1115
+ checks.push(
1116
+ checkDoctor({
1117
+ projectRoot,
1118
+ runDoctor: options.runDoctor,
1119
+ }),
1120
+ );
1121
+ }
1122
+
1123
+ checks.push(checkStalePathSpine(ctx));
1124
+
1125
+ checks.push(checkGitClean(ctx));
1126
+ checks.push(
1127
+ buildCoexistencePreflightCheck({
1128
+ projectRoot,
1129
+ runReconciliation: options.runReconciliation,
1130
+ }),
1131
+ );
1132
+ checks.push(
1133
+ checkNoActiveBatch({
1134
+ projectRoot,
1135
+ runReconciliation: options.runReconciliation,
1136
+ }),
1137
+ );
1138
+ checks.push(checkTasksRoot(ctx));
1139
+ checks.push(checkPiSpineRoot(ctx));
1140
+ checks.push(checkDependenciesJson(ctx));
1141
+ checks.push(checkWorktreeSetupHook(ctx));
1142
+ checks.push(checkTasksValidate(ctx));
1143
+ checks.push(checkStubReleaseCritical(ctx));
1144
+ checks.push(checkOrchMergeConflictWarn(ctx));
1145
+ checks.push(checkPrelandedFileScopeWarn(ctx));
1146
+
1147
+ const plan = runPreflightPlanCheck(ctx);
1148
+ checks.push(
1149
+ makeCheck("plan", plan.status === "ok", plan.message, {
1150
+ details: plan,
1151
+ }),
1152
+ );
1153
+
1154
+ const ok = checks.every((check) => check.ok);
1155
+ return {
1156
+ ok,
1157
+ exitCode: ok ? 0 : 1,
1158
+ checks,
1159
+ };
1160
+ }
1161
+
1162
+ export function formatPreflightHuman(result) {
1163
+ const lines = ["\nBatch preflight\n"];
1164
+ for (const check of result.checks) {
1165
+ const icon = !check.ok ? "❌" : check.warning ? "⚠️" : "✅";
1166
+ lines.push(` ${icon} ${check.id}: ${check.message}`);
1167
+ if (!check.ok && check.suggestedCommand) {
1168
+ lines.push(` → ${check.suggestedCommand}`);
1169
+ } else if (check.warning && check.suggestedCommand) {
1170
+ lines.push(` → ${check.suggestedCommand}`);
1171
+ }
1172
+ }
1173
+ lines.push("");
1174
+ lines.push(
1175
+ result.ok
1176
+ ? "✅ Preflight passed — ready to plan or start a batch.\n"
1177
+ : "❌ Preflight failed.\n",
1178
+ );
1179
+ return lines.join("\n");
1180
+ }