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,259 @@
1
+ /**
2
+ * Select Cursor rules for spine workers from manifest + PROMPT File Scope (SP-091).
3
+ */
4
+
5
+ import { CURSOR_RULES_ROOT_REL } from "./discover.mjs";
6
+ import { expandFileScopeProbes, ruleGlobsMatchFileScope } from "./match-globs.mjs";
7
+ import { priorityRank } from "./priority.mjs";
8
+
9
+ /** Default maximum rules returned before injection (SP-092 may truncate further by bytes). */
10
+ export const DEFAULT_SELECT_MAX_RULES = 48;
11
+
12
+ /** @typedef {import("./priority.mjs").RuleSelectionSource} RuleSelectionSource */
13
+
14
+ /**
15
+ * @typedef {object} RuleSelectionEntry
16
+ * @property {string} relPath Path relative to `.cursor/rules/`
17
+ * @property {string} contextPath Project-relative path for worker context loading
18
+ * @property {RuleSelectionSource} source
19
+ * @property {import("./discover.mjs").CursorRuleSpineClass} [spineClass]
20
+ */
21
+
22
+ /**
23
+ * @typedef {object} RulesSelectionResult
24
+ * @property {true} ok
25
+ * @property {string[]} paths Ordered project-relative context paths (`.cursor/rules/...`)
26
+ * @property {RuleSelectionEntry[]} entries Ordered selection entries for journal / debugging
27
+ * @property {boolean} capped True when `maxRules` dropped lower-priority paths
28
+ * @property {string[]} [dropped] Context paths omitted by the cap (stable order)
29
+ * @property {boolean} globMatchEnabled Whether profile had glob matching enabled
30
+ * @property {number} fileScopeProbeCount Probe count after `expandFileScopeProbes`
31
+ */
32
+
33
+ /**
34
+ * @param {string} relPath
35
+ * @returns {string}
36
+ */
37
+ function toPosixRelPath(relPath) {
38
+ return relPath.replace(/\\/g, "/").replace(/^\.\/+/, "");
39
+ }
40
+
41
+ /**
42
+ * @param {string} relPath Path relative to `.cursor/rules/`
43
+ * @returns {string}
44
+ */
45
+ export function ruleRelPathToContextPath(relPath) {
46
+ const normalized = toPosixRelPath(relPath);
47
+ return `${CURSOR_RULES_ROOT_REL}/${normalized}`;
48
+ }
49
+
50
+ /**
51
+ * @param {string} contextPath Project-relative path (often `.cursor/rules/foo.mdc`)
52
+ * @returns {string|null}
53
+ */
54
+ export function contextPathToRuleRelPath(contextPath) {
55
+ const normalized = toPosixRelPath(contextPath);
56
+ const rulesPrefix = `${CURSOR_RULES_ROOT_REL}/`;
57
+ if (normalized.startsWith(rulesPrefix)) {
58
+ return normalized.slice(rulesPrefix.length);
59
+ }
60
+ if (!normalized.includes("/")) {
61
+ return normalized;
62
+ }
63
+ return null;
64
+ }
65
+
66
+ /**
67
+ * @param {string[]} paths
68
+ * @returns {Set<string>}
69
+ */
70
+ function normalizeBlocklist(paths) {
71
+ /** @type {Set<string>} */
72
+ const blocked = new Set();
73
+ for (const entry of paths) {
74
+ const normalized = toPosixRelPath(entry);
75
+ if (!normalized) {
76
+ continue;
77
+ }
78
+ blocked.add(normalized);
79
+ const rel = contextPathToRuleRelPath(normalized);
80
+ if (rel) {
81
+ blocked.add(rel);
82
+ blocked.add(ruleRelPathToContextPath(rel));
83
+ }
84
+ }
85
+ return blocked;
86
+ }
87
+
88
+ /**
89
+ * Shared manifest-driven rule selection (SP-247). Worker and reviewer wrappers
90
+ * supply profile-specific always/never lists and scope paths.
91
+ *
92
+ * @param {import("./discover.mjs").CursorRulesManifest} manifest
93
+ * @param {string[]} alwaysInclude Paths relative to `.cursor/rules/`
94
+ * @param {string[]} neverInclude Paths relative to `.cursor/rules/`
95
+ * @param {boolean} globMatch When true, glob-triggered rules may match scope paths
96
+ * @param {string[]} scopePaths File-scope paths for glob matching (worker File Scope or review scope)
97
+ * @param {string[]} [standards] `config.standards` paths (appended after auto-selection)
98
+ * @param {string[]} [neverLoad] `config.neverLoad` paths
99
+ * @param {number} [maxRules]
100
+ * @returns {RulesSelectionResult}
101
+ */
102
+ export function selectRulesFromManifest({
103
+ manifest,
104
+ alwaysInclude,
105
+ neverInclude,
106
+ globMatch,
107
+ scopePaths = [],
108
+ standards = [],
109
+ neverLoad = [],
110
+ maxRules = DEFAULT_SELECT_MAX_RULES,
111
+ }) {
112
+ const globMatchEnabled = globMatch !== false;
113
+ const fileScopeProbeCount = expandFileScopeProbes(scopePaths).length;
114
+
115
+ /** @type {Map<string, RuleSelectionEntry>} */
116
+ const byRelPath = new Map();
117
+ const manifestByRel = new Map(manifest.rules.map((rule) => [rule.relPath, rule]));
118
+
119
+ const addEntry = (relPath, source) => {
120
+ const normalized = toPosixRelPath(relPath);
121
+ if (!normalized || byRelPath.has(normalized)) {
122
+ return;
123
+ }
124
+ const manifestRule = manifestByRel.get(normalized);
125
+ byRelPath.set(normalized, {
126
+ relPath: normalized,
127
+ contextPath: ruleRelPathToContextPath(normalized),
128
+ source,
129
+ spineClass: manifestRule?.spineClass,
130
+ });
131
+ };
132
+
133
+ for (const relPath of alwaysInclude) {
134
+ addEntry(relPath, "alwaysInclude");
135
+ }
136
+
137
+ for (const rule of manifest.rules) {
138
+ if (rule.spineClass === "always") {
139
+ addEntry(rule.relPath, "always");
140
+ }
141
+ }
142
+
143
+ if (globMatchEnabled) {
144
+ for (const rule of manifest.rules) {
145
+ if (rule.spineClass !== "glob" || rule.globs.length === 0) {
146
+ continue;
147
+ }
148
+ if (ruleGlobsMatchFileScope(rule.globs, scopePaths)) {
149
+ addEntry(rule.relPath, "glob");
150
+ }
151
+ }
152
+ }
153
+
154
+ for (const standardPath of standards) {
155
+ const rel = contextPathToRuleRelPath(standardPath);
156
+ if (rel) {
157
+ addEntry(rel, "standards");
158
+ }
159
+ }
160
+
161
+ const blocked = normalizeBlocklist([
162
+ ...neverInclude.map((rel) => ruleRelPathToContextPath(rel)),
163
+ ...neverLoad,
164
+ ]);
165
+
166
+ const sorted = [...byRelPath.values()]
167
+ .filter((entry) => !blocked.has(entry.relPath) && !blocked.has(entry.contextPath))
168
+ .sort((left, right) => {
169
+ const rankDiff = priorityRank(left.source) - priorityRank(right.source);
170
+ if (rankDiff !== 0) {
171
+ return rankDiff;
172
+ }
173
+ return left.relPath.localeCompare(right.relPath);
174
+ });
175
+
176
+ const limit = Math.max(1, maxRules);
177
+ const selected = sorted.slice(0, limit);
178
+ const dropped = sorted.slice(limit).map((entry) => entry.contextPath);
179
+
180
+ return {
181
+ ok: true,
182
+ paths: selected.map((entry) => entry.contextPath),
183
+ entries: selected,
184
+ capped: dropped.length > 0,
185
+ dropped: dropped.length > 0 ? dropped : undefined,
186
+ globMatchEnabled,
187
+ fileScopeProbeCount,
188
+ };
189
+ }
190
+
191
+ /**
192
+ * @param {import("./discover.mjs").CursorRulesManifest} manifest
193
+ * @param {import("./profile.mjs").RulesProfile} profile
194
+ * @param {string[]} fileScope PROMPT File Scope paths
195
+ * @param {string[]} [standards] `config.standards` paths (appended after auto-selection)
196
+ * @param {string[]} [neverLoad] `config.neverLoad` paths
197
+ * @param {number} [maxRules]
198
+ * @returns {RulesSelectionResult}
199
+ */
200
+ export function selectRulesForWorker({
201
+ manifest,
202
+ profile,
203
+ fileScope = [],
204
+ standards = [],
205
+ neverLoad = [],
206
+ maxRules = DEFAULT_SELECT_MAX_RULES,
207
+ }) {
208
+ return selectRulesFromManifest({
209
+ manifest,
210
+ alwaysInclude: profile.worker.alwaysInclude,
211
+ neverInclude: profile.worker.neverInclude,
212
+ globMatch: profile.worker.globMatch,
213
+ scopePaths: fileScope,
214
+ standards,
215
+ neverLoad,
216
+ maxRules,
217
+ });
218
+ }
219
+
220
+ /**
221
+ * @param {import("./discover.mjs").CursorRulesManifest} manifest
222
+ * @param {import("./profile.mjs").RulesProfile} profile
223
+ * @param {string[]} scopePaths Review scope paths (PROMPT File Scope, diff paths, or empty for final)
224
+ * @param {string[]} [standards] `config.standards` paths (appended after auto-selection)
225
+ * @param {string[]} [neverLoad] `config.neverLoad` paths
226
+ * @returns {RulesSelectionResult}
227
+ */
228
+ export function selectRulesForReviewer({
229
+ manifest,
230
+ profile,
231
+ scopePaths = [],
232
+ standards = [],
233
+ neverLoad = [],
234
+ }) {
235
+ const globMatchEnabled = profile.reviewer.globMatch !== false;
236
+ const fileScopeProbeCount = expandFileScopeProbes(scopePaths).length;
237
+
238
+ if (!profile.reviewer.enabled) {
239
+ return {
240
+ ok: true,
241
+ paths: [],
242
+ entries: [],
243
+ capped: false,
244
+ globMatchEnabled,
245
+ fileScopeProbeCount,
246
+ };
247
+ }
248
+
249
+ return selectRulesFromManifest({
250
+ manifest,
251
+ alwaysInclude: profile.reviewer.alwaysInclude,
252
+ neverInclude: profile.reviewer.neverInclude,
253
+ globMatch: profile.reviewer.globMatch,
254
+ scopePaths,
255
+ standards,
256
+ neverLoad,
257
+ maxRules: profile.reviewer.maxRules,
258
+ });
259
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * spine-config.json v2.0 default sections (handoff §6.2).
3
+ * Contract defaults are added in SP-142.
4
+ */
5
+
6
+ /** @type {Readonly<{ requireFinalVerdict: boolean; maxFinalAttempts: number }>} */
7
+ export const REVIEW_DEFAULTS = Object.freeze({
8
+ requireFinalVerdict: true,
9
+ maxFinalAttempts: 3,
10
+ });
11
+
12
+ /** @type {Readonly<{ path: string; autoWriteOn: readonly string[] }>} */
13
+ export const HANDOFF_DEFAULTS = Object.freeze({
14
+ path: ".spine/handoff.md",
15
+ autoWriteOn: Object.freeze(["session_start"]),
16
+ });
17
+
18
+ /** @type {Readonly<{ enabled: boolean; path: string }>} */
19
+ export const METRICS_DEFAULTS = Object.freeze({
20
+ enabled: true,
21
+ path: ".spine/run-metrics.jsonl",
22
+ });
23
+
24
+ /** @type {Readonly<{ mode: string; legacyTaskIdPrefixes: readonly string[] }>} */
25
+ export const CONTRACT_DEFAULTS = Object.freeze({
26
+ mode: "required",
27
+ legacyTaskIdPrefixes: Object.freeze(["TP-"]),
28
+ });
29
+
30
+ /** @type {Readonly<{ review: typeof REVIEW_DEFAULTS; handoff: typeof HANDOFF_DEFAULTS; metrics: typeof METRICS_DEFAULTS; contract: typeof CONTRACT_DEFAULTS }>} */
31
+ export const CONFIG_V2_SECTION_DEFAULTS = Object.freeze({
32
+ review: REVIEW_DEFAULTS,
33
+ handoff: HANDOFF_DEFAULTS,
34
+ metrics: METRICS_DEFAULTS,
35
+ contract: CONTRACT_DEFAULTS,
36
+ });
@@ -0,0 +1,207 @@
1
+ /**
2
+ * FR-CFG-04 environment variable overrides (TP-046).
3
+ * Precedence: env > file > defaults (applied in loadSpineConfig after file parse).
4
+ */
5
+
6
+ import path from "node:path";
7
+
8
+ import { validateSettingValue } from "./settings-fields.mjs";
9
+
10
+ /** @typedef {"file" | "env" | "default"} ConfigValueSource */
11
+
12
+ /**
13
+ * @typedef {object} EnvOverrideSpec
14
+ * @property {string} envVar
15
+ * @property {string} configPath Dotted path (e.g. paths.tasksRoot)
16
+ * @property {"tasksRoot" | "maxParallel"} kind
17
+ */
18
+
19
+ /** @type {readonly EnvOverrideSpec[]} */
20
+ export const ENV_OVERRIDE_SPECS = Object.freeze([
21
+ { envVar: "SPINE_TASKS_ROOT", configPath: "paths.tasksRoot", kind: "tasksRoot" },
22
+ { envVar: "SPINE_MAX_LANES", configPath: "lanes.maxParallel", kind: "maxParallel" },
23
+ ]);
24
+
25
+ /**
26
+ * @param {unknown} config
27
+ * @param {string} dottedPath
28
+ * @returns {unknown}
29
+ */
30
+ export function getValueAtPath(config, dottedPath) {
31
+ const parts = dottedPath.split(".");
32
+ let current = config;
33
+ for (const part of parts) {
34
+ if (current == null || typeof current !== "object") {
35
+ return undefined;
36
+ }
37
+ current = /** @type {Record<string, unknown>} */ (current)[part];
38
+ }
39
+ return current;
40
+ }
41
+
42
+ /**
43
+ * @param {object} config
44
+ * @param {string} dottedPath
45
+ * @param {unknown} value
46
+ */
47
+ export function setValueAtPath(config, dottedPath, value) {
48
+ const parts = dottedPath.split(".");
49
+ let current = /** @type {Record<string, unknown>} */ (config);
50
+ for (let i = 0; i < parts.length - 1; i++) {
51
+ const part = parts[i];
52
+ const next = current[part];
53
+ if (next == null || typeof next !== "object" || Array.isArray(next)) {
54
+ current[part] = {};
55
+ }
56
+ current = /** @type {Record<string, unknown>} */ (current[part]);
57
+ }
58
+ current[parts[parts.length - 1]] = value;
59
+ }
60
+
61
+ /**
62
+ * Normalize SPINE_TASKS_ROOT for storage in paths.tasksRoot.
63
+ * Absolute paths are stored as-is; relative paths are normalized like init --tasks-root.
64
+ *
65
+ * @param {string} raw
66
+ * @param {string} projectRoot
67
+ * @returns {{ ok: true, normalized: string } | { ok: false, error: string }}
68
+ */
69
+ export function normalizeTasksRootFromEnv(raw, _projectRoot) {
70
+ const trimmed = raw.trim();
71
+ if (trimmed === "") {
72
+ return { ok: false, error: "SPINE_TASKS_ROOT must be a non-empty path" };
73
+ }
74
+
75
+ if (path.isAbsolute(trimmed)) {
76
+ return { ok: true, normalized: path.normalize(trimmed) };
77
+ }
78
+
79
+ const normalized = trimmed
80
+ .replace(/\\/g, "/")
81
+ .replace(/^\.\/+/, "")
82
+ .replace(/\/+$/, "");
83
+
84
+ if (!normalized || normalized === ".") {
85
+ return { ok: false, error: "SPINE_TASKS_ROOT must not be empty" };
86
+ }
87
+ if (normalized === ".." || normalized.startsWith("../")) {
88
+ return {
89
+ ok: false,
90
+ error: "SPINE_TASKS_ROOT must stay within the project root (paths starting with .. are not allowed)",
91
+ };
92
+ }
93
+
94
+ return { ok: true, normalized };
95
+ }
96
+
97
+ /**
98
+ * @param {string} projectRoot
99
+ * @param {object} config Effective config (paths.tasksRoot set)
100
+ * @returns {string|null}
101
+ */
102
+ export function resolveTasksRootPath(projectRoot, config) {
103
+ const tasksRoot = config?.paths?.tasksRoot;
104
+ if (typeof tasksRoot !== "string" || tasksRoot.trim() === "") {
105
+ return null;
106
+ }
107
+ if (path.isAbsolute(tasksRoot)) {
108
+ return path.normalize(tasksRoot);
109
+ }
110
+ return path.join(projectRoot, tasksRoot);
111
+ }
112
+
113
+ /**
114
+ * @param {object} config Loaded file config (validated)
115
+ * @param {string} projectRoot
116
+ * @param {NodeJS.ProcessEnv} [env]
117
+ * @returns {{
118
+ * ok: true,
119
+ * config: object,
120
+ * sources: Record<string, ConfigValueSource>,
121
+ * envVars: Record<string, string>,
122
+ * } | { ok: false, error: { code: string, message: string, suggestedCommand?: string } }}
123
+ */
124
+ export function applyEnvOverrides(config, projectRoot, env = process.env) {
125
+ /** @type {Record<string, ConfigValueSource>} */
126
+ const sources = {};
127
+ /** @type {Record<string, string>} */
128
+ const envVars = {};
129
+
130
+ for (const spec of ENV_OVERRIDE_SPECS) {
131
+ sources[spec.configPath] = "file";
132
+ }
133
+
134
+ const merged = structuredClone(config);
135
+
136
+ for (const spec of ENV_OVERRIDE_SPECS) {
137
+ const raw = env[spec.envVar];
138
+ if (raw == null || String(raw).trim() === "") {
139
+ continue;
140
+ }
141
+
142
+ if (spec.kind === "tasksRoot") {
143
+ const parsed = normalizeTasksRootFromEnv(String(raw), projectRoot);
144
+ if (!parsed.ok) {
145
+ return {
146
+ ok: false,
147
+ error: {
148
+ code: "CONFIG_ENV_INVALID",
149
+ message: parsed.error,
150
+ suggestedCommand: "unset SPINE_TASKS_ROOT",
151
+ },
152
+ };
153
+ }
154
+ setValueAtPath(merged, spec.configPath, parsed.normalized);
155
+ sources[spec.configPath] = "env";
156
+ envVars[spec.configPath] = spec.envVar;
157
+ continue;
158
+ }
159
+
160
+ if (spec.kind === "maxParallel") {
161
+ const validated = validateSettingValue("lanes.maxParallel", raw);
162
+ if (!validated.ok) {
163
+ return {
164
+ ok: false,
165
+ error: {
166
+ code: "CONFIG_ENV_INVALID",
167
+ message: `SPINE_MAX_LANES: ${validated.error}`,
168
+ suggestedCommand: "unset SPINE_MAX_LANES",
169
+ },
170
+ };
171
+ }
172
+ setValueAtPath(merged, spec.configPath, validated.normalizedValue);
173
+ sources[spec.configPath] = "env";
174
+ envVars[spec.configPath] = spec.envVar;
175
+ }
176
+ }
177
+
178
+ return { ok: true, config: merged, sources, envVars };
179
+ }
180
+
181
+ /**
182
+ * Display fields for settings show / doctor (env-overridable + effective value).
183
+ *
184
+ * @returns {{ path: string, label: string, type: string }[]}
185
+ */
186
+ export function listEnvAwareDisplayFields() {
187
+ return [
188
+ { path: "paths.tasksRoot", label: "Tasks root (relative or absolute)", type: "string" },
189
+ { path: "lanes.maxParallel", label: "Max parallel lanes", type: "number" },
190
+ ];
191
+ }
192
+
193
+ /**
194
+ * @param {Record<string, ConfigValueSource> | undefined} sources
195
+ * @param {Record<string, string> | undefined} envVars
196
+ * @param {string} configPath
197
+ * @param {unknown} value
198
+ * @returns {string}
199
+ */
200
+ export function formatConfigSourceDetail(sources, envVars, configPath, value) {
201
+ const display = value === undefined || value === null ? "(not set)" : String(value);
202
+ const source = sources?.[configPath] ?? "file";
203
+ if (source === "env" && envVars?.[configPath]) {
204
+ return `${display} (source: env, ${envVars[configPath]})`;
205
+ }
206
+ return `${display} (source: ${source})`;
207
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Merge v2.0 config section defaults for repos missing new keys (SP-141).
3
+ */
4
+
5
+ import { CONFIG_V2_SECTION_DEFAULTS } from "./defaults.mjs";
6
+
7
+ /**
8
+ * @param {unknown} value
9
+ * @returns {value is Record<string, unknown>}
10
+ */
11
+ function isPlainObject(value) {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value);
13
+ }
14
+
15
+ /**
16
+ * Deep-merge `defaults` into `target` for missing keys only.
17
+ *
18
+ * @param {Record<string, unknown>} target
19
+ * @param {Record<string, unknown>} defaults
20
+ */
21
+ function mergeMissingDefaults(target, defaults) {
22
+ for (const [key, defaultValue] of Object.entries(defaults)) {
23
+ if (!(key in target) || target[key] === undefined) {
24
+ target[key] = Array.isArray(defaultValue)
25
+ ? [...defaultValue]
26
+ : isPlainObject(defaultValue)
27
+ ? structuredClone(defaultValue)
28
+ : defaultValue;
29
+ continue;
30
+ }
31
+ if (isPlainObject(defaultValue) && isPlainObject(target[key])) {
32
+ mergeMissingDefaults(/** @type {Record<string, unknown>} */ (target[key]), defaultValue);
33
+ }
34
+ }
35
+ }
36
+
37
+ /**
38
+ * @param {object} config Parsed spine-config.json object (mutated in place).
39
+ * @returns {object} Same config reference with v2 sections merged.
40
+ */
41
+ export function applyConfigDefaults(config) {
42
+ if (!isPlainObject(config)) {
43
+ return config;
44
+ }
45
+ mergeMissingDefaults(/** @type {Record<string, unknown>} */ (config), CONFIG_V2_SECTION_DEFAULTS);
46
+ return config;
47
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Resolve pi-spine package root for worker subprocess env (SP-103).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ /**
10
+ * @param {string} root
11
+ * @returns {boolean}
12
+ */
13
+ function looksLikePiSpinePackage(root) {
14
+ return (
15
+ fs.existsSync(path.join(root, "package.json")) &&
16
+ fs.existsSync(path.join(root, "bin", "spine.mjs"))
17
+ );
18
+ }
19
+
20
+ /**
21
+ * @param {string} root
22
+ * @returns {string}
23
+ */
24
+ function realpathOrResolve(root) {
25
+ try {
26
+ return fs.realpathSync(root);
27
+ } catch {
28
+ return root;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * @param {object} [config]
34
+ * @param {string} [projectRoot]
35
+ * @param {string} [importMetaUrl]
36
+ * @returns {string}
37
+ */
38
+ export function resolvePiSpineRoot(
39
+ config = {},
40
+ projectRoot = process.cwd(),
41
+ importMetaUrl = import.meta.url,
42
+ ) {
43
+ const configured = config?.development?.piSpineRoot;
44
+ if (typeof configured === "string" && configured.trim()) {
45
+ const trimmed = configured.trim();
46
+ const resolved = path.isAbsolute(trimmed)
47
+ ? trimmed
48
+ : path.resolve(projectRoot, trimmed);
49
+ return realpathOrResolve(resolved);
50
+ }
51
+
52
+ const moduleDir = path.dirname(fileURLToPath(importMetaUrl));
53
+ const packageRoot = path.resolve(moduleDir, "../..");
54
+ return realpathOrResolve(packageRoot);
55
+ }
56
+
57
+ /**
58
+ * @param {object} [config]
59
+ * @param {string} [projectRoot]
60
+ * @returns {{ code: string, message: string, suggestedCommand: string } | null}
61
+ */
62
+ export function validatePiSpineRootConfig(config, projectRoot = process.cwd()) {
63
+ const configured = config?.development?.piSpineRoot;
64
+ if (configured == null || configured === "") return null;
65
+
66
+ if (typeof configured !== "string" || !configured.trim()) {
67
+ return {
68
+ code: "CONFIG_PI_SPINE_ROOT_INVALID",
69
+ message: "development.piSpineRoot must be a non-empty string when set",
70
+ suggestedCommand: "spine settings set development.piSpineRoot /path/to/pi-spine",
71
+ };
72
+ }
73
+
74
+ const resolved = resolvePiSpineRoot(config, projectRoot);
75
+ if (!fs.existsSync(resolved)) {
76
+ return {
77
+ code: "CONFIG_PI_SPINE_ROOT_MISSING",
78
+ message: `development.piSpineRoot path does not exist: ${resolved}`,
79
+ suggestedCommand: "spine doctor",
80
+ };
81
+ }
82
+
83
+ if (!looksLikePiSpinePackage(resolved)) {
84
+ return {
85
+ code: "CONFIG_PI_SPINE_ROOT_INVALID",
86
+ message:
87
+ "development.piSpineRoot must point at a pi-spine package (package.json and bin/spine.mjs)",
88
+ suggestedCommand: "spine doctor",
89
+ };
90
+ }
91
+
92
+ return null;
93
+ }