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
@@ -1,18 +1,6 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
 
3
- export function commandExists(cmd) {
4
- let result;
5
- try {
6
- result = spawnSync("which", [cmd], {
7
- encoding: "utf-8",
8
- stdio: ["ignore", "pipe", "pipe"],
9
- });
10
- } catch {
11
- return false;
12
- }
13
-
14
- return Boolean(result && !result.error && result.status === 0);
15
- }
3
+ export { commandExists } from "../src/util/command-exists.mjs";
16
4
 
17
5
  export function getVersion(cmd, flag = "--version") {
18
6
  let result;
@@ -9,12 +9,79 @@ import {
9
9
  } from "../src/batch/detached-start.mjs";
10
10
  import { completeBatch, dismissBatch } from "../src/batch/lifecycle.mjs";
11
11
  import { forceMergeWave, startBatch } from "../src/batch/engine.mjs";
12
- import { pauseBatch, resumeBatch } from "../src/batch/resume.mjs";
12
+ import { parseBatchStartWaveFilter } from "../src/planner/wave-scope.mjs";
13
+ import { pauseBatch } from "../src/batch/pause.mjs";
14
+ import { resumeBatch } from "../src/batch/resume.mjs";
13
15
  import { retryTask, skipTask } from "../src/batch/retry.mjs";
14
16
  import { reconcileBatch } from "../src/batch/reconcile.mjs";
17
+ import {
18
+ finishAttachedBatchCli,
19
+ formatAttachedBatchCliResult,
20
+ runAttachedBatchEngine,
21
+ } from "../src/batch/attached-runner.mjs";
15
22
 
16
23
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
17
24
 
25
+ const BATCH_FLAG_VALUE_TAKERS = new Set([
26
+ "--wave",
27
+ "--through-wave",
28
+ "--batch",
29
+ "--reason",
30
+ ]);
31
+
32
+ /**
33
+ * @returns {string}
34
+ */
35
+ export function printBatchHelp() {
36
+ return (
37
+ "Usage: spine batch start <scope>|pause|resume|retry <taskId>|skip <taskId>|force-merge [--wave N]|abort|dismiss|complete [--batch ID] [--reason TEXT] [--hard] [--force] [--force-superseded] [--attached] [--dry-run] [--wave N] [--through-wave N] [--skip-preflight] [--detect-manual-merge] [--json]\n"
38
+ );
39
+ }
40
+
41
+ /**
42
+ * @param {string[]} args
43
+ */
44
+ export function isBatchHelpRequest(args) {
45
+ if (args.includes("--help") || args.includes("-h")) {
46
+ return true;
47
+ }
48
+ if (args.length === 1 && args[0] === "help") {
49
+ return true;
50
+ }
51
+ const subcommand = args.find((token) =>
52
+ ["dismiss", "complete", "abort", "start", "pause", "resume", "retry", "skip", "force-merge"].includes(
53
+ token,
54
+ ),
55
+ );
56
+ if (subcommand && args.includes("help")) {
57
+ const helpIdx = args.indexOf("help");
58
+ const subIdx = args.indexOf(subcommand);
59
+ return helpIdx === subIdx + 1 || (subIdx < 0 && helpIdx === 0);
60
+ }
61
+ return false;
62
+ }
63
+
64
+ /**
65
+ * Remove argv tokens consumed as flag values so they are not parsed as scope.
66
+ *
67
+ * @param {string[]} args
68
+ */
69
+ export function stripBatchFlagValueTokens(args) {
70
+ /** @type {Set<number>} */
71
+ const skipIndices = new Set();
72
+ for (let index = 0; index < args.length; index++) {
73
+ const token = args[index];
74
+ if (!BATCH_FLAG_VALUE_TAKERS.has(token)) {
75
+ continue;
76
+ }
77
+ const valueIndex = index + 1;
78
+ if (valueIndex < args.length && !args[valueIndex].startsWith("--")) {
79
+ skipIndices.add(valueIndex);
80
+ }
81
+ }
82
+ return args.filter((_, index) => !skipIndices.has(index));
83
+ }
84
+
18
85
  /**
19
86
  * @param {object} result
20
87
  * @param {boolean} json
@@ -74,9 +141,6 @@ export function parseBatchArgs(args) {
74
141
  waveIndex = Number(args[waveIdx + 1]);
75
142
  }
76
143
 
77
- const dryRun = flags.has("--dry-run");
78
- const skipPreflight = flags.has("--skip-preflight");
79
-
80
144
  const subcommand =
81
145
  args.find(
82
146
  (t) =>
@@ -91,7 +155,24 @@ export function parseBatchArgs(args) {
91
155
  t === "force-merge",
92
156
  ) ?? null;
93
157
 
94
- const positional = args.filter((a) => !a.startsWith("--") && a !== subcommand);
158
+ let waveFilter = null;
159
+ let waveFilterError = null;
160
+ if (subcommand === "start") {
161
+ const parsedWave = parseBatchStartWaveFilter(args);
162
+ if (parsedWave.error) {
163
+ waveFilterError = parsedWave;
164
+ } else {
165
+ waveFilter = parsedWave.waveFilter;
166
+ }
167
+ }
168
+
169
+ const positional = stripBatchFlagValueTokens(args).filter(
170
+ (a) => !a.startsWith("--") && a !== subcommand && a !== "help",
171
+ );
172
+
173
+ const dryRun = flags.has("--dry-run");
174
+ const skipPreflight = flags.has("--skip-preflight");
175
+ const forceSuperseded = flags.has("--force-superseded");
95
176
 
96
177
  return {
97
178
  json: flags.has("--json"),
@@ -103,9 +184,12 @@ export function parseBatchArgs(args) {
103
184
  noWaitTerminal: flags.has("--no-wait-terminal"),
104
185
  dryRun,
105
186
  skipPreflight,
187
+ forceSuperseded,
106
188
  batchId,
107
189
  reason,
108
190
  waveIndex,
191
+ waveFilter,
192
+ waveFilterError,
109
193
  subcommand,
110
194
  taskId: subcommand === "retry" || subcommand === "skip" ? positional[0] ?? null : null,
111
195
  scope: positional.join(" ") || "all",
@@ -116,9 +200,13 @@ export function parseBatchArgs(args) {
116
200
  * @param {object} options
117
201
  * @param {string} options.projectRoot
118
202
  * @param {string[]} options.args
203
+ * @param {boolean} [options.deferAttachedExit] When true, skip process.exit (unit tests).
119
204
  */
120
205
  export async function runSpineBatch(options) {
121
- const { projectRoot, args } = options;
206
+ const { projectRoot, args, deferAttachedExit = false } = options;
207
+ if (isBatchHelpRequest(args)) {
208
+ return { exitCode: 0, output: printBatchHelp() };
209
+ }
122
210
  const parsed = parseBatchArgs(args);
123
211
 
124
212
  if (parsed.subcommand === "dismiss") {
@@ -163,7 +251,7 @@ export async function runSpineBatch(options) {
163
251
  }
164
252
 
165
253
  if (parsed.subcommand === "pause") {
166
- const result = pauseBatch({ projectRoot });
254
+ const result = await pauseBatch({ projectRoot });
167
255
  if (parsed.json) {
168
256
  return {
169
257
  exitCode: result.exitCode ?? (result.ok ? 0 : 1),
@@ -286,31 +374,28 @@ export async function runSpineBatch(options) {
286
374
  };
287
375
  }
288
376
 
289
- const result = await resumeBatch({ projectRoot, force: parsed.force });
290
- if (parsed.json) {
291
- return {
292
- exitCode: result.exitCode ?? (result.ok ? 0 : 1),
293
- output: `${JSON.stringify(result, null, 2)}\n`,
294
- result,
295
- };
296
- }
297
- const lines = [
298
- "",
299
- result.ok ? "Batch resumed" : "Batch resume failed",
300
- "",
301
- result.output ?? result.error ?? "",
302
- ];
303
- if (result.batchId) lines.push("", ` Batch: ${result.batchId}`);
304
- if (result.taskId) lines.push(` Task: ${result.taskId}`);
305
- lines.push("");
306
- return {
307
- exitCode: result.exitCode ?? (result.ok ? 0 : 1),
308
- output: lines.join("\n"),
377
+ const result = await runAttachedBatchEngine({
378
+ projectRoot,
379
+ runEngine: () => resumeBatch({ projectRoot, force: parsed.force }),
380
+ });
381
+ const cli = formatAttachedBatchCliResult({
382
+ projectRoot,
383
+ operation: "resume",
309
384
  result,
310
- };
385
+ json: parsed.json,
386
+ });
387
+ finishAttachedBatchCli(cli, { deferExit: deferAttachedExit });
388
+ return { ...cli, result };
311
389
  }
312
390
 
313
391
  if (parsed.subcommand === "start") {
392
+ if (parsed.waveFilterError) {
393
+ return {
394
+ exitCode: 1,
395
+ output: parsed.waveFilterError.output ?? "Invalid --wave flag.\n",
396
+ };
397
+ }
398
+
314
399
  const useAttached = parsed.attached || parsed.dryRun;
315
400
  if (!useAttached) {
316
401
  const detached = await startBatchDetached({
@@ -318,6 +403,8 @@ export async function runSpineBatch(options) {
318
403
  spineBin: path.join(__dirname, "spine.mjs"),
319
404
  scope: parsed.scope,
320
405
  skipPreflight: parsed.skipPreflight,
406
+ forceSuperseded: parsed.forceSuperseded,
407
+ waveFilter: parsed.waveFilter,
321
408
  waitTerminal: parsed.waitTerminal,
322
409
  json: parsed.json,
323
410
  });
@@ -328,39 +415,63 @@ export async function runSpineBatch(options) {
328
415
  };
329
416
  }
330
417
 
331
- const result = await startBatch({
332
- projectRoot,
333
- scope: parsed.scope,
334
- dryRun: parsed.dryRun,
335
- skipPreflight: parsed.skipPreflight,
336
- });
337
- if (parsed.json) {
418
+ if (parsed.dryRun) {
419
+ const result = await startBatch({
420
+ projectRoot,
421
+ scope: parsed.scope,
422
+ dryRun: true,
423
+ skipPreflight: parsed.skipPreflight,
424
+ forceSuperseded: parsed.forceSuperseded,
425
+ waveFilter: parsed.waveFilter,
426
+ });
427
+ if (parsed.json) {
428
+ return {
429
+ exitCode: result.exitCode ?? (result.ok ? 0 : 1),
430
+ output: `${JSON.stringify(result, null, 2)}\n`,
431
+ result,
432
+ };
433
+ }
434
+ const lines = [
435
+ "",
436
+ result.ok ? "Batch started" : "Batch start failed",
437
+ "",
438
+ result.output ?? result.error ?? "",
439
+ ];
440
+ if (result.batchId) lines.push("", ` Batch: ${result.batchId}`);
441
+ if (result.taskId) lines.push(` Task: ${result.taskId}`);
442
+ lines.push("");
338
443
  return {
339
444
  exitCode: result.exitCode ?? (result.ok ? 0 : 1),
340
- output: `${JSON.stringify(result, null, 2)}\n`,
445
+ output: lines.join("\n"),
341
446
  result,
342
447
  };
343
448
  }
344
- const lines = [
345
- "",
346
- result.ok ? "Batch started" : "Batch start failed",
347
- "",
348
- result.output ?? result.error ?? "",
349
- ];
350
- if (result.batchId) lines.push("", ` Batch: ${result.batchId}`);
351
- if (result.taskId) lines.push(` Task: ${result.taskId}`);
352
- lines.push("");
353
- return {
354
- exitCode: result.exitCode ?? (result.ok ? 0 : 1),
355
- output: lines.join("\n"),
449
+
450
+ const result = await runAttachedBatchEngine({
451
+ projectRoot,
452
+ runEngine: () =>
453
+ startBatch({
454
+ projectRoot,
455
+ scope: parsed.scope,
456
+ dryRun: false,
457
+ skipPreflight: parsed.skipPreflight,
458
+ forceSuperseded: parsed.forceSuperseded,
459
+ waveFilter: parsed.waveFilter,
460
+ }),
461
+ });
462
+ const cli = formatAttachedBatchCliResult({
463
+ projectRoot,
464
+ operation: "start",
356
465
  result,
357
- };
466
+ json: parsed.json,
467
+ });
468
+ finishAttachedBatchCli(cli, { deferExit: deferAttachedExit });
469
+ return { ...cli, result };
358
470
  }
359
471
 
360
472
  return {
361
473
  exitCode: 1,
362
- output:
363
- "Usage: spine batch start <scope>|pause|resume|retry <taskId>|skip <taskId>|force-merge [--wave N]|abort|dismiss|complete [--batch ID] [--reason TEXT] [--hard] [--force] [--attached] [--dry-run] [--skip-preflight] [--detect-manual-merge] [--json]\n",
474
+ output: printBatchHelp(),
364
475
  };
365
476
  }
366
477
 
@@ -17,10 +17,10 @@ export async function handleBatch(args) {
17
17
  * @param {string[]} args
18
18
  */
19
19
  export async function handleRun(args) {
20
- const { runSpineBatch } = await import("../spine-batch.mjs");
21
- const result = await runSpineBatch({
20
+ const { runSpineRun } = await import("../spine-run.mjs");
21
+ const result = await runSpineRun({
22
22
  projectRoot: process.cwd(),
23
- args: ["start", ...args],
23
+ args,
24
24
  });
25
25
  writeCommandResult(result);
26
26
  }
@@ -0,0 +1,24 @@
1
+ import { c, die } from "./shared.mjs";
2
+
3
+ /**
4
+ * @param {string[]} args
5
+ */
6
+ export async function handleLaneLogs(args) {
7
+ const { runLaneLogs } = await import("../../src/cli/lane-logs.mjs");
8
+ const result = await runLaneLogs({ projectRoot: process.cwd(), args });
9
+ process.stdout.write(result.output ?? "");
10
+ if (result.exitCode !== 0) process.exit(result.exitCode);
11
+ }
12
+
13
+ /**
14
+ * @param {string[]} args
15
+ */
16
+ export async function handleLane(args) {
17
+ const sub = args[0];
18
+ if (sub !== "logs") {
19
+ die(
20
+ `Unknown lane subcommand: ${sub ?? "(none)"}\nRun ${c.cyan}spine lane logs --lane N${c.reset} for usage.`,
21
+ );
22
+ }
23
+ await handleLaneLogs(args.slice(1));
24
+ }
@@ -0,0 +1,298 @@
1
+ /**
2
+ * Operator scenario fixture CLI — list, show, and materialize registry entries.
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ import { resolveBatchStatePath } from "../../src/batch/batch-state-io.mjs";
9
+ import { journalPath } from "../../src/batch/journal.mjs";
10
+ import { saveSpineBatchState } from "../../src/batch/state.mjs";
11
+ import {
12
+ getScenario,
13
+ listScenarios,
14
+ scenarioRegistryPackageRoot,
15
+ } from "../../src/fixtures/scenario-registry.mjs";
16
+ import { c, FAIL, OK, writeCommandResult } from "./shared.mjs";
17
+
18
+ const MATERIALIZE_KINDS = new Set(["incident", "stub", "adoption"]);
19
+
20
+ /**
21
+ * @param {{ packageRoot?: string }} [options]
22
+ */
23
+ function resolvePackageRoot(options = {}) {
24
+ if (options.packageRoot) {
25
+ return options.packageRoot;
26
+ }
27
+ if (process.env.SPINE_SCENARIO_REGISTRY_ROOT) {
28
+ return path.resolve(process.env.SPINE_SCENARIO_REGISTRY_ROOT);
29
+ }
30
+ return scenarioRegistryPackageRoot();
31
+ }
32
+
33
+ /**
34
+ * @param {string} projectRoot
35
+ * @param {boolean} force
36
+ * @returns {{ ok: true } | { ok: false, message: string }}
37
+ */
38
+ export function assertMaterializeAllowed(projectRoot, force) {
39
+ const existingPath = resolveBatchStatePath(projectRoot);
40
+ if (existingPath && !force) {
41
+ return {
42
+ ok: false,
43
+ message:
44
+ `active batch state present at ${path.relative(projectRoot, existingPath)}; ` +
45
+ `re-run with --force to overwrite`,
46
+ };
47
+ }
48
+ return { ok: true };
49
+ }
50
+
51
+ /**
52
+ * @param {object} scenario
53
+ * @param {string} packageRoot
54
+ */
55
+ export function loadScenarioFixture(scenario, packageRoot) {
56
+ if (!MATERIALIZE_KINDS.has(scenario.kind)) {
57
+ throw new Error(`scenario kind ${scenario.kind} cannot be materialized`);
58
+ }
59
+ if (!scenario.fixturePath || typeof scenario.fixturePath !== "string") {
60
+ throw new Error(`scenario ${scenario.id} has no fixturePath`);
61
+ }
62
+
63
+ const fixturePath = path.join(packageRoot, scenario.fixturePath);
64
+ if (!fs.existsSync(fixturePath)) {
65
+ throw new Error(`fixture file not found: ${scenario.fixturePath}`);
66
+ }
67
+
68
+ return JSON.parse(fs.readFileSync(fixturePath, "utf-8"));
69
+ }
70
+
71
+ /**
72
+ * @param {string} projectRoot
73
+ * @param {{ batchState: object, journalTail?: object[], meta?: { batchId?: string } }} fixture
74
+ */
75
+ export function materializeFixtureToProject(projectRoot, fixture) {
76
+ const batchId = fixture.meta?.batchId ?? fixture.batchState?.batchId;
77
+ if (!batchId) {
78
+ throw new Error("fixture is missing batchId in meta or batchState");
79
+ }
80
+ if (!fixture.batchState || typeof fixture.batchState !== "object") {
81
+ throw new Error("fixture is missing batchState");
82
+ }
83
+
84
+ saveSpineBatchState(projectRoot, fixture.batchState, { bypassWriteGuard: true });
85
+
86
+ const journalFile = journalPath(projectRoot, batchId);
87
+ fs.mkdirSync(path.dirname(journalFile), { recursive: true });
88
+ fs.writeFileSync(journalFile, "", "utf-8");
89
+ for (const event of fixture.journalTail ?? []) {
90
+ fs.appendFileSync(journalFile, `${JSON.stringify(event)}\n`, "utf-8");
91
+ }
92
+
93
+ return { batchId, batchStatePath: path.join(".spine", "batch-state.json"), journalPath: journalFile };
94
+ }
95
+
96
+ /**
97
+ * @param {object} params
98
+ * @param {string} [params.packageRoot]
99
+ * @param {boolean} [params.json]
100
+ */
101
+ export function runScenariosList({ packageRoot: packageRootOption, json = false } = {}) {
102
+ const packageRoot = resolvePackageRoot({ packageRoot: packageRootOption });
103
+ const scenarios = listScenarios({ packageRoot });
104
+
105
+ if (json) {
106
+ return {
107
+ exitCode: 0,
108
+ output: `${JSON.stringify({ scenarios }, null, 2)}\n`,
109
+ };
110
+ }
111
+
112
+ if (scenarios.length === 0) {
113
+ return {
114
+ exitCode: 0,
115
+ output: `${OK} No scenarios registered\n`,
116
+ };
117
+ }
118
+
119
+ const lines = ["", `${c.bold}Scenario registry${c.reset}`, ""];
120
+ lines.push(` ${"ID".padEnd(28)} ${"KIND".padEnd(10)} TITLE`);
121
+ for (const scenario of scenarios) {
122
+ lines.push(
123
+ ` ${String(scenario.id).padEnd(28)} ${String(scenario.kind).padEnd(10)} ${scenario.title}`,
124
+ );
125
+ }
126
+ lines.push("");
127
+ return { exitCode: 0, output: lines.join("\n") };
128
+ }
129
+
130
+ /**
131
+ * @param {object} params
132
+ * @param {string} params.id
133
+ * @param {string} [params.packageRoot]
134
+ * @param {boolean} [params.json]
135
+ */
136
+ export function runScenariosShow({ id, packageRoot: packageRootOption, json = false }) {
137
+ if (!id) {
138
+ return {
139
+ exitCode: 1,
140
+ output: `Usage: spine scenarios show <id> [--json]\n`,
141
+ };
142
+ }
143
+
144
+ const packageRoot = resolvePackageRoot({ packageRoot: packageRootOption });
145
+ const scenario = getScenario(id, { packageRoot });
146
+ if (!scenario) {
147
+ return {
148
+ exitCode: 1,
149
+ output: `${FAIL} Unknown scenario: ${id}\n`,
150
+ };
151
+ }
152
+
153
+ if (json) {
154
+ return {
155
+ exitCode: 0,
156
+ output: `${JSON.stringify({ scenario }, null, 2)}\n`,
157
+ };
158
+ }
159
+
160
+ const lines = [
161
+ "",
162
+ `${c.bold}${scenario.title}${c.reset}`,
163
+ ` ID: ${scenario.id}`,
164
+ ` Kind: ${scenario.kind}`,
165
+ ];
166
+ if (scenario.description) lines.push(` Description: ${scenario.description}`);
167
+ if (scenario.fixturePath) lines.push(` Fixture: ${scenario.fixturePath}`);
168
+ if (scenario.batchId) lines.push(` Batch ID: ${scenario.batchId}`);
169
+ if (Array.isArray(scenario.tags) && scenario.tags.length > 0) {
170
+ lines.push(` Tags: ${scenario.tags.join(", ")}`);
171
+ }
172
+ lines.push("");
173
+ return { exitCode: 0, output: lines.join("\n") };
174
+ }
175
+
176
+ /**
177
+ * @param {object} params
178
+ * @param {string} params.id
179
+ * @param {string} params.projectRoot
180
+ * @param {string} [params.packageRoot]
181
+ * @param {boolean} [params.force]
182
+ * @param {boolean} [params.json]
183
+ */
184
+ export function runScenariosMaterialize({
185
+ id,
186
+ projectRoot,
187
+ packageRoot: packageRootOption,
188
+ force = false,
189
+ json = false,
190
+ }) {
191
+ if (!id) {
192
+ return {
193
+ exitCode: 1,
194
+ output: `Usage: spine scenarios materialize <id> [--target DIR] [--force] [--json]\n`,
195
+ };
196
+ }
197
+
198
+ const packageRoot = resolvePackageRoot({ packageRoot: packageRootOption });
199
+ const scenario = getScenario(id, { packageRoot });
200
+ if (!scenario) {
201
+ return {
202
+ exitCode: 1,
203
+ output: `${FAIL} Unknown scenario: ${id}\n`,
204
+ };
205
+ }
206
+
207
+ const guard = assertMaterializeAllowed(projectRoot, force);
208
+ if (!guard.ok) {
209
+ return {
210
+ exitCode: 1,
211
+ output: `${FAIL} ${guard.message}\n`,
212
+ };
213
+ }
214
+
215
+ try {
216
+ const fixture = loadScenarioFixture(scenario, packageRoot);
217
+ const result = materializeFixtureToProject(projectRoot, fixture);
218
+ const payload = {
219
+ scenarioId: scenario.id,
220
+ batchId: result.batchId,
221
+ batchStatePath: result.batchStatePath,
222
+ journalPath: path.relative(projectRoot, result.journalPath),
223
+ };
224
+
225
+ if (json) {
226
+ return {
227
+ exitCode: 0,
228
+ output: `${JSON.stringify(payload, null, 2)}\n`,
229
+ };
230
+ }
231
+
232
+ return {
233
+ exitCode: 0,
234
+ output:
235
+ `${OK} Materialized scenario ${scenario.id} (batch ${result.batchId})\n` +
236
+ ` batch-state: ${result.batchStatePath}\n` +
237
+ ` journal: ${payload.journalPath}\n`,
238
+ };
239
+ } catch (err) {
240
+ const message = err instanceof Error ? err.message : String(err);
241
+ return {
242
+ exitCode: 1,
243
+ output: `${FAIL} ${message}\n`,
244
+ };
245
+ }
246
+ }
247
+
248
+ /**
249
+ * @param {string[]} args
250
+ */
251
+ export async function handleScenarios(args) {
252
+ const json = args.includes("--json");
253
+ const force = args.includes("--force");
254
+ const flags = new Set(["--json", "--force", "--target"]);
255
+ const positional = args.filter((arg) => !flags.has(arg) && !arg.startsWith("--target="));
256
+
257
+ let targetRoot = process.cwd();
258
+ for (let index = 0; index < args.length; index++) {
259
+ if (args[index] === "--target") {
260
+ targetRoot = path.resolve(args[index + 1] ?? "");
261
+ } else if (args[index]?.startsWith("--target=")) {
262
+ targetRoot = path.resolve(args[index].slice("--target=".length));
263
+ }
264
+ }
265
+
266
+ const sub = positional[0];
267
+ const id = positional[1];
268
+
269
+ /** @type {{ exitCode: number, output: string }} */
270
+ let result;
271
+ switch (sub) {
272
+ case "list":
273
+ result = runScenariosList({ json });
274
+ break;
275
+ case "show":
276
+ result = runScenariosShow({ id, json });
277
+ break;
278
+ case "materialize":
279
+ result = runScenariosMaterialize({
280
+ id,
281
+ projectRoot: targetRoot,
282
+ force,
283
+ json,
284
+ });
285
+ break;
286
+ default:
287
+ result = {
288
+ exitCode: 1,
289
+ output:
290
+ `Usage:\n` +
291
+ ` spine scenarios list [--json]\n` +
292
+ ` spine scenarios show <id> [--json]\n` +
293
+ ` spine scenarios materialize <id> [--target DIR] [--force] [--json]\n`,
294
+ };
295
+ }
296
+
297
+ writeCommandResult(result);
298
+ }
@@ -0,0 +1,30 @@
1
+ import { die } from "./shared.mjs";
2
+
3
+ /**
4
+ * @param {string[]} args
5
+ */
6
+ export async function handleWait(args) {
7
+ const { parseWaitArgs, runSpineWait } = await import("../../src/cli/wait.mjs");
8
+
9
+ let parsed;
10
+ try {
11
+ parsed = parseWaitArgs(args);
12
+ } catch (err) {
13
+ const message = err instanceof Error ? err.message : String(err);
14
+ die(
15
+ `${message}\nRun spine wait --until DIAG[,DIAG...] [--timeout DURATION] [--interval SEC] [--json] for usage.`,
16
+ );
17
+ }
18
+
19
+ const result = await runSpineWait({
20
+ projectRoot: process.cwd(),
21
+ untilDiagnoses: parsed.until,
22
+ intervalSec: parsed.intervalSec,
23
+ timeoutMs: parsed.timeoutMs,
24
+ json: parsed.json,
25
+ });
26
+
27
+ if (result.exitCode !== 0) {
28
+ process.exit(result.exitCode);
29
+ }
30
+ }