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,483 @@
1
+ /**
2
+ * Doctor check orchestration — library surface for preflight and CLI.
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { execFileSync, spawnSync } from "node:child_process";
8
+
9
+ import { commandExists } from "../util/command-exists.mjs";
10
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
11
+ import { PACKAGE_ROOT, SPINE_GITIGNORE_ENTRIES } from "../config/spine-init-constants.mjs";
12
+ import {
13
+ buildMaxParallelDoctorCheck,
14
+ detectCpuCount,
15
+ } from "./suggest-max-parallel.mjs";
16
+ import { buildStalePathDoctorCheck } from "./stale-path.mjs";
17
+ import { buildCoexistenceDoctorCheck } from "./coexistence.mjs";
18
+ import { buildTaskPacketSizeDoctorCheck } from "./task-packet-size.mjs";
19
+ import {
20
+ buildPiWorkerTimeoutDoctorCheck,
21
+ buildStallConfigDoctorCheck,
22
+ } from "./stall-config.mjs";
23
+ import { buildRulesManifestDoctorCheck } from "./rules-manifest.mjs";
24
+ import { buildWorktreeHealthDoctorCheck } from "./worktree-health.mjs";
25
+ import { buildStaleWorktreesDoctorCheck } from "./stale-worktrees.mjs";
26
+ import { buildWorkerBackendDoctorCheck } from "../config/worker-backend.mjs";
27
+ import { buildAgentModelInheritDoctorCheck, buildReviewerPerTypePinsDoctorCheck } from "./agent-model-inherit.mjs";
28
+ import { CURSOR_RULES_ROOT_REL } from "../config/cursor-rules/discover.mjs";
29
+ import { RULES_PROFILE_REL_PATH } from "../config/cursor-rules/profile.mjs";
30
+ import {
31
+ formatConfigSourceDetail,
32
+ resolveTasksRootPath,
33
+ } from "../config/env-overrides.mjs";
34
+
35
+ const MIN_NODE_MAJOR = 22;
36
+ const nodeMajor = parseInt(process.versions.node.split(".")[0], 10);
37
+
38
+ const SPINE_CLI_ENTRY = path.join(PACKAGE_ROOT, "bin", "spine.mjs");
39
+
40
+ const REQUIRED_AGENT_FILES = ["worker.md", "reviewer.md", "supervisor.md"];
41
+
42
+ function getVersion(cmd, flag = "--version") {
43
+ let result;
44
+ try {
45
+ result = spawnSync(cmd, [flag], {
46
+ encoding: "utf-8",
47
+ stdio: ["ignore", "pipe", "pipe"],
48
+ });
49
+ } catch {
50
+ return null;
51
+ }
52
+
53
+ if (!result || result.error || result.status !== 0) return null;
54
+
55
+ const stdout = (result.stdout ?? "").toString().trim();
56
+ const stderr = (result.stderr ?? "").toString().trim();
57
+ if (stdout) return stdout;
58
+ if (stderr) return stderr;
59
+ return null;
60
+ }
61
+
62
+ function getPackageVersion() {
63
+ try {
64
+ const pkg = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, "package.json"), "utf-8"));
65
+ return pkg.version || "unknown";
66
+ } catch {
67
+ return "unknown";
68
+ }
69
+ }
70
+
71
+ function getMinPiVersion() {
72
+ try {
73
+ const pkg = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, "package.json"), "utf-8"));
74
+ return pkg.pi?.minPiVersion ?? null;
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+
80
+ function parseSemver(versionText) {
81
+ const match = String(versionText ?? "")
82
+ .trim()
83
+ .match(/(\d+)\.(\d+)\.(\d+)/);
84
+ if (!match) return null;
85
+ return {
86
+ major: Number(match[1]),
87
+ minor: Number(match[2]),
88
+ patch: Number(match[3]),
89
+ };
90
+ }
91
+
92
+ function compareSemver(a, b) {
93
+ if (!a || !b) return null;
94
+ if (a.major !== b.major) return a.major - b.major;
95
+ if (a.minor !== b.minor) return a.minor - b.minor;
96
+ return a.patch - b.patch;
97
+ }
98
+
99
+ function isInsideGitRepo(dir) {
100
+ try {
101
+ execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
102
+ cwd: dir,
103
+ stdio: ["ignore", "pipe", "pipe"],
104
+ timeout: 5000,
105
+ });
106
+ return true;
107
+ } catch {
108
+ return false;
109
+ }
110
+ }
111
+
112
+ function gitSupportsWorktrees() {
113
+ try {
114
+ execFileSync("git", ["worktree", "--help"], {
115
+ stdio: ["ignore", "pipe", "pipe"],
116
+ timeout: 5000,
117
+ });
118
+ return true;
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+
124
+ function parsePiListModelsOutput(output) {
125
+ const lines = output.split(/\r?\n/).filter(Boolean);
126
+ let providerCol = 0;
127
+ let modelCol = 1;
128
+ let headerSeen = false;
129
+
130
+ for (const line of lines) {
131
+ const trimmed = line.trim();
132
+ if (!headerSeen && /^provider\b/i.test(trimmed)) {
133
+ headerSeen = true;
134
+ const lowerHeader = trimmed.toLowerCase().split(/\s+/);
135
+ const providerIdx = lowerHeader.indexOf("provider");
136
+ const modelIdx = lowerHeader.indexOf("model");
137
+ if (providerIdx >= 0) providerCol = providerIdx;
138
+ if (modelIdx >= 0) modelCol = modelIdx;
139
+ continue;
140
+ }
141
+
142
+ const parts = trimmed.split(/\s+/);
143
+ const provider = String(parts[providerCol] ?? parts[0] ?? "").trim();
144
+ const id = String(parts[modelCol] ?? parts[1] ?? "").trim();
145
+ if (!provider || !id) continue;
146
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(provider)) continue;
147
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(id)) continue;
148
+ return { provider, id };
149
+ }
150
+
151
+ return null;
152
+ }
153
+
154
+ function checkModelProvider() {
155
+ if (!commandExists("pi")) {
156
+ return { ok: false, detail: "pi not installed", suggestedCommand: "https://pi.dev" };
157
+ }
158
+
159
+ try {
160
+ const result = spawnSync("pi", ["--list-models"], {
161
+ encoding: "utf-8",
162
+ stdio: ["ignore", "pipe", "pipe"],
163
+ timeout: 30_000,
164
+ });
165
+ if (result.error) throw result.error;
166
+ const output = `${result.stdout ?? ""}
167
+ ${result.stderr ?? ""}`.trim();
168
+ const model = parsePiListModelsOutput(output);
169
+ if (!model) {
170
+ return {
171
+ ok: false,
172
+ detail: "no models available",
173
+ suggestedCommand: "pi login",
174
+ };
175
+ }
176
+ return {
177
+ ok: true,
178
+ detail: `${model.provider}/${model.id}`,
179
+ };
180
+ } catch (err) {
181
+ return {
182
+ ok: false,
183
+ detail: err.message,
184
+ suggestedCommand: "pi login",
185
+ };
186
+ }
187
+ }
188
+
189
+ function resolveTasksRoot(projectRoot, configResult) {
190
+ if (!configResult.config) {
191
+ return null;
192
+ }
193
+ return resolveTasksRootPath(projectRoot, configResult.config);
194
+ }
195
+
196
+ function isTestingCommandEmpty(command) {
197
+ return !command || String(command).trim() === "";
198
+ }
199
+
200
+ /**
201
+ * Warn when evidence gates expect commands that are missing (SP-112).
202
+ *
203
+ * @param {object} [config]
204
+ * @returns {Array<{ label: string, ok: boolean, warning?: boolean, detail: string, suggestedCommand?: string }>}
205
+ */
206
+ export function buildTestingEvidenceDoctorChecks(config = {}) {
207
+ const gates = config.gates ?? {};
208
+ const testing = config.testing ?? {};
209
+ const checks = [];
210
+
211
+ if (gates.collectBuildEvidence === true && isTestingCommandEmpty(testing.build)) {
212
+ checks.push({
213
+ label: "testing.build (evidence gate)",
214
+ ok: true,
215
+ warning: true,
216
+ detail: "collectBuildEvidence enabled but testing.build is empty — integrate evidence will skip build proof",
217
+ suggestedCommand: "spine settings set testing.build \"npm run typecheck\"",
218
+ });
219
+ }
220
+
221
+ if (gates.collectTestEvidence !== false && isTestingCommandEmpty(testing.test)) {
222
+ checks.push({
223
+ label: "testing.test (evidence gate)",
224
+ ok: true,
225
+ warning: true,
226
+ detail: "collectTestEvidence enabled but testing.test is empty — integrate evidence will skip test proof",
227
+ suggestedCommand: "spine settings set testing.test \"npm test\"",
228
+ });
229
+ }
230
+
231
+ return checks;
232
+ }
233
+
234
+ export function runDoctorChecks(projectRoot = process.cwd()) {
235
+ const checks = [];
236
+ let issueCount = 0;
237
+
238
+ const record = (label, ok, extra = {}) => {
239
+ checks.push({ label, ok, ...extra });
240
+ if (!ok) issueCount++;
241
+ };
242
+
243
+ record("Node.js >= 22.0.0", nodeMajor >= MIN_NODE_MAJOR, {
244
+ detail: `v${process.versions.node}`,
245
+ });
246
+ record("git installed", commandExists("git"), { detail: getVersion("git") });
247
+ record("git worktree support", gitSupportsWorktrees(), { detail: getVersion("git") });
248
+ record("pi installed", commandExists("pi"), { detail: getVersion("pi") });
249
+
250
+ const piVersionText = getVersion("pi");
251
+ const minPiVersion = getMinPiVersion();
252
+ if (piVersionText && minPiVersion) {
253
+ const current = parseSemver(piVersionText);
254
+ const minimum = parseSemver(minPiVersion);
255
+ const cmp = compareSemver(current, minimum);
256
+ if (cmp === null) {
257
+ checks.push({
258
+ label: "pi version supported",
259
+ ok: true,
260
+ warning: true,
261
+ detail: `could not parse pi version (${piVersionText})`,
262
+ });
263
+ } else if (cmp < 0) {
264
+ checks.push({
265
+ label: "pi version supported",
266
+ ok: true,
267
+ warning: true,
268
+ detail: `${piVersionText} is below supported minimum ${minPiVersion}`,
269
+ });
270
+ } else {
271
+ checks.push({
272
+ label: "pi version supported",
273
+ ok: true,
274
+ detail: `>= ${minPiVersion}`,
275
+ });
276
+ }
277
+ }
278
+
279
+ const pkgVersion = getPackageVersion();
280
+ const isProjectLocal = PACKAGE_ROOT.includes(".pi");
281
+ const installType = isProjectLocal ? "project-local" : "development";
282
+ checks.push({
283
+ label: "pi-spine package",
284
+ ok: true,
285
+ detail: `v${pkgVersion}, ${installType}`,
286
+ });
287
+
288
+ checks.push(
289
+ buildStalePathDoctorCheck({
290
+ packageRoot: PACKAGE_ROOT,
291
+ runningSpinePath: SPINE_CLI_ENTRY,
292
+ }),
293
+ );
294
+
295
+ const coexistenceCheck = buildCoexistenceDoctorCheck({ projectRoot });
296
+ checks.push(coexistenceCheck);
297
+ if (!coexistenceCheck.ok) issueCount++;
298
+
299
+ record("git repository detected", isInsideGitRepo(projectRoot));
300
+
301
+ const modelCheck = checkModelProvider();
302
+ record("model provider configured", modelCheck.ok, {
303
+ detail: modelCheck.detail,
304
+ suggestedCommand: modelCheck.suggestedCommand,
305
+ });
306
+
307
+ const configResult = loadSpineConfig(projectRoot);
308
+ if (configResult.error) {
309
+ record(".spine/spine-config.json valid", false, {
310
+ detail: configResult.error.message,
311
+ code: configResult.error.code,
312
+ suggestedCommand: configResult.error.suggestedCommand,
313
+ });
314
+ } else {
315
+ const tasksRootDetail = formatConfigSourceDetail(
316
+ configResult.sources,
317
+ configResult.envVars,
318
+ "paths.tasksRoot",
319
+ configResult.config.paths?.tasksRoot,
320
+ );
321
+ const maxParallelDetail = formatConfigSourceDetail(
322
+ configResult.sources,
323
+ configResult.envVars,
324
+ "lanes.maxParallel",
325
+ configResult.config.lanes?.maxParallel,
326
+ );
327
+ record(".spine/spine-config.json valid", true, {
328
+ detail: `project: ${configResult.config.project.name}`,
329
+ });
330
+ checks.push({
331
+ label: "paths.tasksRoot (effective)",
332
+ ok: true,
333
+ detail: tasksRootDetail,
334
+ });
335
+ checks.push({
336
+ label: "lanes.maxParallel (effective)",
337
+ ok: true,
338
+ detail: maxParallelDetail,
339
+ });
340
+
341
+ const configuredMaxParallel = configResult.config.lanes?.maxParallel ?? 3;
342
+ checks.push(
343
+ buildMaxParallelDoctorCheck({
344
+ configured: configuredMaxParallel,
345
+ cpuCount: detectCpuCount(),
346
+ }),
347
+ );
348
+ checks.push(buildStallConfigDoctorCheck({ config: configResult.config }));
349
+ checks.push(buildPiWorkerTimeoutDoctorCheck({ config: configResult.config }));
350
+ checks.push(buildReviewerPerTypePinsDoctorCheck({ config: configResult.config }));
351
+ checks.push(buildAgentModelInheritDoctorCheck({
352
+ config: configResult.config,
353
+ projectRoot,
354
+ }));
355
+ const worktreeHealthCheck = buildWorktreeHealthDoctorCheck({
356
+ projectRoot,
357
+ config: configResult.config,
358
+ });
359
+ checks.push(worktreeHealthCheck);
360
+ if (!worktreeHealthCheck.ok) issueCount++;
361
+ const workerBackendCheck = buildWorkerBackendDoctorCheck(configResult.config);
362
+ checks.push(workerBackendCheck);
363
+ if (!workerBackendCheck.ok) issueCount++;
364
+ for (const testingCheck of buildTestingEvidenceDoctorChecks(configResult.config)) {
365
+ checks.push(testingCheck);
366
+ }
367
+ }
368
+
369
+ for (const agentFile of REQUIRED_AGENT_FILES) {
370
+ const relPath = `.spine/agents/${agentFile}`;
371
+ record(`${relPath} exists`, fs.existsSync(path.join(projectRoot, relPath)), {
372
+ suggestedCommand: "spine init",
373
+ });
374
+ }
375
+
376
+ const tasksRootPath = resolveTasksRoot(projectRoot, configResult);
377
+ const metricsPath = path.join(
378
+ projectRoot,
379
+ configResult.config?.metrics?.path ?? ".spine/run-metrics.jsonl",
380
+ );
381
+ if (fs.existsSync(metricsPath)) {
382
+ try {
383
+ const lines = fs
384
+ .readFileSync(metricsPath, "utf-8")
385
+ .trim()
386
+ .split("\n")
387
+ .filter(Boolean);
388
+ checks.push({
389
+ label: "run metrics available",
390
+ ok: true,
391
+ detail: `${lines.length} record(s) in ${path.relative(projectRoot, metricsPath)}`,
392
+ suggestedCommand: "spine metrics show",
393
+ });
394
+ } catch {
395
+ checks.push({
396
+ label: "run metrics available",
397
+ ok: true,
398
+ warning: true,
399
+ detail: `present but unreadable: ${path.relative(projectRoot, metricsPath)}`,
400
+ suggestedCommand: "spine metrics show",
401
+ });
402
+ }
403
+ }
404
+
405
+ if (tasksRootPath) {
406
+ record("tasks root exists", fs.existsSync(tasksRootPath), {
407
+ detail: path.relative(projectRoot, tasksRootPath),
408
+ suggestedCommand: `mkdir -p ${path.relative(projectRoot, tasksRootPath)}`,
409
+ });
410
+
411
+ const contextPath = path.join(tasksRootPath, "CONTEXT.md");
412
+ checks.push({
413
+ label: "CONTEXT.md exists",
414
+ ok: true,
415
+ warning: !fs.existsSync(contextPath),
416
+ optional: true,
417
+ detail: fs.existsSync(contextPath) ? "present" : "missing (optional)",
418
+ });
419
+ checks.push(buildTaskPacketSizeDoctorCheck({ tasksRoot: tasksRootPath }));
420
+ }
421
+
422
+ if (isInsideGitRepo(projectRoot)) {
423
+ checks.push(buildStaleWorktreesDoctorCheck({ projectRoot }));
424
+
425
+ const gitignorePath = path.join(projectRoot, ".gitignore");
426
+ if (!fs.existsSync(gitignorePath)) {
427
+ checks.push({
428
+ label: ".gitignore has spine runtime entries",
429
+ ok: true,
430
+ warning: true,
431
+ detail: ".gitignore missing",
432
+ suggestedCommand: "spine init",
433
+ });
434
+ } else {
435
+ const content = fs.readFileSync(gitignorePath, "utf-8");
436
+ const existingLines = new Set(content.split(/\r?\n/).map((line) => line.trim()));
437
+ const missing = SPINE_GITIGNORE_ENTRIES.filter((entry) => !existingLines.has(entry));
438
+ checks.push({
439
+ label: ".gitignore has spine runtime entries",
440
+ ok: true,
441
+ warning: missing.length > 0,
442
+ detail:
443
+ missing.length === 0
444
+ ? "complete"
445
+ : `missing ${missing.length} entr${missing.length === 1 ? "y" : "ies"}`,
446
+ suggestedCommand: missing.length > 0 ? "spine init" : undefined,
447
+ });
448
+ }
449
+
450
+ const metricsRelPath = configResult.config?.metrics?.path ?? ".spine/run-metrics.jsonl";
451
+ try {
452
+ const tracked = execFileSync("git", ["ls-files", "--", metricsRelPath], {
453
+ cwd: projectRoot,
454
+ encoding: "utf-8",
455
+ stdio: ["ignore", "pipe", "pipe"],
456
+ timeout: 5000,
457
+ }).trim();
458
+ if (tracked) {
459
+ checks.push({
460
+ label: "run-metrics.jsonl not git-tracked",
461
+ ok: true,
462
+ warning: true,
463
+ detail: `${metricsRelPath} is tracked by git — runtime appends break preflight until untracked`,
464
+ suggestedCommand: `git rm --cached -- ${metricsRelPath}`,
465
+ });
466
+ }
467
+ } catch {
468
+ // Git ls-files unavailable; skip tracked-metrics advisory.
469
+ }
470
+ }
471
+
472
+ const rulesRootPath = path.join(projectRoot, CURSOR_RULES_ROOT_REL);
473
+ const rulesProfilePath = path.join(projectRoot, RULES_PROFILE_REL_PATH);
474
+ if (fs.existsSync(rulesRootPath) || fs.existsSync(rulesProfilePath)) {
475
+ checks.push(buildRulesManifestDoctorCheck(projectRoot));
476
+ }
477
+
478
+ return {
479
+ ok: issueCount === 0,
480
+ issueCount,
481
+ checks,
482
+ };
483
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Sequence auto-approve gate safety (GitHub #54 Tier 2 SP-E).
3
+ */
4
+
5
+ import { isStubWorkerMode } from "./stall-config.mjs";
6
+
7
+ const AUTO_APPROVE_REFUSAL_MESSAGE =
8
+ "--auto-approve-gate bypasses the human integrate gate and is blocked for real pi workers. " +
9
+ "Use SPINE_WORKER_STUB=1 for CI/stub sequences, or pass --force after reviewing the risk.";
10
+
11
+ /**
12
+ * @param {object} [params]
13
+ * @param {boolean} [params.autoApproveGate]
14
+ * @param {boolean} [params.force]
15
+ */
16
+ export function validateSequenceAutoApproveGate({ autoApproveGate = false, force = false } = {}) {
17
+ if (!autoApproveGate) {
18
+ return { ok: true };
19
+ }
20
+
21
+ if (isStubWorkerMode()) {
22
+ return { ok: true, stubMode: true };
23
+ }
24
+
25
+ if (force) {
26
+ return { ok: true, forced: true };
27
+ }
28
+
29
+ return {
30
+ ok: false,
31
+ error: "auto_approve_gate_unsafe",
32
+ output: `${AUTO_APPROVE_REFUSAL_MESSAGE}\n`,
33
+ suggestedCommand: "SPINE_WORKER_STUB=1 spine run sequence <scope> --auto-approve-gate",
34
+ };
35
+ }
36
+
37
+ /**
38
+ * Doctor advisory for sequence auto-approve gate usage.
39
+ */
40
+ export function buildSequenceAutoApproveDoctorCheck() {
41
+ if (isStubWorkerMode()) {
42
+ return {
43
+ label: "sequence --auto-approve-gate",
44
+ ok: true,
45
+ detail: "SPINE_WORKER_STUB set — auto gate approval permitted for stub/CI sequences",
46
+ };
47
+ }
48
+
49
+ return {
50
+ label: "sequence --auto-approve-gate",
51
+ ok: true,
52
+ warning: true,
53
+ detail:
54
+ "real pi — flag blocked unless --force; use manual spine gate approve between waves",
55
+ suggestedCommand: "spine doctor # verify SPINE_WORKER_STUB is unset before production runs",
56
+ };
57
+ }
@@ -154,3 +154,25 @@ export function buildStalePathDoctorCheck({
154
154
  suggestedCommand: `cd ${packageRoot} && npm link`,
155
155
  };
156
156
  }
157
+
158
+ /**
159
+ * True when PATH `spine` exists but is not the checkout binary (version or mtime drift).
160
+ * Used by batch preflight to fail closed before a stale global CLI reproduces SP-306.
161
+ *
162
+ * @param {ReturnType<typeof buildStalePathDoctorCheck>} check
163
+ */
164
+ export function isStalePathSpineBlocking(check) {
165
+ return check.warning === true && String(check.label ?? "").includes("stale");
166
+ }
167
+
168
+ /**
169
+ * Preflight blocks only on PATH vs package **version** mismatch (issue #12 / SP-308).
170
+ * Mtime-only drift remains a doctor warning so linked checkouts are not blocked.
171
+ *
172
+ * @param {ReturnType<typeof buildStalePathDoctorCheck>} check
173
+ */
174
+ export function isStalePathSpinePreflightBlocking(check) {
175
+ return (
176
+ check.warning === true && String(check.detail ?? "").includes("vs package")
177
+ );
178
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Doctor check for leftover `.worktrees/spine-<batchId>/` dirs (issue #26, SP-351).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ import { TERMINAL_BATCH_PHASES } from "../batch/state.mjs";
9
+
10
+ const SPINE_WORKTREE_DIR_PATTERN = /^spine-(.+)$/;
11
+
12
+ /**
13
+ * Batch ID from `.spine/batch-state.json` when the batch is not terminal.
14
+ *
15
+ * @param {string} projectRoot
16
+ * @returns {string|null}
17
+ */
18
+ export function resolveInProgressSpineBatchId(projectRoot) {
19
+ const statePath = path.join(projectRoot, ".spine", "batch-state.json");
20
+ if (!fs.existsSync(statePath)) return null;
21
+
22
+ try {
23
+ const raw = JSON.parse(fs.readFileSync(statePath, "utf-8"));
24
+ const batchId = String(raw.batchId ?? raw.id ?? "").trim();
25
+ if (!batchId) return null;
26
+
27
+ const phase = String(raw.phase ?? raw.status ?? "").toLowerCase();
28
+ if (TERMINAL_BATCH_PHASES.has(phase)) return null;
29
+
30
+ return batchId;
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * List `.worktrees/spine-<batchId>/` directories with no matching in-progress batch.
38
+ *
39
+ * @param {string} projectRoot
40
+ * @param {string|null} [activeBatchId]
41
+ * @returns {string[]} batch IDs (not full paths)
42
+ */
43
+ export function listStaleSpineWorktreeBatchIds(projectRoot, activeBatchId = null) {
44
+ const worktreesRoot = path.join(projectRoot, ".worktrees");
45
+ if (!fs.existsSync(worktreesRoot)) return [];
46
+
47
+ /** @type {string[]} */
48
+ const stale = [];
49
+ const entries = fs.readdirSync(worktreesRoot, { withFileTypes: true });
50
+ for (const entry of entries) {
51
+ if (!entry.isDirectory()) continue;
52
+ const match = SPINE_WORKTREE_DIR_PATTERN.exec(entry.name);
53
+ if (!match) continue;
54
+
55
+ const batchId = match[1].trim();
56
+ if (!batchId) continue;
57
+ if (activeBatchId && batchId === activeBatchId) continue;
58
+
59
+ stale.push(batchId);
60
+ }
61
+
62
+ stale.sort();
63
+ return stale;
64
+ }
65
+
66
+ /**
67
+ * @param {object} params
68
+ * @param {string} params.projectRoot
69
+ * @param {string|null} [params.activeBatchId]
70
+ * @param {(root: string) => string|null} [params.resolveActiveBatchId]
71
+ */
72
+ export function buildStaleWorktreesDoctorCheck({
73
+ projectRoot,
74
+ activeBatchId,
75
+ resolveActiveBatchId = resolveInProgressSpineBatchId,
76
+ }) {
77
+ const inProgressBatchId =
78
+ activeBatchId === undefined ? resolveActiveBatchId(projectRoot) : activeBatchId;
79
+ const staleBatchIds = listStaleSpineWorktreeBatchIds(projectRoot, inProgressBatchId);
80
+
81
+ if (staleBatchIds.length === 0) {
82
+ return {
83
+ label: "stale worktrees",
84
+ ok: true,
85
+ detail: inProgressBatchId
86
+ ? `none (active batch ${inProgressBatchId})`
87
+ : "none",
88
+ };
89
+ }
90
+
91
+ const preview = staleBatchIds.slice(0, 3).map((id) => `spine-${id}`).join(", ");
92
+ const suffix = staleBatchIds.length > 3 ? ` (+${staleBatchIds.length - 3} more)` : "";
93
+
94
+ return {
95
+ label: "stale worktrees",
96
+ ok: true,
97
+ warning: true,
98
+ detail: `${staleBatchIds.length} leftover batch dir(s): ${preview}${suffix}`,
99
+ suggestedCommand:
100
+ "After spine batch complete/dismiss, lane worktrees auto-clean (lanes.cleanupWorktreesOnComplete). Remove legacy dirs: git worktree remove --force .worktrees/spine-<batchId>/lane-N; rm -rf .worktrees/spine-<batchId>",
101
+ };
102
+ }