sdtk-spec-kit 0.3.16 → 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.
@@ -0,0 +1,235 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { readAuthState } = require("./state");
6
+ const { getEntitlementsFile, ensureDir } = require("./suite-state");
7
+ const { evaluateManifestObject } = require("./entitlements");
8
+ const { fetchGithubContents, getEntitlementRepo } = require("./github-access");
9
+ const {
10
+ validatePackMeta,
11
+ writePackToCache,
12
+ resolvePackState,
13
+ } = require("./premium-packs");
14
+
15
+ const DEFAULT_MANIFEST_PATH = "entitlements/spec/entitlements.json";
16
+ const DEFAULT_REF = "main";
17
+
18
+ // Trust states that must block manifest cache writes and pack sync.
19
+ const INVALID_TRUST_STATES = new Set([
20
+ "malformed",
21
+ "unsigned",
22
+ "invalid-signature",
23
+ "untrusted-key",
24
+ ]);
25
+
26
+ /**
27
+ * Run a full entitlement sync for the SPEC product.
28
+ *
29
+ * Flow:
30
+ * 1. Read suite auth token; fail with exitCode 1 if unauthenticated.
31
+ * 2. Fetch signed entitlement manifest from GitHub Contents API.
32
+ * 3. Verify manifest using evaluateManifestObject.
33
+ * 4. Write verified manifest to ~/.sdtk/entitlements.json only after verification.
34
+ * 5. Resolve required SPEC premium packs from signed premium_packs metadata.
35
+ * 6. Fetch and cache each required pack; verify SHA256 before final write.
36
+ * 7. Return a structured summary for CLI output.
37
+ *
38
+ * @param {object} [options]
39
+ * @param {Function} [options.fetcher] - Injectable HTTP fetch function (default: global fetch)
40
+ * @param {number} [options.nowMs] - Current epoch ms (injectable for deterministic tests)
41
+ * @returns {Promise<SyncResult>}
42
+ *
43
+ * @typedef {object} SyncResult
44
+ * @property {"updated"|"unchanged"|"failed"|"unknown"} manifestState
45
+ * @property {string|null} trustState - active | grace | expired | rejected | null
46
+ * @property {{ required: number, installed: number, unchanged: number, rejected: number }} packs
47
+ * @property {number} exitCode - 0 success, 1 auth/network failure, 3 integrity failure, 4 internal
48
+ * @property {string[]} errors - Actionable error messages for stderr
49
+ */
50
+ async function syncEntitlements({ fetcher, nowMs } = {}) {
51
+ const result = {
52
+ manifestState: "unknown",
53
+ trustState: null,
54
+ packs: {
55
+ required: 0,
56
+ installed: 0,
57
+ unchanged: 0,
58
+ rejected: 0,
59
+ },
60
+ exitCode: 0,
61
+ errors: [],
62
+ };
63
+
64
+ // ---- 1. Read auth state ----
65
+ let auth;
66
+ try {
67
+ auth = readAuthState();
68
+ } catch (_e) {
69
+ auth = { authenticated: false, token: "" };
70
+ }
71
+
72
+ if (!auth.authenticated || !auth.token) {
73
+ result.manifestState = "failed";
74
+ result.exitCode = 1;
75
+ result.errors.push(
76
+ "Not authenticated. Run: sdtk-spec auth --token <your-github-token>"
77
+ );
78
+ return result;
79
+ }
80
+
81
+ // ---- 2. Fetch signed manifest ----
82
+ const repo =
83
+ process.env.SDTK_ENTITLEMENT_REPO || getEntitlementRepo();
84
+ const manifestPath =
85
+ process.env.SDTK_ENTITLEMENT_MANIFEST_PATH || DEFAULT_MANIFEST_PATH;
86
+ const ref = process.env.SDTK_ENTITLEMENT_REF || DEFAULT_REF;
87
+
88
+ let manifestBytes;
89
+ try {
90
+ manifestBytes = await fetchGithubContents(
91
+ auth.token,
92
+ repo,
93
+ manifestPath,
94
+ ref,
95
+ fetcher
96
+ );
97
+ } catch (err) {
98
+ result.manifestState = "failed";
99
+ result.exitCode = 1;
100
+ result.errors.push(
101
+ `Failed to fetch entitlement manifest: ${err.message}`
102
+ );
103
+ return result;
104
+ }
105
+
106
+ // ---- 3. Parse manifest ----
107
+ let manifest;
108
+ try {
109
+ manifest = JSON.parse(manifestBytes.toString("utf8"));
110
+ } catch (_e) {
111
+ result.manifestState = "failed";
112
+ result.trustState = "rejected";
113
+ result.exitCode = 3;
114
+ result.errors.push(
115
+ "Remote manifest is malformed JSON. Existing cache preserved."
116
+ );
117
+ return result;
118
+ }
119
+
120
+ // ---- 4. Verify manifest ----
121
+ const now = nowMs !== undefined ? nowMs : Date.now();
122
+ const { state: trustState } = evaluateManifestObject(manifest, now);
123
+ result.trustState = trustState;
124
+
125
+ if (INVALID_TRUST_STATES.has(trustState)) {
126
+ result.manifestState = "failed";
127
+ result.exitCode = 3;
128
+ result.errors.push(
129
+ `Remote manifest verification failed: ${trustState}. Existing cache preserved.`
130
+ );
131
+ return result;
132
+ }
133
+
134
+ // ---- 5. Write verified manifest to cache ----
135
+ const entitlementsFile = getEntitlementsFile();
136
+ try {
137
+ ensureDir(path.dirname(entitlementsFile));
138
+ const newStr = JSON.stringify(manifest, null, 2);
139
+
140
+ let existingStr = null;
141
+ if (fs.existsSync(entitlementsFile)) {
142
+ try {
143
+ const existingRaw = fs.readFileSync(entitlementsFile, "utf8");
144
+ existingStr = JSON.stringify(JSON.parse(existingRaw), null, 2);
145
+ } catch (_) {}
146
+ }
147
+
148
+ if (existingStr !== null && existingStr === newStr) {
149
+ result.manifestState = "unchanged";
150
+ } else {
151
+ fs.writeFileSync(entitlementsFile, newStr, "utf8");
152
+ result.manifestState = "updated";
153
+ }
154
+ } catch (err) {
155
+ result.manifestState = "failed";
156
+ result.exitCode = 4;
157
+ result.errors.push(
158
+ `Failed to write entitlement cache: ${err.message}`
159
+ );
160
+ return result;
161
+ }
162
+
163
+ // ---- 6. Resolve required SPEC packs ----
164
+ const premiumPacks = Array.isArray(manifest.premium_packs)
165
+ ? manifest.premium_packs
166
+ : [];
167
+ const manifestCaps = Array.isArray(manifest.capabilities)
168
+ ? manifest.capabilities
169
+ : [];
170
+
171
+ // A pack is required if its product is "spec" and at least one of its
172
+ // capabilities intersects the verified entitlement capabilities list.
173
+ const requiredPacks = premiumPacks.filter((pack) => {
174
+ if (!pack || pack.product !== "spec") return false;
175
+ if (!Array.isArray(pack.capabilities)) return false;
176
+ return pack.capabilities.some((c) => manifestCaps.includes(c));
177
+ });
178
+
179
+ result.packs.required = requiredPacks.length;
180
+
181
+ // ---- 7. Fetch and cache each required pack ----
182
+ for (const packEntry of requiredPacks) {
183
+ // Validate pack metadata shape before any network access.
184
+ const validation = validatePackMeta(packEntry);
185
+ if (!validation.valid) {
186
+ result.packs.rejected++;
187
+ result.exitCode = Math.max(result.exitCode, 3);
188
+ result.errors.push(
189
+ `Pack "${packEntry.id || "unknown"}" has malformed metadata: ${validation.reason}`
190
+ );
191
+ continue;
192
+ }
193
+
194
+ // Check if pack is already current (no-op path).
195
+ const packState = resolvePackState(packEntry);
196
+ if (packState.state === "present") {
197
+ result.packs.unchanged++;
198
+ continue;
199
+ }
200
+
201
+ // Fetch pack bytes.
202
+ const packRef = packEntry.source.ref || ref;
203
+ let packBytes;
204
+ try {
205
+ packBytes = await fetchGithubContents(
206
+ auth.token,
207
+ repo,
208
+ packEntry.source.path,
209
+ packRef,
210
+ fetcher
211
+ );
212
+ } catch (err) {
213
+ result.packs.rejected++;
214
+ result.exitCode = Math.max(result.exitCode, 1);
215
+ result.errors.push(
216
+ `Failed to fetch pack "${packEntry.id}": ${err.message}`
217
+ );
218
+ continue;
219
+ }
220
+
221
+ // Verify SHA256 and write to cache.
222
+ const writeResult = writePackToCache(packEntry, packBytes);
223
+ if (writeResult.success) {
224
+ result.packs.installed++;
225
+ } else {
226
+ result.packs.rejected++;
227
+ result.exitCode = Math.max(result.exitCode, 3);
228
+ result.errors.push(writeResult.reason);
229
+ }
230
+ }
231
+
232
+ return result;
233
+ }
234
+
235
+ module.exports = { syncEntitlements };
@@ -0,0 +1,332 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const { parseFlags } = require("./args");
5
+ const { resolveProjectConfig } = require("./project-config");
6
+ const { assertProjectRefreshTargetAllowed } = require("./project-target-guard");
7
+ const { loadPremiumHandler } = require("./premium-loader");
8
+
9
+ const CAPABILITY = "spec.project.audit";
10
+
11
+ const VALID_SOURCE_MODES = new Set([
12
+ "cached-foundation+baseline",
13
+ "cached-foundation",
14
+ "ephemeral-analysis",
15
+ ]);
16
+
17
+ const VALID_READINESS_BANDS = new Set(["low", "medium", "high"]);
18
+
19
+ const VALID_SEVERITIES = new Set(["critical", "high", "medium", "low"]);
20
+
21
+ const AUDIT_FLAG_DEFS = {
22
+ "project-path": { type: "string" },
23
+ "output-dir": { type: "string" },
24
+ json: { type: "boolean" },
25
+ };
26
+
27
+ /**
28
+ * Validate a single gap or risk entry.
29
+ *
30
+ * Required fields: id, severity, area, title, finding, evidenceRefs, suggestedAction.
31
+ *
32
+ * @param {"gap"|"risk"} kind
33
+ * @param {*} entry
34
+ * @returns {{ valid: true } | { valid: false, reason: string }}
35
+ */
36
+ function validateAuditEntry(kind, entry) {
37
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
38
+ return { valid: false, reason: `${kind} entry must be a plain object` };
39
+ }
40
+ if (typeof entry.id !== "string" || entry.id.trim() === "") {
41
+ return { valid: false, reason: `${kind} entry missing non-empty "id"` };
42
+ }
43
+ if (!VALID_SEVERITIES.has(entry.severity)) {
44
+ return {
45
+ valid: false,
46
+ reason: `${kind} entry "${entry.id}": severity must be critical|high|medium|low`,
47
+ };
48
+ }
49
+ if (typeof entry.area !== "string" || entry.area.trim() === "") {
50
+ return { valid: false, reason: `${kind} entry "${entry.id}": missing non-empty "area"` };
51
+ }
52
+ if (typeof entry.title !== "string" || entry.title.trim() === "") {
53
+ return { valid: false, reason: `${kind} entry "${entry.id}": missing non-empty "title"` };
54
+ }
55
+ if (typeof entry.finding !== "string" || entry.finding.trim() === "") {
56
+ return { valid: false, reason: `${kind} entry "${entry.id}": missing non-empty "finding"` };
57
+ }
58
+ if (!Array.isArray(entry.evidenceRefs) || entry.evidenceRefs.length === 0) {
59
+ return {
60
+ valid: false,
61
+ reason: `${kind} entry "${entry.id}": evidenceRefs must be a non-empty array`,
62
+ };
63
+ }
64
+ if (typeof entry.suggestedAction !== "string" || entry.suggestedAction.trim() === "") {
65
+ return {
66
+ valid: false,
67
+ reason: `${kind} entry "${entry.id}": missing non-empty "suggestedAction"`,
68
+ };
69
+ }
70
+ return { valid: true };
71
+ }
72
+
73
+ /**
74
+ * Validate the full audit result returned by the premium handler.
75
+ *
76
+ * Required contract (see BK-086 controller spec section 5.2):
77
+ * - top-level audit and summary must be plain objects
78
+ * - audit.sourceMode must be in VALID_SOURCE_MODES
79
+ * - audit.readiness.score must be integer 0..100
80
+ * - audit.readiness.band must be in VALID_READINESS_BANDS
81
+ * - audit.gaps and audit.risks must be arrays
82
+ * - each gap/risk entry must satisfy validateAuditEntry
83
+ * - audit.nextSteps must be an array of plain objects
84
+ * - audit.nonClaims must be an array
85
+ * - summary.gapCount must equal audit.gaps.length
86
+ * - summary.riskCount must equal audit.risks.length
87
+ *
88
+ * @param {*} result
89
+ * @returns {{ valid: true } | { valid: false, reason: string }}
90
+ */
91
+ function validateAuditResult(result) {
92
+ if (!result || typeof result !== "object" || Array.isArray(result)) {
93
+ return { valid: false, reason: "result is not a plain object" };
94
+ }
95
+
96
+ const { audit, summary } = result;
97
+
98
+ if (!audit || typeof audit !== "object" || Array.isArray(audit)) {
99
+ return { valid: false, reason: "result.audit must be a plain object" };
100
+ }
101
+ if (!summary || typeof summary !== "object" || Array.isArray(summary)) {
102
+ return { valid: false, reason: "result.summary must be a plain object" };
103
+ }
104
+
105
+ if (!VALID_SOURCE_MODES.has(audit.sourceMode)) {
106
+ return {
107
+ valid: false,
108
+ reason: `audit.sourceMode must be one of: ${[...VALID_SOURCE_MODES].join(", ")}`,
109
+ };
110
+ }
111
+
112
+ const readiness = audit.readiness;
113
+ if (!readiness || typeof readiness !== "object" || Array.isArray(readiness)) {
114
+ return { valid: false, reason: "audit.readiness must be a plain object" };
115
+ }
116
+ if (
117
+ !Number.isInteger(readiness.score) ||
118
+ readiness.score < 0 ||
119
+ readiness.score > 100
120
+ ) {
121
+ return { valid: false, reason: "audit.readiness.score must be an integer 0..100" };
122
+ }
123
+ if (!VALID_READINESS_BANDS.has(readiness.band)) {
124
+ return {
125
+ valid: false,
126
+ reason: `audit.readiness.band must be one of: ${[...VALID_READINESS_BANDS].join(", ")}`,
127
+ };
128
+ }
129
+
130
+ if (!Array.isArray(audit.gaps)) {
131
+ return { valid: false, reason: "audit.gaps must be an array" };
132
+ }
133
+ if (!Array.isArray(audit.risks)) {
134
+ return { valid: false, reason: "audit.risks must be an array" };
135
+ }
136
+
137
+ for (const entry of audit.gaps) {
138
+ const r = validateAuditEntry("gap", entry);
139
+ if (!r.valid) return r;
140
+ }
141
+ for (const entry of audit.risks) {
142
+ const r = validateAuditEntry("risk", entry);
143
+ if (!r.valid) return r;
144
+ }
145
+
146
+ if (!Array.isArray(audit.nextSteps)) {
147
+ return { valid: false, reason: "audit.nextSteps must be an array" };
148
+ }
149
+ for (const step of audit.nextSteps) {
150
+ if (!step || typeof step !== "object" || Array.isArray(step)) {
151
+ return { valid: false, reason: "each nextStep entry must be a plain object" };
152
+ }
153
+ }
154
+
155
+ if (!Array.isArray(audit.nonClaims)) {
156
+ return { valid: false, reason: "audit.nonClaims must be an array" };
157
+ }
158
+
159
+ if (summary.gapCount !== audit.gaps.length) {
160
+ return {
161
+ valid: false,
162
+ reason: `summary.gapCount (${summary.gapCount}) does not match audit.gaps.length (${audit.gaps.length})`,
163
+ };
164
+ }
165
+ if (summary.riskCount !== audit.risks.length) {
166
+ return {
167
+ valid: false,
168
+ reason: `summary.riskCount (${summary.riskCount}) does not match audit.risks.length (${audit.risks.length})`,
169
+ };
170
+ }
171
+
172
+ return { valid: true };
173
+ }
174
+
175
+ /**
176
+ * Print bounded human-readable audit summary.
177
+ *
178
+ * Includes: source mode, readiness score/band, gap count, risk count,
179
+ * top blocking findings, and bounded next-step recommendation.
180
+ *
181
+ * @param {{ audit: object, summary: object }} result
182
+ * @param {{ projectPath: string }} context
183
+ */
184
+ function renderHumanAudit(result, context) {
185
+ const { audit, summary } = result;
186
+ const r = audit.readiness;
187
+
188
+ console.log("[project audit] Read-only audit complete.");
189
+ console.log(` Project path: ${context.projectPath}`);
190
+ console.log(` Source mode: ${audit.sourceMode}`);
191
+ console.log(` Readiness score: ${r.score}/100 (${r.band})`);
192
+ if (typeof r.blockingCount === "number") {
193
+ console.log(` Blocking issues: ${r.blockingCount}`);
194
+ }
195
+ console.log(` Gaps: ${audit.gaps.length}`);
196
+ console.log(` Risks: ${audit.risks.length}`);
197
+
198
+ if (r.rationale) {
199
+ console.log(` Rationale: ${r.rationale}`);
200
+ }
201
+
202
+ const blocking = [
203
+ ...audit.gaps.filter((g) => g.severity === "critical" || g.severity === "high"),
204
+ ...audit.risks.filter((r2) => r2.severity === "critical" || r2.severity === "high"),
205
+ ];
206
+ if (blocking.length > 0) {
207
+ console.log(" Top findings:");
208
+ for (const item of blocking.slice(0, 3)) {
209
+ console.log(` [${item.severity.toUpperCase()}] ${item.title} -- ${item.finding}`);
210
+ }
211
+ }
212
+
213
+ if (audit.nextSteps.length > 0) {
214
+ console.log(" Next steps:");
215
+ for (const step of audit.nextSteps.slice(0, 3)) {
216
+ if (step.command) {
217
+ console.log(` ${step.action}: ${step.command}`);
218
+ } else if (step.action) {
219
+ console.log(` ${step.action}`);
220
+ }
221
+ }
222
+ }
223
+
224
+ if (audit.nonClaims.length > 0) {
225
+ console.log(" Non-claims (this audit does not imply):");
226
+ for (const nc of audit.nonClaims.slice(0, 3)) {
227
+ console.log(` - ${nc}`);
228
+ }
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Execute sdtk-spec project audit premium command (read-only).
234
+ *
235
+ * Flow:
236
+ * 1. Parse flags and resolve canonical project-local read paths.
237
+ * 2. Reject the SDTK maintainer monorepo root via the target guard.
238
+ * 3. Load and verify the premium handler via loadPremiumHandler.
239
+ * 4. Determine available audit source mode from cached artifact existence.
240
+ * 5. Build bounded read-only context object.
241
+ * 6. Execute the premium handler.
242
+ * 7. Validate the returned audit-result contract.
243
+ * 8. Print human summary or deterministic JSON output.
244
+ *
245
+ * This command performs NO writes on success or failure.
246
+ *
247
+ * @param {string[]} args - Remaining argv after "project audit"
248
+ * @returns {Promise<number>} CLI exit code
249
+ */
250
+ async function runProjectAudit(args) {
251
+ const { flags } = parseFlags(args, AUDIT_FLAG_DEFS);
252
+
253
+ // 1. Resolve canonical project-local read paths (no writes)
254
+ let config;
255
+ try {
256
+ config = resolveProjectConfig(flags);
257
+ } catch (err) {
258
+ console.error(`[project audit] ${err.message}`);
259
+ return 1;
260
+ }
261
+
262
+ // 2. Reject maintainer repo root as audit target
263
+ try {
264
+ assertProjectRefreshTargetAllowed("sdtk-spec", "audit", config.projectPath);
265
+ } catch (err) {
266
+ console.error(`[project audit] ${err.message}`);
267
+ return 1;
268
+ }
269
+
270
+ // 3. Load and verify premium handler (entitlement + pack verification)
271
+ const loaderResult = await loadPremiumHandler(CAPABILITY, "projectAudit");
272
+ if (!loaderResult.ok) {
273
+ console.error(`[project audit] ${loaderResult.message}`);
274
+ return loaderResult.exitCode;
275
+ }
276
+
277
+ // 4. Determine available cached source mode (read-only existence checks)
278
+ const hasCachedFoundation = fs.existsSync(config.censusPath);
279
+ const hasStagedDocsBaseline = fs.existsSync(config.docBaselineDir);
280
+
281
+ // 5. Build bounded read-only context (no writes, canonical paths only)
282
+ const context = {
283
+ capability: CAPABILITY,
284
+ mode: "read-only-audit",
285
+ projectPath: config.projectPath,
286
+ outputDir: config.outputDir,
287
+ configPath: config.configPath,
288
+ statePath: config.statePath,
289
+ censusPath: config.censusPath,
290
+ inventoryPath: config.inventoryPath,
291
+ profilePath: config.profilePath,
292
+ moduleGraphPath: config.moduleGraphPath,
293
+ runtimeMarkersPath: config.runtimeMarkersPath,
294
+ evidencePacksDir: config.evidencePacksDir,
295
+ docBaselineDir: config.docBaselineDir,
296
+ docBaselineDocsRoot: config.docBaselineDocsRoot,
297
+ docSynthesisStatePath: config.docSynthesisStatePath,
298
+ hasCachedFoundation,
299
+ hasStagedDocsBaseline,
300
+ json: !!flags.json,
301
+ argv: args,
302
+ };
303
+
304
+ // 6. Execute premium handler
305
+ let result;
306
+ try {
307
+ result = await loaderResult.handler(context);
308
+ } catch (err) {
309
+ console.error(`[project audit] Premium pack handler error: ${err.message}`);
310
+ return 4;
311
+ }
312
+
313
+ // 7. Validate returned audit-result contract
314
+ const validation = validateAuditResult(result);
315
+ if (!validation.valid) {
316
+ console.error(
317
+ `[project audit] Premium pack output contract is invalid: ${validation.reason}`
318
+ );
319
+ return 3;
320
+ }
321
+
322
+ // 8. Print output (no writes performed)
323
+ if (flags.json) {
324
+ console.log(JSON.stringify({ audit: result.audit, summary: result.summary }));
325
+ } else {
326
+ renderHumanAudit(result, context);
327
+ }
328
+
329
+ return 0;
330
+ }
331
+
332
+ module.exports = { runProjectAudit };
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { ValidationError } = require("./errors");
6
+
7
+ const SCHEMA_VERSION = 1;
8
+
9
+ const DEFAULT_EXCLUDES = [
10
+ ".git",
11
+ ".sdtk",
12
+ "node_modules",
13
+ ".venv",
14
+ "venv",
15
+ "__pycache__",
16
+ ".pytest_cache",
17
+ "dist",
18
+ "build",
19
+ "coverage",
20
+ ".next",
21
+ ".turbo",
22
+ "target",
23
+ ];
24
+
25
+ /**
26
+ * Resolve and validate project path and output directory from parsed flags.
27
+ *
28
+ * Returns the canonical set of output paths for the .sdtk/project foundation
29
+ * and the BK-084 staged doc synthesis workspace.
30
+ *
31
+ * @param {{ "project-path"?: string, "output-dir"?: string }} flags
32
+ * @returns {{
33
+ * projectPath: string,
34
+ * outputDir: string,
35
+ * configPath: string,
36
+ * statePath: string,
37
+ * refreshStatePath: string,
38
+ * censusPath: string,
39
+ * inventoryPath: string,
40
+ * profilePath: string,
41
+ * moduleGraphPath: string,
42
+ * runtimeMarkersPath: string,
43
+ * evidencePacksDir: string,
44
+ * docBaselineDir: string,
45
+ * docBaselineDocsRoot: string,
46
+ * docSynthesisStatePath: string,
47
+ * excludes: string[],
48
+ * }}
49
+ */
50
+ function resolveProjectConfig(flags) {
51
+ const rawPath = (flags && flags["project-path"]) || process.cwd();
52
+ const projectPath = path.resolve(rawPath);
53
+
54
+ if (!fs.existsSync(projectPath) || !fs.statSync(projectPath).isDirectory()) {
55
+ throw new ValidationError(
56
+ `Invalid --project-path: "${rawPath}" is not a valid directory.`
57
+ );
58
+ }
59
+
60
+ const rawOutputDir = flags && flags["output-dir"];
61
+ const outputDir = rawOutputDir
62
+ ? path.resolve(rawOutputDir)
63
+ : path.join(projectPath, ".sdtk", "project");
64
+
65
+ const docBaselineDir = path.join(outputDir, "DOC_SYNTHESIS_BASELINE");
66
+
67
+ return {
68
+ projectPath,
69
+ outputDir,
70
+ configPath: path.join(outputDir, "config.json"),
71
+ statePath: path.join(outputDir, "INGEST_STATE.json"),
72
+ refreshStatePath: path.join(outputDir, "REFRESH_STATE.json"),
73
+ censusPath: path.join(outputDir, "PROJECT_CENSUS.json"),
74
+ inventoryPath: path.join(outputDir, "PROJECT_SOURCE_INVENTORY.json"),
75
+ profilePath: path.join(outputDir, "PROJECT_PROFILE.json"),
76
+ moduleGraphPath: path.join(outputDir, "PROJECT_MODULE_GRAPH.json"),
77
+ runtimeMarkersPath: path.join(outputDir, "PROJECT_RUNTIME_MARKERS.json"),
78
+ evidencePacksDir: path.join(outputDir, "PROJECT_EVIDENCE_PACKS"),
79
+ docBaselineDir,
80
+ docBaselineDocsRoot: path.join(docBaselineDir, "docs"),
81
+ docSynthesisStatePath: path.join(outputDir, "DOC_SYNTHESIS_STATE.json"),
82
+ excludes: DEFAULT_EXCLUDES.slice(),
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Create the output directory if it does not exist and persist config.json.
88
+ *
89
+ * @param {ReturnType<typeof resolveProjectConfig>} config
90
+ */
91
+ function writeProjectConfig(config) {
92
+ if (!fs.existsSync(config.outputDir)) {
93
+ fs.mkdirSync(config.outputDir, { recursive: true });
94
+ }
95
+ const payload = {
96
+ schemaVersion: SCHEMA_VERSION,
97
+ projectPath: config.projectPath,
98
+ outputDir: config.outputDir,
99
+ excludes: config.excludes,
100
+ };
101
+ fs.writeFileSync(config.configPath, JSON.stringify(payload, null, 2), "utf8");
102
+ }
103
+
104
+ module.exports = {
105
+ resolveProjectConfig,
106
+ writeProjectConfig,
107
+ DEFAULT_EXCLUDES,
108
+ };