sdtk-spec-kit 0.4.4 → 0.4.5

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 (127) hide show
  1. package/README.md +369 -376
  2. package/assets/atlas/build_atlas.py +880 -880
  3. package/assets/atlas/doc_atlas_viewer_template.html +3796 -3782
  4. package/assets/atlas/vendor/mermaid.min.js +2029 -2029
  5. package/assets/keys/spec-entitlement-public.pem +11 -11
  6. package/assets/manifest/toolkit-bundle.manifest.json +178 -178
  7. package/assets/manifest/toolkit-bundle.sha256.txt +83 -83
  8. package/assets/toolkit/toolkit/AGENTS.md +247 -245
  9. package/assets/toolkit/toolkit/README.md +50 -50
  10. package/assets/toolkit/toolkit/SDTK_TOOLKIT.md +207 -208
  11. package/assets/toolkit/toolkit/install.ps1 +21 -21
  12. package/assets/toolkit/toolkit/runtimes/claude/CLAUDE_TEMPLATE.md +92 -92
  13. package/assets/toolkit/toolkit/runtimes/codex/CODEX_TEMPLATE.md +70 -70
  14. package/assets/toolkit/toolkit/scripts/agents/run-claude-task.ps1 +332 -332
  15. package/assets/toolkit/toolkit/scripts/agents/run-codex-task.ps1 +618 -618
  16. package/assets/toolkit/toolkit/scripts/agents/validate-mailbox-formal-artifact.py +86 -86
  17. package/assets/toolkit/toolkit/scripts/init-feature.ps1 +262 -262
  18. package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +209 -209
  19. package/assets/toolkit/toolkit/scripts/uninstall-claude-skills.ps1 +139 -139
  20. package/assets/toolkit/toolkit/scripts/uninstall-codex-skills.ps1 +143 -143
  21. package/assets/toolkit/toolkit/sdtk-spec.config.json +27 -27
  22. package/assets/toolkit/toolkit/sdtk-spec.config.profiles.example.json +49 -49
  23. package/assets/toolkit/toolkit/session/SDTK_ACTIVE_BOOTSTRAP.md +47 -47
  24. package/assets/toolkit/toolkit/session/SDTK_AGENT_WORKING_RULES.md +49 -49
  25. package/assets/toolkit/toolkit/skills/sdtk-api-design-spec/SKILL.md +111 -111
  26. package/assets/toolkit/toolkit/skills/sdtk-api-design-spec/scripts/generate_api_design_detail.py +732 -732
  27. package/assets/toolkit/toolkit/skills/sdtk-api-doc/SKILL.md +79 -79
  28. package/assets/toolkit/toolkit/skills/sdtk-arch/SKILL.md +85 -85
  29. package/assets/toolkit/toolkit/skills/sdtk-ba/SKILL.md +46 -46
  30. package/assets/toolkit/toolkit/skills/sdtk-design-layout/SKILL.md +91 -91
  31. package/assets/toolkit/toolkit/skills/sdtk-design-layout/scripts/render_design_layout_images.py +246 -246
  32. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/code-quality-reviewer.md +34 -34
  33. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/implementer.md +60 -60
  34. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/spec-reviewer.md +41 -41
  35. package/assets/toolkit/toolkit/skills/sdtk-dev-backend/SKILL.md +80 -80
  36. package/assets/toolkit/toolkit/skills/sdtk-dev-frontend/SKILL.md +80 -80
  37. package/assets/toolkit/toolkit/skills/sdtk-mailbox-dispatch/SKILL.md +2 -2
  38. package/assets/toolkit/toolkit/skills/sdtk-orchestrator/SKILL.md +17 -17
  39. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/SKILL.md +106 -106
  40. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/excel-image-export.md +50 -50
  41. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/figma-mcp.md +53 -53
  42. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/numbering-rules.md +28 -28
  43. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/scripts/renumber_flow_action_spec_global.py +136 -136
  44. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/scripts/validate_flow_action_spec_numbering.py +414 -414
  45. package/assets/toolkit/toolkit/skills/sdtk-test-case-spec/SKILL.md +110 -110
  46. package/assets/toolkit/toolkit/skills/sdtk-test-case-spec/scripts/validate_test_case_spec.py +97 -97
  47. package/assets/toolkit/toolkit/skills/skills.catalog.yaml +330 -330
  48. package/assets/toolkit/toolkit/skills-claude/api-design-spec/SKILL.md +116 -116
  49. package/assets/toolkit/toolkit/skills-claude/api-doc/SKILL.md +87 -87
  50. package/assets/toolkit/toolkit/skills-claude/arch/SKILL.md +59 -59
  51. package/assets/toolkit/toolkit/skills-claude/ba/SKILL.md +67 -67
  52. package/assets/toolkit/toolkit/skills-claude/design-layout/SKILL.md +91 -91
  53. package/assets/toolkit/toolkit/skills-claude/dev-backend/SKILL.md +73 -73
  54. package/assets/toolkit/toolkit/skills-claude/dev-frontend/SKILL.md +73 -73
  55. package/assets/toolkit/toolkit/skills-claude/mailbox-dispatch/SKILL.md +2 -2
  56. package/assets/toolkit/toolkit/skills-claude/orchestrator/SKILL.md +40 -40
  57. package/assets/toolkit/toolkit/skills-claude/pm/SKILL.md +88 -88
  58. package/assets/toolkit/toolkit/skills-claude/qa/SKILL.md +58 -58
  59. package/assets/toolkit/toolkit/skills-claude/screen-design-spec/SKILL.md +112 -112
  60. package/assets/toolkit/toolkit/skills-claude/test-case-spec/SKILL.md +115 -115
  61. package/assets/toolkit/toolkit/templates/README.md +68 -68
  62. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_CREATION_RULES.md +21 -21
  63. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_DETAIL_TEMPLATE.md +67 -67
  64. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_FLOWCHART_CREATION_RULES.md +468 -468
  65. package/assets/toolkit/toolkit/templates/docs/api/API_ENDPOINTS_TEMPLATE.md +228 -228
  66. package/assets/toolkit/toolkit/templates/docs/api/FEATURE_API_TEMPLATE.yaml +20 -20
  67. package/assets/toolkit/toolkit/templates/docs/api/FLOWCHART_CREATION_RULES.md +20 -20
  68. package/assets/toolkit/toolkit/templates/docs/api/YAML_CREATION_RULES.md +128 -128
  69. package/assets/toolkit/toolkit/templates/docs/api/feature_api_flow_list_TEMPLATE.txt +12 -12
  70. package/assets/toolkit/toolkit/templates/docs/architecture/ARCH_DESIGN_TEMPLATE.md +107 -107
  71. package/assets/toolkit/toolkit/templates/docs/design/DESIGN_LAYOUT_TEMPLATE.md +60 -60
  72. package/assets/toolkit/toolkit/templates/docs/dev/OPS_HANDOFF_CREATION_RULES.md +369 -369
  73. package/assets/toolkit/toolkit/templates/docs/discovery/REQUIREMENT_TEMPLATE.md +155 -155
  74. package/assets/toolkit/toolkit/templates/docs/product/BACKLOG_TEMPLATE.md +50 -50
  75. package/assets/toolkit/toolkit/templates/docs/product/CONDENSED_UPSTREAM_INPUT_TEMPLATE.md +276 -276
  76. package/assets/toolkit/toolkit/templates/docs/product/PRD_TEMPLATE.md +66 -66
  77. package/assets/toolkit/toolkit/templates/docs/product/PROJECT_INITIATION_TEMPLATE.md +98 -98
  78. package/assets/toolkit/toolkit/templates/docs/qa/TEST_CASE_CREATION_RULES.md +129 -129
  79. package/assets/toolkit/toolkit/templates/docs/qa/TEST_CASE_TEMPLATE.md +104 -104
  80. package/assets/toolkit/toolkit/templates/docs/specs/BA_SPEC_TEMPLATE.md +139 -139
  81. package/assets/toolkit/toolkit/templates/docs/specs/FLOW_ACTION_SPEC_TEMPLATE.md +197 -197
  82. package/assets/toolkit/toolkit/templates/handoffs/ARCH_TO_DEV.md +31 -31
  83. package/assets/toolkit/toolkit/templates/handoffs/BA_TO_ARCH.md +28 -28
  84. package/assets/toolkit/toolkit/templates/handoffs/DEV_STAGE1_SPEC_REVIEW.md +26 -26
  85. package/assets/toolkit/toolkit/templates/handoffs/DEV_STAGE2_CODE_QUALITY_REVIEW.md +20 -20
  86. package/assets/toolkit/toolkit/templates/handoffs/DEV_TO_QA.md +33 -33
  87. package/assets/toolkit/toolkit/templates/handoffs/PM_TO_BA.md +29 -29
  88. package/assets/toolkit/toolkit/templates/handoffs/QA_RELEASE_DECISION.md +26 -26
  89. package/assets/toolkit/toolkit/templates/mailbox/AGENT_TASK_TEMPLATE.md +76 -76
  90. package/bin/sdtk.js +15 -15
  91. package/package.json +48 -48
  92. package/src/commands/activate.js +90 -90
  93. package/src/commands/analyze.js +11 -0
  94. package/src/commands/atlas.js +341 -352
  95. package/src/commands/auth.js +85 -85
  96. package/src/commands/entitlement.js +163 -163
  97. package/src/commands/generate.js +209 -147
  98. package/src/commands/help.js +41 -33
  99. package/src/commands/init.js +15 -15
  100. package/src/commands/project.js +51 -51
  101. package/src/commands/runtime.js +239 -239
  102. package/src/index.js +9 -6
  103. package/src/lib/activation-state.js +68 -68
  104. package/src/lib/args.js +116 -116
  105. package/src/lib/atlas-config.js +200 -200
  106. package/src/lib/atlas-runner.js +435 -355
  107. package/src/lib/browser-open.js +39 -39
  108. package/src/lib/capabilities.js +92 -92
  109. package/src/lib/entitlements.js +238 -238
  110. package/src/lib/errors.js +41 -41
  111. package/src/lib/github-access.js +143 -143
  112. package/src/lib/legacy-auth-migration.js +55 -55
  113. package/src/lib/license-activation.js +375 -375
  114. package/src/lib/powershell.js +85 -85
  115. package/src/lib/premium-loader.js +126 -126
  116. package/src/lib/premium-packs.js +331 -331
  117. package/src/lib/premium-sync.js +235 -235
  118. package/src/lib/project-audit.js +332 -332
  119. package/src/lib/project-config.js +108 -108
  120. package/src/lib/project-ingest.js +450 -450
  121. package/src/lib/project-refresh.js +666 -666
  122. package/src/lib/requirement-analysis.js +396 -0
  123. package/src/lib/scope.js +83 -83
  124. package/src/lib/state.js +73 -73
  125. package/src/lib/suite-state.js +70 -70
  126. package/src/lib/toolkit-payload.js +99 -99
  127. package/src/lib/atlas-ask.js +0 -170
@@ -1,355 +1,435 @@
1
- "use strict";
2
-
3
- const fs = require("fs");
4
- const http = require("http");
5
- const net = require("net");
6
- const path = require("path");
7
- const { spawn, execFile } = require("child_process");
8
- const { DependencyError, CliError } = require("./errors");
9
- const { resolveBuilderPath } = require("./atlas-config");
10
- const { openBrowser } = require("./browser-open");
11
-
12
- const HEALTH_CHECK_RETRIES = 20;
13
- const HEALTH_CHECK_INTERVAL_MS = 300;
14
-
15
- /**
16
- * Find an available Python executable.
17
- * Returns 'python3' on Unix, 'python' on Windows as first try.
18
- *
19
- * @returns {Promise<string>} Resolved python executable name.
20
- */
21
- function findPython() {
22
- return new Promise((resolve, reject) => {
23
- const candidates = process.platform === "win32"
24
- ? ["python", "python3"]
25
- : ["python3", "python"];
26
-
27
- let idx = 0;
28
- function tryNext() {
29
- if (idx >= candidates.length) {
30
- reject(
31
- new DependencyError(
32
- "Python not found. Install Python 3.8+ and ensure it is in PATH.\n" +
33
- "Atlas build requires Python to run the local builder."
34
- )
35
- );
36
- return;
37
- }
38
- const candidate = candidates[idx++];
39
- execFile(candidate, ["--version"], { timeout: 5000 }, (err) => {
40
- if (!err) {
41
- resolve(candidate);
42
- } else {
43
- tryNext();
44
- }
45
- });
46
- }
47
- tryNext();
48
- });
49
- }
50
-
51
- /**
52
- * Run the Atlas Python builder with explicit project/output args.
53
- *
54
- * @param {Object} config - Resolved AtlasConfig.
55
- * @returns {Promise<{ docCount: number, nodeCount: number, edgeCount: number, generated: string }>}
56
- */
57
- async function runBuild(config) {
58
- const builderPath = resolveBuilderPath();
59
- if (!fs.existsSync(builderPath)) {
60
- throw new DependencyError(
61
- `Atlas builder not found: ${builderPath}\n` +
62
- "This is a packaging error. Reinstall sdtk-spec-kit."
63
- );
64
- }
65
-
66
- const pythonExe = await findPython();
67
-
68
- const args = [
69
- builderPath,
70
- "--project-root",
71
- config.projectPath,
72
- "--output-dir",
73
- config.outputDir,
74
- ];
75
-
76
- for (const sr of config.scanRoots) {
77
- args.push("--scan-root", sr);
78
- }
79
-
80
- for (const ex of config.excludes) {
81
- args.push("--exclude", ex);
82
- }
83
-
84
- if (config.verbose) {
85
- args.push("--verbose");
86
- }
87
-
88
- return new Promise((resolve, reject) => {
89
- const child = spawn(pythonExe, args, {
90
- stdio: ["ignore", "pipe", "pipe"],
91
- });
92
-
93
- let stdout = "";
94
- let stderr = "";
95
-
96
- child.stdout.on("data", (chunk) => {
97
- const text = chunk.toString();
98
- stdout += text;
99
- // Stream output unless silent
100
- process.stdout.write(text);
101
- });
102
-
103
- child.stderr.on("data", (chunk) => {
104
- const text = chunk.toString();
105
- stderr += text;
106
- process.stderr.write(text);
107
- });
108
-
109
- child.on("error", (err) => {
110
- if (err.code === "ENOENT") {
111
- reject(
112
- new DependencyError(
113
- `Python executable not found: ${pythonExe}\n` +
114
- "Install Python 3.8+ and ensure it is in PATH."
115
- )
116
- );
117
- } else {
118
- reject(new CliError(`Failed to start Atlas builder: ${err.message}`));
119
- }
120
- });
121
-
122
- child.on("close", (code) => {
123
- if (code !== 0) {
124
- reject(
125
- new CliError(
126
- `Atlas build failed (exit code ${code}).\n` +
127
- (stderr ? `Builder error output:\n${stderr}` : "See output above for details.")
128
- )
129
- );
130
- return;
131
- }
132
-
133
- // Parse result JSON from stdout line
134
- const resultLine = stdout.split("\n").find((l) => l.startsWith("[atlas:result] "));
135
- if (resultLine) {
136
- try {
137
- const result = JSON.parse(resultLine.replace("[atlas:result] ", ""));
138
- resolve({
139
- docCount: result.doc_count || 0,
140
- nodeCount: result.node_count || 0,
141
- edgeCount: result.edge_count || 0,
142
- generated: result.generated || "",
143
- });
144
- return;
145
- } catch (_) {
146
- // fall through to defaults
147
- }
148
- }
149
-
150
- resolve({ docCount: 0, nodeCount: 0, edgeCount: 0, generated: "" });
151
- });
152
- });
153
- }
154
-
155
- /**
156
- * Check whether a port is in use (server is listening).
157
- *
158
- * @param {string} host
159
- * @param {number} port
160
- * @returns {Promise<boolean>}
161
- */
162
- function isPortOpen(host, port) {
163
- return new Promise((resolve) => {
164
- const socket = net.createConnection({ host, port, timeout: 500 });
165
- socket.once("connect", () => {
166
- socket.destroy();
167
- resolve(true);
168
- });
169
- socket.once("error", () => resolve(false));
170
- socket.once("timeout", () => {
171
- socket.destroy();
172
- resolve(false);
173
- });
174
- });
175
- }
176
-
177
- /**
178
- * Wait for the local server to become reachable.
179
- *
180
- * @param {string} host
181
- * @param {number} port
182
- * @returns {Promise<void>}
183
- */
184
- async function waitForServer(host, port) {
185
- for (let i = 0; i < HEALTH_CHECK_RETRIES; i++) {
186
- const ok = await isPortOpen(host, port);
187
- if (ok) return;
188
- await new Promise((r) => setTimeout(r, HEALTH_CHECK_INTERVAL_MS));
189
- }
190
- throw new CliError(
191
- `Atlas viewer server did not start on http://${host}:${port}\n` +
192
- "Try passing a different --port if the port is occupied."
193
- );
194
- }
195
-
196
- /**
197
- * Start a lightweight Node.js static file server for the atlas output dir.
198
- * Binds to loopback by default. Prevents path traversal outside outputDir/projectPath.
199
- *
200
- * @param {string} host
201
- * @param {number} port
202
- * @param {string} outputDir - Directory to serve static atlas files from.
203
- * @param {string} projectPath - Project root for /api/note path traversal bound.
204
- * @returns {Promise<http.Server>}
205
- */
206
- function startAtlasServer(host, port, outputDir, projectPath) {
207
- return new Promise((resolve, reject) => {
208
- const MIME_TYPES = {
209
- ".html": "text/html; charset=utf-8",
210
- ".js": "application/javascript; charset=utf-8",
211
- ".json": "application/json; charset=utf-8",
212
- ".css": "text/css; charset=utf-8",
213
- ".md": "text/plain; charset=utf-8",
214
- ".txt": "text/plain; charset=utf-8",
215
- };
216
-
217
- const server = http.createServer((req, res) => {
218
- const url = req.url || "/";
219
-
220
- // Health check endpoint
221
- if (url === "/api/health" || url === "/api/health/") {
222
- res.writeHead(200, { "Content-Type": "application/json" });
223
- res.end(JSON.stringify({ ok: true }));
224
- return;
225
- }
226
-
227
- // Serve full note content with path traversal protection
228
- if (url.startsWith("/api/note")) {
229
- const qs = new URL(url, `http://${host}:${port}`).searchParams;
230
- const notePath = qs.get("path");
231
- if (!notePath) {
232
- res.writeHead(400, { "Content-Type": "application/json" });
233
- res.end(JSON.stringify({ error: "Missing path parameter" }));
234
- return;
235
- }
236
-
237
- // Path traversal protection: resolve and verify it stays within projectPath
238
- const projectRoot = projectPath || outputDir;
239
- const resolved = path.resolve(projectRoot, notePath);
240
- if (!resolved.startsWith(projectRoot + path.sep) && resolved !== projectRoot) {
241
- res.writeHead(403, { "Content-Type": "application/json" });
242
- res.end(JSON.stringify({ error: "Access denied" }));
243
- return;
244
- }
245
-
246
- if (!fs.existsSync(resolved)) {
247
- res.writeHead(404, { "Content-Type": "application/json" });
248
- res.end(JSON.stringify({ error: "Not found" }));
249
- return;
250
- }
251
-
252
- try {
253
- const content = fs.readFileSync(resolved, "utf-8");
254
- res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
255
- res.end(content);
256
- } catch (err) {
257
- res.writeHead(500, { "Content-Type": "application/json" });
258
- res.end(JSON.stringify({ error: "Read error" }));
259
- }
260
- return;
261
- }
262
-
263
- // Static files from outputDir
264
- let filePath = url.split("?")[0];
265
- if (filePath === "/" || filePath === "") {
266
- filePath = "/viewer.html";
267
- }
268
-
269
- const resolved = path.resolve(outputDir, filePath.replace(/^\/+/, ""));
270
- // Path traversal protection: must stay inside outputDir
271
- if (!resolved.startsWith(outputDir + path.sep) && resolved !== outputDir) {
272
- res.writeHead(403, { "Content-Type": "text/plain" });
273
- res.end("403 Forbidden");
274
- return;
275
- }
276
-
277
- if (!fs.existsSync(resolved) || fs.statSync(resolved).isDirectory()) {
278
- res.writeHead(404, { "Content-Type": "text/plain" });
279
- res.end("404 Not Found");
280
- return;
281
- }
282
-
283
- const ext = path.extname(resolved).toLowerCase();
284
- const contentType = MIME_TYPES[ext] || "application/octet-stream";
285
-
286
- try {
287
- const data = fs.readFileSync(resolved);
288
- res.writeHead(200, { "Content-Type": contentType });
289
- res.end(data);
290
- } catch (err) {
291
- res.writeHead(500, { "Content-Type": "text/plain" });
292
- res.end("500 Internal Server Error");
293
- }
294
- });
295
-
296
- server.once("error", (err) => {
297
- if (err.code === "EADDRINUSE") {
298
- reject(
299
- new CliError(
300
- `Port ${port} is already in use on ${host}.\n` +
301
- "Pass --port <number> to use a different port, or stop the process using that port."
302
- )
303
- );
304
- } else {
305
- reject(new CliError(`Atlas server error: ${err.message}`));
306
- }
307
- });
308
-
309
- server.listen(port, host, () => {
310
- resolve(server);
311
- });
312
- });
313
- }
314
-
315
- /**
316
- * Open or reuse the local Atlas viewer server and optionally launch a browser.
317
- *
318
- * @param {Object} config - Resolved AtlasConfig.
319
- * @param {boolean} noOpen - If true, skip browser launch.
320
- * @returns {Promise<{ url: string, server: http.Server | null }>}
321
- */
322
- async function openViewer(config, noOpen = false) {
323
- const { host, port, outputDir } = config;
324
- const viewerUrl = `http://${host}:${port}/viewer.html`;
325
-
326
- // Check if a server is already running on this port
327
- const alreadyRunning = await isPortOpen(host, port);
328
-
329
- let server = null;
330
- if (!alreadyRunning) {
331
- console.log(`[atlas] Starting local atlas viewer on http://${host}:${port} ...`);
332
- server = await startAtlasServer(host, port, outputDir, config.projectPath);
333
- await waitForServer(host, port);
334
- console.log(`[atlas] Viewer server ready: ${viewerUrl}`);
335
- } else {
336
- console.log(`[atlas] Reusing existing server at http://${host}:${port}`);
337
- }
338
-
339
- if (!noOpen) {
340
- console.log("[atlas] Opening viewer in default browser...");
341
- await openBrowser(viewerUrl);
342
- } else {
343
- console.log(`[atlas] Viewer URL: ${viewerUrl}`);
344
- console.log("[atlas] --no-open specified; skipping browser launch.");
345
- }
346
-
347
- return { url: viewerUrl, server };
348
- }
349
-
350
- module.exports = {
351
- runBuild,
352
- openViewer,
353
- startAtlasServer,
354
- findPython,
355
- };
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const http = require("http");
5
+ const https = require("https");
6
+ const net = require("net");
7
+ const path = require("path");
8
+ const { spawn, execFile } = require("child_process");
9
+ const { DependencyError, CliError } = require("./errors");
10
+ const { resolveBuilderPath } = require("./atlas-config");
11
+ const { openBrowser } = require("./browser-open");
12
+
13
+ const HEALTH_CHECK_RETRIES = 20;
14
+ const HEALTH_CHECK_INTERVAL_MS = 300;
15
+
16
+ /**
17
+ * Find an available Python executable.
18
+ * Returns 'python3' on Unix, 'python' on Windows as first try.
19
+ *
20
+ * @returns {Promise<string>} Resolved python executable name.
21
+ */
22
+ function findPython() {
23
+ return new Promise((resolve, reject) => {
24
+ const candidates = process.platform === "win32"
25
+ ? ["python", "python3"]
26
+ : ["python3", "python"];
27
+
28
+ let idx = 0;
29
+ function tryNext() {
30
+ if (idx >= candidates.length) {
31
+ reject(
32
+ new DependencyError(
33
+ "Python not found. Install Python 3.8+ and ensure it is in PATH.\n" +
34
+ "Atlas build requires Python to run the local builder."
35
+ )
36
+ );
37
+ return;
38
+ }
39
+ const candidate = candidates[idx++];
40
+ execFile(candidate, ["--version"], { timeout: 5000 }, (err) => {
41
+ if (!err) {
42
+ resolve(candidate);
43
+ } else {
44
+ tryNext();
45
+ }
46
+ });
47
+ }
48
+ tryNext();
49
+ });
50
+ }
51
+
52
+ /**
53
+ * Run the Atlas Python builder with explicit project/output args.
54
+ *
55
+ * @param {Object} config - Resolved AtlasConfig.
56
+ * @returns {Promise<{ docCount: number, nodeCount: number, edgeCount: number, generated: string }>}
57
+ */
58
+ async function runBuild(config) {
59
+ const builderPath = resolveBuilderPath();
60
+ if (!fs.existsSync(builderPath)) {
61
+ throw new DependencyError(
62
+ `Atlas builder not found: ${builderPath}\n` +
63
+ "This is a packaging error. Reinstall sdtk-spec-kit."
64
+ );
65
+ }
66
+
67
+ const pythonExe = await findPython();
68
+
69
+ const args = [
70
+ builderPath,
71
+ "--project-root",
72
+ config.projectPath,
73
+ "--output-dir",
74
+ config.outputDir,
75
+ ];
76
+
77
+ for (const sr of config.scanRoots) {
78
+ args.push("--scan-root", sr);
79
+ }
80
+
81
+ for (const ex of config.excludes) {
82
+ args.push("--exclude", ex);
83
+ }
84
+
85
+ if (config.verbose) {
86
+ args.push("--verbose");
87
+ }
88
+
89
+ return new Promise((resolve, reject) => {
90
+ const child = spawn(pythonExe, args, {
91
+ stdio: ["ignore", "pipe", "pipe"],
92
+ });
93
+
94
+ let stdout = "";
95
+ let stderr = "";
96
+
97
+ child.stdout.on("data", (chunk) => {
98
+ const text = chunk.toString();
99
+ stdout += text;
100
+ // Stream output unless silent
101
+ process.stdout.write(text);
102
+ });
103
+
104
+ child.stderr.on("data", (chunk) => {
105
+ const text = chunk.toString();
106
+ stderr += text;
107
+ process.stderr.write(text);
108
+ });
109
+
110
+ child.on("error", (err) => {
111
+ if (err.code === "ENOENT") {
112
+ reject(
113
+ new DependencyError(
114
+ `Python executable not found: ${pythonExe}\n` +
115
+ "Install Python 3.8+ and ensure it is in PATH."
116
+ )
117
+ );
118
+ } else {
119
+ reject(new CliError(`Failed to start Atlas builder: ${err.message}`));
120
+ }
121
+ });
122
+
123
+ child.on("close", (code) => {
124
+ if (code !== 0) {
125
+ reject(
126
+ new CliError(
127
+ `Atlas build failed (exit code ${code}).\n` +
128
+ (stderr ? `Builder error output:\n${stderr}` : "See output above for details.")
129
+ )
130
+ );
131
+ return;
132
+ }
133
+
134
+ // Parse result JSON from stdout line
135
+ const resultLine = stdout.split("\n").find((l) => l.startsWith("[atlas:result] "));
136
+ if (resultLine) {
137
+ try {
138
+ const result = JSON.parse(resultLine.replace("[atlas:result] ", ""));
139
+ resolve({
140
+ docCount: result.doc_count || 0,
141
+ nodeCount: result.node_count || 0,
142
+ edgeCount: result.edge_count || 0,
143
+ generated: result.generated || "",
144
+ });
145
+ return;
146
+ } catch (_) {
147
+ // fall through to defaults
148
+ }
149
+ }
150
+
151
+ resolve({ docCount: 0, nodeCount: 0, edgeCount: 0, generated: "" });
152
+ });
153
+ });
154
+ }
155
+
156
+ /**
157
+ * Check whether a port is in use (server is listening).
158
+ *
159
+ * @param {string} host
160
+ * @param {number} port
161
+ * @returns {Promise<boolean>}
162
+ */
163
+ function isPortOpen(host, port) {
164
+ return new Promise((resolve) => {
165
+ const socket = net.createConnection({ host, port, timeout: 500 });
166
+ socket.once("connect", () => {
167
+ socket.destroy();
168
+ resolve(true);
169
+ });
170
+ socket.once("error", () => resolve(false));
171
+ socket.once("timeout", () => {
172
+ socket.destroy();
173
+ resolve(false);
174
+ });
175
+ });
176
+ }
177
+
178
+ /**
179
+ * Wait for the local server to become reachable.
180
+ *
181
+ * @param {string} host
182
+ * @param {number} port
183
+ * @returns {Promise<void>}
184
+ */
185
+ async function waitForServer(host, port) {
186
+ for (let i = 0; i < HEALTH_CHECK_RETRIES; i++) {
187
+ const ok = await isPortOpen(host, port);
188
+ if (ok) return;
189
+ await new Promise((r) => setTimeout(r, HEALTH_CHECK_INTERVAL_MS));
190
+ }
191
+ throw new CliError(
192
+ `Atlas viewer server did not start on http://${host}:${port}\n` +
193
+ "Try passing a different --port if the port is occupied."
194
+ );
195
+ }
196
+
197
+ /**
198
+ * Probe a local Atlas endpoint and capture its HTTP status.
199
+ *
200
+ * @param {string} url
201
+ * @returns {Promise<{ ok: boolean, statusCode: number, body: string }>}
202
+ */
203
+ function probeUrl(url) {
204
+ return new Promise((resolve) => {
205
+ let target;
206
+ try {
207
+ target = new URL(url);
208
+ } catch (_) {
209
+ resolve({ ok: false, statusCode: 0, body: "" });
210
+ return;
211
+ }
212
+
213
+ const transport = target.protocol === "https:" ? https : http;
214
+ const req = transport.request(
215
+ target,
216
+ { method: "GET", timeout: 1200 },
217
+ (res) => {
218
+ let body = "";
219
+ res.setEncoding("utf8");
220
+ res.on("data", (chunk) => {
221
+ if (body.length < 512) {
222
+ body += chunk.slice(0, 512 - body.length);
223
+ }
224
+ });
225
+ res.on("end", () => {
226
+ const statusCode = res.statusCode || 0;
227
+ resolve({
228
+ ok: statusCode >= 200 && statusCode < 300,
229
+ statusCode,
230
+ body,
231
+ });
232
+ });
233
+ }
234
+ );
235
+
236
+ req.on("timeout", () => {
237
+ req.destroy();
238
+ resolve({ ok: false, statusCode: 0, body: "" });
239
+ });
240
+
241
+ req.on("error", () => {
242
+ resolve({ ok: false, statusCode: 0, body: "" });
243
+ });
244
+
245
+ req.end();
246
+ });
247
+ }
248
+
249
+ /**
250
+ * Check whether an existing server on the requested port is a usable Atlas server.
251
+ *
252
+ * @param {string} host
253
+ * @param {number} port
254
+ * @param {string} viewerUrl
255
+ * @returns {Promise<{ reusable: boolean, health: { ok: boolean, statusCode: number }, viewer: { ok: boolean, statusCode: number } }>}
256
+ */
257
+ async function probeExistingAtlasServer(host, port, viewerUrl) {
258
+ const health = await probeUrl(`http://${host}:${port}/api/health`);
259
+ const viewer = await probeUrl(`${viewerUrl}?embedded=1&probe=1`);
260
+ return {
261
+ reusable: health.ok && viewer.ok,
262
+ health: { ok: health.ok, statusCode: health.statusCode },
263
+ viewer: { ok: viewer.ok, statusCode: viewer.statusCode },
264
+ };
265
+ }
266
+
267
+ /**
268
+ * Start a lightweight Node.js static file server for the atlas output dir.
269
+ * Binds to loopback by default. Prevents path traversal outside outputDir/projectPath.
270
+ *
271
+ * @param {string} host
272
+ * @param {number} port
273
+ * @param {string} outputDir - Directory to serve static atlas files from.
274
+ * @param {string} projectPath - Project root for /api/note path traversal bound.
275
+ * @returns {Promise<http.Server>}
276
+ */
277
+ function startAtlasServer(host, port, outputDir, projectPath) {
278
+ return new Promise((resolve, reject) => {
279
+ const MIME_TYPES = {
280
+ ".html": "text/html; charset=utf-8",
281
+ ".js": "application/javascript; charset=utf-8",
282
+ ".json": "application/json; charset=utf-8",
283
+ ".css": "text/css; charset=utf-8",
284
+ ".md": "text/plain; charset=utf-8",
285
+ ".txt": "text/plain; charset=utf-8",
286
+ };
287
+
288
+ const server = http.createServer((req, res) => {
289
+ const url = req.url || "/";
290
+
291
+ // Health check endpoint
292
+ if (url === "/api/health" || url === "/api/health/") {
293
+ res.writeHead(200, { "Content-Type": "application/json" });
294
+ res.end(JSON.stringify({ ok: true }));
295
+ return;
296
+ }
297
+
298
+ // Serve full note content with path traversal protection
299
+ if (url.startsWith("/api/note")) {
300
+ const qs = new URL(url, `http://${host}:${port}`).searchParams;
301
+ const notePath = qs.get("path");
302
+ if (!notePath) {
303
+ res.writeHead(400, { "Content-Type": "application/json" });
304
+ res.end(JSON.stringify({ error: "Missing path parameter" }));
305
+ return;
306
+ }
307
+
308
+ // Path traversal protection: resolve and verify it stays within projectPath
309
+ const projectRoot = projectPath || outputDir;
310
+ const resolved = path.resolve(projectRoot, notePath);
311
+ if (!resolved.startsWith(projectRoot + path.sep) && resolved !== projectRoot) {
312
+ res.writeHead(403, { "Content-Type": "application/json" });
313
+ res.end(JSON.stringify({ error: "Access denied" }));
314
+ return;
315
+ }
316
+
317
+ if (!fs.existsSync(resolved)) {
318
+ res.writeHead(404, { "Content-Type": "application/json" });
319
+ res.end(JSON.stringify({ error: "Not found" }));
320
+ return;
321
+ }
322
+
323
+ try {
324
+ const content = fs.readFileSync(resolved, "utf-8");
325
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
326
+ res.end(content);
327
+ } catch (err) {
328
+ res.writeHead(500, { "Content-Type": "application/json" });
329
+ res.end(JSON.stringify({ error: "Read error" }));
330
+ }
331
+ return;
332
+ }
333
+
334
+ // Static files from outputDir
335
+ let filePath = url.split("?")[0];
336
+ if (filePath === "/" || filePath === "") {
337
+ filePath = "/viewer.html";
338
+ }
339
+
340
+ const resolved = path.resolve(outputDir, filePath.replace(/^\/+/, ""));
341
+ // Path traversal protection: must stay inside outputDir
342
+ if (!resolved.startsWith(outputDir + path.sep) && resolved !== outputDir) {
343
+ res.writeHead(403, { "Content-Type": "text/plain" });
344
+ res.end("403 Forbidden");
345
+ return;
346
+ }
347
+
348
+ if (!fs.existsSync(resolved) || fs.statSync(resolved).isDirectory()) {
349
+ res.writeHead(404, { "Content-Type": "text/plain" });
350
+ res.end("404 Not Found");
351
+ return;
352
+ }
353
+
354
+ const ext = path.extname(resolved).toLowerCase();
355
+ const contentType = MIME_TYPES[ext] || "application/octet-stream";
356
+
357
+ try {
358
+ const data = fs.readFileSync(resolved);
359
+ res.writeHead(200, { "Content-Type": contentType });
360
+ res.end(data);
361
+ } catch (err) {
362
+ res.writeHead(500, { "Content-Type": "text/plain" });
363
+ res.end("500 Internal Server Error");
364
+ }
365
+ });
366
+
367
+ server.once("error", (err) => {
368
+ if (err.code === "EADDRINUSE") {
369
+ reject(
370
+ new CliError(
371
+ `Port ${port} is already in use on ${host}.\n` +
372
+ "Pass --port <number> to use a different port, or stop the process using that port."
373
+ )
374
+ );
375
+ } else {
376
+ reject(new CliError(`Atlas server error: ${err.message}`));
377
+ }
378
+ });
379
+
380
+ server.listen(port, host, () => {
381
+ resolve(server);
382
+ });
383
+ });
384
+ }
385
+
386
+ /**
387
+ * Open or reuse the local Atlas viewer server and optionally launch a browser.
388
+ *
389
+ * @param {Object} config - Resolved AtlasConfig.
390
+ * @param {boolean} noOpen - If true, skip browser launch.
391
+ * @returns {Promise<{ url: string, server: http.Server | null }>}
392
+ */
393
+ async function openViewer(config, noOpen = false) {
394
+ const { host, port, outputDir } = config;
395
+ const viewerUrl = `http://${host}:${port}/viewer.html`;
396
+
397
+ // Check if a server is already running on this port
398
+ const alreadyRunning = await isPortOpen(host, port);
399
+
400
+ let server = null;
401
+ if (!alreadyRunning) {
402
+ console.log(`[atlas] Starting local atlas viewer on http://${host}:${port} ...`);
403
+ server = await startAtlasServer(host, port, outputDir, config.projectPath);
404
+ await waitForServer(host, port);
405
+ console.log(`[atlas] Viewer server ready: ${viewerUrl}`);
406
+ } else {
407
+ const probe = await probeExistingAtlasServer(host, port, viewerUrl);
408
+ if (!probe.reusable) {
409
+ throw new CliError(
410
+ `Port ${port} is already occupied by an incompatible Atlas server.\n` +
411
+ ` Health endpoint status: ${probe.health.statusCode || "unreachable"}\n` +
412
+ ` Viewer endpoint status: ${probe.viewer.statusCode || "unreachable"}\n` +
413
+ "Stop the existing process on that port, then rerun the command, or pass --port <number>."
414
+ );
415
+ }
416
+ console.log(`[atlas] Reusing existing server at http://${host}:${port}`);
417
+ }
418
+
419
+ if (!noOpen) {
420
+ console.log("[atlas] Opening viewer in default browser...");
421
+ await openBrowser(viewerUrl);
422
+ } else {
423
+ console.log(`[atlas] Viewer URL: ${viewerUrl}`);
424
+ console.log("[atlas] --no-open specified; skipping browser launch.");
425
+ }
426
+
427
+ return { url: viewerUrl, server };
428
+ }
429
+
430
+ module.exports = {
431
+ runBuild,
432
+ openViewer,
433
+ startAtlasServer,
434
+ findPython,
435
+ };