pi-spine 1.0.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 (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +563 -0
  3. package/bin/get-version.mjs +35 -0
  4. package/bin/spine-batch.mjs +425 -0
  5. package/bin/spine-cli/batch.mjs +47 -0
  6. package/bin/spine-cli/gate.mjs +10 -0
  7. package/bin/spine-cli/integrate.mjs +10 -0
  8. package/bin/spine-cli/plan.mjs +12 -0
  9. package/bin/spine-cli/shared.mjs +73 -0
  10. package/bin/spine-cli/status.mjs +18 -0
  11. package/bin/spine-cli/verify.mjs +199 -0
  12. package/bin/spine-config.mjs +212 -0
  13. package/bin/spine-dashboard.mjs +178 -0
  14. package/bin/spine-deps.mjs +69 -0
  15. package/bin/spine-doctor.mjs +468 -0
  16. package/bin/spine-gate.mjs +137 -0
  17. package/bin/spine-init.mjs +398 -0
  18. package/bin/spine-integrate.mjs +77 -0
  19. package/bin/spine-journal.mjs +198 -0
  20. package/bin/spine-migrate-from-taskplane.mjs +136 -0
  21. package/bin/spine-plan.mjs +83 -0
  22. package/bin/spine-preflight.mjs +700 -0
  23. package/bin/spine-report-progress.d.mts +28 -0
  24. package/bin/spine-report-progress.mjs +126 -0
  25. package/bin/spine-review-step.d.mts +24 -0
  26. package/bin/spine-review-step.mjs +124 -0
  27. package/bin/spine-rules.mjs +35 -0
  28. package/bin/spine-settings.mjs +186 -0
  29. package/bin/spine-state.mjs +110 -0
  30. package/bin/spine-status.mjs +79 -0
  31. package/bin/spine-tasks.mjs +293 -0
  32. package/bin/spine-worker-runner.mjs +314 -0
  33. package/bin/spine.mjs +404 -0
  34. package/extensions/spine/settings-slash.ts +20 -0
  35. package/extensions/spine/slash-commands.ts +806 -0
  36. package/extensions/spine/worker-tools.ts +279 -0
  37. package/extensions/spine-orchestrator.ts +12 -0
  38. package/package.json +72 -0
  39. package/skills/.gitkeep +0 -0
  40. package/skills/create-spine-tasks/SKILL.md +375 -0
  41. package/skills/create-spine-tasks/references/context-template.md +25 -0
  42. package/skills/create-spine-tasks/references/contract-template.md +98 -0
  43. package/skills/create-spine-tasks/references/explore-template.md +63 -0
  44. package/skills/create-spine-tasks/references/prompt-template.md +276 -0
  45. package/src/batch/abort.mjs +272 -0
  46. package/src/batch/agent-session-worker.mjs +297 -0
  47. package/src/batch/batch-state-io.mjs +53 -0
  48. package/src/batch/contract-verify.mjs +310 -0
  49. package/src/batch/detached-start.mjs +778 -0
  50. package/src/batch/diagnosis.mjs +378 -0
  51. package/src/batch/engine-lanes/merge.mjs +632 -0
  52. package/src/batch/engine-lanes/queue.mjs +208 -0
  53. package/src/batch/engine-lanes/review.mjs +970 -0
  54. package/src/batch/engine-lanes.mjs +388 -0
  55. package/src/batch/engine-scope.mjs +251 -0
  56. package/src/batch/engine.mjs +445 -0
  57. package/src/batch/evidence-command.mjs +157 -0
  58. package/src/batch/evidence.mjs +203 -0
  59. package/src/batch/gate.mjs +359 -0
  60. package/src/batch/git-commit-env.mjs +46 -0
  61. package/src/batch/git-exec.mjs +26 -0
  62. package/src/batch/heartbeat.mjs +430 -0
  63. package/src/batch/integrate.mjs +414 -0
  64. package/src/batch/journal-rebuild.mjs +388 -0
  65. package/src/batch/journal.mjs +373 -0
  66. package/src/batch/lane-commit.mjs +153 -0
  67. package/src/batch/lifecycle.mjs +364 -0
  68. package/src/batch/metrics.mjs +265 -0
  69. package/src/batch/orphan-detect.mjs +210 -0
  70. package/src/batch/post-merge-limbo.mjs +80 -0
  71. package/src/batch/postmortem.mjs +296 -0
  72. package/src/batch/readers/spine-state.mjs +95 -0
  73. package/src/batch/readers/taskplane-state.mjs +136 -0
  74. package/src/batch/reconcile.mjs +729 -0
  75. package/src/batch/resume-common.mjs +104 -0
  76. package/src/batch/resume-engine.mjs +66 -0
  77. package/src/batch/resume-multi-lanes.mjs +479 -0
  78. package/src/batch/resume-multi-validate.mjs +187 -0
  79. package/src/batch/resume-multi.mjs +254 -0
  80. package/src/batch/resume.mjs +475 -0
  81. package/src/batch/retry.mjs +257 -0
  82. package/src/batch/review-scope.mjs +136 -0
  83. package/src/batch/review.mjs +1045 -0
  84. package/src/batch/salvage.mjs +332 -0
  85. package/src/batch/state.mjs +680 -0
  86. package/src/batch/task-stall-budget.mjs +88 -0
  87. package/src/batch/worker-host.mjs +683 -0
  88. package/src/batch/worker-output.mjs +253 -0
  89. package/src/batch/worker-prompt.mjs +84 -0
  90. package/src/batch/worktree.mjs +290 -0
  91. package/src/cli/deps.mjs +141 -0
  92. package/src/cli/handoff.mjs +364 -0
  93. package/src/cli/rules.mjs +429 -0
  94. package/src/cli/settings-set.mjs +171 -0
  95. package/src/cli/settings-show.mjs +140 -0
  96. package/src/cli/settings-slash.mjs +107 -0
  97. package/src/config/contract.mjs +56 -0
  98. package/src/config/cursor-rules/discover.mjs +416 -0
  99. package/src/config/cursor-rules/index.mjs +39 -0
  100. package/src/config/cursor-rules/match-globs.mjs +132 -0
  101. package/src/config/cursor-rules/parse-frontmatter.mjs +222 -0
  102. package/src/config/cursor-rules/priority.mjs +26 -0
  103. package/src/config/cursor-rules/profile.mjs +403 -0
  104. package/src/config/cursor-rules/select.mjs +259 -0
  105. package/src/config/defaults.mjs +36 -0
  106. package/src/config/env-overrides.mjs +207 -0
  107. package/src/config/merge-defaults.mjs +47 -0
  108. package/src/config/pi-spine-root.mjs +93 -0
  109. package/src/config/reviewer-context.mjs +243 -0
  110. package/src/config/settings-fields.mjs +265 -0
  111. package/src/config/worker-backend.mjs +116 -0
  112. package/src/config/worker-context.mjs +402 -0
  113. package/src/config/worker-launch-script.mjs +130 -0
  114. package/src/config/worktree-setup-hook.mjs +122 -0
  115. package/src/dashboard/public/dashboard.css +77 -0
  116. package/src/dashboard/public/dashboard.js +349 -0
  117. package/src/dashboard/public/index.html +80 -0
  118. package/src/dashboard/server.mjs +155 -0
  119. package/src/dashboard/snapshot.mjs +414 -0
  120. package/src/dashboard/sse.mjs +15 -0
  121. package/src/dashboard/view.mjs +292 -0
  122. package/src/doctor/agent-model-inherit.mjs +101 -0
  123. package/src/doctor/batch-size-guidance.mjs +72 -0
  124. package/src/doctor/coexistence.mjs +312 -0
  125. package/src/doctor/rules-manifest.mjs +133 -0
  126. package/src/doctor/stale-path.mjs +156 -0
  127. package/src/doctor/stall-config.mjs +108 -0
  128. package/src/doctor/suggest-max-parallel.mjs +53 -0
  129. package/src/doctor/task-packet-size.mjs +110 -0
  130. package/src/doctor/worktree-health.mjs +71 -0
  131. package/src/migrate/taskplane-config.mjs +116 -0
  132. package/src/planner/cycles.mjs +63 -0
  133. package/src/planner/format-plan.mjs +132 -0
  134. package/src/planner/graph.mjs +99 -0
  135. package/src/planner/index.mjs +125 -0
  136. package/src/planner/lanes.mjs +111 -0
  137. package/src/planner/pending.mjs +39 -0
  138. package/src/planner/scope.mjs +142 -0
  139. package/src/process/liveness.mjs +21 -0
  140. package/src/tasks/packet/discover.mjs +40 -0
  141. package/src/tasks/packet/index.mjs +81 -0
  142. package/src/tasks/packet/merge-deps.mjs +79 -0
  143. package/src/tasks/packet/parse-prompt.mjs +445 -0
  144. package/src/tasks/packet/parse-status.mjs +118 -0
  145. package/src/tasks/packet/validate-contract.mjs +115 -0
  146. package/src/tasks/packet/validate-prompt.mjs +99 -0
  147. package/src/worker-tools/report-progress.d.mts +18 -0
  148. package/src/worker-tools/report-progress.mjs +59 -0
  149. package/src/worker-tools/request-gate.d.mts +17 -0
  150. package/src/worker-tools/request-gate.mjs +54 -0
  151. package/templates/agents/reviewer.md +123 -0
  152. package/templates/agents/supervisor.md +59 -0
  153. package/templates/agents/worker.md +122 -0
  154. package/templates/rules-profile.json +27 -0
  155. package/templates/spine-config.json +64 -0
  156. package/templates/tasks/CONTEXT.md +30 -0
@@ -0,0 +1,429 @@
1
+ /**
2
+ * spine rules discover | select | sync (SP-093).
3
+ */
4
+
5
+ import { loadSpineConfig } from "../../bin/spine-config.mjs";
6
+ import { resolveTasksRootPath } from "../config/env-overrides.mjs";
7
+ import {
8
+ discoverCursorRules,
9
+ loadRulesManifest,
10
+ RULES_MANIFEST_REL_PATH,
11
+ } from "../config/cursor-rules/discover.mjs";
12
+ import { loadRulesProfile, RULES_PROFILE_REL_PATH } from "../config/cursor-rules/profile.mjs";
13
+ import { selectRulesForReviewer, selectRulesForWorker } from "../config/cursor-rules/select.mjs";
14
+ import { resolveReviewScopePaths } from "../batch/review-scope.mjs";
15
+ import { discoverTasks } from "../tasks/packet/discover.mjs";
16
+ import { loadTaskPacket } from "../tasks/packet/index.mjs";
17
+
18
+ /**
19
+ * @param {string[]} argv
20
+ */
21
+ export function parseRulesArgv(argv) {
22
+ const json = argv.includes("--json");
23
+ const taskIdx = argv.indexOf("--task");
24
+ const taskId = taskIdx !== -1 ? argv[taskIdx + 1] : undefined;
25
+ if (taskIdx !== -1 && (!taskId || taskId.startsWith("--"))) {
26
+ throw new Error("Missing value for --task <task-id>.");
27
+ }
28
+
29
+ const roleIdx = argv.indexOf("--role");
30
+ let role = "worker";
31
+ if (roleIdx !== -1) {
32
+ const roleValue = argv[roleIdx + 1];
33
+ if (!roleValue || roleValue.startsWith("--")) {
34
+ throw new Error("Missing value for --role <worker|reviewer>.");
35
+ }
36
+ if (roleValue !== "worker" && roleValue !== "reviewer") {
37
+ throw new Error(`Invalid --role: ${roleValue}. Use worker or reviewer.`);
38
+ }
39
+ role = roleValue;
40
+ }
41
+
42
+ const reviewTypeIdx = argv.indexOf("--review-type");
43
+ let reviewType;
44
+ if (reviewTypeIdx !== -1) {
45
+ const reviewTypeValue = argv[reviewTypeIdx + 1];
46
+ if (!reviewTypeValue || reviewTypeValue.startsWith("--")) {
47
+ throw new Error("Missing value for --review-type <plan|code|final>.");
48
+ }
49
+ if (!["plan", "code", "final"].includes(reviewTypeValue)) {
50
+ throw new Error(`Invalid --review-type: ${reviewTypeValue}. Use plan, code, or final.`);
51
+ }
52
+ reviewType = reviewTypeValue;
53
+ }
54
+
55
+ const baselineIdx = argv.indexOf("--baseline");
56
+ let baseline;
57
+ if (baselineIdx !== -1) {
58
+ const baselineValue = argv[baselineIdx + 1];
59
+ if (!baselineValue || baselineValue.startsWith("--")) {
60
+ throw new Error("Missing value for --baseline <sha>.");
61
+ }
62
+ baseline = baselineValue;
63
+ }
64
+
65
+ if (role === "reviewer" && !reviewType) {
66
+ throw new Error("spine rules select --role reviewer requires --review-type <plan|code|final>.");
67
+ }
68
+ if (role === "worker" && reviewType) {
69
+ throw new Error("spine rules select --review-type is only valid with --role reviewer.");
70
+ }
71
+ if (baseline && role !== "reviewer") {
72
+ throw new Error("spine rules select --baseline is only valid with --role reviewer.");
73
+ }
74
+
75
+ return { json, taskId, role, reviewType, baseline };
76
+ }
77
+
78
+ /**
79
+ * @param {import("../config/cursor-rules/discover.mjs").DiscoverCursorRulesResult} result
80
+ */
81
+ export function formatRulesDiscoverHuman(result) {
82
+ const { manifest, manifestPath } = result;
83
+ const summary = `${manifest.rules.length} rules, ${manifest.excluded.length} excluded`;
84
+ const warningNote =
85
+ manifest.warnings?.length > 0 ? ` (${manifest.warnings.length} warning(s))` : "";
86
+ const pathNote = manifestPath ? `\n wrote ${RULES_MANIFEST_REL_PATH}` : "";
87
+ return `Discovered ${summary}${warningNote}.${pathNote}\n`;
88
+ }
89
+
90
+ /**
91
+ * @param {object} params
92
+ * @param {string} params.projectRoot
93
+ * @param {boolean} [params.json]
94
+ * @param {boolean} [params.writeManifest]
95
+ */
96
+ export function runRulesDiscover({ projectRoot, json = false, writeManifest = true }) {
97
+ const profileResult = loadRulesProfile(projectRoot);
98
+ if (!profileResult.ok) {
99
+ const message = profileResult.error.message;
100
+ if (json) {
101
+ return {
102
+ exitCode: 1,
103
+ output: `${JSON.stringify({ ok: false, error: message, code: profileResult.error.code }, null, 2)}\n`,
104
+ };
105
+ }
106
+ return { exitCode: 1, output: `Error: ${message}\n` };
107
+ }
108
+
109
+ const result = discoverCursorRules({
110
+ projectRoot,
111
+ profile: profileResult.profile,
112
+ writeManifest,
113
+ });
114
+
115
+ if (json) {
116
+ return {
117
+ exitCode: 0,
118
+ output: `${JSON.stringify(result, null, 2)}\n`,
119
+ result,
120
+ };
121
+ }
122
+
123
+ return {
124
+ exitCode: 0,
125
+ output: formatRulesDiscoverHuman(result),
126
+ result,
127
+ };
128
+ }
129
+
130
+ /**
131
+ * @param {object} params
132
+ * @param {string} params.projectRoot
133
+ * @param {boolean} [params.json]
134
+ */
135
+ export function runRulesSync({ projectRoot, json = false }) {
136
+ return runRulesDiscover({ projectRoot, json, writeManifest: true });
137
+ }
138
+
139
+ /**
140
+ * @param {string} tasksRoot
141
+ * @param {string} taskId
142
+ */
143
+ export function resolveTaskPromptFileScope(tasksRoot, taskId) {
144
+ const match = discoverTasks(tasksRoot).find((task) => task.taskId === taskId);
145
+ if (!match) {
146
+ return {
147
+ ok: false,
148
+ error: `Task not found: ${taskId}`,
149
+ suggestedCommand: "spine deps all",
150
+ };
151
+ }
152
+
153
+ const packet = loadTaskPacket(match.folderPath);
154
+ if (!packet.validation.ok) {
155
+ return {
156
+ ok: false,
157
+ error: packet.validation.errors.join("; "),
158
+ errors: packet.validation.errors,
159
+ promptPath: packet.promptPath,
160
+ };
161
+ }
162
+
163
+ const prompt = packet.prompt;
164
+ if (!prompt.taskId) {
165
+ return {
166
+ ok: false,
167
+ error: `Invalid PROMPT.md in ${match.folderName}`,
168
+ };
169
+ }
170
+
171
+ return {
172
+ ok: true,
173
+ taskId: prompt.taskId,
174
+ folderName: match.folderName,
175
+ folderPath: match.folderPath,
176
+ fileScope: prompt.fileScope,
177
+ };
178
+ }
179
+
180
+ /**
181
+ * @param {import("../config/cursor-rules/select.mjs").RulesSelectionResult} selection
182
+ * @param {object} meta
183
+ */
184
+ export function formatRulesSelectHuman(selection, meta) {
185
+ const lines = [
186
+ `Task ${meta.taskId} (${meta.folderName})`,
187
+ ];
188
+ if (meta.role === "reviewer") {
189
+ lines.push(` role: reviewer (${meta.reviewType})`);
190
+ lines.push(` scope paths: ${meta.scopePaths.length} path(s)`);
191
+ } else {
192
+ lines.push(` file scope: ${meta.fileScope.length} path(s)`);
193
+ }
194
+ lines.push(` selected: ${selection.paths.length} rule(s)`);
195
+ if (selection.capped && selection.dropped?.length) {
196
+ lines.push(` capped: dropped ${selection.dropped.length} lower-priority rule(s)`);
197
+ }
198
+ for (const entry of selection.entries) {
199
+ lines.push(` - ${entry.contextPath} (${entry.source})`);
200
+ }
201
+ return `${lines.join("\n")}\n`;
202
+ }
203
+
204
+ /**
205
+ * @param {object} params
206
+ * @param {string} params.projectRoot
207
+ * @param {string} params.taskId
208
+ * @param {boolean} [params.json]
209
+ * @param {"worker"|"reviewer"} [params.role]
210
+ * @param {"plan"|"code"|"final"} [params.reviewType]
211
+ * @param {string} [params.baseline]
212
+ */
213
+ export function runRulesSelect({
214
+ projectRoot,
215
+ taskId,
216
+ json = false,
217
+ role = "worker",
218
+ reviewType,
219
+ baseline,
220
+ }) {
221
+ const configResult = loadSpineConfig(projectRoot);
222
+ if (configResult.error) {
223
+ const message = configResult.error.message;
224
+ const suggestedCommand = configResult.error.suggestedCommand;
225
+ if (json) {
226
+ return {
227
+ exitCode: 1,
228
+ output: `${JSON.stringify({ ok: false, error: message, suggestedCommand }, null, 2)}\n`,
229
+ };
230
+ }
231
+ return {
232
+ exitCode: 1,
233
+ output: `Error: ${message}\nSuggested: ${suggestedCommand}\n`,
234
+ };
235
+ }
236
+
237
+ const tasksRoot = resolveTasksRootPath(projectRoot, configResult.config);
238
+ const scopeResult = resolveTaskPromptFileScope(tasksRoot, taskId);
239
+ if (!scopeResult.ok) {
240
+ if (json) {
241
+ return {
242
+ exitCode: 1,
243
+ output: `${JSON.stringify({ ok: false, error: scopeResult.error, suggestedCommand: scopeResult.suggestedCommand }, null, 2)}\n`,
244
+ };
245
+ }
246
+ const hint = scopeResult.suggestedCommand ? `\nSuggested: ${scopeResult.suggestedCommand}` : "";
247
+ return { exitCode: 1, output: `Error: ${scopeResult.error}${hint}\n` };
248
+ }
249
+
250
+ const profileResult = loadRulesProfile(projectRoot);
251
+ if (!profileResult.ok) {
252
+ const message = profileResult.error.message;
253
+ if (json) {
254
+ return {
255
+ exitCode: 1,
256
+ output: `${JSON.stringify({ ok: false, error: message, code: profileResult.error.code }, null, 2)}\n`,
257
+ };
258
+ }
259
+ return { exitCode: 1, output: `Error: ${message}\n` };
260
+ }
261
+
262
+ const manifest = loadRulesManifest(projectRoot);
263
+ if (!manifest) {
264
+ const message = `${RULES_MANIFEST_REL_PATH} missing — run spine rules sync`;
265
+ if (json) {
266
+ return {
267
+ exitCode: 1,
268
+ output: `${JSON.stringify({ ok: false, error: message, suggestedCommand: "spine rules sync" }, null, 2)}\n`,
269
+ };
270
+ }
271
+ return {
272
+ exitCode: 1,
273
+ output: `Error: ${message}\n`,
274
+ suggestedCommand: "spine rules sync",
275
+ };
276
+ }
277
+
278
+ const standards = Array.isArray(configResult.config.standards) ? configResult.config.standards : [];
279
+ const neverLoad = Array.isArray(configResult.config.neverLoad) ? configResult.config.neverLoad : [];
280
+
281
+ /** @type {import("../config/cursor-rules/select.mjs").RulesSelectionResult} */
282
+ let selection;
283
+ /** @type {string[]} */
284
+ let scopePaths = scopeResult.fileScope;
285
+
286
+ if (role === "reviewer") {
287
+ const scopeResolution = resolveReviewScopePaths({
288
+ worktreePath: projectRoot,
289
+ baseline,
290
+ reviewType: /** @type {"plan"|"code"|"final"} */ (reviewType),
291
+ taskFolder: scopeResult.folderPath,
292
+ });
293
+ scopePaths = scopeResolution.scopePaths;
294
+ selection = selectRulesForReviewer({
295
+ manifest,
296
+ profile: profileResult.profile,
297
+ scopePaths,
298
+ standards,
299
+ neverLoad,
300
+ });
301
+ } else {
302
+ selection = selectRulesForWorker({
303
+ manifest,
304
+ profile: profileResult.profile,
305
+ fileScope: scopeResult.fileScope,
306
+ standards,
307
+ neverLoad,
308
+ });
309
+ }
310
+
311
+ const payload =
312
+ role === "reviewer"
313
+ ? {
314
+ ok: true,
315
+ role: "reviewer",
316
+ reviewType,
317
+ taskId: scopeResult.taskId,
318
+ folderName: scopeResult.folderName,
319
+ scopePaths,
320
+ selection,
321
+ }
322
+ : {
323
+ ok: true,
324
+ taskId: scopeResult.taskId,
325
+ folderName: scopeResult.folderName,
326
+ fileScope: scopeResult.fileScope,
327
+ selection,
328
+ };
329
+
330
+ if (json) {
331
+ return {
332
+ exitCode: 0,
333
+ output: `${JSON.stringify(payload, null, 2)}\n`,
334
+ selection,
335
+ };
336
+ }
337
+
338
+ const meta =
339
+ role === "reviewer"
340
+ ? {
341
+ taskId: scopeResult.taskId,
342
+ folderName: scopeResult.folderName,
343
+ role: "reviewer",
344
+ reviewType,
345
+ scopePaths,
346
+ }
347
+ : scopeResult;
348
+
349
+ return {
350
+ exitCode: 0,
351
+ output: formatRulesSelectHuman(selection, meta),
352
+ selection,
353
+ };
354
+ }
355
+
356
+ export function printRulesHelp() {
357
+ return `
358
+ Usage:
359
+ spine rules discover [--json]
360
+ spine rules select --task <task-id> [--role worker|reviewer] [--review-type plan|code|final] [--baseline <sha>] [--json]
361
+ spine rules sync [--json]
362
+
363
+ Discover scans .cursor/rules and writes .spine/rules-manifest.json (committed to git).
364
+ Select previews rule selection for a task. Default role is worker (PROMPT File Scope).
365
+ Reviewer role resolves review-type-specific scope paths and uses profile.reviewer.
366
+ Sync re-runs discovery and updates the committed manifest.
367
+
368
+ Files:
369
+ ${RULES_PROFILE_REL_PATH} Worker/discovery profile (copied by spine init)
370
+ ${RULES_MANIFEST_REL_PATH} Committed discovery manifest
371
+
372
+ Examples:
373
+ spine rules discover
374
+ spine rules discover --json
375
+ spine rules select --task SP-093
376
+ spine rules select --task SP-093 --role reviewer --review-type plan
377
+ spine rules select --task SP-093 --role reviewer --review-type code --baseline abc1234
378
+ spine rules select --task SP-093 --role reviewer --review-type final --json
379
+ spine rules sync
380
+ `;
381
+ }
382
+
383
+ /**
384
+ * @param {object} options
385
+ * @param {string} options.projectRoot
386
+ * @param {string[]} options.args
387
+ */
388
+ export function runSpineRules({ projectRoot, args }) {
389
+ if (args.includes("--help") || args.includes("-h") || args.length === 0) {
390
+ return { exitCode: 0, output: printRulesHelp() };
391
+ }
392
+
393
+ const sub = args[0];
394
+ const rest = args.slice(1);
395
+
396
+ try {
397
+ const { json, taskId, role, reviewType, baseline } = parseRulesArgv(rest);
398
+
399
+ if (sub === "discover") {
400
+ return runRulesDiscover({ projectRoot, json, writeManifest: true });
401
+ }
402
+ if (sub === "sync") {
403
+ return runRulesSync({ projectRoot, json });
404
+ }
405
+ if (sub === "select") {
406
+ if (!taskId) {
407
+ return {
408
+ exitCode: 1,
409
+ output: "Error: spine rules select requires --task <task-id>\n",
410
+ };
411
+ }
412
+ return runRulesSelect({ projectRoot, taskId, json, role, reviewType, baseline });
413
+ }
414
+
415
+ return {
416
+ exitCode: 1,
417
+ output: `Error: Unknown rules subcommand: ${sub}\n${printRulesHelp()}`,
418
+ };
419
+ } catch (err) {
420
+ const message = err instanceof Error ? err.message : String(err);
421
+ if (rest.includes("--json")) {
422
+ return {
423
+ exitCode: 1,
424
+ output: `${JSON.stringify({ ok: false, error: message }, null, 2)}\n`,
425
+ };
426
+ }
427
+ return { exitCode: 1, output: `Error: ${message}\n` };
428
+ }
429
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * spine settings set — validate, merge, and persist editable spine-config fields (FR-CFG-03).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { randomBytes } from "node:crypto";
8
+
9
+ import { parseSettingPath, validateSettingValue } from "../config/settings-fields.mjs";
10
+ import { validateSpineConfig } from "../../bin/spine-config.mjs";
11
+ import { getValueAtPath } from "./settings-show.mjs";
12
+
13
+ /**
14
+ * @param {object} config
15
+ * @param {string} dottedPath
16
+ * @param {boolean | number | string} value
17
+ * @returns {object}
18
+ */
19
+ export function applySetting(config, dottedPath, value) {
20
+ const parts = dottedPath.split(".");
21
+ const next = structuredClone(config);
22
+ let current = next;
23
+
24
+ for (let i = 0; i < parts.length - 1; i++) {
25
+ const part = parts[i];
26
+ const existing = current[part];
27
+ if (existing == null || typeof existing !== "object" || Array.isArray(existing)) {
28
+ current[part] = {};
29
+ }
30
+ current = /** @type {Record<string, unknown>} */ (current[part]);
31
+ }
32
+
33
+ current[parts[parts.length - 1]] = value;
34
+ return next;
35
+ }
36
+
37
+ /**
38
+ * @param {string} projectRoot
39
+ * @param {object} config
40
+ */
41
+ export function writeSpineConfigAtomic(projectRoot, config) {
42
+ 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
+ }
62
+ }
63
+
64
+ /**
65
+ * @param {object} config
66
+ * @param {{ path: string, rawValue: unknown, dryRun?: boolean, json?: boolean }} options
67
+ * @returns {{
68
+ * exitCode: number,
69
+ * output: string,
70
+ * error?: string,
71
+ * suggestedCommand?: string,
72
+ * path?: string,
73
+ * previousValue?: unknown,
74
+ * newValue?: boolean | number | string,
75
+ * config?: object,
76
+ * dryRun?: boolean,
77
+ * wrote?: boolean,
78
+ * }}
79
+ */
80
+ export function runSettingsSetOperation(config, { path, rawValue, dryRun = false, json = false }) {
81
+ const parsed = parseSettingPath(path);
82
+ if (!parsed.ok) {
83
+ const message = parsed.error;
84
+ if (json) {
85
+ return {
86
+ exitCode: 1,
87
+ output: `${JSON.stringify({ error: message }, null, 2)}\n`,
88
+ error: message,
89
+ };
90
+ }
91
+ return {
92
+ exitCode: 1,
93
+ output: `Error: ${message}\n`,
94
+ error: message,
95
+ };
96
+ }
97
+
98
+ const validated = validateSettingValue(path, rawValue);
99
+ if (!validated.ok) {
100
+ const message = validated.error;
101
+ if (json) {
102
+ return {
103
+ exitCode: 1,
104
+ output: `${JSON.stringify({ error: message }, null, 2)}\n`,
105
+ error: message,
106
+ };
107
+ }
108
+ return {
109
+ exitCode: 1,
110
+ output: `Error: ${message}\n`,
111
+ error: message,
112
+ };
113
+ }
114
+
115
+ const previousValue = getValueAtPath(config, parsed.path);
116
+ const nextConfig = applySetting(config, parsed.path, validated.normalizedValue);
117
+ const validationError = validateSpineConfig(nextConfig);
118
+ if (validationError) {
119
+ const message = validationError.message;
120
+ if (json) {
121
+ return {
122
+ exitCode: 1,
123
+ output: `${JSON.stringify({ error: message, suggestedCommand: validationError.suggestedCommand }, null, 2)}\n`,
124
+ error: message,
125
+ suggestedCommand: validationError.suggestedCommand,
126
+ };
127
+ }
128
+ return {
129
+ exitCode: 1,
130
+ output: `Error: ${message}\nSuggested: ${validationError.suggestedCommand}\n`,
131
+ error: message,
132
+ suggestedCommand: validationError.suggestedCommand,
133
+ };
134
+ }
135
+
136
+ const wrote = !dryRun;
137
+ const payload = {
138
+ path: parsed.path,
139
+ previousValue,
140
+ newValue: validated.normalizedValue,
141
+ dryRun,
142
+ wrote,
143
+ };
144
+
145
+ if (json) {
146
+ return {
147
+ exitCode: 0,
148
+ output: `${JSON.stringify(payload, null, 2)}\n`,
149
+ ...payload,
150
+ config: nextConfig,
151
+ };
152
+ }
153
+
154
+ return {
155
+ exitCode: 0,
156
+ output: `Updated ${parsed.path}: ${formatValue(previousValue)} → ${formatValue(validated.normalizedValue)}${dryRun ? " (dry run)" : ""}\n`,
157
+ ...payload,
158
+ config: nextConfig,
159
+ };
160
+ }
161
+
162
+ /**
163
+ * @param {unknown} value
164
+ * @returns {string}
165
+ */
166
+ function formatValue(value) {
167
+ if (value === undefined || value === null) {
168
+ return "(not set)";
169
+ }
170
+ return String(value);
171
+ }