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,169 @@
1
+ /**
2
+ * Detect pi-web-access duplicate extension sources (GitHub #104, SP-450).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+
9
+ /** Tools registered by pi-web-access that collide when loaded twice. */
10
+ export const PI_WEB_ACCESS_TOOL_NAMES = ["web_search", "fetch_content", "get_search_content"];
11
+
12
+ const PI_WEB_ACCESS_PACKAGE_RE = /pi-web-access/i;
13
+
14
+ /**
15
+ * @param {string} [agentDir]
16
+ */
17
+ export function resolvePiAgentDir(agentDir = process.env.PI_AGENT_DIR) {
18
+ if (agentDir && String(agentDir).trim()) {
19
+ return path.resolve(String(agentDir));
20
+ }
21
+ return path.join(os.homedir(), ".pi", "agent");
22
+ }
23
+
24
+ /**
25
+ * @param {string} settingsPath
26
+ * @returns {string[]}
27
+ */
28
+ export function readPiPackageSources(settingsPath) {
29
+ if (!fs.existsSync(settingsPath)) return [];
30
+ try {
31
+ const raw = JSON.parse(fs.readFileSync(settingsPath, "utf-8"));
32
+ const packages = raw?.packages;
33
+ if (!Array.isArray(packages)) return [];
34
+ return packages.map((entry) => String(entry ?? "").trim()).filter(Boolean);
35
+ } catch {
36
+ return [];
37
+ }
38
+ }
39
+
40
+ /**
41
+ * @param {string} source
42
+ * @returns {boolean}
43
+ */
44
+ export function isPiWebAccessPackageSource(source) {
45
+ return PI_WEB_ACCESS_PACKAGE_RE.test(String(source ?? ""));
46
+ }
47
+
48
+ /**
49
+ * Resolve a package source entry to an absolute path when possible.
50
+ *
51
+ * @param {string} source
52
+ * @param {string} settingsDir
53
+ * @param {string} [agentDir]
54
+ */
55
+ export function resolvePiPackageSourcePath(source, settingsDir, agentDir = resolvePiAgentDir()) {
56
+ const normalized = String(source ?? "").trim();
57
+ if (!normalized) return null;
58
+ if (normalized.startsWith("npm:")) {
59
+ const pkgName = normalized.slice(4);
60
+ const segments = pkgName.split("/").filter(Boolean);
61
+ return path.join(agentDir, "npm", "node_modules", ...segments);
62
+ }
63
+ if (path.isAbsolute(normalized)) {
64
+ return normalized;
65
+ }
66
+ return path.resolve(settingsDir, normalized);
67
+ }
68
+
69
+ /**
70
+ * @param {object} [options]
71
+ * @param {string} [options.projectRoot]
72
+ * @param {string} [options.agentDir]
73
+ * @returns {{ conflict: boolean, sources: string[], detail: string }}
74
+ */
75
+ export function detectPiWebAccessExtensionConflict({
76
+ projectRoot = process.cwd(),
77
+ agentDir = resolvePiAgentDir(),
78
+ } = {}) {
79
+ /** @type {Set<string>} */
80
+ const resolvedSources = new Set();
81
+ /** @type {string[]} */
82
+ const rawSources = [];
83
+
84
+ const userSettings = path.join(agentDir, "settings.json");
85
+ for (const source of readPiPackageSources(userSettings)) {
86
+ if (!isPiWebAccessPackageSource(source)) continue;
87
+ rawSources.push(source);
88
+ const resolved = resolvePiPackageSourcePath(source, agentDir);
89
+ if (resolved) resolvedSources.add(path.resolve(resolved));
90
+ }
91
+
92
+ const projectSettings = path.join(projectRoot, ".pi", "settings.json");
93
+ for (const source of readPiPackageSources(projectSettings)) {
94
+ if (!isPiWebAccessPackageSource(source)) continue;
95
+ rawSources.push(source);
96
+ const resolved = resolvePiPackageSourcePath(source, path.dirname(projectSettings));
97
+ if (resolved) resolvedSources.add(path.resolve(resolved));
98
+ }
99
+
100
+ const npmDefault = path.join(agentDir, "npm", "node_modules", "pi-web-access");
101
+ if (fs.existsSync(npmDefault)) {
102
+ resolvedSources.add(path.resolve(npmDefault));
103
+ if (!rawSources.some((entry) => entry.startsWith("npm:pi-web-access"))) {
104
+ rawSources.push("npm:pi-web-access");
105
+ }
106
+ }
107
+
108
+ const conflict = resolvedSources.size > 1 || rawSources.length > 1;
109
+ const detail =
110
+ rawSources.length === 0
111
+ ? "no pi-web-access sources detected"
112
+ : conflict
113
+ ? `duplicate pi-web-access sources: ${rawSources.join(", ")}`
114
+ : `single pi-web-access source: ${rawSources[0]}`;
115
+
116
+ return { conflict, sources: [...rawSources], detail };
117
+ }
118
+
119
+ /**
120
+ * Whether batch workers should pass `pi -ne` (skip user extension discovery).
121
+ *
122
+ * @param {object} [options]
123
+ * @param {string} [options.projectRoot]
124
+ * @param {string} [options.agentDir]
125
+ * @returns {boolean}
126
+ */
127
+ export function shouldWorkerUsePiNoExtensions({
128
+ projectRoot = process.cwd(),
129
+ agentDir = resolvePiAgentDir(),
130
+ } = {}) {
131
+ return detectPiWebAccessExtensionConflict({ projectRoot, agentDir }).conflict;
132
+ }
133
+
134
+ /**
135
+ * @param {string} output
136
+ */
137
+ export function isPiExtensionConflictOutput(output) {
138
+ const text = String(output ?? "");
139
+ if (!/conflicts with/i.test(text)) return false;
140
+ return PI_WEB_ACCESS_TOOL_NAMES.some((tool) => text.includes(`Tool "${tool}"`));
141
+ }
142
+
143
+ /**
144
+ * @param {object} [options]
145
+ * @param {string} [options.projectRoot]
146
+ * @param {string} [options.agentDir]
147
+ */
148
+ export function buildPiExtensionConflictDoctorCheck({
149
+ projectRoot = process.cwd(),
150
+ agentDir = resolvePiAgentDir(),
151
+ } = {}) {
152
+ const assessment = detectPiWebAccessExtensionConflict({ projectRoot, agentDir });
153
+ if (!assessment.conflict) {
154
+ return {
155
+ label: "pi-web-access extension conflict",
156
+ ok: true,
157
+ detail: assessment.detail,
158
+ };
159
+ }
160
+
161
+ return {
162
+ label: "pi-web-access extension conflict",
163
+ ok: true,
164
+ warning: true,
165
+ detail: `${assessment.detail} — batch workers pass pi -ne when this conflict is detected; remove duplicate source or run pi remove for npm:pi-web-access`,
166
+ suggestedCommand:
167
+ "pi remove npm:pi-web-access -l || pi remove ../../Documents/github/pi-web-access -l",
168
+ };
169
+ }
@@ -22,8 +22,11 @@ import {
22
22
  } from "./stall-config.mjs";
23
23
  import { buildRulesManifestDoctorCheck } from "./rules-manifest.mjs";
24
24
  import { buildWorktreeHealthDoctorCheck } from "./worktree-health.mjs";
25
+ import { buildStaleWorktreesDoctorCheck } from "./stale-worktrees.mjs";
25
26
  import { buildWorkerBackendDoctorCheck } from "../config/worker-backend.mjs";
26
- import { buildAgentModelInheritDoctorCheck } from "./agent-model-inherit.mjs";
27
+ import { buildAgentModelInheritDoctorCheck, buildReviewerPerTypePinsDoctorCheck } from "./agent-model-inherit.mjs";
28
+ import { buildAgentModelIdsDoctorCheck } from "./agent-models.mjs";
29
+ import { buildPiExtensionConflictDoctorCheck } from "./pi-extension-conflict.mjs";
27
30
  import { CURSOR_RULES_ROOT_REL } from "../config/cursor-rules/discover.mjs";
28
31
  import { RULES_PROFILE_REL_PATH } from "../config/cursor-rules/profile.mjs";
29
32
  import {
@@ -245,6 +248,7 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
245
248
  record("git installed", commandExists("git"), { detail: getVersion("git") });
246
249
  record("git worktree support", gitSupportsWorktrees(), { detail: getVersion("git") });
247
250
  record("pi installed", commandExists("pi"), { detail: getVersion("pi") });
251
+ checks.push(buildPiExtensionConflictDoctorCheck({ projectRoot }));
248
252
 
249
253
  const piVersionText = getVersion("pi");
250
254
  const minPiVersion = getMinPiVersion();
@@ -346,10 +350,14 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
346
350
  );
347
351
  checks.push(buildStallConfigDoctorCheck({ config: configResult.config }));
348
352
  checks.push(buildPiWorkerTimeoutDoctorCheck({ config: configResult.config }));
353
+ checks.push(buildReviewerPerTypePinsDoctorCheck({ config: configResult.config }));
349
354
  checks.push(buildAgentModelInheritDoctorCheck({
350
355
  config: configResult.config,
351
356
  projectRoot,
352
357
  }));
358
+ const modelIdsCheck = buildAgentModelIdsDoctorCheck({ config: configResult.config });
359
+ checks.push(modelIdsCheck);
360
+ if (!modelIdsCheck.ok) issueCount++;
353
361
  const worktreeHealthCheck = buildWorktreeHealthDoctorCheck({
354
362
  projectRoot,
355
363
  config: configResult.config,
@@ -418,6 +426,8 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
418
426
  }
419
427
 
420
428
  if (isInsideGitRepo(projectRoot)) {
429
+ checks.push(buildStaleWorktreesDoctorCheck({ projectRoot }));
430
+
421
431
  const gitignorePath = path.join(projectRoot, ".gitignore");
422
432
  if (!fs.existsSync(gitignorePath)) {
423
433
  checks.push({
@@ -442,6 +452,27 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
442
452
  suggestedCommand: missing.length > 0 ? "spine init" : undefined,
443
453
  });
444
454
  }
455
+
456
+ const metricsRelPath = configResult.config?.metrics?.path ?? ".spine/run-metrics.jsonl";
457
+ try {
458
+ const tracked = execFileSync("git", ["ls-files", "--", metricsRelPath], {
459
+ cwd: projectRoot,
460
+ encoding: "utf-8",
461
+ stdio: ["ignore", "pipe", "pipe"],
462
+ timeout: 5000,
463
+ }).trim();
464
+ if (tracked) {
465
+ checks.push({
466
+ label: "run-metrics.jsonl not git-tracked",
467
+ ok: true,
468
+ warning: true,
469
+ detail: `${metricsRelPath} is tracked by git — runtime appends break preflight until untracked`,
470
+ suggestedCommand: `git rm --cached -- ${metricsRelPath}`,
471
+ });
472
+ }
473
+ } catch {
474
+ // Git ls-files unavailable; skip tracked-metrics advisory.
475
+ }
445
476
  }
446
477
 
447
478
  const rulesRootPath = path.join(projectRoot, CURSOR_RULES_ROOT_REL);
@@ -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
+ }
@@ -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
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Scenario fixture registry — central catalog for incident, stub, adoption, and recipe fixtures.
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ import { resolvePiSpineRoot } from "../config/pi-spine-root.mjs";
9
+
10
+ export const REGISTRY_SCHEMA_VERSION = 1;
11
+
12
+ /** @type {readonly string[]} */
13
+ export const SCENARIO_KINDS = Object.freeze([
14
+ "incident",
15
+ "stub",
16
+ "adoption",
17
+ "recipe",
18
+ ]);
19
+
20
+ const REGISTRY_RELATIVE_PATH = path.join("tests", "fixtures", "scenarios", "registry.json");
21
+
22
+ /**
23
+ * @param {string} [packageRoot]
24
+ * @returns {string}
25
+ */
26
+ export function resolveRegistryPath(packageRoot = resolvePiSpineRoot({}, process.cwd(), import.meta.url)) {
27
+ return path.join(packageRoot, REGISTRY_RELATIVE_PATH);
28
+ }
29
+
30
+ /**
31
+ * @param {{ packageRoot?: string }} [options]
32
+ * @returns {{ schemaVersion: number, scenarios: object[] }}
33
+ */
34
+ export function loadRegistry(options = {}) {
35
+ const packageRoot =
36
+ options.packageRoot ?? resolvePiSpineRoot({}, process.cwd(), import.meta.url);
37
+ const registryPath = resolveRegistryPath(packageRoot);
38
+ const raw = fs.readFileSync(registryPath, "utf-8");
39
+ return JSON.parse(raw);
40
+ }
41
+
42
+ /**
43
+ * @param {{ packageRoot?: string }} [options]
44
+ * @returns {object[]}
45
+ */
46
+ export function listScenarios(options = {}) {
47
+ const registry = loadRegistry(options);
48
+ return [...registry.scenarios].sort((left, right) =>
49
+ String(left.id).localeCompare(String(right.id)),
50
+ );
51
+ }
52
+
53
+ /**
54
+ * @param {string} id
55
+ * @param {{ packageRoot?: string }} [options]
56
+ * @returns {object | null}
57
+ */
58
+ export function getScenario(id, options = {}) {
59
+ const registry = loadRegistry(options);
60
+ return registry.scenarios.find((entry) => entry.id === id) ?? null;
61
+ }
62
+
63
+ /**
64
+ * @param {unknown} value
65
+ * @returns {value is string}
66
+ */
67
+ function isNonEmptyString(value) {
68
+ return typeof value === "string" && value.trim().length > 0;
69
+ }
70
+
71
+ /**
72
+ * @param {unknown} value
73
+ * @returns {value is string[]}
74
+ */
75
+ function isStringArray(value) {
76
+ return Array.isArray(value) && value.every((entry) => isNonEmptyString(entry));
77
+ }
78
+
79
+ /**
80
+ * @param {object} scenario
81
+ * @param {Set<string>} seenIds
82
+ * @param {{ packageRoot: string, checkFixturePaths: boolean }} context
83
+ * @returns {string[]}
84
+ */
85
+ function validateScenarioEntry(scenario, seenIds, context) {
86
+ /** @type {string[]} */
87
+ const errors = [];
88
+
89
+ if (!scenario || typeof scenario !== "object" || Array.isArray(scenario)) {
90
+ return ["scenario entry must be an object"];
91
+ }
92
+
93
+ if (!isNonEmptyString(scenario.id)) {
94
+ errors.push("scenario.id must be a non-empty string");
95
+ } else if (seenIds.has(scenario.id)) {
96
+ errors.push(`duplicate scenario id: ${scenario.id}`);
97
+ } else {
98
+ seenIds.add(scenario.id);
99
+ }
100
+
101
+ if (!isNonEmptyString(scenario.kind)) {
102
+ errors.push("scenario.kind must be a non-empty string");
103
+ } else if (!SCENARIO_KINDS.includes(scenario.kind)) {
104
+ errors.push(`scenario.kind must be one of: ${SCENARIO_KINDS.join(", ")}`);
105
+ }
106
+
107
+ if (!isNonEmptyString(scenario.title)) {
108
+ errors.push("scenario.title must be a non-empty string");
109
+ }
110
+
111
+ if (scenario.description != null && typeof scenario.description !== "string") {
112
+ errors.push("scenario.description must be a string when set");
113
+ }
114
+
115
+ const requiresFixturePath = scenario.kind === "incident" || scenario.kind === "stub" || scenario.kind === "adoption";
116
+ if (requiresFixturePath && !isNonEmptyString(scenario.fixturePath)) {
117
+ errors.push(`scenario.fixturePath is required for kind ${scenario.kind ?? "(missing)"}`);
118
+ }
119
+
120
+ if (scenario.fixturePath != null && !isNonEmptyString(scenario.fixturePath)) {
121
+ errors.push("scenario.fixturePath must be a non-empty string when set");
122
+ }
123
+
124
+ if (scenario.batchId != null && !isNonEmptyString(scenario.batchId)) {
125
+ errors.push("scenario.batchId must be a non-empty string when set");
126
+ }
127
+
128
+ for (const field of ["tests", "docs", "relatedTasks", "tags"]) {
129
+ if (scenario[field] != null && !isStringArray(scenario[field])) {
130
+ errors.push(`scenario.${field} must be an array of non-empty strings when set`);
131
+ }
132
+ }
133
+
134
+ if (
135
+ context.checkFixturePaths &&
136
+ isNonEmptyString(scenario.fixturePath) &&
137
+ isNonEmptyString(scenario.id)
138
+ ) {
139
+ const fixturePath = path.join(context.packageRoot, scenario.fixturePath);
140
+ if (!fs.existsSync(fixturePath)) {
141
+ errors.push(`scenario.fixturePath does not exist: ${scenario.fixturePath}`);
142
+ }
143
+ }
144
+
145
+ return errors;
146
+ }
147
+
148
+ /**
149
+ * @param {object} registry
150
+ * @param {{ packageRoot?: string, checkFixturePaths?: boolean }} [options]
151
+ * @returns {{ ok: boolean, errors: string[] }}
152
+ */
153
+ export function validateRegistry(registry, options = {}) {
154
+ const packageRoot =
155
+ options.packageRoot ?? resolvePiSpineRoot({}, process.cwd(), import.meta.url);
156
+ const checkFixturePaths = options.checkFixturePaths ?? true;
157
+ /** @type {string[]} */
158
+ const errors = [];
159
+
160
+ if (!registry || typeof registry !== "object" || Array.isArray(registry)) {
161
+ return { ok: false, errors: ["registry must be an object"] };
162
+ }
163
+
164
+ if (registry.schemaVersion !== REGISTRY_SCHEMA_VERSION) {
165
+ errors.push(`schemaVersion must be ${REGISTRY_SCHEMA_VERSION}`);
166
+ }
167
+
168
+ if (!Array.isArray(registry.scenarios)) {
169
+ errors.push("scenarios must be an array");
170
+ return { ok: errors.length === 0, errors };
171
+ }
172
+
173
+ const seenIds = new Set();
174
+ for (const scenario of registry.scenarios) {
175
+ const prefix = isNonEmptyString(scenario?.id) ? `scenario ${scenario.id}:` : "scenario:";
176
+ for (const issue of validateScenarioEntry(scenario, seenIds, {
177
+ packageRoot,
178
+ checkFixturePaths,
179
+ })) {
180
+ errors.push(`${prefix} ${issue}`);
181
+ }
182
+ }
183
+
184
+ return { ok: errors.length === 0, errors };
185
+ }
186
+
187
+ /**
188
+ * Resolve package root from this module location (for tests and CLI callers).
189
+ *
190
+ * @returns {string}
191
+ */
192
+ export function scenarioRegistryPackageRoot() {
193
+ return resolvePiSpineRoot({}, process.cwd(), import.meta.url);
194
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Atomic file writes via temp file + rename (orchestration artifact persistence).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { randomBytes } from "node:crypto";
8
+
9
+ /**
10
+ * @param {string} targetPath
11
+ * @returns {string}
12
+ */
13
+ export function makeAtomicTempPath(targetPath) {
14
+ return `${targetPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
15
+ }
16
+
17
+ /**
18
+ * @param {string} filePath
19
+ * @param {string} content
20
+ */
21
+ export function writeTextAtomic(filePath, content) {
22
+ const dir = path.dirname(filePath);
23
+ fs.mkdirSync(dir, { recursive: true });
24
+
25
+ const tmpPath = makeAtomicTempPath(filePath);
26
+
27
+ try {
28
+ fs.writeFileSync(tmpPath, content, "utf-8");
29
+ fs.renameSync(tmpPath, filePath);
30
+ } catch (err) {
31
+ try {
32
+ if (fs.existsSync(tmpPath)) {
33
+ fs.unlinkSync(tmpPath);
34
+ }
35
+ } catch {
36
+ // ignore cleanup failure
37
+ }
38
+ throw err;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * @param {string} filePath
44
+ * @param {unknown} data
45
+ */
46
+ export function writeJsonAtomic(filePath, data) {
47
+ const content = `${JSON.stringify(data, null, 2)}\n`;
48
+ writeTextAtomic(filePath, content);
49
+ }