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,402 @@
1
+ /**
2
+ * FR-WORK-05: tiered worker context from spine-config referenceDocs/standards.
3
+ * SP-092: auto-select `.cursor/rules/` via manifest + PROMPT File Scope.
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { appendJournalEvent } from "../batch/journal.mjs";
9
+ import {
10
+ CURSOR_RULES_ROOT_REL,
11
+ discoverCursorRules,
12
+ loadRulesManifest,
13
+ } from "./cursor-rules/discover.mjs";
14
+ import { loadRulesProfile } from "./cursor-rules/profile.mjs";
15
+ import { selectRulesForWorker } from "./cursor-rules/select.mjs";
16
+
17
+ /** Default injected standards for pi-spine / JS-CLI projects (matches bootstrap checklist). */
18
+ export const DEFAULT_SPINE_INIT_STANDARDS = [
19
+ ".cursor/rules/javascript-3-development-standards.mdc",
20
+ ".cursor/rules/general-llm-anti-patterns.mdc",
21
+ ".cursor/rules/critical-rules-quick-reference.mdc",
22
+ ".cursor/rules/taskplane-task-authoring.mdc",
23
+ ".cursor/rules/taskplane-worker-cursor.mdc",
24
+ ];
25
+
26
+ export const DEFAULT_WORKER_CONTEXT_BYTE_CAP = 32_768;
27
+
28
+ /**
29
+ * @param {unknown} value
30
+ * @returns {string[]|null}
31
+ */
32
+ export function normalizeContextPathList(value) {
33
+ if (value == null) return [];
34
+ if (!Array.isArray(value)) return null;
35
+ const paths = [];
36
+ for (const entry of value) {
37
+ if (typeof entry !== "string" || !entry.trim()) {
38
+ return null;
39
+ }
40
+ paths.push(entry.trim().replace(/\\/g, "/"));
41
+ }
42
+ return paths;
43
+ }
44
+
45
+ /**
46
+ * @param {string} projectRoot
47
+ * @param {string} relPath
48
+ */
49
+ export function resolveContextDocPath(projectRoot, relPath) {
50
+ const normalized = relPath.replace(/\\/g, "/").replace(/^\.\/+/, "");
51
+ if (path.isAbsolute(normalized)) {
52
+ return { ok: false, error: "absolute paths are not allowed in worker context lists" };
53
+ }
54
+ if (normalized.includes("..")) {
55
+ return { ok: false, error: "path traversal is not allowed in worker context lists" };
56
+ }
57
+
58
+ const absPath = path.resolve(projectRoot, normalized);
59
+ const rel = path.relative(projectRoot, absPath);
60
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
61
+ return { ok: false, error: `path escapes project root: ${relPath}` };
62
+ }
63
+
64
+ return { ok: true, absPath, relPath: rel.replace(/\\/g, "/") };
65
+ }
66
+
67
+ /**
68
+ * @param {object} params
69
+ * @param {string} params.projectRoot
70
+ * @param {string[]} params.paths
71
+ * @param {Set<string>} [params.neverLoad]
72
+ * @param {number} [params.byteCap]
73
+ */
74
+ export function loadContextDocEntries({ projectRoot, paths, neverLoad = new Set(), byteCap = DEFAULT_WORKER_CONTEXT_BYTE_CAP }) {
75
+ /** @type {{ relPath: string, content: string }[]} */
76
+ const loaded = [];
77
+ let totalBytes = 0;
78
+ /** @type {string[]} */
79
+ const skipped = [];
80
+
81
+ for (const relPath of paths) {
82
+ if (neverLoad.has(relPath)) {
83
+ skipped.push(relPath);
84
+ continue;
85
+ }
86
+
87
+ const resolved = resolveContextDocPath(projectRoot, relPath);
88
+ if (!resolved.ok) {
89
+ return { ok: false, error: resolved.error, relPath };
90
+ }
91
+
92
+ if (!fs.existsSync(resolved.absPath) || !fs.statSync(resolved.absPath).isFile()) {
93
+ skipped.push(relPath);
94
+ continue;
95
+ }
96
+
97
+ const content = fs.readFileSync(resolved.absPath, "utf-8");
98
+ const size = Buffer.byteLength(content, "utf-8");
99
+ if (totalBytes + size > byteCap) {
100
+ return {
101
+ ok: true,
102
+ entries: loaded,
103
+ truncated: true,
104
+ skipped: [...skipped, relPath, "...remaining paths omitted (byte cap)"],
105
+ bytesUsed: totalBytes,
106
+ byteCap,
107
+ };
108
+ }
109
+
110
+ loaded.push({ relPath: resolved.relPath, content });
111
+ totalBytes += size;
112
+ }
113
+
114
+ return {
115
+ ok: true,
116
+ entries: loaded,
117
+ truncated: false,
118
+ skipped,
119
+ bytesUsed: totalBytes,
120
+ byteCap,
121
+ };
122
+ }
123
+
124
+ /**
125
+ * @param {object} [config]
126
+ * @param {string} [projectRoot]
127
+ * @param {number} [byteCap]
128
+ */
129
+ export function buildWorkerContext(config = {}, projectRoot = process.cwd(), byteCap = DEFAULT_WORKER_CONTEXT_BYTE_CAP) {
130
+ const neverLoad = new Set(normalizeContextPathList(config.neverLoad) ?? []);
131
+ const referenceDocs = normalizeContextPathList(config.referenceDocs) ?? [];
132
+ const standards = normalizeContextPathList(config.standards) ?? [];
133
+ const orderedPaths = [...referenceDocs, ...standards];
134
+
135
+ if (orderedPaths.length === 0) {
136
+ return { text: "", entries: [], truncated: false, skipped: [], bytesUsed: 0, byteCap };
137
+ }
138
+
139
+ const result = loadContextDocEntries({ projectRoot, paths: orderedPaths, neverLoad, byteCap });
140
+ if (!result.ok) {
141
+ return {
142
+ text: "",
143
+ entries: [],
144
+ truncated: false,
145
+ skipped: [],
146
+ bytesUsed: 0,
147
+ byteCap,
148
+ error: result.error,
149
+ blockedPath: result.relPath,
150
+ };
151
+ }
152
+
153
+ const parts = result.entries.map(
154
+ (entry) => `--- ${entry.relPath} ---\n${entry.content.trim()}\n`,
155
+ );
156
+ const text = parts.length > 0 ? `\n\n## Project standards & reference\n\n${parts.join("\n")}` : "";
157
+
158
+ return {
159
+ text,
160
+ entries: result.entries,
161
+ truncated: result.truncated,
162
+ skipped: result.skipped,
163
+ bytesUsed: result.bytesUsed,
164
+ byteCap: result.byteCap,
165
+ };
166
+ }
167
+
168
+ /**
169
+ * @param {object} config
170
+ * @returns {{ code: string, message: string, suggestedCommand: string } | null}
171
+ */
172
+ /**
173
+ * @param {string} projectRoot
174
+ */
175
+ export function cursorRulesRootExists(projectRoot) {
176
+ const rulesRoot = path.join(projectRoot, CURSOR_RULES_ROOT_REL);
177
+ return fs.existsSync(rulesRoot) && fs.statSync(rulesRoot).isDirectory();
178
+ }
179
+
180
+ /**
181
+ * @typedef {object} WorkerRulesJournalContext
182
+ * @property {string} projectRoot
183
+ * @property {string} batchId
184
+ * @property {string} [taskId]
185
+ * @property {number} [laneNumber]
186
+ * @property {string} [correlationId]
187
+ */
188
+
189
+ /**
190
+ * @param {import("./cursor-rules/select.mjs").RulesSelectionResult} selection
191
+ * @returns {object[]}
192
+ */
193
+ function journalEntriesFromSelection(selection) {
194
+ return selection.entries.map((entry) => ({
195
+ relPath: entry.relPath,
196
+ contextPath: entry.contextPath,
197
+ source: entry.source,
198
+ ...(entry.spineClass ? { spineClass: entry.spineClass } : {}),
199
+ }));
200
+ }
201
+
202
+ /**
203
+ * @param {WorkerRulesJournalContext | undefined} journal
204
+ * @param {Record<string, unknown>} payload
205
+ */
206
+ export function emitWorkerRulesSelected(journal, payload) {
207
+ if (!journal?.projectRoot || !journal?.batchId) {
208
+ return;
209
+ }
210
+ appendJournalEvent(journal.projectRoot, journal.batchId, "worker.rules_selected", {
211
+ taskId: journal.taskId,
212
+ laneNumber: journal.laneNumber,
213
+ correlationId: journal.correlationId,
214
+ ...payload,
215
+ });
216
+ }
217
+
218
+ /**
219
+ * @param {object} params
220
+ * @param {object} [params.config]
221
+ * @param {string} [params.projectRoot]
222
+ * @param {string[]} [params.taskFileScope]
223
+ * @param {number} [params.byteCap]
224
+ * @param {WorkerRulesJournalContext} [params.journal]
225
+ */
226
+ export async function buildWorkerContextAsync({
227
+ config = {},
228
+ projectRoot = process.cwd(),
229
+ taskFileScope = [],
230
+ byteCap = DEFAULT_WORKER_CONTEXT_BYTE_CAP,
231
+ journal,
232
+ } = {}) {
233
+ const neverLoad = new Set(normalizeContextPathList(config.neverLoad) ?? []);
234
+ const referenceDocs = normalizeContextPathList(config.referenceDocs) ?? [];
235
+ const standards = normalizeContextPathList(config.standards) ?? [];
236
+
237
+ if (!cursorRulesRootExists(projectRoot)) {
238
+ const staticPaths = [...referenceDocs, ...standards];
239
+ const staticResult = buildWorkerContext(config, projectRoot, byteCap);
240
+ emitWorkerRulesSelected(journal, {
241
+ mode: "static",
242
+ manifestSource: "none",
243
+ pathCount: staticPaths.filter((entry) => !neverLoad.has(entry)).length,
244
+ paths: staticPaths.filter((entry) => !neverLoad.has(entry)),
245
+ fileScopeCount: taskFileScope.length,
246
+ });
247
+ return {
248
+ ...staticResult,
249
+ selection: {
250
+ mode: "static",
251
+ manifestSource: "none",
252
+ paths: staticPaths,
253
+ },
254
+ };
255
+ }
256
+
257
+ const profileResult = loadRulesProfile(projectRoot);
258
+ if (!profileResult.ok) {
259
+ const staticResult = buildWorkerContext(config, projectRoot, byteCap);
260
+ emitWorkerRulesSelected(journal, {
261
+ mode: "static",
262
+ manifestSource: "none",
263
+ profileError: profileResult.error,
264
+ pathCount: 0,
265
+ paths: [],
266
+ fileScopeCount: taskFileScope.length,
267
+ });
268
+ return {
269
+ ...staticResult,
270
+ selection: {
271
+ mode: "static",
272
+ manifestSource: "none",
273
+ profileError: profileResult.error,
274
+ },
275
+ };
276
+ }
277
+
278
+ let manifest = loadRulesManifest(projectRoot);
279
+ let manifestSource = "committed";
280
+ if (!manifest) {
281
+ const discovered = discoverCursorRules({
282
+ projectRoot,
283
+ profile: profileResult.profile,
284
+ writeManifest: false,
285
+ });
286
+ manifest = discovered.manifest;
287
+ manifestSource = "discovered";
288
+ }
289
+
290
+ const selection = selectRulesForWorker({
291
+ manifest,
292
+ profile: profileResult.profile,
293
+ fileScope: taskFileScope,
294
+ standards,
295
+ neverLoad: [...neverLoad],
296
+ });
297
+
298
+ const selectedSet = new Set(selection.paths);
299
+ const orderedPaths = [
300
+ ...selection.paths,
301
+ ...referenceDocs.filter((entry) => !neverLoad.has(entry) && !selectedSet.has(entry)),
302
+ ];
303
+
304
+ emitWorkerRulesSelected(journal, {
305
+ mode: "auto",
306
+ manifestSource,
307
+ profileSource: profileResult.source,
308
+ pathCount: selection.paths.length,
309
+ paths: selection.paths,
310
+ entries: journalEntriesFromSelection(selection),
311
+ capped: selection.capped,
312
+ dropped: selection.dropped,
313
+ globMatchEnabled: selection.globMatchEnabled,
314
+ fileScopeProbeCount: selection.fileScopeProbeCount,
315
+ fileScopeCount: taskFileScope.length,
316
+ referenceDocCount: referenceDocs.filter(
317
+ (entry) => !neverLoad.has(entry) && !selectedSet.has(entry),
318
+ ).length,
319
+ });
320
+
321
+ if (orderedPaths.length === 0) {
322
+ return {
323
+ text: "",
324
+ entries: [],
325
+ truncated: false,
326
+ skipped: [],
327
+ bytesUsed: 0,
328
+ byteCap,
329
+ selection: {
330
+ mode: "auto",
331
+ manifestSource,
332
+ profileSource: profileResult.source,
333
+ ...selection,
334
+ },
335
+ };
336
+ }
337
+
338
+ const loaded = loadContextDocEntries({
339
+ projectRoot,
340
+ paths: orderedPaths,
341
+ neverLoad,
342
+ byteCap,
343
+ });
344
+ if (!loaded.ok) {
345
+ return {
346
+ text: "",
347
+ entries: [],
348
+ truncated: false,
349
+ skipped: [],
350
+ bytesUsed: 0,
351
+ byteCap,
352
+ error: loaded.error,
353
+ blockedPath: loaded.relPath,
354
+ selection: {
355
+ mode: "auto",
356
+ manifestSource,
357
+ profileSource: profileResult.source,
358
+ ...selection,
359
+ },
360
+ };
361
+ }
362
+
363
+ const parts = loaded.entries.map(
364
+ (entry) => `--- ${entry.relPath} ---\n${entry.content.trim()}\n`,
365
+ );
366
+ const text =
367
+ parts.length > 0 ? `\n\n## Project standards & reference\n\n${parts.join("\n")}` : "";
368
+
369
+ return {
370
+ text,
371
+ entries: loaded.entries,
372
+ truncated: loaded.truncated,
373
+ skipped: loaded.skipped,
374
+ bytesUsed: loaded.bytesUsed,
375
+ byteCap: loaded.byteCap,
376
+ selection: {
377
+ mode: "auto",
378
+ manifestSource,
379
+ profileSource: profileResult.source,
380
+ ...selection,
381
+ },
382
+ };
383
+ }
384
+
385
+ export function validateWorkerContextConfig(config) {
386
+ for (const [field, label] of [
387
+ ["referenceDocs", "referenceDocs"],
388
+ ["standards", "standards"],
389
+ ["neverLoad", "neverLoad"],
390
+ ]) {
391
+ if (config[field] == null) continue;
392
+ const normalized = normalizeContextPathList(config[field]);
393
+ if (normalized === null) {
394
+ return {
395
+ code: "CONFIG_WORKER_CONTEXT_INVALID",
396
+ message: `${label} must be an array of non-empty strings`,
397
+ suggestedCommand: "spine settings set",
398
+ };
399
+ }
400
+ }
401
+ return null;
402
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Sandbox validation for development.workerLaunchScript (SP-077).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ export const DEFAULT_WORKER_LAUNCH_SCRIPT = "scripts/spine-worker-launch.sh";
9
+
10
+ /**
11
+ * @param {string} projectRoot
12
+ * @param {string} configured
13
+ */
14
+ export function validateWorkerLaunchScriptPath(projectRoot, configured) {
15
+ const root = fs.realpathSync.native?.(projectRoot) ?? fs.realpathSync(projectRoot);
16
+ if (typeof configured !== "string" || !configured.trim()) {
17
+ return {
18
+ ok: false,
19
+ code: "CONFIG_LAUNCH_SCRIPT_INVALID",
20
+ message: "development.workerLaunchScript must be a non-empty string",
21
+ suggestedCommand: `spine settings set development.workerLaunchScript ${DEFAULT_WORKER_LAUNCH_SCRIPT}`,
22
+ };
23
+ }
24
+
25
+ const trimmed = configured.trim().replace(/\\/g, "/");
26
+ if (path.isAbsolute(trimmed)) {
27
+ return {
28
+ ok: false,
29
+ code: "CONFIG_LAUNCH_SCRIPT_INVALID",
30
+ message: "development.workerLaunchScript must be relative to the project root",
31
+ suggestedCommand: `spine settings set development.workerLaunchScript ${DEFAULT_WORKER_LAUNCH_SCRIPT}`,
32
+ };
33
+ }
34
+ if (trimmed.includes("..")) {
35
+ return {
36
+ ok: false,
37
+ code: "CONFIG_LAUNCH_SCRIPT_UNSAFE",
38
+ message: "development.workerLaunchScript must not traverse outside the project",
39
+ suggestedCommand: `spine settings set development.workerLaunchScript ${DEFAULT_WORKER_LAUNCH_SCRIPT}`,
40
+ };
41
+ }
42
+
43
+ const normalized = path.posix.normalize(trimmed);
44
+ const scriptsPrefix = "scripts/";
45
+ if (!normalized.startsWith(scriptsPrefix)) {
46
+ return {
47
+ ok: false,
48
+ code: "CONFIG_LAUNCH_SCRIPT_UNSAFE",
49
+ message: `development.workerLaunchScript must live under ${scriptsPrefix}`,
50
+ suggestedCommand: `spine settings set development.workerLaunchScript ${DEFAULT_WORKER_LAUNCH_SCRIPT}`,
51
+ };
52
+ }
53
+
54
+ const absPath = path.resolve(root, normalized);
55
+ const rel = path.relative(root, absPath);
56
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
57
+ return {
58
+ ok: false,
59
+ code: "CONFIG_LAUNCH_SCRIPT_UNSAFE",
60
+ message: "development.workerLaunchScript resolves outside the project root",
61
+ suggestedCommand: `spine settings set development.workerLaunchScript ${DEFAULT_WORKER_LAUNCH_SCRIPT}`,
62
+ };
63
+ }
64
+
65
+ let resolvedPath = absPath;
66
+ try {
67
+ if (fs.existsSync(absPath)) {
68
+ resolvedPath = fs.realpathSync(absPath);
69
+ }
70
+ } catch (err) {
71
+ return {
72
+ ok: false,
73
+ code: "CONFIG_LAUNCH_SCRIPT_UNSAFE",
74
+ message: `Cannot resolve worker launch script: ${err instanceof Error ? err.message : String(err)}`,
75
+ suggestedCommand: `spine settings set development.workerLaunchScript ${DEFAULT_WORKER_LAUNCH_SCRIPT}`,
76
+ };
77
+ }
78
+
79
+ const resolvedRel = path.relative(root, resolvedPath).replace(/\\/g, "/");
80
+ if (resolvedRel.startsWith("..") || path.isAbsolute(resolvedRel) || !resolvedRel.startsWith(scriptsPrefix)) {
81
+ return {
82
+ ok: false,
83
+ code: "CONFIG_LAUNCH_SCRIPT_UNSAFE",
84
+ message: "development.workerLaunchScript symlink escapes project scripts/",
85
+ suggestedCommand: `spine settings set development.workerLaunchScript ${DEFAULT_WORKER_LAUNCH_SCRIPT}`,
86
+ };
87
+ }
88
+
89
+ return { ok: true, scriptPath: resolvedPath, relPath: resolvedRel };
90
+ }
91
+
92
+ /**
93
+ * @param {object} config
94
+ * @param {string} [projectRoot]
95
+ * @returns {{ code: string, message: string, suggestedCommand: string } | null}
96
+ */
97
+ export function validateWorkerLaunchScriptConfig(config, projectRoot = process.cwd()) {
98
+ const configured = config?.development?.workerLaunchScript;
99
+ if (configured == null || configured === "") return null;
100
+ const result = validateWorkerLaunchScriptPath(projectRoot, configured);
101
+ if (result.ok) return null;
102
+ return {
103
+ code: result.code,
104
+ message: result.message,
105
+ suggestedCommand: result.suggestedCommand,
106
+ };
107
+ }
108
+
109
+ /**
110
+ * @param {string} projectRoot
111
+ * @param {object} [config]
112
+ * @returns {string|null}
113
+ */
114
+ export function resolveSafeWorkerLaunchScript(projectRoot, config = {}) {
115
+ const root = fs.existsSync(projectRoot)
116
+ ? (fs.realpathSync.native?.(projectRoot) ?? fs.realpathSync(projectRoot))
117
+ : projectRoot;
118
+ const configured = config?.development?.workerLaunchScript;
119
+ if (typeof configured === "string" && configured.trim()) {
120
+ const validated = validateWorkerLaunchScriptPath(root, configured);
121
+ if (!validated.ok || !fs.existsSync(validated.scriptPath)) return null;
122
+ return validated.scriptPath;
123
+ }
124
+
125
+ const conventional = path.join(root, DEFAULT_WORKER_LAUNCH_SCRIPT);
126
+ if (!fs.existsSync(conventional)) return null;
127
+ const validated = validateWorkerLaunchScriptPath(root, DEFAULT_WORKER_LAUNCH_SCRIPT);
128
+ if (!validated.ok) return null;
129
+ return validated.scriptPath;
130
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Sandbox validation for worktreeSetupHook (SP-102).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ /**
9
+ * @param {string} projectRoot
10
+ * @param {string} configured
11
+ */
12
+ export function validateWorktreeSetupHookPath(projectRoot, configured) {
13
+ const root = fs.realpathSync.native?.(projectRoot) ?? fs.realpathSync(projectRoot);
14
+ if (typeof configured !== "string" || !configured.trim()) {
15
+ return {
16
+ ok: false,
17
+ code: "CONFIG_SETUP_HOOK_INVALID",
18
+ message: "worktreeSetupHook must be a non-empty string when set",
19
+ suggestedCommand: "spine settings set worktreeSetupHook scripts/spine-worktree-setup.sh",
20
+ };
21
+ }
22
+
23
+ const trimmed = configured.trim().replace(/\\/g, "/");
24
+ if (path.isAbsolute(trimmed)) {
25
+ return {
26
+ ok: false,
27
+ code: "CONFIG_SETUP_HOOK_INVALID",
28
+ message: "worktreeSetupHook must be relative to the project root",
29
+ suggestedCommand: "spine settings set worktreeSetupHook scripts/spine-worktree-setup.sh",
30
+ };
31
+ }
32
+ if (trimmed.includes("..")) {
33
+ return {
34
+ ok: false,
35
+ code: "CONFIG_SETUP_HOOK_UNSAFE",
36
+ message: "worktreeSetupHook must not traverse outside the project",
37
+ suggestedCommand: "spine settings set worktreeSetupHook scripts/spine-worktree-setup.sh",
38
+ };
39
+ }
40
+
41
+ const normalized = path.posix.normalize(trimmed);
42
+ const scriptsPrefix = "scripts/";
43
+ if (!normalized.startsWith(scriptsPrefix)) {
44
+ return {
45
+ ok: false,
46
+ code: "CONFIG_SETUP_HOOK_UNSAFE",
47
+ message: `worktreeSetupHook must live under ${scriptsPrefix}`,
48
+ suggestedCommand: "spine settings set worktreeSetupHook scripts/spine-worktree-setup.sh",
49
+ };
50
+ }
51
+
52
+ const absPath = path.resolve(root, normalized);
53
+ const rel = path.relative(root, absPath);
54
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
55
+ return {
56
+ ok: false,
57
+ code: "CONFIG_SETUP_HOOK_UNSAFE",
58
+ message: "worktreeSetupHook resolves outside the project root",
59
+ suggestedCommand: "spine settings set worktreeSetupHook scripts/spine-worktree-setup.sh",
60
+ };
61
+ }
62
+
63
+ let resolvedPath = absPath;
64
+ try {
65
+ if (fs.existsSync(absPath)) {
66
+ resolvedPath = fs.realpathSync(absPath);
67
+ }
68
+ } catch (err) {
69
+ return {
70
+ ok: false,
71
+ code: "CONFIG_SETUP_HOOK_UNSAFE",
72
+ message: `Cannot resolve worktree setup hook: ${err instanceof Error ? err.message : String(err)}`,
73
+ suggestedCommand: "spine settings set worktreeSetupHook scripts/spine-worktree-setup.sh",
74
+ };
75
+ }
76
+
77
+ const resolvedRel = path.relative(root, resolvedPath).replace(/\\/g, "/");
78
+ if (resolvedRel.startsWith("..") || path.isAbsolute(resolvedRel) || !resolvedRel.startsWith(scriptsPrefix)) {
79
+ return {
80
+ ok: false,
81
+ code: "CONFIG_SETUP_HOOK_UNSAFE",
82
+ message: "worktreeSetupHook symlink escapes project scripts/",
83
+ suggestedCommand: "spine settings set worktreeSetupHook scripts/spine-worktree-setup.sh",
84
+ };
85
+ }
86
+
87
+ return { ok: true, scriptPath: resolvedPath, relPath: resolvedRel };
88
+ }
89
+
90
+ /**
91
+ * @param {object} config
92
+ * @param {string} [projectRoot]
93
+ * @returns {{ code: string, message: string, suggestedCommand: string } | null}
94
+ */
95
+ export function validateWorktreeSetupHookConfig(config, projectRoot = process.cwd()) {
96
+ const configured = config?.worktreeSetupHook;
97
+ if (configured == null || configured === "") return null;
98
+ const result = validateWorktreeSetupHookPath(projectRoot, configured);
99
+ if (result.ok) return null;
100
+ return {
101
+ code: result.code,
102
+ message: result.message,
103
+ suggestedCommand: result.suggestedCommand,
104
+ };
105
+ }
106
+
107
+ /**
108
+ * @param {string} projectRoot
109
+ * @param {object} [config]
110
+ * @returns {string|null}
111
+ */
112
+ export function resolveWorktreeSetupHook(projectRoot, config = {}) {
113
+ const root = fs.existsSync(projectRoot)
114
+ ? (fs.realpathSync.native?.(projectRoot) ?? fs.realpathSync(projectRoot))
115
+ : projectRoot;
116
+ const configured = config?.worktreeSetupHook;
117
+ if (typeof configured !== "string" || !configured.trim()) return null;
118
+
119
+ const validated = validateWorktreeSetupHookPath(root, configured);
120
+ if (!validated.ok || !fs.existsSync(validated.scriptPath)) return null;
121
+ return validated.scriptPath;
122
+ }