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,291 @@
1
+ /**
2
+ * Resolve and tail lane worker logs (issue #50, SP-366).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import {
8
+ classifyTasks,
9
+ loadBatchStateFile,
10
+ parseBatchState,
11
+ } from "../batch/reconcile.mjs";
12
+ import {
13
+ workerLiveLogPath,
14
+ workerOutputLogPath,
15
+ } from "../batch/worker-output.mjs";
16
+ import { resolveTasksRootPath } from "../config/env-overrides.mjs";
17
+ import { resolveFollowBatchId } from "./journal-follow.mjs";
18
+
19
+ const LIVE_LOG_PREFIX = "worker-live-";
20
+ const OUTPUT_LOG_PREFIX = "worker-output-";
21
+ const LOG_SUFFIX = ".log";
22
+
23
+ /**
24
+ * @param {string|undefined|null} value
25
+ */
26
+ export function parseLaneNumber(value) {
27
+ const laneNumber = Number(value);
28
+ if (!Number.isFinite(laneNumber) || laneNumber < 1) return null;
29
+ return laneNumber;
30
+ }
31
+
32
+ /**
33
+ * @param {string[]} args
34
+ */
35
+ export function parseLaneLogsArgs(args) {
36
+ const batchIdx = args.indexOf("--batch");
37
+ const batchId = batchIdx >= 0 ? args[batchIdx + 1] ?? null : null;
38
+ const laneIdx = args.indexOf("--lane");
39
+ const laneNumber = laneIdx >= 0 ? parseLaneNumber(args[laneIdx + 1]) : null;
40
+ const taskIdx = args.indexOf("--task");
41
+ const taskId = taskIdx >= 0 ? args[taskIdx + 1] ?? null : null;
42
+ const follow = args.includes("--follow");
43
+ return { batchId, laneNumber, taskId, follow };
44
+ }
45
+
46
+ /**
47
+ * @param {string} projectRoot
48
+ * @param {string} batchId
49
+ * @param {number} laneNumber
50
+ */
51
+ export function laneRuntimeDir(projectRoot, batchId, laneNumber) {
52
+ return path.join(
53
+ projectRoot,
54
+ ".spine",
55
+ "runtime",
56
+ batchId,
57
+ "lanes",
58
+ `lane-${laneNumber}`,
59
+ );
60
+ }
61
+
62
+ /**
63
+ * @param {string} filename
64
+ * @param {string} prefix
65
+ */
66
+ export function extractTaskIdFromLogFilename(filename, prefix) {
67
+ if (!filename.startsWith(prefix) || !filename.endsWith(LOG_SUFFIX)) return null;
68
+ const taskId = filename.slice(prefix.length, filename.length - LOG_SUFFIX.length);
69
+ return taskId.length > 0 ? taskId : null;
70
+ }
71
+
72
+ /**
73
+ * @param {string} laneDir
74
+ * @param {typeof fs} fileSystem
75
+ */
76
+ export function findMostRecentLogTaskId(laneDir, fileSystem = fs) {
77
+ if (!fileSystem.existsSync(laneDir)) return null;
78
+
79
+ /** @type {{ taskId: string, mtimeMs: number } | null} */
80
+ let latest = null;
81
+
82
+ for (const entry of fileSystem.readdirSync(laneDir)) {
83
+ if (!entry.endsWith(LOG_SUFFIX)) continue;
84
+ const taskId =
85
+ extractTaskIdFromLogFilename(entry, LIVE_LOG_PREFIX) ??
86
+ extractTaskIdFromLogFilename(entry, OUTPUT_LOG_PREFIX);
87
+ if (!taskId) continue;
88
+
89
+ const stat = fileSystem.statSync(path.join(laneDir, entry));
90
+ if (!latest || stat.mtimeMs > latest.mtimeMs) {
91
+ latest = { taskId, mtimeMs: stat.mtimeMs };
92
+ }
93
+ }
94
+
95
+ return latest?.taskId ?? null;
96
+ }
97
+
98
+ /**
99
+ * @param {string} projectRoot
100
+ * @param {number} laneNumber
101
+ */
102
+ export function resolveRunningTaskIdForLane(projectRoot, laneNumber) {
103
+ const loaded = loadBatchStateFile(projectRoot, null);
104
+ const batch = loaded.raw ? parseBatchState(loaded.raw, loaded.path ?? "") : null;
105
+ if (!batch) return null;
106
+
107
+ const tasksRoot = resolveTasksRootPath(projectRoot);
108
+ const classifiedTasks = classifyTasks(batch, tasksRoot);
109
+ const running = classifiedTasks.filter(
110
+ (task) =>
111
+ Number(task.laneNumber) === laneNumber && task.classification === "running",
112
+ );
113
+ if (running.length === 1) return running[0].taskId;
114
+ if (running.length > 1) {
115
+ return running[running.length - 1].taskId;
116
+ }
117
+ return null;
118
+ }
119
+
120
+ /**
121
+ * @param {object} params
122
+ * @param {string} params.projectRoot
123
+ * @param {string} params.batchId
124
+ * @param {number} params.laneNumber
125
+ * @param {string|null|undefined} params.taskId
126
+ * @param {typeof fs} [params.fileSystem]
127
+ */
128
+ export function resolveLaneLogTaskId(
129
+ { projectRoot, batchId, laneNumber, taskId },
130
+ fileSystem = fs,
131
+ ) {
132
+ if (taskId) return taskId;
133
+
134
+ const runningTaskId = resolveRunningTaskIdForLane(projectRoot, laneNumber);
135
+ if (runningTaskId) return runningTaskId;
136
+
137
+ return findMostRecentLogTaskId(laneRuntimeDir(projectRoot, batchId, laneNumber), fileSystem);
138
+ }
139
+
140
+ /**
141
+ * Prefer live log when present, else terminal worker-output log.
142
+ *
143
+ * @param {object} params
144
+ * @param {string} params.projectRoot
145
+ * @param {string} params.batchId
146
+ * @param {number} params.laneNumber
147
+ * @param {string} params.taskId
148
+ * @param {typeof fs} [params.fileSystem]
149
+ */
150
+ export function resolveLaneLogPath(
151
+ { projectRoot, batchId, laneNumber, taskId },
152
+ fileSystem = fs,
153
+ ) {
154
+ const livePath = workerLiveLogPath(projectRoot, batchId, laneNumber, taskId);
155
+ if (fileSystem.existsSync(livePath)) {
156
+ return { logPath: livePath, kind: "live" };
157
+ }
158
+
159
+ const outputPath = workerOutputLogPath(projectRoot, batchId, laneNumber, taskId);
160
+ if (fileSystem.existsSync(outputPath)) {
161
+ return { logPath: outputPath, kind: "output" };
162
+ }
163
+
164
+ return { logPath: livePath, kind: "missing" };
165
+ }
166
+
167
+ /**
168
+ * @param {string} filePath
169
+ * @param {{ onChunk: (chunk: string) => void }} options
170
+ * @param {typeof fs} fileSystem
171
+ * @returns {number}
172
+ */
173
+ export function readLaneLogSnapshot(filePath, options, fileSystem = fs) {
174
+ const content = fileSystem.readFileSync(filePath, "utf-8");
175
+ if (content) options.onChunk(content);
176
+ const stat = fileSystem.statSync(filePath);
177
+ return stat.size;
178
+ }
179
+
180
+ const defaultDeps = {
181
+ fs,
182
+ stdout: process.stdout,
183
+ onSignal: (signal, handler) => process.on(signal, handler),
184
+ offSignal: (signal, handler) => process.off(signal, handler),
185
+ };
186
+
187
+ /**
188
+ * @param {object} options
189
+ * @param {string} options.projectRoot
190
+ * @param {string[]} [options.args]
191
+ * @param {boolean} [options.follow]
192
+ * @param {typeof defaultDeps} [options.deps]
193
+ */
194
+ export async function runLaneLogs(options) {
195
+ const { projectRoot, args = [], follow: followOverride, deps = defaultDeps } = options;
196
+ const { batchId: argBatchId, laneNumber, taskId: argTaskId, follow: argFollow } =
197
+ parseLaneLogsArgs(args);
198
+ const follow = followOverride ?? argFollow;
199
+
200
+ if (laneNumber == null) {
201
+ return {
202
+ exitCode: 1,
203
+ output: "Lane number is required (pass --lane N)\n",
204
+ };
205
+ }
206
+
207
+ const batchId = resolveFollowBatchId(projectRoot, argBatchId);
208
+ if (!batchId) {
209
+ return {
210
+ exitCode: 1,
211
+ output: "No active batch for lane logs (pass --batch {id} or start a batch)\n",
212
+ };
213
+ }
214
+
215
+ const taskId = resolveLaneLogTaskId(
216
+ { projectRoot, batchId, laneNumber, taskId: argTaskId },
217
+ deps.fs,
218
+ );
219
+ if (!taskId) {
220
+ return {
221
+ exitCode: 1,
222
+ output: `No worker log found for lane ${laneNumber} (pass --task {id})\n`,
223
+ };
224
+ }
225
+
226
+ const resolved = resolveLaneLogPath(
227
+ { projectRoot, batchId, laneNumber, taskId },
228
+ deps.fs,
229
+ );
230
+ if (resolved.kind === "missing") {
231
+ return {
232
+ exitCode: 1,
233
+ output: `Worker log not found for lane ${laneNumber} task ${taskId}: ${resolved.logPath}\n`,
234
+ };
235
+ }
236
+
237
+ /** @type {string[]} */
238
+ const chunks = [];
239
+ const onChunk = (chunk) => {
240
+ chunks.push(chunk);
241
+ deps.stdout.write(chunk);
242
+ };
243
+
244
+ let offset = readLaneLogSnapshot(resolved.logPath, { onChunk }, deps.fs);
245
+
246
+ if (!follow) {
247
+ return { exitCode: 0, output: chunks.join("") };
248
+ }
249
+
250
+ return new Promise((resolve) => {
251
+ /** @type {import("node:fs").FSWatcher|null} */
252
+ let watcher = null;
253
+
254
+ const cleanup = (exitCode = 0) => {
255
+ if (watcher) watcher.close();
256
+ resolve({ exitCode, output: chunks.join("") });
257
+ };
258
+
259
+ const onChange = () => {
260
+ try {
261
+ const filePath = resolved.logPath;
262
+ if (!deps.fs.existsSync(filePath)) return;
263
+
264
+ const stat = deps.fs.statSync(filePath);
265
+ if (stat.size < offset) {
266
+ offset = 0;
267
+ }
268
+ if (stat.size <= offset) return;
269
+
270
+ const toRead = stat.size - offset;
271
+ const fd = deps.fs.openSync(filePath, "r");
272
+ try {
273
+ const buffer = Buffer.alloc(toRead);
274
+ deps.fs.readSync(fd, buffer, 0, toRead, offset);
275
+ offset = stat.size;
276
+ onChunk(buffer.toString("utf-8"));
277
+ } finally {
278
+ deps.fs.closeSync(fd);
279
+ }
280
+ } catch {
281
+ // Transient read races while the worker appends are expected during follow.
282
+ }
283
+ };
284
+
285
+ watcher = deps.fs.watch(resolved.logPath, onChange);
286
+ const onSigInt = () => cleanup(0);
287
+ const onSigTerm = () => cleanup(0);
288
+ deps.onSignal("SIGINT", onSigInt);
289
+ deps.onSignal("SIGTERM", onSigTerm);
290
+ });
291
+ }
package/src/cli/rules.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  * spine rules discover | select | sync (SP-093).
3
3
  */
4
4
 
5
- import { loadSpineConfig } from "../../bin/spine-config.mjs";
5
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
6
6
  import { resolveTasksRootPath } from "../config/env-overrides.mjs";
7
7
  import {
8
8
  discoverCursorRules,
@@ -0,0 +1,108 @@
1
+ /**
2
+ * CLI for planner wave sequence runner (GitHub #54 Tier 2).
3
+ * Entry: `spine run sequence <scope>` — not `spine batch sequence` (see issue #54 open Q1).
4
+ */
5
+
6
+ import { buildSequencePlan, runSequence } from "../batch/sequence.mjs";
7
+ import { resolveDefaultSpineBin } from "../batch/post-merge-limbo.mjs";
8
+
9
+ /**
10
+ * @param {string[]} argv
11
+ */
12
+ export function parseSequenceArgs(argv) {
13
+ /** @type {{ scope: string, fromWave: number, throughWave: number|null, attached: boolean, stopOnFailure: boolean, dryRun: boolean, json: boolean, skipPreflight: boolean }} */
14
+ const parsed = {
15
+ scope: "pending",
16
+ fromWave: 0,
17
+ throughWave: null,
18
+ attached: false,
19
+ stopOnFailure: true,
20
+ dryRun: false,
21
+ json: false,
22
+ skipPreflight: false,
23
+ };
24
+
25
+ /** @type {string[]} */
26
+ const positional = [];
27
+ for (let i = 0; i < argv.length; i++) {
28
+ const arg = argv[i];
29
+ if (arg === "--from-wave") {
30
+ parsed.fromWave = Number(argv[++i]);
31
+ } else if (arg === "--through-wave") {
32
+ parsed.throughWave = Number(argv[++i]);
33
+ } else if (arg === "--attached") {
34
+ parsed.attached = true;
35
+ } else if (arg === "--stop-on-failure") {
36
+ parsed.stopOnFailure = true;
37
+ } else if (arg === "--no-stop-on-failure") {
38
+ parsed.stopOnFailure = false;
39
+ } else if (arg === "--dry-run") {
40
+ parsed.dryRun = true;
41
+ } else if (arg === "--json") {
42
+ parsed.json = true;
43
+ } else if (arg === "--skip-preflight") {
44
+ parsed.skipPreflight = true;
45
+ } else if (!arg.startsWith("--")) {
46
+ positional.push(arg);
47
+ }
48
+ }
49
+
50
+ if (positional.length > 0) {
51
+ parsed.scope = positional.join(" ");
52
+ }
53
+
54
+ return parsed;
55
+ }
56
+
57
+ /**
58
+ * @param {object} result
59
+ * @param {boolean} json
60
+ */
61
+ export function formatSequenceResult(result, json) {
62
+ if (json) {
63
+ return `${JSON.stringify(result, null, 2)}\n`;
64
+ }
65
+ return result.output ?? "";
66
+ }
67
+
68
+ /**
69
+ * @param {object} options
70
+ * @param {string} options.projectRoot
71
+ * @param {string[]} [options.args]
72
+ * @param {string|null} [options.spineBin]
73
+ */
74
+ export async function runSpineSequence({ projectRoot, args = [], spineBin = null }) {
75
+ const parsed = parseSequenceArgs(args);
76
+ const built = buildSequencePlan(projectRoot, parsed.scope);
77
+ if (!built.ok) {
78
+ const failure = {
79
+ ok: false,
80
+ exitCode: 1,
81
+ error: built.error,
82
+ output: built.output,
83
+ };
84
+ return {
85
+ exitCode: 1,
86
+ output: formatSequenceResult(failure, parsed.json),
87
+ result: failure,
88
+ };
89
+ }
90
+
91
+ const result = await runSequence({
92
+ projectRoot,
93
+ plan: built.plan,
94
+ fromWave: parsed.fromWave,
95
+ throughWave: parsed.throughWave,
96
+ attached: parsed.attached,
97
+ stopOnFailure: parsed.stopOnFailure,
98
+ dryRun: parsed.dryRun,
99
+ skipPreflight: parsed.skipPreflight,
100
+ spineBin: parsed.attached ? null : resolveDefaultSpineBin(spineBin),
101
+ });
102
+
103
+ return {
104
+ exitCode: result.exitCode ?? (result.ok ? 0 : 1),
105
+ output: formatSequenceResult(result, parsed.json),
106
+ result,
107
+ };
108
+ }
@@ -2,12 +2,11 @@
2
2
  * spine settings set — validate, merge, and persist editable spine-config fields (FR-CFG-03).
3
3
  */
4
4
 
5
- import fs from "node:fs";
6
5
  import path from "node:path";
7
- import { randomBytes } from "node:crypto";
8
6
 
7
+ import { writeJsonAtomic } from "../fs/atomic-write.mjs";
9
8
  import { parseSettingPath, validateSettingValue } from "../config/settings-fields.mjs";
10
- import { validateSpineConfig } from "../../bin/spine-config.mjs";
9
+ import { validateSpineConfig } from "../config/spine-config-load.mjs";
11
10
  import { getValueAtPath } from "./settings-show.mjs";
12
11
 
13
12
  /**
@@ -40,25 +39,7 @@ export function applySetting(config, dottedPath, value) {
40
39
  */
41
40
  export function writeSpineConfigAtomic(projectRoot, config) {
42
41
  const configPath = path.join(projectRoot, ".spine", "spine-config.json");
43
- const dir = path.dirname(configPath);
44
- fs.mkdirSync(dir, { recursive: true });
45
-
46
- const tmpPath = `${configPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
47
- const content = `${JSON.stringify(config, null, 2)}\n`;
48
-
49
- try {
50
- fs.writeFileSync(tmpPath, content, "utf-8");
51
- fs.renameSync(tmpPath, configPath);
52
- } catch (err) {
53
- try {
54
- if (fs.existsSync(tmpPath)) {
55
- fs.unlinkSync(tmpPath);
56
- }
57
- } catch {
58
- // ignore cleanup failure
59
- }
60
- throw err;
61
- }
42
+ writeJsonAtomic(configPath, config);
62
43
  }
63
44
 
64
45
  /**
@@ -2,9 +2,9 @@
2
2
  * /spine-settings menu formatter and handler (FR-CFG-03).
3
3
  */
4
4
 
5
- import { loadSpineConfig } from "../../bin/spine-config.mjs";
6
- import { runSpineSettingsSet } from "../../bin/spine-settings.mjs";
5
+ import { loadSpineConfig, loadSpineConfigFile } from "../config/spine-config-load.mjs";
7
6
  import { buildSettingsShowFields } from "./settings-show.mjs";
7
+ import { runSettingsSetOperation, writeSpineConfigAtomic } from "./settings-set.mjs";
8
8
 
9
9
  /**
10
10
  * @param {unknown} value
@@ -77,11 +77,33 @@ export async function runSpineSettingsSlash(args, ui, cwd = process.cwd()) {
77
77
  return;
78
78
  }
79
79
 
80
- const result = runSpineSettingsSet({
81
- projectRoot: cwd,
82
- args: [parsed.path, parsed.rawValue],
80
+ const configResult = loadSpineConfigFile(cwd);
81
+ if (configResult.error) {
82
+ const suggested = configResult.error.suggestedCommand ?? "spine init";
83
+ ui.notify(
84
+ `${configResult.error.message}
85
+
86
+ → ${suggested}`,
87
+ "error",
88
+ );
89
+ return;
90
+ }
91
+
92
+ const result = runSettingsSetOperation(configResult.config, {
93
+ path: parsed.path,
94
+ rawValue: parsed.rawValue,
83
95
  });
84
96
 
97
+ if (result.exitCode === 0 && result.config) {
98
+ try {
99
+ writeSpineConfigAtomic(cwd, result.config);
100
+ } catch (err) {
101
+ const message = err instanceof Error ? err.message : String(err);
102
+ ui.notify(`Failed to write spine config: ${message}`, "error");
103
+ return;
104
+ }
105
+ }
106
+
85
107
  if (result.exitCode !== 0) {
86
108
  ui.notify(result.output.trim() || "spine settings set failed", "error");
87
109
  return;
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Block until reconcile diagnosis reaches a target set (issue #46, SP-362).
3
+ */
4
+
5
+ import { DIAGNOSIS_TAXONOMY } from "../batch/diagnosis.mjs";
6
+ import { reconcileBatch } from "../batch/reconcile.mjs";
7
+ import {
8
+ buildWatchSnapshot,
9
+ DEFAULT_WATCH_INTERVAL_SEC,
10
+ } from "./watch.mjs";
11
+
12
+ /** @type {ReadonlySet<string>} */
13
+ const VALID_UNTIL_DIAGNOSES = new Set(DIAGNOSIS_TAXONOMY);
14
+
15
+ /**
16
+ * @param {string} raw
17
+ * @returns {number}
18
+ */
19
+ export function parseDurationMs(raw) {
20
+ const trimmed = String(raw).trim();
21
+ if (trimmed.length === 0) {
22
+ throw new Error("--timeout requires a duration (e.g. 30s, 5m, 2h, or seconds)");
23
+ }
24
+
25
+ if (/^\d+$/.test(trimmed)) {
26
+ const seconds = Number(trimmed);
27
+ if (!Number.isFinite(seconds) || seconds <= 0) {
28
+ throw new Error("--timeout requires a positive duration");
29
+ }
30
+ return seconds * 1000;
31
+ }
32
+
33
+ const match = trimmed.match(/^(\d+(?:\.\d+)?)([smh])$/i);
34
+ if (!match) {
35
+ throw new Error("--timeout requires a duration like 30s, 5m, 2h, or plain seconds");
36
+ }
37
+
38
+ const value = Number(match[1]);
39
+ const unit = match[2].toLowerCase();
40
+ if (!Number.isFinite(value) || value <= 0) {
41
+ throw new Error("--timeout requires a positive duration");
42
+ }
43
+
44
+ const multipliers = { s: 1000, m: 60_000, h: 3_600_000 };
45
+ return value * multipliers[unit];
46
+ }
47
+
48
+ /**
49
+ * @param {string} raw
50
+ * @returns {Set<string>}
51
+ */
52
+ export function parseUntilDiagnoses(raw) {
53
+ const trimmed = String(raw).trim();
54
+ if (trimmed.length === 0) {
55
+ throw new Error("--until requires a comma-separated diagnosis list");
56
+ }
57
+
58
+ /** @type {Set<string>} */
59
+ const diagnoses = new Set();
60
+ for (const part of trimmed.split(",")) {
61
+ const diagnosis = part.trim();
62
+ if (diagnosis.length === 0) {
63
+ throw new Error("--until contains an empty diagnosis entry");
64
+ }
65
+ if (!VALID_UNTIL_DIAGNOSES.has(diagnosis)) {
66
+ throw new Error(
67
+ `Unknown diagnosis in --until: ${diagnosis} (valid: ${DIAGNOSIS_TAXONOMY.join(", ")})`,
68
+ );
69
+ }
70
+ diagnoses.add(diagnosis);
71
+ }
72
+
73
+ return diagnoses;
74
+ }
75
+
76
+ /**
77
+ * @param {string[]} argv
78
+ */
79
+ export function parseWaitArgs(argv) {
80
+ /** @type {{ until: Set<string> | null, timeoutMs: number | null, intervalSec: number, json: boolean }} */
81
+ const args = {
82
+ until: null,
83
+ timeoutMs: null,
84
+ intervalSec: DEFAULT_WATCH_INTERVAL_SEC,
85
+ json: false,
86
+ };
87
+
88
+ for (let i = 0; i < argv.length; i++) {
89
+ const arg = argv[i];
90
+ if (arg === "--until") {
91
+ args.until = parseUntilDiagnoses(argv[++i] ?? "");
92
+ } else if (arg === "--timeout") {
93
+ args.timeoutMs = parseDurationMs(argv[++i] ?? "");
94
+ } else if (arg === "--interval") {
95
+ const raw = argv[++i];
96
+ const value = Number(raw);
97
+ if (!Number.isFinite(value) || value <= 0) {
98
+ throw new Error("--interval requires a positive number of seconds");
99
+ }
100
+ args.intervalSec = value;
101
+ } else if (arg === "--json") {
102
+ args.json = true;
103
+ } else if (arg.startsWith("-")) {
104
+ throw new Error(`Unknown wait option: ${arg}`);
105
+ }
106
+ }
107
+
108
+ if (!args.until || args.until.size === 0) {
109
+ throw new Error("--until is required (comma-separated diagnoses)");
110
+ }
111
+
112
+ return args;
113
+ }
114
+
115
+ /**
116
+ * @param {string | null | undefined} diagnosis
117
+ * @param {Set<string>} untilDiagnoses
118
+ */
119
+ export function diagnosisMatchesUntil(diagnosis, untilDiagnoses) {
120
+ if (diagnosis == null) {
121
+ return false;
122
+ }
123
+ return untilDiagnoses.has(diagnosis);
124
+ }
125
+
126
+ /**
127
+ * @param {object} options
128
+ * @param {string} options.projectRoot
129
+ * @param {Set<string>} options.untilDiagnoses
130
+ * @param {number} [options.intervalSec]
131
+ * @param {number | null} [options.timeoutMs]
132
+ * @param {boolean} [options.json]
133
+ * @param {(ctx: { projectRoot: string }) => import("../batch/reconcile.mjs").ReconciliationResult} [options.reconcileFn]
134
+ * @param {(ms: number) => Promise<void>} [options.sleepFn]
135
+ * @param {() => number} [options.nowFn]
136
+ * @param {(text: string) => void} [options.writeStdout]
137
+ */
138
+ export async function runSpineWait(options) {
139
+ const {
140
+ projectRoot,
141
+ untilDiagnoses,
142
+ intervalSec = DEFAULT_WATCH_INTERVAL_SEC,
143
+ timeoutMs = null,
144
+ json = false,
145
+ reconcileFn = reconcileBatch,
146
+ sleepFn = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
147
+ nowFn = () => Date.now(),
148
+ writeStdout = (text) => process.stdout.write(text),
149
+ } = options;
150
+
151
+ const startedAt = nowFn();
152
+ const deadline = timeoutMs != null ? startedAt + timeoutMs : null;
153
+
154
+ /** @type {boolean} */
155
+ let running = true;
156
+ const onSigInt = () => {
157
+ running = false;
158
+ };
159
+ process.on("SIGINT", onSigInt);
160
+
161
+ try {
162
+ while (running) {
163
+ const result = reconcileFn({ projectRoot });
164
+ const diagnosis = result.diagnosis ?? null;
165
+
166
+ if (diagnosisMatchesUntil(diagnosis, untilDiagnoses)) {
167
+ if (json) {
168
+ writeStdout(`${JSON.stringify(buildWatchSnapshot(result, nowFn()))}\n`);
169
+ }
170
+ return { exitCode: 0, matched: true, diagnosis, timedOut: false };
171
+ }
172
+
173
+ if (deadline != null && nowFn() >= deadline) {
174
+ if (json) {
175
+ writeStdout(`${JSON.stringify(buildWatchSnapshot(result, nowFn()))}\n`);
176
+ }
177
+ return { exitCode: 1, matched: false, diagnosis, timedOut: true };
178
+ }
179
+
180
+ await sleepFn(intervalSec * 1000);
181
+ }
182
+
183
+ return { exitCode: 130, matched: false, diagnosis: null, timedOut: false, interrupted: true };
184
+ } finally {
185
+ process.off("SIGINT", onSigInt);
186
+ }
187
+ }