sdtk-spec-kit 0.4.11 → 0.4.14

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 (143) hide show
  1. package/README.md +353 -353
  2. package/assets/atlas/build_atlas.py +880 -880
  3. package/assets/atlas/doc_atlas_viewer_template.html +3796 -3796
  4. package/assets/atlas/vendor/mermaid.min.js +2029 -2029
  5. package/assets/keys/spec-entitlement-public.pem +9 -9
  6. package/assets/manifest/toolkit-bundle.manifest.json +496 -496
  7. package/assets/manifest/toolkit-bundle.sha256.txt +97 -97
  8. package/assets/toolkit/toolkit/AGENTS.md +157 -241
  9. package/assets/toolkit/toolkit/README.md +51 -51
  10. package/assets/toolkit/toolkit/SDTK_TOOLKIT.md +206 -206
  11. package/assets/toolkit/toolkit/install.ps1 +362 -362
  12. package/assets/toolkit/toolkit/runtimes/claude/CLAUDE_TEMPLATE.md +95 -91
  13. package/assets/toolkit/toolkit/runtimes/codex/CODEX_TEMPLATE.md +70 -69
  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 +87 -87
  17. package/assets/toolkit/toolkit/scripts/generate-code-handoff.ps1 +317 -317
  18. package/assets/toolkit/toolkit/scripts/init-feature.ps1 +262 -262
  19. package/assets/toolkit/toolkit/scripts/install-claude-skills.ps1 +180 -180
  20. package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +209 -209
  21. package/assets/toolkit/toolkit/scripts/uninstall-claude-skills.ps1 +139 -139
  22. package/assets/toolkit/toolkit/scripts/uninstall-codex-skills.ps1 +143 -143
  23. package/assets/toolkit/toolkit/sdtk-spec.config.json +28 -28
  24. package/assets/toolkit/toolkit/sdtk-spec.config.profiles.example.json +50 -50
  25. package/assets/toolkit/toolkit/session/SDTK_ACTIVE_BOOTSTRAP.md +46 -46
  26. package/assets/toolkit/toolkit/session/SDTK_AGENT_WORKING_RULES.md +48 -48
  27. package/assets/toolkit/toolkit/skills/sdtk-api-design-spec/SKILL.md +111 -111
  28. package/assets/toolkit/toolkit/skills/sdtk-api-design-spec/scripts/generate_api_design_detail.py +732 -732
  29. package/assets/toolkit/toolkit/skills/sdtk-api-doc/SKILL.md +79 -79
  30. package/assets/toolkit/toolkit/skills/sdtk-arch/SKILL.md +85 -85
  31. package/assets/toolkit/toolkit/skills/sdtk-ba/SKILL.md +46 -46
  32. package/assets/toolkit/toolkit/skills/sdtk-design-layout/SKILL.md +91 -91
  33. package/assets/toolkit/toolkit/skills/sdtk-design-layout/scripts/render_design_layout_images.py +246 -246
  34. package/assets/toolkit/toolkit/skills/sdtk-dev/SKILL.md +133 -133
  35. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/code-quality-reviewer.md +34 -34
  36. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/implementer.md +60 -60
  37. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/spec-reviewer.md +41 -41
  38. package/assets/toolkit/toolkit/skills/sdtk-dev-backend/SKILL.md +80 -80
  39. package/assets/toolkit/toolkit/skills/sdtk-dev-frontend/SKILL.md +80 -80
  40. package/assets/toolkit/toolkit/skills/sdtk-mailbox-dispatch/SKILL.md +73 -73
  41. package/assets/toolkit/toolkit/skills/sdtk-orchestrator/SKILL.md +176 -108
  42. package/assets/toolkit/toolkit/skills/sdtk-pm/SKILL.md +74 -74
  43. package/assets/toolkit/toolkit/skills/sdtk-qa/SKILL.md +75 -75
  44. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/SKILL.md +108 -107
  45. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/excel-image-export.md +51 -51
  46. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/figma-mcp.md +54 -54
  47. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/numbering-rules.md +28 -28
  48. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/scripts/renumber_flow_action_spec_global.py +136 -136
  49. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/scripts/validate_flow_action_spec_numbering.py +414 -414
  50. package/assets/toolkit/toolkit/skills/sdtk-test-case-spec/SKILL.md +110 -110
  51. package/assets/toolkit/toolkit/skills/sdtk-test-case-spec/scripts/validate_test_case_spec.py +97 -97
  52. package/assets/toolkit/toolkit/skills/skills.catalog.yaml +330 -330
  53. package/assets/toolkit/toolkit/skills-claude/api-design-spec/SKILL.md +116 -116
  54. package/assets/toolkit/toolkit/skills-claude/api-doc/SKILL.md +87 -87
  55. package/assets/toolkit/toolkit/skills-claude/arch/SKILL.md +59 -59
  56. package/assets/toolkit/toolkit/skills-claude/ba/SKILL.md +67 -67
  57. package/assets/toolkit/toolkit/skills-claude/design-layout/SKILL.md +91 -91
  58. package/assets/toolkit/toolkit/skills-claude/dev/SKILL.md +59 -59
  59. package/assets/toolkit/toolkit/skills-claude/dev-backend/SKILL.md +73 -73
  60. package/assets/toolkit/toolkit/skills-claude/dev-frontend/SKILL.md +73 -73
  61. package/assets/toolkit/toolkit/skills-claude/mailbox-dispatch/SKILL.md +73 -73
  62. package/assets/toolkit/toolkit/skills-claude/orchestrator/SKILL.md +88 -42
  63. package/assets/toolkit/toolkit/skills-claude/pm/SKILL.md +88 -88
  64. package/assets/toolkit/toolkit/skills-claude/qa/SKILL.md +58 -58
  65. package/assets/toolkit/toolkit/skills-claude/screen-design-spec/SKILL.md +113 -112
  66. package/assets/toolkit/toolkit/skills-claude/test-case-spec/SKILL.md +115 -115
  67. package/assets/toolkit/toolkit/templates/QUALITY_CHECKLIST.md +124 -124
  68. package/assets/toolkit/toolkit/templates/README.md +68 -68
  69. package/assets/toolkit/toolkit/templates/SHARED_PLANNING.md +81 -81
  70. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_CREATION_RULES.md +21 -21
  71. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_DETAIL_TEMPLATE.md +67 -67
  72. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_FLOWCHART_CREATION_RULES.md +468 -468
  73. package/assets/toolkit/toolkit/templates/docs/api/API_ENDPOINTS_TEMPLATE.md +229 -229
  74. package/assets/toolkit/toolkit/templates/docs/api/FEATURE_API_TEMPLATE.yaml +20 -20
  75. package/assets/toolkit/toolkit/templates/docs/api/FLOWCHART_CREATION_RULES.md +20 -20
  76. package/assets/toolkit/toolkit/templates/docs/api/YAML_CREATION_RULES.md +128 -128
  77. package/assets/toolkit/toolkit/templates/docs/api/feature_api_flow_list_TEMPLATE.txt +12 -12
  78. package/assets/toolkit/toolkit/templates/docs/architecture/ARCH_DESIGN_TEMPLATE.md +109 -109
  79. package/assets/toolkit/toolkit/templates/docs/database/DATABASE_SPEC_TEMPLATE.md +175 -175
  80. package/assets/toolkit/toolkit/templates/docs/design/DESIGN_LAYOUT_TEMPLATE.md +60 -60
  81. package/assets/toolkit/toolkit/templates/docs/dev/FEATURE_IMPL_PLAN_TEMPLATE.md +117 -117
  82. package/assets/toolkit/toolkit/templates/docs/dev/OPS_HANDOFF_CREATION_RULES.md +369 -369
  83. package/assets/toolkit/toolkit/templates/docs/discovery/REQUIREMENT_TEMPLATE.md +155 -155
  84. package/assets/toolkit/toolkit/templates/docs/product/BACKLOG_TEMPLATE.md +50 -50
  85. package/assets/toolkit/toolkit/templates/docs/product/CONDENSED_UPSTREAM_INPUT_TEMPLATE.md +276 -276
  86. package/assets/toolkit/toolkit/templates/docs/product/PRD_TEMPLATE.md +66 -66
  87. package/assets/toolkit/toolkit/templates/docs/product/PROJECT_INITIATION_TEMPLATE.md +98 -98
  88. package/assets/toolkit/toolkit/templates/docs/qa/CONTROLLER_ACCEPTANCE_TEMPLATE.md +90 -90
  89. package/assets/toolkit/toolkit/templates/docs/qa/QA_RELEASE_REPORT_TEMPLATE.md +162 -162
  90. package/assets/toolkit/toolkit/templates/docs/qa/TEST_CASE_CREATION_RULES.md +129 -129
  91. package/assets/toolkit/toolkit/templates/docs/qa/TEST_CASE_TEMPLATE.md +104 -104
  92. package/assets/toolkit/toolkit/templates/docs/specs/BA_SPEC_TEMPLATE.md +139 -139
  93. package/assets/toolkit/toolkit/templates/docs/specs/FLOW_ACTION_SPEC_CREATION_RULES.md +220 -220
  94. package/assets/toolkit/toolkit/templates/docs/specs/FLOW_ACTION_SPEC_TEMPLATE.md +197 -197
  95. package/assets/toolkit/toolkit/templates/handoffs/ARCH_TO_DEV.md +31 -31
  96. package/assets/toolkit/toolkit/templates/handoffs/BA_TO_ARCH.md +28 -28
  97. package/assets/toolkit/toolkit/templates/handoffs/DEV_STAGE1_SPEC_REVIEW.md +26 -26
  98. package/assets/toolkit/toolkit/templates/handoffs/DEV_STAGE2_CODE_QUALITY_REVIEW.md +20 -20
  99. package/assets/toolkit/toolkit/templates/handoffs/DEV_TO_QA.md +33 -33
  100. package/assets/toolkit/toolkit/templates/handoffs/DEV_TO_SDTK_CODE.md +60 -60
  101. package/assets/toolkit/toolkit/templates/handoffs/PM_TO_BA.md +30 -30
  102. package/assets/toolkit/toolkit/templates/handoffs/QA_RELEASE_DECISION.md +26 -26
  103. package/assets/toolkit/toolkit/templates/mailbox/AGENT_REPORT_TEMPLATE.md +63 -63
  104. package/assets/toolkit/toolkit/templates/mailbox/AGENT_TASK_TEMPLATE.md +76 -76
  105. package/bin/sdtk.js +15 -15
  106. package/package.json +48 -48
  107. package/src/commands/activate.js +94 -94
  108. package/src/commands/atlas.js +339 -339
  109. package/src/commands/auth.js +85 -85
  110. package/src/commands/entitlement.js +170 -170
  111. package/src/commands/generate.js +191 -170
  112. package/src/commands/help.js +248 -246
  113. package/src/commands/init.js +117 -117
  114. package/src/commands/project.js +51 -51
  115. package/src/commands/runtime.js +239 -239
  116. package/src/commands/update.js +11 -11
  117. package/src/index.js +68 -68
  118. package/src/lib/activation-state.js +68 -68
  119. package/src/lib/args.js +116 -116
  120. package/src/lib/atlas-config.js +200 -200
  121. package/src/lib/atlas-runner.js +435 -435
  122. package/src/lib/browser-open.js +39 -39
  123. package/src/lib/capabilities.js +89 -89
  124. package/src/lib/entitlements.js +245 -245
  125. package/src/lib/errors.js +41 -41
  126. package/src/lib/github-access.js +143 -143
  127. package/src/lib/legacy-auth-migration.js +56 -56
  128. package/src/lib/license-activation.js +386 -386
  129. package/src/lib/powershell.js +85 -85
  130. package/src/lib/premium-loader.js +124 -124
  131. package/src/lib/premium-packs.js +333 -333
  132. package/src/lib/premium-sync.js +235 -235
  133. package/src/lib/project-audit.js +332 -332
  134. package/src/lib/project-config.js +108 -108
  135. package/src/lib/project-ingest.js +450 -450
  136. package/src/lib/project-refresh.js +666 -666
  137. package/src/lib/project-target-guard.js +79 -79
  138. package/src/lib/requirement-analysis.js +14 -4
  139. package/src/lib/scope.js +83 -83
  140. package/src/lib/state.js +74 -74
  141. package/src/lib/suite-state.js +70 -70
  142. package/src/lib/toolkit-payload.js +99 -99
  143. package/src/lib/update.js +333 -333
@@ -1,435 +1,435 @@
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
- };
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
+ };