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
@@ -62,7 +62,82 @@ async function checkRepoAccess(token, repo) {
62
62
  }
63
63
  }
64
64
 
65
+ /**
66
+ * Fetch a file from the GitHub Contents API and return its decoded bytes.
67
+ *
68
+ * The GitHub Contents API returns the file content base64-encoded (with line breaks).
69
+ * This function strips line breaks and decodes to a Buffer.
70
+ *
71
+ * @param {string} token - GitHub PAT
72
+ * @param {string} repo - Repository in "owner/name" format
73
+ * @param {string} filePath - Repo-relative file path
74
+ * @param {string} ref - Branch, tag, or commit SHA
75
+ * @param {Function} [fetcher] - Injectable fetch function (default: global fetch)
76
+ * @returns {Promise<Buffer>} Decoded file bytes
77
+ * @throws {ValidationError} on HTTP error or missing content field
78
+ */
79
+ async function fetchGithubContents(token, repo, filePath, ref, fetcher) {
80
+ const _fetch = fetcher || fetch;
81
+ const encodedRef = encodeURIComponent(ref);
82
+ const url = `https://api.github.com/repos/${repo}/contents/${filePath}?ref=${encodedRef}`;
83
+
84
+ let response;
85
+ try {
86
+ response = await _fetch(url, {
87
+ headers: {
88
+ Authorization: `Bearer ${token}`,
89
+ Accept: "application/vnd.github.v3+json",
90
+ "User-Agent": "sdtk-cli",
91
+ },
92
+ });
93
+ } catch (err) {
94
+ throw new ValidationError(
95
+ `Failed to reach GitHub API: ${err.message}\nCheck your network connection.`
96
+ );
97
+ }
98
+
99
+ if (response.status === 401) {
100
+ throw new ValidationError(
101
+ "GitHub token is invalid or expired. Run: sdtk-spec auth --token <value>"
102
+ );
103
+ }
104
+ if (response.status === 403) {
105
+ throw new ValidationError(
106
+ `No access to ${repo}. Check your token permissions.`
107
+ );
108
+ }
109
+ if (response.status === 404) {
110
+ throw new ValidationError(
111
+ `Remote content not found: ${filePath} at ${repo}@${ref}.`
112
+ );
113
+ }
114
+ if (response.status !== 200) {
115
+ throw new ValidationError(
116
+ `Unexpected HTTP ${response.status} from GitHub Contents API.`
117
+ );
118
+ }
119
+
120
+ let data;
121
+ try {
122
+ data = await response.json();
123
+ } catch (_e) {
124
+ throw new ValidationError(
125
+ "GitHub Contents API response is not valid JSON."
126
+ );
127
+ }
128
+
129
+ if (!data || typeof data.content !== "string") {
130
+ throw new ValidationError(
131
+ "GitHub Contents API response missing content field."
132
+ );
133
+ }
134
+
135
+ // GitHub encodes file content as base64 with embedded newlines.
136
+ return Buffer.from(data.content.replace(/\n/g, ""), "base64");
137
+ }
138
+
65
139
  module.exports = {
66
140
  checkRepoAccess,
141
+ fetchGithubContents,
67
142
  getEntitlementRepo,
68
143
  };
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const os = require("os");
5
+ const path = require("path");
6
+ const { ensureDir, getAuthFile, hardenFilePermissions } = require("./suite-state");
7
+
8
+ function getLegacyAuthFile() {
9
+ return path.join(os.homedir(), ".sdtkrc");
10
+ }
11
+
12
+ function buildMigratedPayload(payload) {
13
+ const token = typeof payload.github_token === "string" ? payload.github_token : "";
14
+ const updatedAt =
15
+ typeof payload.updated_at === "string" && payload.updated_at.trim().length > 0
16
+ ? payload.updated_at
17
+ : new Date().toISOString();
18
+
19
+ return {
20
+ github_token: token,
21
+ updated_at: updatedAt,
22
+ };
23
+ }
24
+
25
+ function migrateLegacyAuthStateIfNeeded() {
26
+ const authFile = getAuthFile();
27
+ if (fs.existsSync(authFile)) {
28
+ return { migrated: false, malformedLegacy: false, path: authFile };
29
+ }
30
+
31
+ const legacyAuthFile = getLegacyAuthFile();
32
+ if (!fs.existsSync(legacyAuthFile)) {
33
+ return { migrated: false, malformedLegacy: false, path: authFile };
34
+ }
35
+
36
+ try {
37
+ const payload = JSON.parse(fs.readFileSync(legacyAuthFile, "utf8"));
38
+ const migratedPayload = buildMigratedPayload(payload);
39
+ ensureDir(path.dirname(authFile));
40
+ fs.writeFileSync(authFile, JSON.stringify(migratedPayload, null, 2), "utf8");
41
+ const hardened = hardenFilePermissions(authFile);
42
+ return {
43
+ migrated: true,
44
+ malformedLegacy: false,
45
+ path: authFile,
46
+ hardened,
47
+ };
48
+ } catch (_error) {
49
+ return { migrated: false, malformedLegacy: true, path: authFile };
50
+ }
51
+ }
52
+
53
+ module.exports = {
54
+ getLegacyAuthFile,
55
+ migrateLegacyAuthStateIfNeeded,
56
+ };
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+
3
+ const { loadEntitlementState } = require("./entitlements");
4
+ const { checkCapability } = require("./capabilities");
5
+ const { resolvePackState, getPackFile } = require("./premium-packs");
6
+
7
+ /**
8
+ * Load a verified premium pack handler for the specified capability.
9
+ *
10
+ * Steps:
11
+ * 1. Load local entitlement state.
12
+ * 2. Check the required capability via checkCapability.
13
+ * 3. Find the matching premium pack entry in manifest.premium_packs.
14
+ * 4. Verify the pack cache state via resolvePackState.
15
+ * 5. Require the pack module from cache.
16
+ * 6. Resolve the handler export (prefer named export, fallback to "run").
17
+ *
18
+ * Failure mapping:
19
+ * integrity failure state -> { ok: false, exitCode: 3 }
20
+ * missing / expired / no cap -> { ok: false, exitCode: 1 }
21
+ * missing / stale pack -> { ok: false, exitCode: 1 }
22
+ * malformed pack -> { ok: false, exitCode: 3 }
23
+ * require failure -> { ok: false, exitCode: 4 }
24
+ * bad handler export -> { ok: false, exitCode: 3 }
25
+ * success -> { ok: true, handler, packEntry }
26
+ *
27
+ * @param {string} capability - Required capability ID (e.g. "spec.atlas.ask").
28
+ * @param {string} preferredExport - Preferred handler export name (e.g. "atlasAsk").
29
+ * @returns {Promise<
30
+ * { ok: true, handler: Function, packEntry: object } |
31
+ * { ok: false, exitCode: number, message: string }
32
+ * >}
33
+ */
34
+ async function loadPremiumHandler(capability, preferredExport) {
35
+ // 1. Load entitlement state
36
+ const entitlementState = loadEntitlementState();
37
+
38
+ // 2. Check capability (handles integrity, missing, expired, not-included)
39
+ const check = checkCapability(capability, entitlementState);
40
+ if (!check.allowed) {
41
+ return { ok: false, exitCode: check.exitCode, message: check.reason };
42
+ }
43
+
44
+ // 3. Find matching pack entry from manifest.premium_packs
45
+ const manifest = entitlementState.manifest;
46
+ const packs =
47
+ manifest && Array.isArray(manifest.premium_packs)
48
+ ? manifest.premium_packs
49
+ : [];
50
+
51
+ const packEntry = packs.find(
52
+ (p) =>
53
+ p.product === "spec" &&
54
+ Array.isArray(p.capabilities) &&
55
+ p.capabilities.includes(capability)
56
+ );
57
+
58
+ if (!packEntry) {
59
+ return {
60
+ ok: false,
61
+ exitCode: 1,
62
+ message:
63
+ `Premium pack providing "${capability}" is not available. ` +
64
+ `Run "sdtk-spec entitlement sync" to install the required premium pack.`,
65
+ };
66
+ }
67
+
68
+ // 4. Verify pack cache state
69
+ const packState = resolvePackState(packEntry);
70
+
71
+ if (packState.state === "malformed") {
72
+ return {
73
+ ok: false,
74
+ exitCode: 3,
75
+ message:
76
+ `Premium pack integrity failure: ${packState.reason} ` +
77
+ `Run "sdtk-spec entitlement status" for details.`,
78
+ };
79
+ }
80
+
81
+ if (packState.state !== "present") {
82
+ // missing or stale
83
+ return {
84
+ ok: false,
85
+ exitCode: 1,
86
+ message:
87
+ `Premium pack is not ready (${packState.state}). ` +
88
+ (packState.reason ||
89
+ `Run "sdtk-spec entitlement sync" to install or refresh the premium pack.`),
90
+ };
91
+ }
92
+
93
+ // 5. Load pack module from cache
94
+ const packFile = getPackFile(packEntry.id, packEntry.version);
95
+ let packModule;
96
+ try {
97
+ packModule = require(packFile);
98
+ } catch (err) {
99
+ return {
100
+ ok: false,
101
+ exitCode: 4,
102
+ message: `Failed to load premium pack handler: ${err.message}`,
103
+ };
104
+ }
105
+
106
+ // 6. Resolve handler export: prefer named export, fallback to "run"
107
+ const handler =
108
+ preferredExport &&
109
+ typeof packModule[preferredExport] === "function"
110
+ ? packModule[preferredExport]
111
+ : packModule.run;
112
+
113
+ if (typeof handler !== "function") {
114
+ return {
115
+ ok: false,
116
+ exitCode: 3,
117
+ message:
118
+ `Premium pack handler contract is invalid: ` +
119
+ `expected export "${preferredExport}" or "run" to be a function.`,
120
+ };
121
+ }
122
+
123
+ return { ok: true, handler, packEntry };
124
+ }
125
+
126
+ module.exports = { loadPremiumHandler };
@@ -0,0 +1,333 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const crypto = require("crypto");
6
+ const { getPacksRoot, ensureDir } = require("./suite-state");
7
+
8
+ // Required fields in a pack manifest entry (from the signed entitlement manifest).
9
+ const SAFE_PACK_PART_RE = /^[A-Za-z0-9._-]+$/;
10
+
11
+ function isSafePackPathPart(value) {
12
+ return (
13
+ typeof value === "string" &&
14
+ SAFE_PACK_PART_RE.test(value) &&
15
+ value !== "." &&
16
+ value !== ".."
17
+ );
18
+ }
19
+
20
+ const REQUIRED_PACK_FIELDS = [
21
+ "id",
22
+ "product",
23
+ "version",
24
+ "capabilities",
25
+ "source",
26
+ "sha256",
27
+ ];
28
+
29
+ /**
30
+ * Resolve the cache directory for a specific pack version.
31
+ * Layout: ~/.sdtk/packs/spec/<pack_id>/<pack_version>/
32
+ *
33
+ * @param {string} packId
34
+ * @param {string} packVersion
35
+ * @returns {string}
36
+ */
37
+ function getPackDir(packId, packVersion) {
38
+ return path.join(getPacksRoot(), "spec", packId, packVersion);
39
+ }
40
+
41
+ /**
42
+ * Resolve the cached pack payload path.
43
+ * @param {string} packId
44
+ * @param {string} packVersion
45
+ * @returns {string}
46
+ */
47
+ function getPackFile(packId, packVersion) {
48
+ return path.join(getPackDir(packId, packVersion), "pack.js");
49
+ }
50
+
51
+ /**
52
+ * Resolve the cached pack metadata path.
53
+ * @param {string} packId
54
+ * @param {string} packVersion
55
+ * @returns {string}
56
+ */
57
+ function getPackMetaFile(packId, packVersion) {
58
+ return path.join(getPackDir(packId, packVersion), "pack.json");
59
+ }
60
+
61
+ /**
62
+ * Compute lowercase hex SHA256 over exact bytes.
63
+ * @param {Buffer} bytes
64
+ * @returns {string}
65
+ */
66
+ function computeSha256(bytes) {
67
+ return crypto.createHash("sha256").update(bytes).digest("hex");
68
+ }
69
+
70
+ /**
71
+ * Validate the shape of a pack metadata entry from the signed manifest.
72
+ *
73
+ * @param {*} meta - Value to validate (may be any type)
74
+ * @returns {{ valid: true } | { valid: false, reason: string }}
75
+ */
76
+ function validatePackMeta(meta) {
77
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
78
+ return { valid: false, reason: "pack metadata is not an object" };
79
+ }
80
+
81
+ for (const field of REQUIRED_PACK_FIELDS) {
82
+ if (!(field in meta)) {
83
+ return { valid: false, reason: `missing required field: ${field}` };
84
+ }
85
+ }
86
+
87
+ if (!isSafePackPathPart(meta.id)) {
88
+ return {
89
+ valid: false,
90
+ reason: "id must be a non-empty safe identifier",
91
+ };
92
+ }
93
+
94
+ if (
95
+ !isSafePackPathPart(meta.version)
96
+ ) {
97
+ return {
98
+ valid: false,
99
+ reason: "version must be a non-empty safe identifier",
100
+ };
101
+ }
102
+
103
+ if (meta.product !== "spec") {
104
+ return {
105
+ valid: false,
106
+ reason: `product must be "spec", got "${meta.product}"`,
107
+ };
108
+ }
109
+
110
+ if (
111
+ !meta.source ||
112
+ typeof meta.source !== "object" ||
113
+ Array.isArray(meta.source) ||
114
+ meta.source.type !== "github-content"
115
+ ) {
116
+ return { valid: false, reason: 'source.type must be "github-content"' };
117
+ }
118
+
119
+ if (typeof meta.source.path !== "string" || !meta.source.path) {
120
+ return {
121
+ valid: false,
122
+ reason: "source.path must be a non-empty string",
123
+ };
124
+ }
125
+
126
+ if (
127
+ typeof meta.sha256 !== "string" ||
128
+ !/^[0-9a-f]{64}$/.test(meta.sha256)
129
+ ) {
130
+ return {
131
+ valid: false,
132
+ reason: "sha256 must be a 64-character lowercase hex string",
133
+ };
134
+ }
135
+
136
+ if (!Array.isArray(meta.capabilities)) {
137
+ return { valid: false, reason: "capabilities must be an array" };
138
+ }
139
+
140
+ return { valid: true };
141
+ }
142
+
143
+ /**
144
+ * Write a pack payload to cache using a temp-write + hash-check + rename pattern.
145
+ *
146
+ * Steps:
147
+ * 1. Verify SHA256 of bytes matches signed manifest entry
148
+ * 2. Write bytes to a temp file
149
+ * 3. Rename temp file to final pack.js path
150
+ * 4. Write pack.json metadata
151
+ *
152
+ * @param {object} packMeta - Validated pack metadata from signed manifest
153
+ * @param {Buffer} packBytes - Raw pack.js content
154
+ * @returns {{ success: boolean, reason?: string }}
155
+ */
156
+ function writePackToCache(packMeta, packBytes) {
157
+ const validation = validatePackMeta(packMeta);
158
+ if (!validation.valid) {
159
+ return { success: false, reason: `Invalid pack metadata: ${validation.reason}` };
160
+ }
161
+
162
+ if (!Buffer.isBuffer(packBytes)) {
163
+ return { success: false, reason: "packBytes must be a Buffer" };
164
+ }
165
+
166
+ const actualHash = computeSha256(packBytes);
167
+ if (actualHash !== packMeta.sha256) {
168
+ return {
169
+ success: false,
170
+ reason:
171
+ `SHA256 mismatch for pack "${packMeta.id}@${packMeta.version}": ` +
172
+ `expected ${packMeta.sha256}, got ${actualHash}`,
173
+ };
174
+ }
175
+
176
+ const packDir = getPackDir(packMeta.id, packMeta.version);
177
+ try {
178
+ ensureDir(packDir);
179
+ } catch (err) {
180
+ return {
181
+ success: false,
182
+ reason: `Failed to create pack cache directory: ${err.message}`,
183
+ };
184
+ }
185
+
186
+ // Write to a temp file in the same cache directory, then rename (atomic-style).
187
+ // Keeping temp and final on the same volume avoids EXDEV failures on Windows.
188
+ const tmpFile = path.join(
189
+ packDir,
190
+ `.pack.js.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
191
+ );
192
+
193
+ try {
194
+ fs.writeFileSync(tmpFile, packBytes);
195
+ } catch (err) {
196
+ return {
197
+ success: false,
198
+ reason: `Failed to write pack temp file: ${err.message}`,
199
+ };
200
+ }
201
+
202
+ const finalPackFile = getPackFile(packMeta.id, packMeta.version);
203
+ try {
204
+ if (fs.existsSync(finalPackFile)) {
205
+ fs.unlinkSync(finalPackFile);
206
+ }
207
+ fs.renameSync(tmpFile, finalPackFile);
208
+ } catch (err) {
209
+ try {
210
+ fs.unlinkSync(tmpFile);
211
+ } catch (_) {}
212
+ return {
213
+ success: false,
214
+ reason: `Failed to move pack to cache: ${err.message}`,
215
+ };
216
+ }
217
+
218
+ // Write pack.json metadata after content integrity passes.
219
+ const packJsonMeta = {
220
+ id: packMeta.id,
221
+ product: packMeta.product,
222
+ version: packMeta.version,
223
+ capabilities: packMeta.capabilities,
224
+ sha256: packMeta.sha256,
225
+ source: packMeta.source,
226
+ installed_at: new Date().toISOString(),
227
+ entrypoint: "pack.js",
228
+ };
229
+
230
+ try {
231
+ fs.writeFileSync(
232
+ getPackMetaFile(packMeta.id, packMeta.version),
233
+ JSON.stringify(packJsonMeta, null, 2),
234
+ "utf8"
235
+ );
236
+ } catch (err) {
237
+ return {
238
+ success: false,
239
+ reason: `Failed to write pack.json: ${err.message}`,
240
+ };
241
+ }
242
+
243
+ return { success: true };
244
+ }
245
+
246
+ /**
247
+ * Resolve the local cache state for a pack without executing pack code.
248
+ *
249
+ * States:
250
+ * present - pack.js and pack.json exist with matching sha256
251
+ * missing - pack files are absent
252
+ * stale - pack.json sha256 does not match the manifest entry
253
+ * malformed - pack entry is invalid or pack.json cannot be parsed
254
+ *
255
+ * @param {object} manifestPackEntry - Pack entry from the verified entitlement manifest
256
+ * @returns {{ state: "present"|"missing"|"stale"|"malformed", reason?: string }}
257
+ */
258
+ function resolvePackState(manifestPackEntry) {
259
+ const validation = validatePackMeta(manifestPackEntry);
260
+ if (!validation.valid) {
261
+ return { state: "malformed", reason: validation.reason };
262
+ }
263
+
264
+ const { id, version, sha256 } = manifestPackEntry;
265
+ const packFile = getPackFile(id, version);
266
+ const metaFile = getPackMetaFile(id, version);
267
+
268
+ if (!fs.existsSync(packFile) || !fs.existsSync(metaFile)) {
269
+ return {
270
+ state: "missing",
271
+ reason:
272
+ `Pack "${id}@${version}" is not installed. ` +
273
+ `Run "sdtk-spec entitlement sync" to install.`,
274
+ };
275
+ }
276
+
277
+ let cachedMeta;
278
+ try {
279
+ cachedMeta = JSON.parse(fs.readFileSync(metaFile, "utf8"));
280
+ } catch (_e) {
281
+ return {
282
+ state: "malformed",
283
+ reason: `pack.json for "${id}@${version}" could not be parsed`,
284
+ };
285
+ }
286
+
287
+ if (!cachedMeta || typeof cachedMeta !== "object" || Array.isArray(cachedMeta)) {
288
+ return {
289
+ state: "malformed",
290
+ reason: `pack.json for "${id}@${version}" is not a valid object`,
291
+ };
292
+ }
293
+
294
+ if (cachedMeta.sha256 !== sha256) {
295
+ return {
296
+ state: "stale",
297
+ reason:
298
+ `Pack "${id}@${version}" hash in metadata does not match manifest. ` +
299
+ `Run "sdtk-spec entitlement sync" to refresh.`,
300
+ };
301
+ }
302
+
303
+ let packBytes;
304
+ try {
305
+ packBytes = fs.readFileSync(packFile);
306
+ } catch (err) {
307
+ return {
308
+ state: "malformed",
309
+ reason: `pack.js for "${id}@${version}" could not be read: ${err.message}`,
310
+ };
311
+ }
312
+
313
+ if (computeSha256(packBytes) !== sha256) {
314
+ return {
315
+ state: "stale",
316
+ reason:
317
+ `Pack "${id}@${version}" bytes do not match the signed manifest hash. ` +
318
+ `Run "sdtk-spec entitlement sync" to refresh.`,
319
+ };
320
+ }
321
+
322
+ return { state: "present" };
323
+ }
324
+
325
+ module.exports = {
326
+ getPackDir,
327
+ getPackFile,
328
+ getPackMetaFile,
329
+ computeSha256,
330
+ validatePackMeta,
331
+ writePackToCache,
332
+ resolvePackState,
333
+ };