sdtk-spec-kit 0.3.15 → 0.3.17

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 (37) hide show
  1. package/README.md +131 -2
  2. package/assets/atlas/build_atlas.py +865 -0
  3. package/assets/atlas/doc_atlas_viewer_template.html +3706 -0
  4. package/assets/atlas/vendor/mermaid.min.js +2029 -0
  5. package/assets/manifest/toolkit-bundle.manifest.json +16 -16
  6. package/assets/manifest/toolkit-bundle.sha256.txt +7 -7
  7. package/assets/toolkit/toolkit/SDTK_TOOLKIT.md +14 -0
  8. package/assets/toolkit/toolkit/scripts/agents/run-claude-task.ps1 +332 -111
  9. package/assets/toolkit/toolkit/scripts/agents/run-codex-task.ps1 +517 -16
  10. package/assets/toolkit/toolkit/skills/sdtk-mailbox-dispatch/SKILL.md +73 -71
  11. package/assets/toolkit/toolkit/skills-claude/mailbox-dispatch/SKILL.md +73 -71
  12. package/assets/toolkit/toolkit/templates/mailbox/AGENT_REPORT_TEMPLATE.md +62 -49
  13. package/assets/toolkit/toolkit/templates/mailbox/AGENT_TASK_TEMPLATE.md +21 -10
  14. package/package.json +48 -48
  15. package/src/commands/atlas.js +379 -0
  16. package/src/commands/entitlement.js +163 -0
  17. package/src/commands/help.js +140 -6
  18. package/src/commands/project.js +51 -0
  19. package/src/index.js +10 -1
  20. package/src/lib/atlas-ask.js +170 -0
  21. package/src/lib/atlas-config.js +200 -0
  22. package/src/lib/atlas-runner.js +355 -0
  23. package/src/lib/browser-open.js +39 -0
  24. package/src/lib/capabilities.js +98 -0
  25. package/src/lib/entitlements.js +203 -0
  26. package/src/lib/github-access.js +75 -0
  27. package/src/lib/legacy-auth-migration.js +56 -0
  28. package/src/lib/premium-loader.js +126 -0
  29. package/src/lib/premium-packs.js +333 -0
  30. package/src/lib/premium-sync.js +235 -0
  31. package/src/lib/project-audit.js +332 -0
  32. package/src/lib/project-config.js +108 -0
  33. package/src/lib/project-ingest.js +450 -0
  34. package/src/lib/project-refresh.js +666 -0
  35. package/src/lib/project-target-guard.js +28 -2
  36. package/src/lib/state.js +37 -46
  37. package/src/lib/suite-state.js +65 -0
@@ -0,0 +1,379 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { parseFlags } = require("../lib/args");
6
+ const {
7
+ resolveAtlasConfig,
8
+ writeAtlasConfig,
9
+ isAtlasInitialized,
10
+ isAtlasBuilt,
11
+ readBuildMeta,
12
+ readGraphMeta,
13
+ } = require("../lib/atlas-config");
14
+ const { runBuild, openViewer } = require("../lib/atlas-runner");
15
+ const { runAtlasAsk } = require("../lib/atlas-ask");
16
+ const { ValidationError } = require("../lib/errors");
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Shared flag definitions
20
+ // ---------------------------------------------------------------------------
21
+ const BASE_FLAG_DEFS = {
22
+ "project-path": { type: "string" },
23
+ "output-dir": { type: "string" },
24
+ "scan-root": { type: "string" },
25
+ verbose: { type: "boolean" },
26
+ };
27
+
28
+ const OPEN_FLAG_DEFS = {
29
+ ...BASE_FLAG_DEFS,
30
+ host: { type: "string" },
31
+ port: { type: "string" },
32
+ "no-open": { type: "boolean" },
33
+ };
34
+
35
+ const INIT_FLAG_DEFS = {
36
+ ...OPEN_FLAG_DEFS,
37
+ force: { type: "boolean" },
38
+ "no-build": { type: "boolean" },
39
+ };
40
+
41
+ const WATCH_FLAG_DEFS = {
42
+ ...BASE_FLAG_DEFS,
43
+ port: { type: "string" },
44
+ "no-open": { type: "boolean" },
45
+ };
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // Flag parsing with repeatable --scan-root support
49
+ // ---------------------------------------------------------------------------
50
+
51
+ /**
52
+ * Parse args and collect repeated --scan-root values into an array.
53
+ * The base parseFlags only captures the last value for string flags.
54
+ * This thin wrapper collects all occurrences.
55
+ */
56
+ function parseAtlasFlags(args, defs) {
57
+ const scanRoots = [];
58
+ // Collect raw --scan-root values before parseFlags strips them
59
+ const filteredArgs = [];
60
+ let i = 0;
61
+ while (i < args.length) {
62
+ const arg = args[i];
63
+ if (arg === "--scan-root") {
64
+ i++;
65
+ if (i < args.length) {
66
+ scanRoots.push(args[i]);
67
+ i++;
68
+ }
69
+ } else if (arg.startsWith("--scan-root=")) {
70
+ scanRoots.push(arg.slice("--scan-root=".length));
71
+ i++;
72
+ } else {
73
+ filteredArgs.push(arg);
74
+ i++;
75
+ }
76
+ }
77
+
78
+ const { flags, positional } = parseFlags(filteredArgs, defs);
79
+ // Inject the collected scan roots as an array
80
+ flags["scan-root"] = scanRoots.length > 0 ? scanRoots : undefined;
81
+ return { flags, positional };
82
+ }
83
+
84
+ // ---------------------------------------------------------------------------
85
+ // atlas init
86
+ // ---------------------------------------------------------------------------
87
+ async function cmdAtlasInit(args) {
88
+ const { flags } = parseAtlasFlags(args, INIT_FLAG_DEFS);
89
+ const config = resolveAtlasConfig(flags);
90
+
91
+ if (isAtlasInitialized(config.outputDir) && !flags.force) {
92
+ console.log(`[atlas] Atlas already initialized at: ${config.outputDir}`);
93
+ console.log("[atlas] Use --force to overwrite existing config.");
94
+ } else {
95
+ writeAtlasConfig(config);
96
+ console.log(`[atlas] Initialized Atlas config: ${config.configPath}`);
97
+ console.log(`[atlas] Project root: ${config.projectPath}`);
98
+ console.log(`[atlas] Output dir: ${config.outputDir}`);
99
+ console.log(`[atlas] Scan roots: ${config.scanRoots.join(", ")}`);
100
+ }
101
+
102
+ if (flags["no-build"]) {
103
+ console.log("[atlas] --no-build specified; skipping initial build.");
104
+ return 0;
105
+ }
106
+
107
+ console.log("");
108
+ const buildResult = await runBuild(config);
109
+ console.log(`[atlas] Build complete: ${buildResult.docCount} docs, ${buildResult.nodeCount} nodes, ${buildResult.edgeCount} edges.`);
110
+
111
+ if (flags["no-open"]) {
112
+ console.log("[atlas] --no-open specified; skipping viewer launch.");
113
+ return 0;
114
+ }
115
+
116
+ const { url } = await openViewer(config, false);
117
+ console.log(`[atlas] Viewer: ${url}`);
118
+ return 0;
119
+ }
120
+
121
+ // ---------------------------------------------------------------------------
122
+ // atlas build
123
+ // ---------------------------------------------------------------------------
124
+ async function cmdAtlasBuild(args) {
125
+ const { flags } = parseAtlasFlags(args, BASE_FLAG_DEFS);
126
+ const config = resolveAtlasConfig(flags);
127
+
128
+ if (!isAtlasInitialized(config.outputDir)) {
129
+ console.log("[atlas] Atlas not initialized. Run: sdtk-spec atlas init");
130
+ console.log(`[atlas] Output dir: ${config.outputDir}`);
131
+ }
132
+
133
+ const startMs = Date.now();
134
+ const buildResult = await runBuild(config);
135
+ const durationMs = Date.now() - startMs;
136
+
137
+ console.log("");
138
+ console.log("[atlas] Build summary:");
139
+ console.log(` Documents: ${buildResult.docCount}`);
140
+ console.log(` Graph nodes: ${buildResult.nodeCount}`);
141
+ console.log(` Graph edges: ${buildResult.edgeCount}`);
142
+ console.log(` Output dir: ${config.outputDir}`);
143
+ console.log(` Duration: ${(durationMs / 1000).toFixed(1)}s`);
144
+ if (buildResult.generated) {
145
+ console.log(` Generated: ${buildResult.generated}`);
146
+ }
147
+ return 0;
148
+ }
149
+
150
+ // ---------------------------------------------------------------------------
151
+ // atlas open
152
+ // ---------------------------------------------------------------------------
153
+ async function cmdAtlasOpen(args) {
154
+ const { flags } = parseAtlasFlags(args, OPEN_FLAG_DEFS);
155
+ const config = resolveAtlasConfig(flags);
156
+
157
+ if (!isAtlasBuilt(config.outputDir)) {
158
+ console.error("[atlas] No atlas build found.");
159
+ console.error(` Expected: ${config.outputDir}/viewer.html`);
160
+ console.error(" Run: sdtk-spec atlas init");
161
+ console.error(" Or: sdtk-spec atlas build");
162
+ return 1;
163
+ }
164
+
165
+ const noOpen = !!flags["no-open"];
166
+ const { url } = await openViewer(config, noOpen);
167
+
168
+ if (!noOpen) {
169
+ // If the server was started inline, keep it alive until user exits
170
+ console.log("[atlas] Press Ctrl+C to stop the viewer server.");
171
+ await new Promise(() => {}); // keep alive
172
+ }
173
+
174
+ return 0;
175
+ }
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // atlas watch
179
+ // ---------------------------------------------------------------------------
180
+ async function cmdAtlasWatch(args) {
181
+ const { flags } = parseAtlasFlags(args, WATCH_FLAG_DEFS);
182
+ const config = resolveAtlasConfig(flags);
183
+
184
+ if (!isAtlasInitialized(config.outputDir)) {
185
+ console.log("[atlas] Atlas not initialized. Running init first...");
186
+ writeAtlasConfig(config);
187
+ console.log(`[atlas] Initialized Atlas config: ${config.configPath}`);
188
+ }
189
+
190
+ const DEBOUNCE_MS = 800;
191
+ let debounceTimer = null;
192
+ let rebuilding = false;
193
+
194
+ async function rebuild(reason) {
195
+ if (rebuilding) return;
196
+ rebuilding = true;
197
+ console.log(`\n[atlas] Change detected (${reason}). Rebuilding...`);
198
+ try {
199
+ const buildResult = await runBuild(config);
200
+ console.log(`[atlas] Rebuild complete: ${buildResult.docCount} docs, ${buildResult.nodeCount} nodes.`);
201
+ } catch (err) {
202
+ console.error(`[atlas] Rebuild failed: ${err.message}`);
203
+ } finally {
204
+ rebuilding = false;
205
+ }
206
+ }
207
+
208
+ // Initial build
209
+ console.log("[atlas] Running initial build...");
210
+ try {
211
+ const buildResult = await runBuild(config);
212
+ console.log(`[atlas] Initial build complete: ${buildResult.docCount} docs.`);
213
+ } catch (err) {
214
+ console.error(`[atlas] Initial build failed: ${err.message}`);
215
+ // Continue watching even if initial build fails
216
+ }
217
+
218
+ // Open viewer unless --no-open
219
+ let viewerServer = null;
220
+ if (!flags["no-open"] && isAtlasBuilt(config.outputDir)) {
221
+ const result = await openViewer(config, false);
222
+ viewerServer = result.server;
223
+ }
224
+
225
+ // Watch each scan root for markdown changes
226
+ const watchers = [];
227
+ for (const scanRoot of config.scanRoots) {
228
+ if (!fs.existsSync(scanRoot)) {
229
+ console.log(`[atlas] Warning: scan root does not exist, skipping watch: ${scanRoot}`);
230
+ continue;
231
+ }
232
+
233
+ try {
234
+ const watcher = fs.watch(scanRoot, { recursive: true }, (eventType, filename) => {
235
+ if (!filename || !filename.endsWith(".md")) return;
236
+ if (debounceTimer) clearTimeout(debounceTimer);
237
+ debounceTimer = setTimeout(() => {
238
+ rebuild(`${eventType}: ${filename}`);
239
+ }, DEBOUNCE_MS);
240
+ });
241
+
242
+ watcher.on("error", (err) => {
243
+ console.error(`[atlas] Watch error on ${scanRoot}: ${err.message}`);
244
+ });
245
+
246
+ watchers.push(watcher);
247
+ console.log(`[atlas] Watching: ${scanRoot}`);
248
+ } catch (err) {
249
+ console.error(`[atlas] Could not watch ${scanRoot}: ${err.message}`);
250
+ }
251
+ }
252
+
253
+ if (watchers.length === 0) {
254
+ console.error("[atlas] No scan roots could be watched. Exiting.");
255
+ return 1;
256
+ }
257
+
258
+ console.log("[atlas] Watching for markdown changes. Press Ctrl+C to stop.");
259
+
260
+ // Graceful shutdown
261
+ function shutdown() {
262
+ console.log("\n[atlas] Stopping watch...");
263
+ if (debounceTimer) clearTimeout(debounceTimer);
264
+ for (const w of watchers) {
265
+ try { w.close(); } catch (_) {}
266
+ }
267
+ if (viewerServer) {
268
+ try { viewerServer.close(); } catch (_) {}
269
+ }
270
+ process.exit(0);
271
+ }
272
+
273
+ process.on("SIGINT", shutdown);
274
+ process.on("SIGTERM", shutdown);
275
+
276
+ // Keep process alive
277
+ await new Promise(() => {});
278
+ return 0;
279
+ }
280
+
281
+ // ---------------------------------------------------------------------------
282
+ // atlas status
283
+ // ---------------------------------------------------------------------------
284
+ async function cmdAtlasStatus(args) {
285
+ const { flags } = parseAtlasFlags(args, BASE_FLAG_DEFS);
286
+
287
+ // Use defaults-only resolution (no validation errors for status)
288
+ let config;
289
+ try {
290
+ config = resolveAtlasConfig(flags);
291
+ } catch (err) {
292
+ console.error(`[atlas] Config error: ${err.message}`);
293
+ return 1;
294
+ }
295
+
296
+ const initialized = isAtlasInitialized(config.outputDir);
297
+ const built = isAtlasBuilt(config.outputDir);
298
+
299
+ console.log("[atlas] Status");
300
+ console.log("=".repeat(40));
301
+ console.log(` Initialized: ${initialized ? "yes" : "no"}`);
302
+ console.log(` Built: ${built ? "yes" : "no"}`);
303
+ console.log(` Project root: ${config.projectPath}`);
304
+ console.log(` Output dir: ${config.outputDir}`);
305
+ console.log(` Scan roots: ${config.scanRoots.join(", ")}`);
306
+ console.log(` Viewer host: ${config.host}:${config.port}`);
307
+
308
+ if (built) {
309
+ const meta = readBuildMeta(config.outputDir);
310
+ const graphMeta = readGraphMeta(config.outputDir);
311
+ if (meta) {
312
+ console.log(` Last build: ${meta.generated || "unknown"}`);
313
+ console.log(` Documents: ${meta.count}`);
314
+ }
315
+ if (graphMeta) {
316
+ console.log(` Graph nodes: ${graphMeta.nodeCount}`);
317
+ console.log(` Graph edges: ${graphMeta.edgeCount}`);
318
+ }
319
+ }
320
+
321
+ if (!initialized) {
322
+ console.log("");
323
+ console.log("[atlas] Hint: run 'sdtk-spec atlas init' to initialize Atlas for this project.");
324
+ } else if (!built) {
325
+ console.log("");
326
+ console.log("[atlas] Hint: run 'sdtk-spec atlas build' to build the local document graph.");
327
+ }
328
+
329
+ return 0;
330
+ }
331
+
332
+ // ---------------------------------------------------------------------------
333
+ // atlas ask (premium -- requires spec.atlas.ask entitlement)
334
+ // ---------------------------------------------------------------------------
335
+ async function cmdAtlasAsk(args) {
336
+ return runAtlasAsk(args);
337
+ }
338
+
339
+ // ---------------------------------------------------------------------------
340
+ // Top-level atlas dispatcher
341
+ // ---------------------------------------------------------------------------
342
+ const ATLAS_SUBCOMMANDS = new Set(["init", "build", "open", "watch", "status", "ask"]);
343
+
344
+ async function cmdAtlas(args) {
345
+ if (!args || args.length === 0) {
346
+ console.error("[atlas] Usage: sdtk-spec atlas <subcommand> [options]");
347
+ console.error(" Subcommands: init, build, open, watch, status");
348
+ console.error(" Premium subcommands: ask (requires Pro entitlement)");
349
+ console.error(" Run 'sdtk-spec --help' for full usage.");
350
+ return 1;
351
+ }
352
+
353
+ const [subcommand, ...rest] = args;
354
+
355
+ if (!ATLAS_SUBCOMMANDS.has(subcommand)) {
356
+ throw new ValidationError(
357
+ `Unknown atlas subcommand: "${subcommand}". Valid subcommands: init, build, open, watch, status, ask.`
358
+ );
359
+ }
360
+
361
+ switch (subcommand) {
362
+ case "init":
363
+ return cmdAtlasInit(rest);
364
+ case "build":
365
+ return cmdAtlasBuild(rest);
366
+ case "open":
367
+ return cmdAtlasOpen(rest);
368
+ case "watch":
369
+ return cmdAtlasWatch(rest);
370
+ case "status":
371
+ return cmdAtlasStatus(rest);
372
+ case "ask":
373
+ return cmdAtlasAsk(rest);
374
+ }
375
+ }
376
+
377
+ module.exports = {
378
+ cmdAtlas,
379
+ };
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const { loadEntitlementState } = require("../lib/entitlements");
5
+ const { syncEntitlements } = require("../lib/premium-sync");
6
+ const { getAuthFile } = require("../lib/suite-state");
7
+
8
+ // Trust/integrity states that require exit code 3.
9
+ const INTEGRITY_FAILURE_STATES = new Set([
10
+ "malformed",
11
+ "unsigned",
12
+ "invalid-signature",
13
+ "untrusted-key",
14
+ ]);
15
+
16
+ /**
17
+ * Read the suite auth file and return a simple auth summary.
18
+ * @param {string} authFilePath
19
+ * @returns {{ authenticated: boolean }}
20
+ */
21
+ function loadAuthState(authFilePath) {
22
+ if (!fs.existsSync(authFilePath)) {
23
+ return { authenticated: false };
24
+ }
25
+ try {
26
+ const data = JSON.parse(fs.readFileSync(authFilePath, "utf8"));
27
+ const token = data.github_token;
28
+ return { authenticated: typeof token === "string" && token.length > 0 };
29
+ } catch (_e) {
30
+ return { authenticated: false };
31
+ }
32
+ }
33
+
34
+ /**
35
+ * `sdtk-spec entitlement status`
36
+ *
37
+ * Reads local auth and entitlement state. Never hits the network.
38
+ * Prints a bounded summary and exits:
39
+ * 0 - informational state (missing, active, grace, expired)
40
+ * 3 - trust/integrity failure (malformed, unsigned, invalid-signature, untrusted-key)
41
+ */
42
+ function entitlementStatus() {
43
+ const auth = loadAuthState(getAuthFile());
44
+ const { state, manifest } = loadEntitlementState();
45
+
46
+ const lines = [
47
+ "Entitlement Status",
48
+ "------------------",
49
+ `Auth state: ${auth.authenticated ? "authenticated" : "not authenticated"}`,
50
+ `Manifest state: ${state}`,
51
+ ];
52
+
53
+ if (manifest) {
54
+ if (manifest.plan) {
55
+ lines.push(`Plan: ${manifest.plan}`);
56
+ }
57
+ if (manifest.products && manifest.products.spec) {
58
+ lines.push(`SPEC tier: ${manifest.products.spec}`);
59
+ }
60
+ const caps = Array.isArray(manifest.capabilities) ? manifest.capabilities : [];
61
+ const capWord = caps.length === 1 ? "capability" : "capabilities";
62
+ lines.push(`Capabilities: ${caps.length} ${capWord}`);
63
+ if (manifest.expires_at) {
64
+ lines.push(`Expires at: ${manifest.expires_at}`);
65
+ }
66
+ if (manifest.offline_grace_until) {
67
+ lines.push(`Grace until: ${manifest.offline_grace_until}`);
68
+ }
69
+ }
70
+
71
+ console.log(lines.join("\n"));
72
+
73
+ if (INTEGRITY_FAILURE_STATES.has(state)) {
74
+ process.stderr.write(
75
+ `Entitlement trust failure: ${state}. ` +
76
+ `Manifest cannot be used for premium capability decisions.\n`
77
+ );
78
+ return 3;
79
+ }
80
+
81
+ return 0;
82
+ }
83
+
84
+ /**
85
+ * `sdtk-spec entitlement sync`
86
+ *
87
+ * Fetches and verifies a signed entitlement manifest from GitHub Contents API,
88
+ * caches it locally, and installs required SPEC premium packs.
89
+ *
90
+ * Prints a bounded sync summary and exits:
91
+ * 0 - manifest verified and required pack sync completed (or no packs required)
92
+ * 1 - unauthenticated, network failure, or unauthorized
93
+ * 3 - manifest trust failure or pack SHA256 mismatch
94
+ * 4 - unexpected internal error
95
+ */
96
+ async function entitlementSync() {
97
+ let result;
98
+ try {
99
+ result = await syncEntitlements();
100
+ } catch (err) {
101
+ process.stderr.write(`Unexpected error during sync: ${err.message}\n`);
102
+ return 4;
103
+ }
104
+
105
+ const lines = [
106
+ "Entitlement Sync",
107
+ "----------------",
108
+ `Manifest state: ${result.manifestState}`,
109
+ ];
110
+
111
+ if (result.trustState) {
112
+ lines.push(`Trust state: ${result.trustState}`);
113
+ }
114
+
115
+ if (result.packs.required > 0) {
116
+ lines.push(`Packs required: ${result.packs.required}`);
117
+ lines.push(` installed: ${result.packs.installed}`);
118
+ lines.push(` unchanged: ${result.packs.unchanged}`);
119
+ lines.push(` rejected: ${result.packs.rejected}`);
120
+ } else {
121
+ lines.push("Packs required: 0");
122
+ }
123
+
124
+ console.log(lines.join("\n"));
125
+
126
+ for (const msg of result.errors) {
127
+ process.stderr.write(`${msg}\n`);
128
+ }
129
+
130
+ return result.exitCode;
131
+ }
132
+
133
+ /**
134
+ * Entry point for the `entitlement` command.
135
+ *
136
+ * Supported subcommands:
137
+ * status - Show local entitlement and capability state (local-only, no network)
138
+ * sync - Fetch and verify a signed entitlement manifest; install required SPEC packs
139
+ *
140
+ * @param {string[]} args - Remaining argv after "entitlement"
141
+ * @returns {number|Promise<number>} CLI exit code
142
+ */
143
+ async function cmdEntitlement(args) {
144
+ const [subcommand] = args || [];
145
+
146
+ if (!subcommand || subcommand === "status") {
147
+ return entitlementStatus();
148
+ }
149
+
150
+ if (subcommand === "sync") {
151
+ return entitlementSync();
152
+ }
153
+
154
+ process.stderr.write(
155
+ `Unknown entitlement subcommand: "${subcommand}". ` +
156
+ `Run "sdtk-spec entitlement status" or "sdtk-spec entitlement sync".\n`
157
+ );
158
+ return 1;
159
+ }
160
+
161
+ module.exports = {
162
+ cmdEntitlement,
163
+ };