@aisdlc/cli 1.0.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,2200 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command } from "commander";
5
+ import pc10 from "picocolors";
6
+
7
+ // src/commands/check.ts
8
+ import pc2 from "picocolors";
9
+ import {
10
+ checkGherkinInSync,
11
+ extractGherkinFeatures,
12
+ syncPdacDigests,
13
+ verifyArtifactsSchemas as verifyArtifactsSchemas2,
14
+ verifyLicenses as verifyLicenses2,
15
+ verifyPdacGraph as verifyPdacGraph2,
16
+ verifyQualityGate as verifyQualityGate2,
17
+ verifySast as verifySast2,
18
+ verifySecrets as verifySecrets2,
19
+ verifyTasksGovernance as verifyTasksGovernance2,
20
+ verifyTestingCoverage as verifyTestingCoverage2,
21
+ verifyTraceability as verifyTraceability2
22
+ } from "@aisdlc/core";
23
+
24
+ // src/commands/verify.ts
25
+ import pc from "picocolors";
26
+ import {
27
+ verifyArtifactDuplicates,
28
+ verifyArtifactsSchemas,
29
+ verifyLicenses,
30
+ verifyPdacGraph,
31
+ verifyProgressiveFriction,
32
+ verifyQualityGate,
33
+ verifySast,
34
+ verifySecrets,
35
+ verifyTasksGovernance,
36
+ verifyTestingCoverage,
37
+ verifyTraceability
38
+ } from "@aisdlc/core";
39
+ function isJsonOutput(options = {}) {
40
+ if (options.json !== void 0) {
41
+ return Boolean(options.json);
42
+ }
43
+ if (options.format !== void 0) {
44
+ return options.format.trim().toLowerCase() === "json";
45
+ }
46
+ const env = process.env.AISDLC_FORMAT?.trim().toLowerCase() || process.env.AISDLC_OUTPUT?.trim().toLowerCase();
47
+ return env === "json";
48
+ }
49
+ function runVerifyQuality(options = {}) {
50
+ const rootDir = options.root || process.cwd();
51
+ const useJson = isJsonOutput(options);
52
+ const isSilent = Boolean(options.silent || useJson);
53
+ if (!isSilent) {
54
+ console.log(pc.bold(pc.cyan("\n\u{1F50D} [AI-SDLC] Verifying Quality Gate (Complexity & Maintainability)...")));
55
+ }
56
+ const thresholds = {
57
+ max_cyclomatic: options.maxCyclomatic !== void 0 ? Number(options.maxCyclomatic) : void 0,
58
+ max_cognitive: options.maxCognitive !== void 0 ? Number(options.maxCognitive) : void 0,
59
+ min_maintainability: options.minMaintainability !== void 0 ? Number(options.minMaintainability) : void 0,
60
+ max_function_lines: options.maxLines !== void 0 ? Number(options.maxLines) : void 0,
61
+ enforce_mode: options.enforceMode
62
+ };
63
+ const result = verifyQualityGate({ rootDir, policyPath: options.policy, thresholds });
64
+ if (useJson) {
65
+ const violations = result.results.filter((r) => r.status === "FAIL").flatMap(
66
+ (r) => r.violations.map((v) => ({
67
+ file: r.relPath,
68
+ function: r.functionName,
69
+ metric: "quality",
70
+ message: v,
71
+ metrics: {
72
+ loc: r.loc,
73
+ cyclomatic: r.cyclomatic,
74
+ cognitive: r.cognitive,
75
+ maintainability: r.maintainability
76
+ }
77
+ }))
78
+ );
79
+ const payload = {
80
+ gate: "quality",
81
+ success: result.success,
82
+ exitCode: result.success ? 0 : 1,
83
+ summary: {
84
+ totalFiles: result.totalFiles,
85
+ totalFunctions: result.totalFunctions,
86
+ passCount: result.passCount,
87
+ failCount: result.failCount
88
+ },
89
+ violations
90
+ };
91
+ console.log(JSON.stringify(payload, null, 2));
92
+ return result.success;
93
+ }
94
+ if (!options.silent) {
95
+ console.log(
96
+ ` Active thresholds: CC <= ${result.policy.max_cyclomatic} | Cognitive <= ${result.policy.max_cognitive} | MI >= ${result.policy.min_maintainability} | Lines <= ${result.policy.max_function_lines} | Mode: ${result.policy.enforce_mode}`
97
+ );
98
+ console.log(` Analyzed files: ${pc.bold(String(result.totalFiles))}`);
99
+ console.log(` Evaluated functions: ${pc.bold(String(result.totalFunctions))}`);
100
+ console.log(` Compliant functions: ${pc.green(String(result.passCount))}`);
101
+ console.log(` Failing functions: ${result.failCount > 0 ? pc.red(String(result.failCount)) : pc.green("0")}`);
102
+ if (result.failCount > 0) {
103
+ console.log(pc.red("\n Detected violations:"));
104
+ for (const f of result.results.filter((r) => r.status === "FAIL")) {
105
+ console.log(` ${pc.red("\u2716")} ${pc.bold(f.relPath)} [${f.functionName}]: ${f.violations.join(", ")}`);
106
+ }
107
+ }
108
+ }
109
+ const isOk = result.success;
110
+ if (!options.silent) {
111
+ console.log(isOk ? pc.green("\n\u2714 Release Gate PASSED\n") : pc.red("\n\u2716 Release Gate BLOCKED\n"));
112
+ }
113
+ return isOk;
114
+ }
115
+ function runVerifyTraceability(options = {}) {
116
+ const rootDir = options.root || process.cwd();
117
+ const useJson = isJsonOutput(options);
118
+ const isSilent = Boolean(options.silent || useJson);
119
+ if (!isSilent) {
120
+ console.log(pc.bold(pc.cyan("\n\u{1F50D} [AI-SDLC] Verifying 360\xB0 Traceability (Product -> Architecture -> Testing)...")));
121
+ }
122
+ const result = verifyTraceability({ rootDir });
123
+ if (useJson) {
124
+ const payload = {
125
+ gate: "traceability",
126
+ success: result.success,
127
+ exitCode: result.success ? 0 : 1,
128
+ summary: {
129
+ totalRequirements: result.totalRequirements,
130
+ conformingCount: result.totalRequirements - result.orphanCount,
131
+ orphanCount: result.orphanCount
132
+ },
133
+ violations: result.orphans.map((o) => ({
134
+ id: o.id,
135
+ title: o.title,
136
+ productStatus: o.productStatus,
137
+ archStatus: o.archStatus,
138
+ testStatus: o.testStatus,
139
+ message: `Orphan requirement [${o.id}]`
140
+ }))
141
+ };
142
+ console.log(JSON.stringify(payload, null, 2));
143
+ return result.success;
144
+ }
145
+ if (!options.silent) {
146
+ console.log(` Total requirements: ${pc.bold(String(result.totalRequirements))}`);
147
+ console.log(` Compliant requirements: ${pc.green(String(result.totalRequirements - result.orphanCount))}`);
148
+ console.log(` Orphan requirements: ${result.orphanCount > 0 ? pc.red(String(result.orphanCount)) : pc.green("0")}`);
149
+ if (result.orphanCount > 0) {
150
+ console.log(pc.red("\n Traceability gaps:"));
151
+ for (const o of result.orphans) {
152
+ console.log(` ${pc.red("\u2716")} [${o.id}] Product: ${o.productStatus}, Architecture: ${o.archStatus}, Testing: ${o.testStatus}`);
153
+ }
154
+ }
155
+ }
156
+ const isOk = result.success;
157
+ if (!options.silent) {
158
+ console.log(isOk ? pc.green("\n\u2714 360\xB0 Traceability COMPLIANT (100%)\n") : pc.red("\n\u2716 Traceability BLOCKED\n"));
159
+ }
160
+ return isOk;
161
+ }
162
+ function runVerifyGovernance(options = {}) {
163
+ const rootDir = options.root || process.cwd();
164
+ const useJson = isJsonOutput(options);
165
+ const isSilent = Boolean(options.silent || useJson);
166
+ if (!isSilent) {
167
+ console.log(pc.bold(pc.cyan("\n\u{1F50D} [AI-SDLC] Verifying Tasks Governance and Autonomy Classification...")));
168
+ }
169
+ const result = verifyTasksGovernance({ rootDir });
170
+ if (useJson) {
171
+ const payload = {
172
+ gate: "governance",
173
+ success: result.success,
174
+ exitCode: result.success ? 0 : 1,
175
+ summary: {
176
+ totalTasks: result.totalTasks,
177
+ verifiedCount: result.verifiedCount,
178
+ unverifiedCount: result.unverifiedCount,
179
+ modeCounts: result.modeCounts,
180
+ riskCounts: result.riskCounts
181
+ },
182
+ violations: result.violations.map((v) => ({ message: v }))
183
+ };
184
+ console.log(JSON.stringify(payload, null, 2));
185
+ return result.success;
186
+ }
187
+ if (!options.silent) {
188
+ console.log(` Total audited tasks: ${pc.bold(String(result.totalTasks))}`);
189
+ console.log(` Tasks with verification: ${pc.green(String(result.verifiedCount))}`);
190
+ console.log(` Tasks without verif.: ${result.unverifiedCount > 0 ? pc.red(String(result.unverifiedCount)) : pc.green("0")}`);
191
+ console.log(` Autonomy distribution:`);
192
+ console.log(` \u{1F7E2} AUTONOMOUS: ${result.modeCounts["AUTONOMOUS"] || 0}`);
193
+ console.log(` \u{1F7E1} HUMAN_REVIEW_PLAN: ${result.modeCounts["HUMAN_REVIEW_PLAN"] || 0}`);
194
+ console.log(` \u{1F7E0} AMBIGUOUS: ${result.modeCounts["AMBIGUOUS"] || 0}`);
195
+ console.log(` \u{1F534} HIGH_RISK_MANUAL: ${result.modeCounts["HIGH_RISK_MANUAL"] || 0}`);
196
+ if (result.violations.length > 0) {
197
+ console.log(pc.red("\n Governance violations:"));
198
+ for (const v of result.violations) {
199
+ console.log(` ${pc.red("\u2716")} ${v}`);
200
+ }
201
+ }
202
+ }
203
+ const isOk = result.success;
204
+ if (!options.silent) {
205
+ console.log(isOk ? pc.green("\n\u2714 Tasks Governance COMPLIANT\n") : pc.red("\n\u2716 Tasks Governance BLOCKED\n"));
206
+ }
207
+ return isOk;
208
+ }
209
+ function runVerifyTesting(options = {}) {
210
+ const rootDir = options.root || process.cwd();
211
+ const useJson = isJsonOutput(options);
212
+ const isSilent = Boolean(options.silent || useJson);
213
+ if (!isSilent) {
214
+ console.log(pc.bold(pc.cyan("\n\u{1F50D} [AI-SDLC] Verifying Test Coverage in Requirements and Tasks...")));
215
+ }
216
+ const result = verifyTestingCoverage({ rootDir });
217
+ if (useJson) {
218
+ const reqViolations = result.requirements.filter((r) => r.status !== "VERIFICADO_CON_PRUEBA").map((r) => ({
219
+ type: "REQUIREMENT",
220
+ id: r.id,
221
+ title: r.title,
222
+ file: r.file,
223
+ message: `Requirement without verifiable test [${r.id}]`
224
+ }));
225
+ const taskViolations = result.tasks.filter((t) => t.status !== "VERIFICADO_CON_PRUEBA").map((t) => ({
226
+ type: "TASK",
227
+ id: t.id,
228
+ title: t.title,
229
+ file: t.file,
230
+ message: `Task without test verification [${t.id}]`
231
+ }));
232
+ const payload = {
233
+ gate: "testing",
234
+ success: result.success,
235
+ exitCode: result.success ? 0 : 1,
236
+ summary: {
237
+ totalRequirements: result.totalRequirements,
238
+ passedRequirements: result.passedRequirements,
239
+ failedRequirements: result.failedRequirements,
240
+ totalTasks: result.totalTasks,
241
+ passedTasks: result.passedTasks,
242
+ failedTasks: result.failedTasks
243
+ },
244
+ violations: [...reqViolations, ...taskViolations]
245
+ };
246
+ console.log(JSON.stringify(payload, null, 2));
247
+ return result.success;
248
+ }
249
+ if (!options.silent) {
250
+ console.log(` Verified requirements: ${pc.green(`${result.passedRequirements}/${result.totalRequirements}`)}`);
251
+ console.log(` Verified tasks: ${pc.green(`${result.passedTasks}/${result.totalTasks}`)}`);
252
+ if (result.failedRequirements > 0 || result.failedTasks > 0) {
253
+ console.log(pc.red("\n Items lacking executable tests:"));
254
+ for (const r of result.requirements.filter((r2) => r2.status !== "VERIFICADO_CON_PRUEBA")) {
255
+ console.log(` ${pc.red("\u2716")} [Requirement: ${r.id}] ${r.title} (${r.file})`);
256
+ }
257
+ for (const t of result.tasks.filter((t2) => t2.status !== "VERIFICADO_CON_PRUEBA")) {
258
+ console.log(` ${pc.red("\u2716")} [Task: ${t.id}] ${t.title} (${t.file})`);
259
+ }
260
+ }
261
+ }
262
+ const isOk = result.success;
263
+ if (!options.silent) {
264
+ console.log(isOk ? pc.green("\n\u2714 Test Coverage COMPLIANT (100%)\n") : pc.red("\n\u2716 Test Coverage INSUFFICIENT\n"));
265
+ }
266
+ return isOk;
267
+ }
268
+ function runVerifyLicenses(options = {}) {
269
+ const rootDir = options.root || process.cwd();
270
+ const useJson = isJsonOutput(options);
271
+ const isSilent = Boolean(options.silent || useJson);
272
+ if (!isSilent) {
273
+ console.log(pc.bold(pc.cyan("\n\u{1F50D} [AI-SDLC] Verifying Open Source License Compliance (SCA)...")));
274
+ }
275
+ const sbomPath = typeof options.sbom === "string" ? options.sbom : void 0;
276
+ const generateSbom = options.sbom !== void 0 ? Boolean(options.sbom) : void 0;
277
+ const noticesPath = typeof options.notices === "string" ? options.notices : void 0;
278
+ const generateNotices = options.notices !== void 0 ? Boolean(options.notices) : void 0;
279
+ const result = verifyLicenses({
280
+ rootDir,
281
+ policyPath: options.policy,
282
+ manifestPath: options.manifest,
283
+ dynamic: options.dynamic,
284
+ tool: options.tool,
285
+ depth: options.depth,
286
+ generateSbom,
287
+ sbomPath,
288
+ generateNotices,
289
+ noticesPath
290
+ });
291
+ if (useJson) {
292
+ const payload = {
293
+ gate: "licenses",
294
+ success: result.success,
295
+ exitCode: result.success ? 0 : 1,
296
+ summary: {
297
+ totalEvaluated: result.totalEvaluated,
298
+ permittedCount: result.permittedCount,
299
+ violationsCount: result.violations.length
300
+ },
301
+ violations: result.violations.map((v) => ({
302
+ package: v.packageName,
303
+ version: v.version,
304
+ license: v.license,
305
+ category: v.category,
306
+ message: v.reason
307
+ })),
308
+ artifacts: {
309
+ sbomPath: result.sbomPath,
310
+ noticesPath: result.noticesPath
311
+ }
312
+ };
313
+ console.log(JSON.stringify(payload, null, 2));
314
+ return result.success;
315
+ }
316
+ if (!options.silent) {
317
+ console.log(` Evaluated dependencies: ${pc.bold(String(result.totalEvaluated))}`);
318
+ console.log(` Compliant dependencies: ${pc.green(String(result.permittedCount))}`);
319
+ console.log(` License violations: ${result.violations.length > 0 ? pc.red(String(result.violations.length)) : pc.green("0")}`);
320
+ if (result.sbomPath) {
321
+ console.log(` CycloneDX SBOM generated: ${pc.cyan(result.sbomPath)}`);
322
+ }
323
+ if (result.noticesPath) {
324
+ console.log(` Legal notices generated: ${pc.cyan(result.noticesPath)}`);
325
+ }
326
+ if (result.violations.length > 0) {
327
+ console.log(pc.red("\n Detected license violations:"));
328
+ for (const v of result.violations) {
329
+ console.log(` ${pc.red("\u2716")} [${v.category}] ${v.packageName} (${v.license}): ${v.reason}`);
330
+ }
331
+ }
332
+ }
333
+ const isOk = result.success;
334
+ if (!options.silent) {
335
+ console.log(isOk ? pc.green("\n\u2714 OSS License Governance COMPLIANT\n") : pc.red("\n\u2716 OSS License Governance BLOCKED\n"));
336
+ }
337
+ return isOk;
338
+ }
339
+ function runVerifyPdac(options = {}) {
340
+ const rootDir = options.root || process.cwd();
341
+ const useJson = isJsonOutput(options);
342
+ const isSilent = Boolean(options.silent || useJson);
343
+ if (!isSilent) {
344
+ console.log(pc.bold(pc.cyan("\n\u{1F50D} [AI-SDLC] Verifying PDaC Graph and Cryptographic Drift (SHA-256)...")));
345
+ }
346
+ const result = verifyPdacGraph({ rootDir });
347
+ if (useJson) {
348
+ const payload = {
349
+ gate: "pdac",
350
+ success: result.success,
351
+ exitCode: result.success ? 0 : 1,
352
+ summary: {
353
+ totalNodes: result.totalNodes,
354
+ totalEdges: result.totalEdges,
355
+ driftCount: result.drifts.length
356
+ },
357
+ violations: result.drifts.map((d) => ({
358
+ sourceId: d.sourceId,
359
+ targetId: d.targetId,
360
+ sourceFile: d.sourceFile,
361
+ expectedDigest: d.expectedDigest,
362
+ actualDigest: d.actualDigest,
363
+ message: `Cryptographic drift in ${d.sourceFile} citing ${d.targetId}`
364
+ }))
365
+ };
366
+ console.log(JSON.stringify(payload, null, 2));
367
+ return result.success;
368
+ }
369
+ if (!options.silent) {
370
+ console.log(` PDaC baseline nodes: ${pc.bold(String(result.totalNodes))}`);
371
+ console.log(` Evaluated citations: ${pc.bold(String(result.totalEdges))}`);
372
+ console.log(` Cryptographic drifts: ${result.drifts.length > 0 ? pc.red(String(result.drifts.length)) : pc.green("0")}`);
373
+ if (result.drifts.length > 0) {
374
+ console.log(pc.red("\n Detected drifts (Status: STALE):"));
375
+ for (const d of result.drifts) {
376
+ console.log(` ${pc.red("\u2716")} In ${d.sourceFile} citing ${d.targetId}: misaligned digest.`);
377
+ }
378
+ }
379
+ }
380
+ const isOk = result.success;
381
+ if (!options.silent) {
382
+ console.log(isOk ? pc.green("\n\u2714 PDaC Graph Free of Drift\n") : pc.red("\n\u2716 Cryptographic Drift Detected\n"));
383
+ }
384
+ return isOk;
385
+ }
386
+ function runVerifySchemas(options = {}) {
387
+ const rootDir = options.root || process.cwd();
388
+ const useJson = isJsonOutput(options);
389
+ const isSilent = Boolean(options.silent || useJson);
390
+ if (!isSilent) {
391
+ console.log(pc.bold(pc.cyan("\n\u{1F50D} [AI-SDLC] Verifying JSON Schemas Compliance (Draft 2020-12)...")));
392
+ }
393
+ const result = verifyArtifactsSchemas({ rootDir, targetPath: options.path });
394
+ if (useJson) {
395
+ const payload = {
396
+ gate: "schemas",
397
+ success: result.success,
398
+ exitCode: result.success ? 0 : 1,
399
+ summary: {
400
+ totalEvaluated: result.totalEvaluated,
401
+ validCount: result.validCount,
402
+ invalidCount: result.invalidCount
403
+ },
404
+ violations: result.violations.map((v) => ({
405
+ file: v.filePath,
406
+ id: v.id,
407
+ schemaId: v.schemaId,
408
+ property: v.property,
409
+ message: v.message
410
+ }))
411
+ };
412
+ console.log(JSON.stringify(payload, null, 2));
413
+ return result.success;
414
+ }
415
+ if (!options.silent) {
416
+ console.log(` Evaluated artifacts: ${pc.bold(String(result.totalEvaluated))}`);
417
+ console.log(` Compliant artifacts: ${pc.green(String(result.validCount))}`);
418
+ console.log(` Schema violations: ${result.invalidCount > 0 ? pc.red(String(result.invalidCount)) : pc.green("0")}`);
419
+ if (result.violations.length > 0) {
420
+ console.log(pc.red("\n Detected JSON schema violations:"));
421
+ for (const v of result.violations) {
422
+ console.log(` ${pc.red("\u2716")} [${v.id || v.filePath}] (${v.schemaId || "schema"}): ${v.message}`);
423
+ }
424
+ }
425
+ }
426
+ const isOk = result.success;
427
+ if (!options.silent) {
428
+ console.log(isOk ? pc.green("\n\u2714 Artifact Schemas COMPLIANT (100%)\n") : pc.red("\n\u2716 Artifact Schemas BLOCKED\n"));
429
+ }
430
+ return isOk;
431
+ }
432
+ function runVerifyFriction(options = {}) {
433
+ const rootDir = options.root || process.cwd();
434
+ const useJson = isJsonOutput(options);
435
+ const isSilent = Boolean(options.silent || useJson);
436
+ if (!isSilent) {
437
+ console.log(pc.bold(pc.cyan("\n\u{1F6E1}\uFE0F [AI-SDLC] Verifying Progressive Friction and Anti-Bypass Guardrails...")));
438
+ }
439
+ const result = verifyProgressiveFriction({
440
+ rootDir,
441
+ changeId: options.change,
442
+ diffFiles: options.diffFiles
443
+ });
444
+ if (useJson) {
445
+ const violations = [
446
+ ...result.bypassedRules.map((rule) => ({ type: "ANTI_BYPASS", message: rule })),
447
+ ...result.errors.map((err) => ({ type: "PROFILE_ERROR", message: err }))
448
+ ];
449
+ const payload = {
450
+ gate: "friction",
451
+ success: result.success,
452
+ exitCode: result.success ? 0 : 1,
453
+ summary: {
454
+ profile: result.profile,
455
+ evaluatedFilesCount: result.evaluatedFiles.length,
456
+ bypassed: result.bypassed
457
+ },
458
+ violations
459
+ };
460
+ console.log(JSON.stringify(payload, null, 2));
461
+ return result.success;
462
+ }
463
+ if (!options.silent) {
464
+ console.log(` Detected profile: ${pc.magenta(result.profile)}`);
465
+ console.log(` Evaluated files: ${pc.bold(String(result.evaluatedFiles.length))}`);
466
+ if (result.bypassedRules.length > 0) {
467
+ console.log(pc.red("\n Anti-Bypass violations detected:"));
468
+ for (const rule of result.bypassedRules) {
469
+ console.log(` ${pc.red("\u2716")} ${rule}`);
470
+ }
471
+ }
472
+ if (result.errors.length > 0) {
473
+ console.log(pc.red("\n Profile validation errors:"));
474
+ for (const err of result.errors) {
475
+ console.log(` ${pc.red("\u2716")} ${err}`);
476
+ }
477
+ }
478
+ }
479
+ const isOk = result.success;
480
+ if (!options.silent) {
481
+ console.log(
482
+ isOk ? pc.green("\n\u2714 Progressive Friction COMPLIANT (EXIT 0)\n") : pc.red("\n\u2716 Progressive Friction BLOCKED (EXIT 1)\n")
483
+ );
484
+ }
485
+ return isOk;
486
+ }
487
+ function runVerifyDuplicates(options = {}) {
488
+ const rootDir = options.root || process.cwd();
489
+ const similarityThreshold = options.similarity !== void 0 ? Number(options.similarity) : void 0;
490
+ const useJson = isJsonOutput(options);
491
+ const isSilent = Boolean(options.silent || useJson);
492
+ if (!isSilent) {
493
+ console.log(
494
+ pc.bold(
495
+ pc.cyan(
496
+ "\n\u{1F50D} [AI-SDLC] Verifying Duplicate Requirements and Redundancy (Shift-Left Pre-Flight)..."
497
+ )
498
+ )
499
+ );
500
+ }
501
+ const result = verifyArtifactDuplicates({
502
+ rootDir,
503
+ titleSimilarityThreshold: similarityThreshold
504
+ });
505
+ if (useJson) {
506
+ const payload = {
507
+ gate: "duplicates",
508
+ success: result.success,
509
+ exitCode: result.success ? 0 : 1,
510
+ summary: {
511
+ totalRequirements: result.totalRequirements,
512
+ errorCount: result.errorCount,
513
+ warningCount: result.warningCount
514
+ },
515
+ violations: result.issues.map((i) => ({
516
+ type: i.type,
517
+ severity: i.severity,
518
+ id: i.id,
519
+ file: i.file,
520
+ conflictingId: i.conflictingId,
521
+ message: i.message
522
+ }))
523
+ };
524
+ console.log(JSON.stringify(payload, null, 2));
525
+ return result.success;
526
+ }
527
+ if (!options.silent) {
528
+ console.log(` Evaluated requirements: ${pc.bold(String(result.totalRequirements))}`);
529
+ console.log(
530
+ ` Duplication errors: ${result.errorCount > 0 ? pc.red(String(result.errorCount)) : pc.green("0")}`
531
+ );
532
+ console.log(
533
+ ` Warnings: ${result.warningCount > 0 ? pc.yellow(String(result.warningCount)) : pc.green("0")}`
534
+ );
535
+ if (result.issues.length > 0) {
536
+ console.log(pc.red("\n Detected issues:"));
537
+ for (const issue of result.issues) {
538
+ const icon = issue.severity === "ERROR" ? pc.red("\u2716") : pc.yellow("\u26A0");
539
+ const badge = issue.severity === "ERROR" ? pc.red(`[${issue.type}]`) : pc.yellow(`[${issue.type}]`);
540
+ console.log(` ${icon} ${badge} [${issue.id}] in ${issue.file}: ${issue.message}`);
541
+ }
542
+ }
543
+ }
544
+ const isOk = result.success;
545
+ if (!options.silent) {
546
+ console.log(
547
+ isOk ? pc.green("\n\u2714 Duplicates Verification COMPLIANT (0 Collisions)\n") : pc.red("\n\u2716 Duplicates Verification BLOCKED (Collisions Detected)\n")
548
+ );
549
+ }
550
+ return isOk;
551
+ }
552
+ function runVerifySecrets(options = {}) {
553
+ const rootDir = options.root || process.cwd();
554
+ const entropyThreshold = options.entropy !== void 0 ? Number(options.entropy) : void 0;
555
+ const useJson = isJsonOutput(options);
556
+ const isSilent = Boolean(options.silent || useJson);
557
+ if (!isSilent) {
558
+ console.log(
559
+ pc.bold(
560
+ pc.cyan(
561
+ "\n\u{1F510} [AI-SDLC] Verifying Deterministic Secrets and Credentials Detection (Gitleaks Gate)..."
562
+ )
563
+ )
564
+ );
565
+ }
566
+ const result = verifySecrets({
567
+ rootDir,
568
+ diff: options.diff,
569
+ baseBranch: options.base,
570
+ gitleaks: options.gitleaks,
571
+ entropyThreshold
572
+ });
573
+ if (useJson) {
574
+ const payload = {
575
+ gate: "secrets",
576
+ success: result.success,
577
+ exitCode: result.success ? 0 : 4,
578
+ summary: {
579
+ totalFilesScanned: result.totalFilesScanned,
580
+ findingsCount: result.findingsCount,
581
+ scannedWithGitleaks: result.scannedWithGitleaks
582
+ },
583
+ violations: result.findings.map((f) => ({
584
+ ruleId: f.ruleId,
585
+ file: f.relPath,
586
+ line: f.lineNumber,
587
+ type: f.type,
588
+ maskedMatch: f.maskedMatch,
589
+ message: f.message
590
+ }))
591
+ };
592
+ console.log(JSON.stringify(payload, null, 2));
593
+ return result.success;
594
+ }
595
+ if (!options.silent) {
596
+ console.log(` Analyzed files: ${pc.bold(String(result.totalFilesScanned))}`);
597
+ console.log(
598
+ ` Credential leaks: ${result.findingsCount > 0 ? pc.red(String(result.findingsCount)) : pc.green("0")}`
599
+ );
600
+ console.log(
601
+ ` Native Gitleaks engine: ${result.scannedWithGitleaks ? pc.cyan("Active / Integrated") : pc.dim("Deterministic Scanner (@aisdlc/core)")}`
602
+ );
603
+ if (result.findings.length > 0) {
604
+ console.log(pc.red("\n Detected exposed credentials:"));
605
+ for (const f of result.findings) {
606
+ console.log(
607
+ ` ${pc.red("\u2716")} [${f.ruleId}] ${pc.bold(`${f.relPath}:${f.lineNumber}`)}: ${f.maskedMatch} - ${f.message}`
608
+ );
609
+ }
610
+ }
611
+ }
612
+ const isOk = result.success;
613
+ if (!options.silent) {
614
+ console.log(
615
+ isOk ? pc.green("\n\u2714 Secrets Detection COMPLIANT (0 Credential Leaks)\n") : pc.red("\n\u2716 Secrets Detection BLOCKED (Exit Code 4: Exposed Secret)\n")
616
+ );
617
+ }
618
+ return isOk;
619
+ }
620
+ function runVerifySast(options = {}) {
621
+ const rootDir = options.root || process.cwd();
622
+ const useJson = isJsonOutput(options);
623
+ const isSilent = Boolean(options.silent || useJson);
624
+ if (!isSilent) {
625
+ console.log(
626
+ pc.bold(
627
+ pc.cyan(
628
+ "\n\u{1F6E1}\uFE0F [AI-SDLC] Verifying Shift-Left SAST Security (Injections & OWASP Top 10)..."
629
+ )
630
+ )
631
+ );
632
+ }
633
+ const result = verifySast({
634
+ rootDir,
635
+ semgrep: options.semgrep,
636
+ minSeverity: options.minSeverity
637
+ });
638
+ if (useJson) {
639
+ const payload = {
640
+ gate: "sast",
641
+ success: result.success,
642
+ exitCode: result.success ? 0 : 1,
643
+ summary: {
644
+ totalFilesScanned: result.totalFilesScanned,
645
+ violationsCount: result.violationsCount
646
+ },
647
+ violations: result.violations.map((v) => ({
648
+ ruleId: v.ruleId,
649
+ file: v.relPath,
650
+ line: v.lineNumber,
651
+ type: v.type,
652
+ severity: v.severity,
653
+ message: v.message
654
+ }))
655
+ };
656
+ console.log(JSON.stringify(payload, null, 2));
657
+ return result.success;
658
+ }
659
+ if (!options.silent) {
660
+ console.log(` Evaluated files: ${pc.bold(String(result.totalFilesScanned))}`);
661
+ console.log(
662
+ ` SAST vulnerabilities: ${result.violationsCount > 0 ? pc.red(String(result.violationsCount)) : pc.green("0")}`
663
+ );
664
+ if (result.violations.length > 0) {
665
+ console.log(pc.red("\n Detected vulnerabilities:"));
666
+ for (const v of result.violations) {
667
+ console.log(
668
+ ` ${pc.red("\u2716")} [${v.severity}] [${v.ruleId}] ${pc.bold(`${v.relPath}:${v.lineNumber}`)}: ${v.message}`
669
+ );
670
+ }
671
+ }
672
+ }
673
+ const isOk = result.success;
674
+ if (!options.silent) {
675
+ console.log(
676
+ isOk ? pc.green("\n\u2714 SAST Analysis COMPLIANT (0 Critical Vulnerabilities)\n") : pc.red("\n\u2716 SAST Analysis BLOCKED (Vulnerabilities Detected)\n")
677
+ );
678
+ }
679
+ return isOk;
680
+ }
681
+ function runVerifySecurity(options = {}) {
682
+ const rootDir = options.root || process.cwd();
683
+ const useJson = isJsonOutput(options);
684
+ const entropyThreshold = options.entropy !== void 0 ? Number(options.entropy) : void 0;
685
+ const resultSecrets = verifySecrets({
686
+ rootDir,
687
+ diff: options.diff,
688
+ baseBranch: options.base,
689
+ gitleaks: options.gitleaks,
690
+ entropyThreshold
691
+ });
692
+ const resultSast = verifySast({
693
+ rootDir,
694
+ semgrep: options.semgrep,
695
+ minSeverity: options.minSeverity
696
+ });
697
+ const okSecrets = resultSecrets.success;
698
+ const okSast = resultSast.success;
699
+ const isOk = okSecrets && okSast;
700
+ if (useJson) {
701
+ const exitCode = isOk ? 0 : !okSecrets ? 4 : 1;
702
+ const payload = {
703
+ gate: "security",
704
+ success: isOk,
705
+ exitCode,
706
+ summary: {
707
+ secretsScanned: resultSecrets.totalFilesScanned,
708
+ secretFindings: resultSecrets.findingsCount,
709
+ sastScanned: resultSast.totalFilesScanned,
710
+ sastViolations: resultSast.violationsCount
711
+ },
712
+ violations: [
713
+ ...resultSecrets.findings.map((f) => ({
714
+ type: "SECRET",
715
+ ruleId: f.ruleId,
716
+ file: f.relPath,
717
+ line: f.lineNumber,
718
+ message: f.message
719
+ })),
720
+ ...resultSast.violations.map((v) => ({
721
+ type: "SAST",
722
+ ruleId: v.ruleId,
723
+ file: v.relPath,
724
+ line: v.lineNumber,
725
+ severity: v.severity,
726
+ message: v.message
727
+ }))
728
+ ]
729
+ };
730
+ console.log(JSON.stringify(payload, null, 2));
731
+ return isOk;
732
+ }
733
+ const okS = runVerifySecrets({ ...options, silent: options.silent });
734
+ const okA = runVerifySast({ ...options, silent: options.silent });
735
+ return okS && okA;
736
+ }
737
+ function runVerifyAll(options = {}) {
738
+ const useJson = isJsonOutput(options);
739
+ const isSilent = Boolean(options.silent || useJson);
740
+ if (!isSilent) {
741
+ console.log(pc.bold(pc.magenta("================================================================")));
742
+ console.log(pc.bold(pc.magenta(" AI-SDLC: FULL QUALITY GATES AND GOVERNANCE SUITE ")));
743
+ console.log(pc.bold(pc.magenta("================================================================")));
744
+ }
745
+ const root = options.root || process.cwd();
746
+ const okQuality = runVerifyQuality({ ...options, root, silent: isSilent, json: false });
747
+ const okTrace = runVerifyTraceability({ root, silent: isSilent, json: false });
748
+ const okGov = runVerifyGovernance({ root, silent: isSilent, json: false });
749
+ const okTest = runVerifyTesting({ root, silent: isSilent, json: false });
750
+ const okLic = runVerifyLicenses({ root, silent: isSilent, json: false });
751
+ const okPdac = runVerifyPdac({ root, silent: isSilent, json: false });
752
+ const okSchemas = runVerifySchemas({ root, silent: isSilent, json: false });
753
+ const okDuplicates = runVerifyDuplicates({ root, silent: isSilent, json: false });
754
+ const okSecurity = runVerifySecurity({ root, silent: isSilent, json: false });
755
+ const allPassed = okQuality && okTrace && okGov && okTest && okLic && okPdac && okSchemas && okDuplicates && okSecurity;
756
+ if (useJson) {
757
+ const gatesSummary = {
758
+ quality: { success: okQuality },
759
+ traceability: { success: okTrace },
760
+ governance: { success: okGov },
761
+ testing: { success: okTest },
762
+ licenses: { success: okLic },
763
+ pdac: { success: okPdac },
764
+ schemas: { success: okSchemas },
765
+ duplicates: { success: okDuplicates },
766
+ security: { success: okSecurity }
767
+ };
768
+ const passedCount = Object.values(gatesSummary).filter((g) => g.success).length;
769
+ const failedCount = 9 - passedCount;
770
+ const exitCode = allPassed ? 0 : !okSecurity ? 4 : 1;
771
+ const violations = Object.entries(gatesSummary).filter(([, g]) => !g.success).map(([name]) => ({ gate: name, message: `Gate ${name} failed verification criteria` }));
772
+ const payload = {
773
+ gate: "all",
774
+ success: allPassed,
775
+ exitCode,
776
+ summary: {
777
+ totalGates: 9,
778
+ passedGates: passedCount,
779
+ failedGates: failedCount
780
+ },
781
+ gates: gatesSummary,
782
+ violations
783
+ };
784
+ console.log(JSON.stringify(payload, null, 2));
785
+ return allPassed;
786
+ }
787
+ if (!options.silent) {
788
+ console.log(pc.bold(pc.magenta("================================================================")));
789
+ console.log(pc.bold("CI/CD EVALUATION SUMMARY:"));
790
+ console.log(` 1. Quality Gate (Complexity/Maintainability): ${okQuality ? pc.green("PASSED") : pc.red("FAILED")}`);
791
+ console.log(` 2. 360\xB0 Traceability (RTM): ${okTrace ? pc.green("PASSED") : pc.red("FAILED")}`);
792
+ console.log(` 3. Governance and Autonomy Modes: ${okGov ? pc.green("PASSED") : pc.red("FAILED")}`);
793
+ console.log(` 4. Test Coverage (Reqs & Tasks): ${okTest ? pc.green("PASSED") : pc.red("FAILED")}`);
794
+ console.log(` 5. Open Source Licenses: ${okLic ? pc.green("PASSED") : pc.red("FAILED")}`);
795
+ console.log(` 6. PDaC & Cryptographic Drift: ${okPdac ? pc.green("PASSED") : pc.red("FAILED")}`);
796
+ console.log(` 7. Artifact JSON Schemas: ${okSchemas ? pc.green("PASSED") : pc.red("FAILED")}`);
797
+ console.log(` 8. Duplicate Requirements (Shift-Left Gate): ${okDuplicates ? pc.green("PASSED") : pc.red("FAILED")}`);
798
+ console.log(` 9. Shift-Left Security (Secrets & SAST): ${okSecurity ? pc.green("PASSED") : pc.red("FAILED")}`);
799
+ console.log(pc.bold(pc.magenta("================================================================")));
800
+ if (allPassed) {
801
+ console.log(pc.bold(pc.green("\n\u2728 FINAL VERDICT: REPOSITORY COMPLIANT WITH AI-SDLC STANDARD (EXIT 0)\n")));
802
+ } else {
803
+ console.log(pc.bold(pc.red("\n\u26D4 FINAL VERDICT: BLOCKED BY DETECTED VIOLATIONS (EXIT 1)\n")));
804
+ }
805
+ }
806
+ return allPassed;
807
+ }
808
+
809
+ // src/commands/check.ts
810
+ function runAutoFix(rootDir, silent) {
811
+ const gherkinRes = extractGherkinFeatures({ rootDir });
812
+ const pdacRes = syncPdacDigests({ rootDir });
813
+ if (!silent) {
814
+ if (gherkinRes.features.length > 0) {
815
+ console.log(` ${pc2.cyan("\u{1F527} [AUTO-FIX]")} Synchronized ${pc2.bold(String(gherkinRes.features.length))} .feature files (${gherkinRes.totalScenarios} scenarios).`);
816
+ }
817
+ if (pdacRes.syncedCount > 0) {
818
+ console.log(` ${pc2.cyan("\u{1F527} [AUTO-FIX]")} Synchronized ${pc2.bold(String(pdacRes.syncedCount))} SHA-256 digests across ${pdacRes.updatedFiles.length} files.`);
819
+ }
820
+ }
821
+ return { gherkinCount: gherkinRes.features.length, digestsCount: pdacRes.syncedCount };
822
+ }
823
+ function auditGherkinGate(rootDir, wasAutoFixed) {
824
+ const syncCheck = checkGherkinInSync({ rootDir });
825
+ if (wasAutoFixed) {
826
+ return {
827
+ name: "BDD Synchronization (Gherkin -> .feature)",
828
+ status: "FIXED",
829
+ message: `${syncCheck.totalFeatures} specifications automatically synchronized`
830
+ };
831
+ }
832
+ if (!syncCheck.inSync) {
833
+ const totalOut = syncCheck.missingFiles.length + syncCheck.outOfSyncFiles.length;
834
+ return {
835
+ name: "BDD Synchronization (Gherkin -> .feature)",
836
+ status: "FAILED",
837
+ message: `${totalOut} out-of-sync or missing .feature file(s)`,
838
+ remediation: "Run 'aisdlc check --fix' to extract and regenerate .feature files."
839
+ };
840
+ }
841
+ return {
842
+ name: "BDD Synchronization (Gherkin -> .feature)",
843
+ status: "PASSED",
844
+ message: `${syncCheck.totalFeatures} specifications up to date on disk`
845
+ };
846
+ }
847
+ function auditPdacGate(rootDir, wasAutoFixed) {
848
+ const res = verifyPdacGraph2({ rootDir });
849
+ if (res.success) {
850
+ return {
851
+ name: "PDaC Integrity & SHA-256 Drift",
852
+ status: wasAutoFixed ? "FIXED" : "PASSED",
853
+ message: `${res.totalNodes} nodes and ${res.totalEdges} citations cryptographically aligned`
854
+ };
855
+ }
856
+ return {
857
+ name: "PDaC Integrity & SHA-256 Drift",
858
+ status: "FAILED",
859
+ message: `${res.drifts.length} digest drift(s) detected (STALE)`,
860
+ remediation: "Run 'aisdlc check --fix' to automatically synchronize citation digests."
861
+ };
862
+ }
863
+ function auditQualityGate(rootDir) {
864
+ const res = verifyQualityGate2({ rootDir });
865
+ if (res.success) {
866
+ return {
867
+ name: "Quality Gate (Complexity & Maintainability)",
868
+ status: "PASSED",
869
+ message: `${res.passCount}/${res.totalFunctions} compliant functions (CC <= 10, LOC <= 40)`
870
+ };
871
+ }
872
+ const firstFail = res.results.find((r) => r.status === "FAIL");
873
+ const detail = firstFail ? ` (e.g. ${firstFail.functionName}: ${firstFail.violations.join(", ")})` : "";
874
+ return {
875
+ name: "Quality Gate (Complexity & Maintainability)",
876
+ status: "FAILED",
877
+ message: `${res.failCount} function(s) exceed quality thresholds${detail}`,
878
+ remediation: "Refactor offending functions by reducing conditional branches and lines of code."
879
+ };
880
+ }
881
+ function auditTraceabilityGate(rootDir) {
882
+ const res = verifyTraceability2({ rootDir });
883
+ if (res.success) {
884
+ return {
885
+ name: "360\xB0 Traceability (Reverse RTM)",
886
+ status: "PASSED",
887
+ message: `${res.totalRequirements} requirements with 360\xB0 coverage (0 orphans)`
888
+ };
889
+ }
890
+ const orphanIds = res.orphans.map((o) => o.id).slice(0, 3).join(", ");
891
+ return {
892
+ name: "360\xB0 Traceability (Reverse RTM)",
893
+ status: "FAILED",
894
+ message: `${res.orphanCount} orphan requirement(s) (${orphanIds})`,
895
+ remediation: "Link orphan requirements to their components in arc42 or test suites."
896
+ };
897
+ }
898
+ function auditGovernanceGate(rootDir) {
899
+ const res = verifyTasksGovernance2({ rootDir });
900
+ if (res.success) {
901
+ return {
902
+ name: "Tasks Governance & Autonomy Classification",
903
+ status: "PASSED",
904
+ message: `${res.totalTasks} tasks audited and compliant with autonomy modes`
905
+ };
906
+ }
907
+ return {
908
+ name: "Tasks Governance & Autonomy Classification",
909
+ status: "FAILED",
910
+ message: `${res.violations.length} governance violation(s) detected`,
911
+ remediation: "Review tasks.md to assign verifiable criteria and valid autonomy modes."
912
+ };
913
+ }
914
+ function auditTestingGate(rootDir) {
915
+ const res = verifyTestingCoverage2({ rootDir });
916
+ if (res.success) {
917
+ return {
918
+ name: "Test Coverage in Requirements & Tasks",
919
+ status: "PASSED",
920
+ message: `${res.passedRequirements}/${res.totalRequirements} reqs and ${res.passedTasks}/${res.totalTasks} tasks verified`
921
+ };
922
+ }
923
+ return {
924
+ name: "Test Coverage in Requirements & Tasks",
925
+ status: "FAILED",
926
+ message: `${res.failedRequirements} req(s) and ${res.failedTasks} task(s) without verifiable tests`,
927
+ remediation: "Add executable tests (.spec or .feature) for pending requirements and tasks."
928
+ };
929
+ }
930
+ function auditLicensesGate(rootDir) {
931
+ const res = verifyLicenses2({ rootDir });
932
+ if (res.success) {
933
+ return {
934
+ name: "Open Source License Governance",
935
+ status: "PASSED",
936
+ message: `${res.permittedCount} dependencies compliant with license-policy.yaml`
937
+ };
938
+ }
939
+ const badPkgs = res.violations.map((v) => `${v.packageName} (${v.license})`).slice(0, 2).join(", ");
940
+ return {
941
+ name: "Open Source License Governance",
942
+ status: "FAILED",
943
+ message: `${res.violations.length} prohibited license(s) detected: ${badPkgs}`,
944
+ remediation: "Replace packages with restricted licenses or request approval in license-policy.yaml."
945
+ };
946
+ }
947
+ function auditSchemasGate(rootDir) {
948
+ const res = verifyArtifactsSchemas2({ rootDir });
949
+ if (res.success) {
950
+ return {
951
+ name: "JSON Schemas Compliance (Draft 2020-12)",
952
+ status: "PASSED",
953
+ message: `${res.validCount}/${res.totalEvaluated} artifacts compliant with their schemas`
954
+ };
955
+ }
956
+ const firstViolation = res.violations[0]?.message || "Invalid structure";
957
+ return {
958
+ name: "JSON Schemas Compliance (Draft 2020-12)",
959
+ status: "FAILED",
960
+ message: `${res.invalidCount} artifact(s) do not comply with JSON schema: ${firstViolation}`,
961
+ remediation: "Run 'aisdlc verify schemas' to audit and fix required fields."
962
+ };
963
+ }
964
+ function auditSecurityGate(rootDir) {
965
+ const secRes = verifySecrets2({ rootDir });
966
+ const sastRes = verifySast2({ rootDir });
967
+ if (secRes.success && sastRes.success) {
968
+ return {
969
+ name: "Shift-Left Security (Gitleaks Secrets & SAST)",
970
+ status: "PASSED",
971
+ message: `${secRes.totalFilesScanned} clean files (0 secrets, 0 vulnerabilities)`
972
+ };
973
+ }
974
+ const errors = [];
975
+ if (!secRes.success) {
976
+ const f = secRes.findings[0];
977
+ errors.push(`${secRes.findingsCount} secret(s) (e.g. ${f.ruleId} in ${f.relPath}:${f.lineNumber})`);
978
+ }
979
+ if (!sastRes.success) {
980
+ const v = sastRes.violations[0];
981
+ errors.push(`${sastRes.violationsCount} SAST violation(s) (e.g. ${v.ruleId} in ${v.relPath}:${v.lineNumber})`);
982
+ }
983
+ return {
984
+ name: "Shift-Left Security (Gitleaks Secrets & SAST)",
985
+ status: "FAILED",
986
+ message: errors.join("; "),
987
+ remediation: "Run 'aisdlc verify security' and resolve credentials or vulnerable patterns."
988
+ };
989
+ }
990
+ function renderDashboard(gates, autoFixExecuted, gherkinCount, digestsCount) {
991
+ console.log(pc2.bold(pc2.cyan("\n==============================================================================")));
992
+ console.log(pc2.bold(pc2.cyan(" AI-SDLC: CONSOLIDATED PRE-FLIGHT DASHBOARD (aisdlc check) ")));
993
+ console.log(pc2.bold(pc2.cyan("==============================================================================\n")));
994
+ if (autoFixExecuted) {
995
+ console.log(pc2.bold(` ${pc2.magenta("AUTO-FIX MODE ACTIVE:")} Non-destructive preliminary syncs applied:`));
996
+ console.log(` - Gherkin scenarios synchronized: ${pc2.bold(String(gherkinCount))}`);
997
+ console.log(` - SHA-256 digests synchronized: ${pc2.bold(String(digestsCount))}
998
+ `);
999
+ }
1000
+ for (const gate of gates) {
1001
+ const badge = gate.status === "PASSED" ? pc2.green("\u2714 PASSED ") : gate.status === "FIXED" ? pc2.cyan("\u{1F527} AUTO-FIX ") : pc2.red("\u2716 FAILED ");
1002
+ console.log(` [${badge}] ${pc2.bold(gate.name)}`);
1003
+ console.log(` ${pc2.dim(gate.message)}`);
1004
+ }
1005
+ const failedGates = gates.filter((g) => g.status === "FAILED");
1006
+ if (failedGates.length > 0) {
1007
+ console.log(pc2.bold(pc2.red("\n------------------------------------------------------------------------------")));
1008
+ console.log(pc2.bold(pc2.red(" REQUIRED ACTIONS TO RESOLVE BLOCKING ERRORS:")));
1009
+ console.log(pc2.bold(pc2.red("------------------------------------------------------------------------------")));
1010
+ failedGates.forEach((g, idx) => {
1011
+ console.log(` ${pc2.bold(String(idx + 1))}. ${pc2.yellow(g.name)}:`);
1012
+ console.log(` \u{1F449} ${pc2.bold(g.remediation || "Review affected files.")}`);
1013
+ });
1014
+ console.log(pc2.bold(pc2.red("\n\u26D4 VERDICT: PRE-FLIGHT BLOCKED (EXIT 1)\n")));
1015
+ } else {
1016
+ console.log(pc2.bold(pc2.green("\n==============================================================================")));
1017
+ console.log(pc2.bold(pc2.green("\u2728 VERDICT: PRE-FLIGHT PASSED (EXIT 0) - Repository ready for Pull Request")));
1018
+ console.log(pc2.bold(pc2.green("==============================================================================\n")));
1019
+ }
1020
+ }
1021
+ function executePreflightCheck(options = {}) {
1022
+ const rootDir = options.root || process.cwd();
1023
+ const useJson = isJsonOutput(options);
1024
+ const isSilent = Boolean(options.silent || useJson);
1025
+ let gherkinCount = 0;
1026
+ let digestsCount = 0;
1027
+ if (options.fix) {
1028
+ const fixResult = runAutoFix(rootDir, isSilent);
1029
+ gherkinCount = fixResult.gherkinCount;
1030
+ digestsCount = fixResult.digestsCount;
1031
+ }
1032
+ const gates = [
1033
+ auditGherkinGate(rootDir, options.fix === true && gherkinCount > 0),
1034
+ auditPdacGate(rootDir, options.fix === true && digestsCount > 0),
1035
+ auditQualityGate(rootDir),
1036
+ auditTraceabilityGate(rootDir),
1037
+ auditGovernanceGate(rootDir),
1038
+ auditTestingGate(rootDir),
1039
+ auditLicensesGate(rootDir),
1040
+ auditSchemasGate(rootDir),
1041
+ auditSecurityGate(rootDir)
1042
+ ];
1043
+ const success = gates.every((g) => g.status === "PASSED" || g.status === "FIXED");
1044
+ if (!isSilent) {
1045
+ renderDashboard(gates, Boolean(options.fix), gherkinCount, digestsCount);
1046
+ }
1047
+ const result = {
1048
+ success,
1049
+ autoFixExecuted: Boolean(options.fix),
1050
+ gherkinSynced: gherkinCount,
1051
+ digestsSynced: digestsCount,
1052
+ gates
1053
+ };
1054
+ if (useJson) {
1055
+ const payload = {
1056
+ command: "check",
1057
+ success: result.success,
1058
+ exitCode: result.success ? 0 : 1,
1059
+ autoFixExecuted: result.autoFixExecuted,
1060
+ gherkinSynced: result.gherkinSynced,
1061
+ digestsSynced: result.digestsSynced,
1062
+ gates: result.gates
1063
+ };
1064
+ console.log(JSON.stringify(payload, null, 2));
1065
+ }
1066
+ return result;
1067
+ }
1068
+ function runCheck(options = {}) {
1069
+ const result = executePreflightCheck(options);
1070
+ return result.success;
1071
+ }
1072
+
1073
+ // src/commands/gherkin.ts
1074
+ import pc3 from "picocolors";
1075
+ import { extractGherkinFeatures as extractGherkinFeatures2 } from "@aisdlc/core";
1076
+ function runGherkinExtract(options = {}) {
1077
+ const rootDir = options.root || process.cwd();
1078
+ const useJson = isJsonOutput(options);
1079
+ const isSilent = Boolean(options.silent || useJson);
1080
+ if (!isSilent) {
1081
+ console.log(pc3.bold(pc3.cyan("\n\u{1F952} [AI-SDLC] Extracting Gherkin scenarios to .feature files...")));
1082
+ }
1083
+ const result = extractGherkinFeatures2({
1084
+ rootDir,
1085
+ targetPath: options.path,
1086
+ all: options.all
1087
+ });
1088
+ if (!isSilent) {
1089
+ console.log(` Generated .feature files: ${pc3.bold(String(result.features.length))}`);
1090
+ console.log(` Total scenarios: ${pc3.bold(String(result.totalScenarios))}`);
1091
+ for (const f of result.features) {
1092
+ console.log(` ${pc3.green("\u2714")} ${pc3.bold(f.featureName)} \u2794 ${f.outputFile} (${f.scenarioCount} scenarios)`);
1093
+ }
1094
+ console.log(pc3.green("\n\u2714 BDD synchronization completed successfully.\n"));
1095
+ }
1096
+ if (useJson) {
1097
+ const payload = {
1098
+ command: "gherkin:extract",
1099
+ success: result.success,
1100
+ exitCode: result.success ? 0 : 1,
1101
+ totalScenarios: result.totalScenarios,
1102
+ features: result.features
1103
+ };
1104
+ console.log(JSON.stringify(payload, null, 2));
1105
+ }
1106
+ return result.success;
1107
+ }
1108
+
1109
+ // src/commands/git.ts
1110
+ import pc4 from "picocolors";
1111
+ import {
1112
+ classifyBranch,
1113
+ generateBranchHierarchyPlan,
1114
+ checkoutTaskBranch,
1115
+ installGitHooks,
1116
+ detectAuthorIdentity
1117
+ } from "@aisdlc/core";
1118
+ function runGitValidate(branchName) {
1119
+ if (!branchName) {
1120
+ console.error(pc4.red("\n[ERROR] Branch name to validate must be specified.\n"));
1121
+ return false;
1122
+ }
1123
+ const result = classifyBranch(branchName);
1124
+ if (result.valid) {
1125
+ console.log(pc4.green(`
1126
+ \u2714 [COMPLIANT] Valid branch in 4-tier model:`));
1127
+ console.log(` - Level (Tier): ${pc4.bold(`Tier ${result.tier} (${result.tierName})`)}`);
1128
+ console.log(` - Base Origin: ${result.parentRequirement}`);
1129
+ console.log(` - Target Merge: ${result.targetMerge}
1130
+ `);
1131
+ return true;
1132
+ } else {
1133
+ console.error(pc4.red(`
1134
+ \u2716 [NAMING ERROR] ${result.error}`));
1135
+ console.error(pc4.yellow("\nAllowed patterns:"));
1136
+ console.error(" Tier 1: main");
1137
+ console.error(" Tier 2: release/vX.Y.Z");
1138
+ console.error(" Tier 3: feat/<FEAT-ID>-<slug> or bug/<BUG-ID>-<slug>");
1139
+ console.error(" Tier 4: task/<PARENT-ID>/<TSK-ID>-<slug>\n");
1140
+ return false;
1141
+ }
1142
+ }
1143
+ function runGitPlan(options) {
1144
+ const version = options.version || "v1.1.0";
1145
+ const feature = options.feature || "CHG-001-telemetry";
1146
+ const rawTasks = options.tasks || "TSK-001-dto,TSK-002-gateway";
1147
+ const tasks = rawTasks.split(",").map((t) => t.trim());
1148
+ const plan = generateBranchHierarchyPlan(version, feature, tasks);
1149
+ console.log(pc4.cyan("\n" + plan.planText));
1150
+ return true;
1151
+ }
1152
+ function runGitCheckout(taskId, options = {}) {
1153
+ if (!taskId) {
1154
+ console.error(pc4.red("\n[ERROR] Task identifier to navigate must be specified (e.g. TSK-001).\n"));
1155
+ return false;
1156
+ }
1157
+ const rootDir = options.root || process.cwd();
1158
+ console.log(pc4.cyan(`
1159
+ \u{1F680} [AI-SDLC Git] Navigating and preparing branches for task '${pc4.bold(taskId)}'...`));
1160
+ const result = checkoutTaskBranch(taskId, { rootDir });
1161
+ if (!result.success) {
1162
+ console.error(pc4.red(`
1163
+ \u2716 [ERROR] ${result.error}`));
1164
+ if (result.availableTasks && result.availableTasks.length > 0) {
1165
+ console.log(pc4.yellow("\nAvailable tasks in active changes:"));
1166
+ for (const t of result.availableTasks) {
1167
+ console.log(` - [${pc4.cyan(t.changeId)}] ${pc4.bold(t.id)}${t.title ? `: ${t.title}` : ""}`);
1168
+ }
1169
+ }
1170
+ console.log();
1171
+ return false;
1172
+ }
1173
+ console.log(` - Detected change: ${pc4.bold(result.changeId || "N/A")}`);
1174
+ console.log(` - Release Branch: ${pc4.green(result.releaseBranch || "")} (Tier 2)`);
1175
+ console.log(` - Feature Branch: ${pc4.green(result.featureBranch || "")} (Tier 3)`);
1176
+ console.log(` - Task Branch: ${pc4.green(result.taskBranch || "")} (Tier 4)`);
1177
+ if (result.createdBranches && result.createdBranches.length > 0) {
1178
+ console.log(pc4.green(`
1179
+ \u2714 Cascading branches created:`));
1180
+ for (const b of result.createdBranches) {
1181
+ console.log(` \u251C\u2500\u2500 ${pc4.bold(b)}`);
1182
+ }
1183
+ }
1184
+ console.log(pc4.green(`
1185
+ \u2714 [CHECKOUT] Successfully switched to working branch:`));
1186
+ console.log(` \u{1F449} ${pc4.bold(pc4.cyan(result.switchedBranch || result.taskBranch || ""))}
1187
+ `);
1188
+ return true;
1189
+ }
1190
+ function runGitHookInstall(options = {}) {
1191
+ const rootDir = options.root || process.cwd();
1192
+ console.log(pc4.cyan(`
1193
+ \u{1F527} [AI-SDLC Git] Installing deterministic hook for commit trailers...`));
1194
+ const result = installGitHooks(rootDir);
1195
+ if (result.success) {
1196
+ console.log(pc4.green(`\u2714 [COMPLIANT] Git Hook successfully installed at:`));
1197
+ console.log(` \u{1F449} ${pc4.bold(result.hookPath || ".git/hooks/prepare-commit-msg")}
1198
+ `);
1199
+ return true;
1200
+ } else {
1201
+ console.error(pc4.red(`
1202
+ \u2716 [ERROR] ${result.error}
1203
+ `));
1204
+ return false;
1205
+ }
1206
+ }
1207
+ function runGitDetectAuthor(options = {}) {
1208
+ const rootDir = options.root || process.cwd();
1209
+ const identity = detectAuthorIdentity({ cwd: rootDir });
1210
+ if (options.json) {
1211
+ console.log(JSON.stringify(identity, null, 2));
1212
+ } else {
1213
+ console.log(`${identity.authorType}|${identity.model}|${identity.promptTokens}|${identity.completionTokens}|${identity.activeTimeSeconds}`);
1214
+ }
1215
+ return true;
1216
+ }
1217
+
1218
+ // src/commands/init.ts
1219
+ import * as readline from "readline/promises";
1220
+ import { initProject } from "@aisdlc/core";
1221
+ import pc5 from "picocolors";
1222
+ async function promptForArchitecture() {
1223
+ const rl = readline.createInterface({
1224
+ input: process.stdin,
1225
+ output: process.stdout
1226
+ });
1227
+ console.log(pc5.bold(pc5.cyan("\n\u{1F3DB}\uFE0F [AI-SDLC] Architecture Granularity Level:")));
1228
+ console.log(" 1) " + pc5.green("Minimal / Baseline") + " (CMP-* Components and ADR-* Decisions only) " + pc5.yellow("[Recommended for microservices and CLI]"));
1229
+ console.log(" 2) " + pc5.cyan("Full / arc42 + NAF v4") + " (12 complete architecture sections)");
1230
+ console.log(" 3) " + pc5.gray("None") + " (No architecture templates)");
1231
+ try {
1232
+ const answer = await rl.question(
1233
+ pc5.bold("\nWhich architecture granularity level do you wish to configure? [1-3] (default 1): ")
1234
+ );
1235
+ const trimmed = answer.trim().toLowerCase();
1236
+ if (!trimmed || trimmed === "1" || trimmed === "minimal") return "minimal";
1237
+ if (trimmed === "2" || trimmed === "full" || trimmed === "complete") return "full";
1238
+ if (trimmed === "3" || trimmed === "none") return "none";
1239
+ return trimmed;
1240
+ } finally {
1241
+ rl.close();
1242
+ }
1243
+ }
1244
+ async function promptForAgents() {
1245
+ const rl = readline.createInterface({
1246
+ input: process.stdin,
1247
+ output: process.stdout
1248
+ });
1249
+ console.log(pc5.bold(pc5.cyan("\n\u{1F916} [AI-SDLC] Project AI Agents Configuration:")));
1250
+ console.log(" 1) " + pc5.green("All") + " (Cursor, Claude Code, Antigravity, Copilot, MCP) " + pc5.yellow("[Recommended]"));
1251
+ console.log(" 2) Cursor (.cursor/rules and .cursor/mcp.json)");
1252
+ console.log(" 3) Claude Code (CLAUDE.md)");
1253
+ console.log(" 4) Google Antigravity / Gemini CLI (.agent/rules and antigravity.mcp.json)");
1254
+ console.log(" 5) GitHub Copilot (.github/copilot-instructions.md)");
1255
+ console.log(" 6) MCP connectors only (.cursor/mcp.json, antigravity.mcp.json, .vscode/mcp.json)");
1256
+ console.log(" 7) None (only core policies and base templates)");
1257
+ try {
1258
+ const answer = await rl.question(
1259
+ pc5.bold("\nWhich agents do you wish to deploy? [1-7 or comma-separated list] (default 1): ")
1260
+ );
1261
+ const trimmed = answer.trim();
1262
+ if (!trimmed || trimmed === "1") return "all";
1263
+ if (trimmed === "2") return "cursor";
1264
+ if (trimmed === "3") return "claude";
1265
+ if (trimmed === "4") return "antigravity";
1266
+ if (trimmed === "5") return "copilot";
1267
+ if (trimmed === "6") return "mcp";
1268
+ if (trimmed === "7") return "none";
1269
+ return trimmed;
1270
+ } finally {
1271
+ rl.close();
1272
+ }
1273
+ }
1274
+ function runInit(targetDir = ".", options = {}) {
1275
+ const useJson = isJsonOutput(options);
1276
+ const isSilent = Boolean(options.silent || useJson);
1277
+ const result = initProject({
1278
+ rootDir: process.cwd(),
1279
+ targetDir,
1280
+ ci: options.ci,
1281
+ agents: options.agents === "none" ? false : options.agents,
1282
+ architecture: options.architecture,
1283
+ dryRun: options.dryRun
1284
+ });
1285
+ if (!result.success) {
1286
+ if (!isSilent) {
1287
+ console.error(pc5.red(`
1288
+ \u2716 [ERROR] ${result.error || "Error initializing project."}
1289
+ `));
1290
+ }
1291
+ if (useJson) {
1292
+ const payload = {
1293
+ command: "init",
1294
+ success: false,
1295
+ exitCode: 1,
1296
+ targetDir: result.targetDir,
1297
+ directoriesCreated: result.directoriesCreated,
1298
+ filesCreated: result.filesCreated,
1299
+ ciProvider: result.ciProvider,
1300
+ agentsConfigured: result.agentsConfigured,
1301
+ gitHookInstalled: result.gitHookInstalled,
1302
+ dryRun: Boolean(options.dryRun),
1303
+ error: result.error || "Error initializing project."
1304
+ };
1305
+ console.log(JSON.stringify(payload, null, 2));
1306
+ }
1307
+ return false;
1308
+ }
1309
+ if (!isSilent) {
1310
+ console.log(pc5.bold(pc5.cyan(`
1311
+ \u{1F680} [AI-SDLC] Initializing governance structure in: ${result.targetDir}
1312
+ `)));
1313
+ for (const d of result.directoriesCreated) {
1314
+ if (options.dryRun) {
1315
+ console.log(` ${pc5.blue("DRY-RUN")} Create directory: ${d}`);
1316
+ } else {
1317
+ console.log(` ${pc5.green("\u2714")} Directory created: ${d}`);
1318
+ }
1319
+ }
1320
+ for (const f of result.filesCreated) {
1321
+ if (options.dryRun) {
1322
+ console.log(` ${pc5.blue("DRY-RUN")} Create file: ${f}`);
1323
+ } else {
1324
+ console.log(` ${pc5.green("\u2714")} File generated: ${f}`);
1325
+ }
1326
+ }
1327
+ if (result.ciProvider) {
1328
+ console.log(pc5.cyan(`
1329
+ \u2714 CI/CD configuration generated for provider: ${pc5.bold(result.ciProvider)}`));
1330
+ }
1331
+ if (result.agentsConfigured && result.agentsConfigured.length > 0) {
1332
+ console.log(pc5.cyan(`
1333
+ \u2714 Configured AI agents: ${pc5.bold(result.agentsConfigured.join(", "))}`));
1334
+ }
1335
+ if (result.architectureGranularity) {
1336
+ const label = result.architectureGranularity === "full" || result.architectureGranularity === "complete" ? "Full (arc42 + NAF v4, 12 sections)" : result.architectureGranularity === "minimal" ? "Minimal / Baseline (CMP-* and ADR-*)" : "None";
1337
+ console.log(pc5.cyan(`
1338
+ \u2714 Architecture granularity: ${pc5.bold(label)}`));
1339
+ }
1340
+ if (options.dryRun) {
1341
+ console.log(` ${pc5.blue("DRY-RUN")} Install Git Hook: .git/hooks/prepare-commit-msg`);
1342
+ } else if (result.gitHookInstalled) {
1343
+ console.log(` ${pc5.green("\u2714")} Git Hook installed: ${pc5.bold("prepare-commit-msg")}`);
1344
+ } else {
1345
+ console.log(` ${pc5.yellow("\u2139")} Git repository not detected at target.`);
1346
+ console.log(` ${pc5.gray("Run 'git init' and then 'aisdlc git hook install' to activate commit hooks.")}`);
1347
+ }
1348
+ console.log(pc5.green("\n\u2714 Repository configured with AI-SDLC policies and templates.\n"));
1349
+ }
1350
+ if (useJson) {
1351
+ const payload = {
1352
+ command: "init",
1353
+ success: true,
1354
+ exitCode: 0,
1355
+ targetDir: result.targetDir,
1356
+ directoriesCreated: result.directoriesCreated,
1357
+ filesCreated: result.filesCreated,
1358
+ ciProvider: result.ciProvider,
1359
+ agentsConfigured: result.agentsConfigured,
1360
+ architectureGranularity: result.architectureGranularity,
1361
+ gitHookInstalled: result.gitHookInstalled,
1362
+ dryRun: Boolean(options.dryRun)
1363
+ };
1364
+ console.log(JSON.stringify(payload, null, 2));
1365
+ }
1366
+ return true;
1367
+ }
1368
+
1369
+ // src/commands/kpi.ts
1370
+ import * as fs from "fs";
1371
+ import pc6 from "picocolors";
1372
+ import {
1373
+ aggregatePrKpis,
1374
+ formatPrKpiMarkdown,
1375
+ injectKpisIntoPrBody,
1376
+ aggregateReleaseKpis,
1377
+ writeReleaseKpiReport
1378
+ } from "@aisdlc/core";
1379
+ function runKpiPr(options) {
1380
+ const baseRef = options.base || "main";
1381
+ const headRef = options.head || "HEAD";
1382
+ const rootDir = options.root || process.cwd();
1383
+ try {
1384
+ const kpi = aggregatePrKpis(baseRef, headRef, { cwd: rootDir });
1385
+ if (options.json) {
1386
+ console.log(JSON.stringify(kpi, null, 2));
1387
+ return true;
1388
+ }
1389
+ const markdown = formatPrKpiMarkdown(kpi);
1390
+ if (options.updateFile) {
1391
+ if (!fs.existsSync(options.updateFile)) {
1392
+ console.error(pc6.red(`
1393
+ \u2716 [ERROR] Target file '${options.updateFile}' does not exist.
1394
+ `));
1395
+ return false;
1396
+ }
1397
+ const original = fs.readFileSync(options.updateFile, "utf-8");
1398
+ const updated = injectKpisIntoPrBody(original, markdown);
1399
+ fs.writeFileSync(options.updateFile, updated, "utf-8");
1400
+ console.log(pc6.green(`\u2714 [UPDATED] KPI summary injected into '${options.updateFile}'.`));
1401
+ } else {
1402
+ console.log("\n" + markdown + "\n");
1403
+ }
1404
+ return true;
1405
+ } catch (err) {
1406
+ const msg = err instanceof Error ? err.message : String(err);
1407
+ console.error(pc6.red(`
1408
+ \u2716 [ERROR] Failed to calculate PR KPIs: ${msg}
1409
+ `));
1410
+ return false;
1411
+ }
1412
+ }
1413
+ function runKpiRelease(options) {
1414
+ if (!options.release) {
1415
+ console.error(pc6.red("\n\u2716 [ERROR] Release branch must be specified (--release <branch>).\n"));
1416
+ return false;
1417
+ }
1418
+ const baseBranch = options.base || "main";
1419
+ const rootDir = options.root || process.cwd();
1420
+ try {
1421
+ console.log(pc6.cyan(`
1422
+ \u{1F4CA} [AI-SDLC Release KPI] Consolidating metrics for '${pc6.bold(options.release)}'...`));
1423
+ const report = aggregateReleaseKpis(options.release, baseBranch, { cwd: rootDir });
1424
+ if (options.json) {
1425
+ console.log(JSON.stringify(report, null, 2));
1426
+ return true;
1427
+ }
1428
+ const { markdownPath, jsonPath } = writeReleaseKpiReport(report, { outputDir: options.output });
1429
+ console.log(pc6.green(`\u2714 [COMPLIANT] Consolidated report successfully generated:`));
1430
+ console.log(` - Markdown: ${pc6.bold(markdownPath)}`);
1431
+ console.log(` - JSON: ${pc6.bold(jsonPath)}`);
1432
+ console.log(` - KLoC: ${report.totalKloc} (${report.totalCommits} commits)`);
1433
+ console.log(` - Bugs: ${report.totalBugs} (Density: ${report.globalDefectDensity} bugs/KLoC)`);
1434
+ console.log(` - Rework: ${report.reworkTimePercent}% time | ${report.reworkTokensPercent}% tokens
1435
+ `);
1436
+ return true;
1437
+ } catch (err) {
1438
+ const msg = err instanceof Error ? err.message : String(err);
1439
+ console.error(pc6.red(`
1440
+ \u2716 [ERROR] Failed to calculate Release KPIs: ${msg}
1441
+ `));
1442
+ return false;
1443
+ }
1444
+ }
1445
+
1446
+ // src/commands/mcp.ts
1447
+ import pc7 from "picocolors";
1448
+ import { startMcpServer } from "@aisdlc/mcp";
1449
+ async function runMcpServer(options = {}) {
1450
+ const rootDir = options.root || process.cwd();
1451
+ if (!options.silent) {
1452
+ console.error(pc7.bold(pc7.cyan("\n\u{1F680} [AI-SDLC MCP] Starting native Model Context Protocol (MCP) server (stdio)...")));
1453
+ console.error(pc7.gray(` Base directory: ${rootDir}
1454
+ `));
1455
+ }
1456
+ await startMcpServer({ rootDir });
1457
+ }
1458
+
1459
+ // src/commands/report.ts
1460
+ import * as path from "path";
1461
+ import { spawn } from "child_process";
1462
+ import pc8 from "picocolors";
1463
+ import { generateDashboardReport, generateQualityReport } from "@aisdlc/core";
1464
+ function openInBrowser(filePath) {
1465
+ const resolved = path.resolve(filePath);
1466
+ const platform = process.platform;
1467
+ try {
1468
+ if (platform === "win32") {
1469
+ spawn("cmd.exe", ["/c", "start", "", resolved], { detached: true, stdio: "ignore" });
1470
+ } else if (platform === "darwin") {
1471
+ spawn("open", [resolved], { detached: true, stdio: "ignore" });
1472
+ } else {
1473
+ spawn("xdg-open", [resolved], { detached: true, stdio: "ignore" });
1474
+ }
1475
+ } catch {
1476
+ }
1477
+ }
1478
+ function runReportDashboard(options = {}) {
1479
+ const rootDir = options.root || process.cwd();
1480
+ console.log(pc8.bold(pc8.cyan("\n\u{1F310} [AI-SDLC] Generating Interactive Web Dashboard and PDaC / RTM Graph...")));
1481
+ try {
1482
+ const result = generateDashboardReport({
1483
+ rootDir,
1484
+ outputPath: options.output,
1485
+ title: options.title
1486
+ });
1487
+ console.log(` Compiled nodes: ${pc8.bold(String(result.totalNodes))}`);
1488
+ console.log(` Connections (edges): ${pc8.bold(String(result.totalEdges))}`);
1489
+ console.log(` Compliant nodes: ${pc8.green(String(result.conformingCount))}`);
1490
+ console.log(` Nodes with issues: ${result.issueCount > 0 ? pc8.red(String(result.issueCount)) : pc8.green("0")}`);
1491
+ console.log(` Global traceability: ${pc8.green(String(result.metrics.traceabilityRatio) + "%")}`);
1492
+ console.log(` Maintainability: ${pc8.bold(String(result.metrics.avgMaintainability) + " / 100")}`);
1493
+ console.log(` Gate verdict: ${result.metrics.qualityVerdict === "PASS" ? pc8.green("PASS") : pc8.red("FAIL")}`);
1494
+ const relPath = path.relative(rootDir, result.outputPath);
1495
+ console.log(pc8.green(`
1496
+ \u2714 Self-contained HTML dashboard successfully generated at: ${pc8.bold(relPath)}
1497
+ `));
1498
+ if (options.open) {
1499
+ openInBrowser(result.outputPath);
1500
+ }
1501
+ return true;
1502
+ } catch (err) {
1503
+ const msg = err instanceof Error ? err.message : String(err);
1504
+ console.error(pc8.red(`
1505
+ \u2716 [ERROR] Failed to generate web dashboard: ${msg}
1506
+ `));
1507
+ return false;
1508
+ }
1509
+ }
1510
+ function runReportQuality(options = {}) {
1511
+ const rootDir = options.root || process.cwd();
1512
+ console.log(pc8.bold(pc8.cyan("\n\u{1F4CA} Generating Formal Quality Report...")));
1513
+ const thresholds = {
1514
+ max_cyclomatic: options.maxCyclomatic !== void 0 ? Number(options.maxCyclomatic) : void 0,
1515
+ max_cognitive: options.maxCognitive !== void 0 ? Number(options.maxCognitive) : void 0,
1516
+ min_maintainability: options.minMaintainability !== void 0 ? Number(options.minMaintainability) : void 0,
1517
+ max_function_lines: options.maxLines !== void 0 ? Number(options.maxLines) : void 0,
1518
+ enforce_mode: options.enforceMode
1519
+ };
1520
+ const result = generateQualityReport({ rootDir, policyPath: options.policy, thresholds });
1521
+ console.log(` Analyzed files: ${pc8.bold(String(result.totalFiles))}`);
1522
+ console.log(` Evaluated functions: ${pc8.bold(String(result.totalFunctions))}`);
1523
+ console.log(` Average maintainability: ${pc8.green(String(result.avgMaintainability) + " / 100")}`);
1524
+ console.log(` Average complexity (CC): ${pc8.bold(String(result.avgCyclomatic))}`);
1525
+ console.log(` Release Gate verdict: ${result.verdict === "PASS" ? pc8.green("PASS") : pc8.red("FAIL")}`);
1526
+ const reportRelPath = path.relative(rootDir, path.join(rootDir, "reports", "QUALITY_REPORT.md"));
1527
+ console.log(pc8.green(`
1528
+ \u2714 Report successfully generated at: ${pc8.bold(reportRelPath)}
1529
+ `));
1530
+ return result.verdict === "PASS";
1531
+ }
1532
+
1533
+ // src/commands/sdd.ts
1534
+ import * as path2 from "path";
1535
+ import pc9 from "picocolors";
1536
+ import {
1537
+ depositProductHandoffSidecar,
1538
+ detectActiveChangeForIntegration,
1539
+ integrateSddChange,
1540
+ scaffoldSddChange,
1541
+ scanAllProductHandoffs,
1542
+ verifyArtifactDuplicates as verifyArtifactDuplicates2
1543
+ } from "@aisdlc/core";
1544
+ function runSddDeposit(options) {
1545
+ const rootDir = options.root || process.cwd();
1546
+ const changeId = options.change;
1547
+ const framework = options.framework || "openspec";
1548
+ const useJson = isJsonOutput(options);
1549
+ const isSilent = Boolean(options.silent || useJson);
1550
+ if (!isSilent) {
1551
+ console.log(
1552
+ pc9.bold(
1553
+ pc9.cyan(`
1554
+ \u{1F4E6} [AI-SDLC SDD] Depositing PDaC Handoff Sidecar for '${changeId}' (${framework})...`)
1555
+ )
1556
+ );
1557
+ }
1558
+ const reqList = options.requirements ? options.requirements.split(",").map((r) => r.trim()) : ["FR-001"];
1559
+ const ucList = options.useCases ? options.useCases.split(",").map((u) => u.trim()) : ["UC-001"];
1560
+ const handoff = {
1561
+ id: `HOF-${changeId.toUpperCase()}`,
1562
+ type: "handoff",
1563
+ title: options.title || `PDaC Handoff for ${changeId}`,
1564
+ changeId,
1565
+ version: "1.0.0",
1566
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1567
+ subgraph: {
1568
+ requirements: reqList,
1569
+ useCases: ucList
1570
+ }
1571
+ };
1572
+ try {
1573
+ const depositedPath = depositProductHandoffSidecar({
1574
+ rootDir,
1575
+ changeId,
1576
+ framework,
1577
+ handoff
1578
+ });
1579
+ if (!isSilent) {
1580
+ console.log(` ${pc9.green("\u2714")} Sidecar successfully deposited: ${pc9.bold(depositedPath)}`);
1581
+ console.log(` Handoff ID: ${pc9.cyan(handoff.id)}`);
1582
+ console.log(` Delivered requirements: ${reqList.join(", ")}
1583
+ `);
1584
+ }
1585
+ if (useJson) {
1586
+ const payload = {
1587
+ command: "sdd:deposit",
1588
+ success: true,
1589
+ exitCode: 0,
1590
+ changeId,
1591
+ framework,
1592
+ depositedPath,
1593
+ handoff
1594
+ };
1595
+ console.log(JSON.stringify(payload, null, 2));
1596
+ }
1597
+ return true;
1598
+ } catch (err) {
1599
+ if (!isSilent) {
1600
+ console.error(pc9.red(` \u2716 Error depositing sidecar: ${err?.message || err}
1601
+ `));
1602
+ }
1603
+ if (useJson) {
1604
+ const payload = {
1605
+ command: "sdd:deposit",
1606
+ success: false,
1607
+ exitCode: 1,
1608
+ changeId,
1609
+ framework,
1610
+ error: err?.message || String(err)
1611
+ };
1612
+ console.log(JSON.stringify(payload, null, 2));
1613
+ }
1614
+ return false;
1615
+ }
1616
+ }
1617
+ function runSddVerify(options = {}) {
1618
+ const rootDir = options.root || process.cwd();
1619
+ const useJson = isJsonOutput(options);
1620
+ const isSilent = Boolean(options.silent || useJson);
1621
+ if (!isSilent) {
1622
+ console.log(
1623
+ pc9.bold(
1624
+ pc9.cyan("\n\u{1F50D} [AI-SDLC SDD] Verifying SDD Workspaces and Handoff Sidecars (HOF-*)...")
1625
+ )
1626
+ );
1627
+ }
1628
+ const handoffsMap = scanAllProductHandoffs(rootDir);
1629
+ const totalFound = handoffsMap.size;
1630
+ if (!isSilent) {
1631
+ console.log(` Found PDaC sidecars: ${pc9.bold(String(totalFound))}`);
1632
+ }
1633
+ let validCount = 0;
1634
+ let invalidCount = 0;
1635
+ const handoffItems = [];
1636
+ if (totalFound === 0) {
1637
+ if (!isSilent) {
1638
+ console.log(pc9.yellow(" [NOTICE] No handoff.yaml sidecar companion files found in specs/."));
1639
+ }
1640
+ } else {
1641
+ for (const [, { handoff, changeDir }] of handoffsMap.entries()) {
1642
+ const relDir = path2.relative(rootDir, changeDir).replace(/\\/g, "/");
1643
+ const reqCount = handoff.subgraph && Array.isArray(handoff.subgraph.requirements) ? handoff.subgraph.requirements.length : 0;
1644
+ const isValid = Boolean(handoff.id && handoff.id.startsWith("HOF-") && reqCount > 0);
1645
+ handoffItems.push({
1646
+ id: handoff.id || "UNKNOWN",
1647
+ changeDir: relDir,
1648
+ isValid,
1649
+ requirementsCount: reqCount
1650
+ });
1651
+ if (isValid) {
1652
+ validCount++;
1653
+ if (!isSilent) {
1654
+ console.log(
1655
+ ` ${pc9.green("\u2714")} [${pc9.bold(handoff.id)}] in ${relDir} (Requirements: ${reqCount})`
1656
+ );
1657
+ }
1658
+ } else {
1659
+ invalidCount++;
1660
+ if (!isSilent) {
1661
+ console.log(
1662
+ ` ${pc9.red("\u2716")} [${pc9.bold(handoff.id || "UNKNOWN")}] in ${relDir} - Invalid handoff schema or subgraph.`
1663
+ );
1664
+ }
1665
+ }
1666
+ }
1667
+ }
1668
+ let duplicateErrors = 0;
1669
+ let duplicateIssues = [];
1670
+ if (options.checkDuplicates !== false) {
1671
+ const dupResult = verifyArtifactDuplicates2({ rootDir });
1672
+ duplicateErrors = dupResult.errorCount;
1673
+ duplicateIssues = dupResult.issues;
1674
+ if (duplicateErrors > 0 && !isSilent) {
1675
+ console.log(
1676
+ pc9.red(
1677
+ `
1678
+ \u2716 [Shift-Left Gate] Detected ${duplicateErrors} requirement collision(s)/duplicate(s) in workspace:`
1679
+ )
1680
+ );
1681
+ for (const issue of dupResult.issues.filter((i) => i.severity === "ERROR")) {
1682
+ console.log(` ${pc9.red("\u2716")} [${issue.type}] ${issue.id} in ${issue.file}: ${issue.message}`);
1683
+ }
1684
+ }
1685
+ }
1686
+ const isOk = invalidCount === 0 && duplicateErrors === 0;
1687
+ if (!isSilent) {
1688
+ console.log(
1689
+ isOk ? pc9.green("\n\u2714 SDD Integration COMPLIANT: All sidecars and requirements are valid.\n") : pc9.red("\n\u2716 SDD Integration BLOCKED: Non-compliant sidecars or duplicate requirements detected.\n")
1690
+ );
1691
+ }
1692
+ if (useJson) {
1693
+ const payload = {
1694
+ command: "sdd:verify",
1695
+ success: isOk,
1696
+ exitCode: isOk ? 0 : 1,
1697
+ totalHandoffs: totalFound,
1698
+ validHandoffs: validCount,
1699
+ invalidHandoffs: invalidCount,
1700
+ duplicateErrors,
1701
+ handoffs: handoffItems,
1702
+ duplicateIssues
1703
+ };
1704
+ console.log(JSON.stringify(payload, null, 2));
1705
+ }
1706
+ return isOk;
1707
+ }
1708
+ function runSddIntegrate(options) {
1709
+ const rootDir = options.root || process.cwd();
1710
+ const useJson = isJsonOutput(options);
1711
+ const isSilent = Boolean(options.silent || useJson);
1712
+ let changeId = options.change;
1713
+ if (!changeId && options.auto) {
1714
+ const detection = detectActiveChangeForIntegration({
1715
+ rootDir,
1716
+ headRef: options.headRef,
1717
+ prTitle: options.prTitle,
1718
+ prBody: options.prBody
1719
+ });
1720
+ if (!detection.detected || !detection.changeId) {
1721
+ if (!isSilent) {
1722
+ console.log(pc9.yellow("\n\u2139 [AI-SDLC SDD] No active SDD change detected to integrate:"));
1723
+ for (const r of detection.reasons) {
1724
+ console.log(` - ${r}`);
1725
+ }
1726
+ console.log("");
1727
+ }
1728
+ if (useJson) {
1729
+ const payload = {
1730
+ command: "sdd:integrate",
1731
+ success: false,
1732
+ exitCode: 1,
1733
+ reasons: detection.reasons,
1734
+ error: "No active SDD change detected to integrate"
1735
+ };
1736
+ console.log(JSON.stringify(payload, null, 2));
1737
+ }
1738
+ return false;
1739
+ }
1740
+ if (!detection.allTasksCompleted) {
1741
+ if (!isSilent) {
1742
+ console.log(
1743
+ pc9.red(
1744
+ `
1745
+ \u2716 [AI-SDLC SDD] Detected change '${detection.changeId}' has pending tasks (${detection.completedTasksCount}/${detection.totalTasksCount} completed). All tasks must be in COMPLETED status.
1746
+ `
1747
+ )
1748
+ );
1749
+ }
1750
+ if (useJson) {
1751
+ const payload = {
1752
+ command: "sdd:integrate",
1753
+ success: false,
1754
+ exitCode: 1,
1755
+ changeId: detection.changeId,
1756
+ completedTasksCount: detection.completedTasksCount,
1757
+ totalTasksCount: detection.totalTasksCount,
1758
+ error: `Detected change '${detection.changeId}' has pending tasks (${detection.completedTasksCount}/${detection.totalTasksCount} completed).`
1759
+ };
1760
+ console.log(JSON.stringify(payload, null, 2));
1761
+ }
1762
+ return false;
1763
+ }
1764
+ changeId = detection.changeId;
1765
+ if (!isSilent) {
1766
+ console.log(
1767
+ pc9.cyan(` \u2714 Automatically detected SDD change: ${pc9.bold(changeId)} (via ${detection.source})`)
1768
+ );
1769
+ }
1770
+ }
1771
+ if (!changeId) {
1772
+ if (!isSilent) {
1773
+ console.error(pc9.red("\n\u2716 Change identifier (--change <id>) or --auto option must be specified.\n"));
1774
+ }
1775
+ if (useJson) {
1776
+ const payload = {
1777
+ command: "sdd:integrate",
1778
+ success: false,
1779
+ exitCode: 1,
1780
+ error: "Change identifier (--change <id>) or --auto option must be specified."
1781
+ };
1782
+ console.log(JSON.stringify(payload, null, 2));
1783
+ }
1784
+ return false;
1785
+ }
1786
+ if (!isSilent) {
1787
+ console.log(
1788
+ pc9.bold(
1789
+ pc9.cyan(`
1790
+ \u{1F504} [AI-SDLC SDD] Integrating change '${changeId}' into canonical specification...`)
1791
+ )
1792
+ );
1793
+ }
1794
+ const result = integrateSddChange({
1795
+ rootDir,
1796
+ changeId,
1797
+ author: options.author,
1798
+ autoArchive: options.autoArchive
1799
+ });
1800
+ if (!isSilent) {
1801
+ if (result.success) {
1802
+ console.log(` ${pc9.green("\u2714")} Change '${changeId}' successfully processed:`);
1803
+ console.log(` - Completed tasks: ${pc9.bold(String(result.completedTasks.length))}`);
1804
+ console.log(` - Integrated requirements: ${pc9.green(result.integratedRequirements.join(", ") || "None")}`);
1805
+ console.log(` - Created canonical artifacts: ${pc9.green(result.createdCanonicalArtifacts?.join(", ") || "None")}`);
1806
+ console.log(` - Updated product artifacts: ${pc9.green(result.updatedProductArtifacts.join(", ") || "None")}`);
1807
+ console.log(` - Updated arc42 architecture: ${pc9.green(result.updatedArchitectureArtifacts.join(", ") || "None")}`);
1808
+ if (result.archived) {
1809
+ console.log(` - Archived to: ${pc9.cyan(result.archivedPath || "specs/changes/completed")}`);
1810
+ }
1811
+ console.log(pc9.green("\n\u2714 Canonical specification integration COMPLETED (EXIT 0)\n"));
1812
+ } else {
1813
+ console.log(pc9.red(`
1814
+ \u2716 Failed to integrate change '${changeId}':`));
1815
+ for (const err of result.errors) {
1816
+ console.log(` ${pc9.red("\u2716")} ${err}`);
1817
+ }
1818
+ console.log(pc9.red("\n\u2716 Integration BLOCKED (EXIT 1)\n"));
1819
+ }
1820
+ }
1821
+ if (useJson) {
1822
+ const payload = {
1823
+ command: "sdd:integrate",
1824
+ success: result.success,
1825
+ exitCode: result.success ? 0 : 1,
1826
+ changeId,
1827
+ completedTasks: result.completedTasks,
1828
+ integratedRequirements: result.integratedRequirements,
1829
+ createdCanonicalArtifacts: result.createdCanonicalArtifacts ?? [],
1830
+ updatedProductArtifacts: result.updatedProductArtifacts,
1831
+ updatedArchitectureArtifacts: result.updatedArchitectureArtifacts,
1832
+ archived: result.archived,
1833
+ archivedPath: result.archivedPath,
1834
+ errors: result.errors
1835
+ };
1836
+ console.log(JSON.stringify(payload, null, 2));
1837
+ }
1838
+ return result.success;
1839
+ }
1840
+ function runChangeNew(options) {
1841
+ const rootDir = options.root || process.cwd();
1842
+ const name = options.name;
1843
+ const framework = options.framework || "openspec";
1844
+ const useJson = isJsonOutput(options);
1845
+ const isSilent = Boolean(options.silent || useJson);
1846
+ if (!isSilent) {
1847
+ console.log(
1848
+ pc9.bold(
1849
+ pc9.cyan(`
1850
+ \u{1F4E6} [AI-SDLC SDD] Scaffolding new SDD change '${name}' (${framework})...`)
1851
+ )
1852
+ );
1853
+ }
1854
+ const result = scaffoldSddChange({
1855
+ rootDir,
1856
+ name,
1857
+ changeId: options.id,
1858
+ profile: options.profile,
1859
+ from: options.from,
1860
+ framework,
1861
+ author: options.author,
1862
+ silent: isSilent
1863
+ });
1864
+ if (!isSilent) {
1865
+ if (result.success) {
1866
+ console.log(` ${pc9.green("\u2714")} Change directory: ${pc9.bold(result.changeDir)}`);
1867
+ console.log(` ${pc9.green("\u2714")} SDD Change ID: ${pc9.cyan(result.canonicalId)} (${result.changeId})`);
1868
+ console.log(` ${pc9.green("\u2714")} Risk profile: ${pc9.magenta(result.profile || "standard")}`);
1869
+ if (result.productArtifactCreated) {
1870
+ console.log(` ${pc9.green("\u2714")} Product artifact: ${pc9.bold(result.productArtifactCreated)} (status: draft)`);
1871
+ }
1872
+ console.log(` ${pc9.green("\u2714")} Cited artifacts: ${result.citedArtifacts.length}`);
1873
+ for (const cite of result.citedArtifacts) {
1874
+ console.log(` - [${pc9.cyan(cite.id)}] ${cite.digest.substring(0, 19)}... (${cite.title || "Untitled"})`);
1875
+ }
1876
+ console.log(` ${pc9.green("\u2714")} Generated files: ${result.createdFiles.length}`);
1877
+ console.log(pc9.green("\n\u2714 SDD change successfully initialized and validated.\n"));
1878
+ } else {
1879
+ console.log(pc9.red(`
1880
+ \u2716 Failed to create SDD change '${name}':`));
1881
+ for (const err of result.errors) {
1882
+ console.log(` ${pc9.red("\u2716")} ${err}`);
1883
+ }
1884
+ console.log(pc9.red("\n\u2716 Change creation BLOCKED\n"));
1885
+ }
1886
+ }
1887
+ if (useJson) {
1888
+ const payload = {
1889
+ command: "change:new",
1890
+ success: result.success,
1891
+ exitCode: result.success ? 0 : 1,
1892
+ name,
1893
+ canonicalId: result.canonicalId,
1894
+ changeId: result.changeId,
1895
+ changeDir: result.changeDir,
1896
+ profile: result.profile,
1897
+ createdFiles: result.createdFiles,
1898
+ productArtifactCreated: result.productArtifactCreated,
1899
+ citedArtifacts: result.citedArtifacts,
1900
+ errors: result.errors
1901
+ };
1902
+ console.log(JSON.stringify(payload, null, 2));
1903
+ }
1904
+ return result.success;
1905
+ }
1906
+
1907
+ // src/index.ts
1908
+ var program = new Command();
1909
+ program.name("aisdlc").description("AI-SDLC: Spec-Driven Development, Governance & Quality Gates for AI & Humans").version("1.0.0");
1910
+ program.command("check").description("Unified pre-flight command: validates Quality Gates with optional non-destructive auto-fix").option("--fix", "Automatically synchronize Gherkin scenarios (.feature) and cryptographic digests of PDaC citations").option("-r, --root <path>", "Project root directory").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
1911
+ const passed = runCheck({
1912
+ fix: opts.fix,
1913
+ root: opts.root,
1914
+ json: opts.json,
1915
+ format: opts.format
1916
+ });
1917
+ process.exit(passed ? 0 : 1);
1918
+ });
1919
+ var verifyCommand = program.command("verify").description("Run deterministic verifiers for quality, traceability, governance, and licenses");
1920
+ verifyCommand.command("all", { isDefault: true }).description("Run the full quality and governance suite (Quality Gate + RTM + Tasks + Tests + Licenses + PDaC + Schemas + Duplicates + Security)").option("-r, --root <path>", "Project root directory").option("-p, --policy <path>", "Path to quality-policy.yaml").option("-C, --max-cyclomatic <number>", "Maximum Cyclomatic Complexity threshold").option("-K, --max-cognitive <number>", "Maximum Cognitive Complexity threshold").option("-M, --min-maintainability <number>", "Minimum Maintainability threshold (0-100)").option("-L, --max-lines <number>", "Maximum lines per function threshold").option("-m, --mode <mode>", "Enforcement mode: STRICT or PERMISSIVE").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
1921
+ const passed = runVerifyAll({
1922
+ root: opts.root,
1923
+ policy: opts.policy,
1924
+ maxCyclomatic: opts.maxCyclomatic,
1925
+ maxCognitive: opts.maxCognitive,
1926
+ minMaintainability: opts.minMaintainability,
1927
+ maxLines: opts.maxLines,
1928
+ enforceMode: opts.mode,
1929
+ json: opts.json,
1930
+ format: opts.format
1931
+ });
1932
+ process.exit(passed ? 0 : 1);
1933
+ });
1934
+ verifyCommand.command("quality").description("Quality Release Gate (Cyclomatic Complexity <= 10, Maintainability >= 50)").option("-r, --root <path>", "Project root directory").option("-p, --policy <path>", "Path to quality-policy.yaml").option("-C, --max-cyclomatic <number>", "Maximum Cyclomatic Complexity threshold").option("-K, --max-cognitive <number>", "Maximum Cognitive Complexity threshold").option("-M, --min-maintainability <number>", "Minimum Maintainability threshold (0-100)").option("-L, --max-lines <number>", "Maximum lines per function threshold").option("-m, --mode <mode>", "Enforcement mode: STRICT or PERMISSIVE").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
1935
+ const passed = runVerifyQuality({
1936
+ root: opts.root,
1937
+ policy: opts.policy,
1938
+ maxCyclomatic: opts.maxCyclomatic,
1939
+ maxCognitive: opts.maxCognitive,
1940
+ minMaintainability: opts.minMaintainability,
1941
+ maxLines: opts.maxLines,
1942
+ enforceMode: opts.mode,
1943
+ json: opts.json,
1944
+ format: opts.format
1945
+ });
1946
+ process.exit(passed ? 0 : 1);
1947
+ });
1948
+ verifyCommand.command("traceability").description("Audit the 360\xB0 Requirements Traceability Matrix (Product -> Architecture -> Testing)").option("-r, --root <path>", "Project root directory").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
1949
+ const passed = runVerifyTraceability({ root: opts.root, json: opts.json, format: opts.format });
1950
+ process.exit(passed ? 0 : 1);
1951
+ });
1952
+ verifyCommand.command("governance").description("Audit task governance and human autonomy modes (AUTONOMOUS, HUMAN_REVIEW_PLAN, etc.)").option("-r, --root <path>", "Project root directory").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
1953
+ const passed = runVerifyGovernance({ root: opts.root, json: opts.json, format: opts.format });
1954
+ process.exit(passed ? 0 : 1);
1955
+ });
1956
+ verifyCommand.command("testing").description("Audit that 100% of requirements and tasks have verifiable tests").option("-r, --root <path>", "Project root directory").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
1957
+ const passed = runVerifyTesting({ root: opts.root, json: opts.json, format: opts.format });
1958
+ process.exit(passed ? 0 : 1);
1959
+ });
1960
+ verifyCommand.command("licenses").description("Verify OSS license compliance against license-policy.yaml (dynamic SCA and SBOM)").option("-r, --root <path>", "Project root directory").option("-p, --policy <path>", "Path to license-policy.yaml").option("-m, --manifest <path>", "Path to license-manifest.yaml").option("--no-dynamic", "Disable dynamic scanning and require static manifest file").option("--sbom [path]", "Generate CycloneDX 1.5 JSON standard SBOM file").option("--notices [path]", "Generate THIRD_PARTY_NOTICES.md legal notices and attributions file").option("--tool <tool>", "SCA tool: native, trivy, syft", "native").option("--depth <depth>", "Analysis depth: direct or transitive", "transitive").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
1961
+ const passed = runVerifyLicenses({
1962
+ root: opts.root,
1963
+ policy: opts.policy,
1964
+ manifest: opts.manifest,
1965
+ dynamic: opts.dynamic,
1966
+ tool: opts.tool,
1967
+ depth: opts.depth,
1968
+ sbom: opts.sbom,
1969
+ notices: opts.notices,
1970
+ json: opts.json,
1971
+ format: opts.format
1972
+ });
1973
+ process.exit(passed ? 0 : 1);
1974
+ });
1975
+ verifyCommand.command("pdac").description("Verify PDaC graph and evaluate cryptographic drift of SHA-256 citations").option("-r, --root <path>", "Project root directory").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
1976
+ const passed = runVerifyPdac({ root: opts.root, json: opts.json, format: opts.format });
1977
+ process.exit(passed ? 0 : 1);
1978
+ });
1979
+ verifyCommand.command("schemas").description("Verify Markdown artifacts compliance against canonical JSON schemas (Draft 2020-12)").option("-r, --root <path>", "Project root directory").option("-p, --path <path>", "Target file or directory path").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
1980
+ const passed = runVerifySchemas({ root: opts.root, path: opts.path, json: opts.json, format: opts.format });
1981
+ process.exit(passed ? 0 : 1);
1982
+ });
1983
+ verifyCommand.command("duplicates").description("Audit duplicate requirements, ID collisions, lexical redundancy, and BDD overlaps").option("-r, --root <path>", "Project root directory").option("-s, --similarity <number>", "Lexical similarity threshold for titles (0.0 to 1.0)", "0.85").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
1984
+ const passed = runVerifyDuplicates({ root: opts.root, similarity: opts.similarity, json: opts.json, format: opts.format });
1985
+ process.exit(passed ? 0 : 1);
1986
+ });
1987
+ verifyCommand.command("security").description("Unified security verification: deterministic secrets detection (Gitleaks) and shift-left SAST").option("-r, --root <path>", "Project root directory").option("-d, --diff", "Scan only lines added in the current branch git diff").option("-b, --base <branch>", "Base branch for git diff calculation (default: origin/main or HEAD)").option("-g, --gitleaks", "Delegate or contrast with native Gitleaks binary if available").option("-s, --semgrep", "Delegate to Semgrep CLI if installed").option("-e, --entropy <number>", "Minimum Shannon entropy threshold (0.0 to 8.0)", "4.3").option("-m, --min-severity <level>", "Minimum severity for SAST failure: CRITICAL, HIGH, MEDIUM", "HIGH").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
1988
+ const passed = runVerifySecurity({
1989
+ root: opts.root,
1990
+ diff: opts.diff,
1991
+ base: opts.base,
1992
+ gitleaks: opts.gitleaks,
1993
+ semgrep: opts.semgrep,
1994
+ entropy: opts.entropy,
1995
+ minSeverity: opts.minSeverity,
1996
+ json: opts.json,
1997
+ format: opts.format
1998
+ });
1999
+ process.exit(passed ? 0 : 4);
2000
+ });
2001
+ verifyCommand.command("secrets").description("Verify absence of exposed credentials, API keys, and certificates (Gitleaks Gate)").option("-r, --root <path>", "Project root directory").option("-d, --diff", "Scan only lines added in the current branch git diff").option("-b, --base <branch>", "Base branch for git diff calculation (default: origin/main or HEAD)").option("-g, --gitleaks", "Delegate or contrast with native Gitleaks binary if available").option("-e, --entropy <number>", "Minimum Shannon entropy threshold (0.0 to 8.0)", "4.3").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
2002
+ const passed = runVerifySecrets({
2003
+ root: opts.root,
2004
+ diff: opts.diff,
2005
+ base: opts.base,
2006
+ gitleaks: opts.gitleaks,
2007
+ entropy: opts.entropy,
2008
+ json: opts.json,
2009
+ format: opts.format
2010
+ });
2011
+ process.exit(passed ? 0 : 4);
2012
+ });
2013
+ verifyCommand.command("sast").description("Shift-left static application security testing (SAST) for critical patterns (SQLi, exec, SSRF)").option("-r, --root <path>", "Project root directory").option("-s, --semgrep", "Delegate to Semgrep CLI if installed").option("-m, --min-severity <level>", "Minimum severity for failure: CRITICAL, HIGH, MEDIUM", "HIGH").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((opts) => {
2014
+ const passed = runVerifySast({
2015
+ root: opts.root,
2016
+ semgrep: opts.semgrep,
2017
+ minSeverity: opts.minSeverity,
2018
+ json: opts.json,
2019
+ format: opts.format
2020
+ });
2021
+ process.exit(passed ? 0 : 1);
2022
+ });
2023
+ verifyCommand.command("friction [change]").description("Verify progressive friction and Anti-Bypass guardrails for quick patches").option("-r, --root <path>", "Project root directory").option("--json", "Emit verification results in structured JSON format").option("-F, --format <format>", "Output format: text or json").action((change, opts) => {
2024
+ const passed = runVerifyFriction({ root: opts.root, change, json: opts.json, format: opts.format });
2025
+ process.exit(passed ? 0 : 1);
2026
+ });
2027
+ var reportCommand = program.command("report").description("Generate formal metric reports in Markdown format");
2028
+ reportCommand.command("quality").description("Generate formal polyglot code quality report (reports/QUALITY_REPORT.md)").option("-r, --root <path>", "Project root directory").option("-p, --policy <path>", "Path to quality-policy.yaml").option("-C, --max-cyclomatic <number>", "Maximum Cyclomatic Complexity threshold").option("-K, --max-cognitive <number>", "Maximum Cognitive Complexity threshold").option("-M, --min-maintainability <number>", "Minimum Maintainability threshold (0-100)").option("-L, --max-lines <number>", "Maximum lines per function threshold").option("-m, --mode <mode>", "Enforcement mode: STRICT or PERMISSIVE").action((opts) => {
2029
+ const passed = runReportQuality({
2030
+ root: opts.root,
2031
+ policy: opts.policy,
2032
+ maxCyclomatic: opts.maxCyclomatic,
2033
+ maxCognitive: opts.maxCognitive,
2034
+ minMaintainability: opts.minMaintainability,
2035
+ maxLines: opts.maxLines,
2036
+ enforceMode: opts.mode
2037
+ });
2038
+ process.exit(passed ? 0 : 1);
2039
+ });
2040
+ reportCommand.command("dashboard").description("Generate interactive web dashboard and PDaC / RTM graph visualizer (reports/dashboard.html)").option("-r, --root <path>", "Project root directory").option("-o, --output <path>", "Output HTML file path (default: reports/dashboard.html)").option("-t, --title <title>", "Web dashboard title").option("--open", "Open dashboard in default browser").action((opts) => {
2041
+ const passed = runReportDashboard({
2042
+ root: opts.root,
2043
+ output: opts.output,
2044
+ title: opts.title,
2045
+ open: opts.open
2046
+ });
2047
+ process.exit(passed ? 0 : 1);
2048
+ });
2049
+ var gherkinCommand = program.command("gherkin").description("BDD / Gherkin synchronization and extraction tools");
2050
+ gherkinCommand.command("extract").description("Extract ```gherkin``` blocks from Markdown specifications into .feature files").option("-r, --root <path>", "Project root directory").option("-p, --path <path>", "Target Markdown file or directory").option("-a, --all", "Process all specifications and requirements").option("--json", "Structured JSON format output").option("-F, --format <format>", "Output format: text or json").action((opts) => {
2051
+ const passed = runGherkinExtract({
2052
+ root: opts.root,
2053
+ path: opts.path,
2054
+ all: opts.all,
2055
+ json: opts.json,
2056
+ format: opts.format
2057
+ });
2058
+ process.exit(passed ? 0 : 1);
2059
+ });
2060
+ var gitCommand = program.command("git").description("Tools for the 4-tier hierarchical Git branch model");
2061
+ gitCommand.command("validate <branch>").description("Validate naming and hierarchy of a Git branch (Tier 1 to 4)").action((branch) => {
2062
+ const passed = runGitValidate(branch);
2063
+ process.exit(passed ? 0 : 1);
2064
+ });
2065
+ gitCommand.command("plan").description("Plan 4-tier Git branch hierarchy for a version and feature").option("-r, --release <version>", "Release version (e.g. v1.1.0)", "v1.1.0").option("-f, --feature <feature>", "Feature identifier (e.g. CHG-001-telemetry)", "CHG-001-telemetry").option("-t, --tasks <tasks>", "Comma-separated tasks list (e.g. TSK-001,TSK-002)", "TSK-001,TSK-002").action((opts) => {
2066
+ runGitPlan({ version: opts.release, feature: opts.feature, tasks: opts.tasks });
2067
+ process.exit(0);
2068
+ });
2069
+ gitCommand.command("checkout <task>").description("Navigate and automatically create 4-tier cascading branches for a task").option("-r, --root <path>", "Project root directory").action((task, opts) => {
2070
+ const passed = runGitCheckout(task, { root: opts.root });
2071
+ process.exit(passed ? 0 : 1);
2072
+ });
2073
+ var gitHookCommand = gitCommand.command("hook").description("AI-SDLC automated Git Hooks management and installation");
2074
+ gitHookCommand.command("install").description("Install prepare-commit-msg hook for automatic commit trailer injection").option("-r, --root <path>", "Project root directory").action((opts) => {
2075
+ const passed = runGitHookInstall({ root: opts.root });
2076
+ process.exit(passed ? 0 : 1);
2077
+ });
2078
+ gitCommand.command("detect-author").description("Universally detect IDE-independently whether the author is human or an agent").option("--json", "Structured JSON format output").option("-r, --root <path>", "Project root directory").action((opts) => {
2079
+ const passed = runGitDetectAuthor({ root: opts.root, json: opts.json });
2080
+ process.exit(passed ? 0 : 1);
2081
+ });
2082
+ var kpiCommand = program.command("kpi").description("Metrics, telemetry, and KPI aggregation tools (PR and Release)");
2083
+ kpiCommand.command("pr").description("Calculate and generate aggregated Markdown KPI table for a Pull Request").option("-b, --base <branch>", "Comparison base branch", "main").option("-h, --head <branch>", "Source branch or HEAD", "HEAD").option("-u, --update-file <path>", "File where to inject the KPI block (e.g. .github/PULL_REQUEST_TEMPLATE.md)").option("--json", "Print output in structured JSON format").option("-r, --root <path>", "Project root directory").action((opts) => {
2084
+ const passed = runKpiPr({
2085
+ base: opts.base,
2086
+ head: opts.head,
2087
+ updateFile: opts.updateFile,
2088
+ json: opts.json,
2089
+ root: opts.root
2090
+ });
2091
+ process.exit(passed ? 0 : 1);
2092
+ });
2093
+ kpiCommand.command("release").description("Consolidate release KPIs, DIR by model/human, and rework costs").requiredOption("--release <branch>", "Release branch to audit (e.g. release/v1.1.0)").option("-b, --base <branch>", "Stable base branch (e.g. main)", "main").option("-o, --output <dir>", "Output directory for reports (default: reports/releases/)").option("--json", "Print output in structured JSON format").option("-r, --root <path>", "Project root directory").action((opts) => {
2094
+ const passed = runKpiRelease({
2095
+ release: opts.release,
2096
+ base: opts.base,
2097
+ output: opts.output,
2098
+ json: opts.json,
2099
+ root: opts.root
2100
+ });
2101
+ process.exit(passed ? 0 : 1);
2102
+ });
2103
+ var changeCommand = program.command("change").description("SDD change lifecycle and scaffolding management");
2104
+ changeCommand.command("new <name>").description("Create complete scaffolding for a new SDD change (proposal, spec, design, tasks, handoff.yaml)").option("-r, --root <path>", "Project root directory").option("--from <ids...>", "Identifier or list of identifiers to cite (UC-*, FR-*, etc.)").option("--id <changeId>", "Explicit change identifier (e.g. chg-002-my-change)").option("-p, --profile <profile>", "Change risk profile: patch, standard, or critical", "standard").option("-f, --framework <framework>", "SDD framework: openspec or speckit", "openspec").option("-a, --author <author>", "Author name or developer agent").option("--json", "Structured JSON format output").option("-F, --format <format>", "Output format: text or json").action((name, opts) => {
2105
+ const passed = runChangeNew({
2106
+ root: opts.root,
2107
+ name,
2108
+ from: opts.from,
2109
+ id: opts.id,
2110
+ profile: opts.profile,
2111
+ framework: opts.framework,
2112
+ author: opts.author,
2113
+ json: opts.json,
2114
+ format: opts.format
2115
+ });
2116
+ process.exit(passed ? 0 : 1);
2117
+ });
2118
+ var sddCommand = program.command("sdd").description("Tools for integration with SDD ecosystems (OpenSpec and Spec Kit)");
2119
+ sddCommand.command("new <name>").description("Alias of `aisdlc change new`: create complete scaffolding for a new SDD change").option("-r, --root <path>", "Project root directory").option("--from <ids...>", "Identifier or list of identifiers to cite (UC-*, FR-*, etc.)").option("--id <changeId>", "Explicit change identifier (e.g. chg-002-my-change)").option("-p, --profile <profile>", "Change risk profile: patch, standard, or critical", "standard").option("-f, --framework <framework>", "SDD framework: openspec or speckit", "openspec").option("-a, --author <author>", "Author name or developer agent").option("--json", "Structured JSON format output").option("-F, --format <format>", "Output format: text or json").action((name, opts) => {
2120
+ const passed = runChangeNew({
2121
+ root: opts.root,
2122
+ name,
2123
+ from: opts.from,
2124
+ id: opts.id,
2125
+ profile: opts.profile,
2126
+ framework: opts.framework,
2127
+ author: opts.author,
2128
+ json: opts.json,
2129
+ format: opts.format
2130
+ });
2131
+ process.exit(passed ? 0 : 1);
2132
+ });
2133
+ sddCommand.command("deposit").description("Deposit a product subgraph as a sidecar companion file (handoff.yaml)").requiredOption("-c, --change <id>", "Change identifier (e.g. chg-001-telemetry)").option("-f, --framework <framework>", "SDD framework: openspec or speckit", "openspec").option("-r, --root <path>", "Project root directory").option("-t, --title <title>", "PDaC handoff title").option("--requirements <reqs>", "Comma-separated list of requirement IDs").option("--use-cases <ucs>", "Comma-separated list of use case IDs").option("--json", "Structured JSON format output").option("-F, --format <format>", "Output format: text or json").action((opts) => {
2134
+ const passed = runSddDeposit({
2135
+ root: opts.root,
2136
+ change: opts.change,
2137
+ framework: opts.framework,
2138
+ title: opts.title,
2139
+ requirements: opts.requirements,
2140
+ useCases: opts.useCases,
2141
+ json: opts.json,
2142
+ format: opts.format
2143
+ });
2144
+ process.exit(passed ? 0 : 1);
2145
+ });
2146
+ sddCommand.command("verify").description("Validate compliance of handoff.yaml sidecar files (HOF-*) in changes").option("-r, --root <path>", "Project root directory").option("-f, --framework <framework>", "SDD framework: openspec or speckit").option("--json", "Structured JSON format output").option("-F, --format <format>", "Output format: text or json").action((opts) => {
2147
+ const passed = runSddVerify({
2148
+ root: opts.root,
2149
+ framework: opts.framework,
2150
+ json: opts.json,
2151
+ format: opts.format
2152
+ });
2153
+ process.exit(passed ? 0 : 1);
2154
+ });
2155
+ sddCommand.command("integrate").description("Integrate and synchronize implemented SDD changes into canonical specification (product, requirements, and architecture)").option("-c, --change <id>", "Change identifier (e.g. chg-001-telemetry)").option("--auto", "Automatically detect active change to integrate based on branch, PR, or diff").option("--head-ref <ref>", "Source branch for automatic resolution").option("--pr-title <title>", "Pull Request title for automatic resolution").option("--pr-body <body>", "Pull Request body for automatic resolution").option("-r, --root <path>", "Project root directory").option("-a, --author <author>", "Name of author or agent performing integration").option("--no-archive", "Do not archive change to specs/changes/completed after integration").option("--json", "Structured JSON format output").option("-F, --format <format>", "Output format: text or json").action((opts) => {
2156
+ const passed = runSddIntegrate({
2157
+ root: opts.root,
2158
+ change: opts.change,
2159
+ auto: opts.auto,
2160
+ headRef: opts.headRef,
2161
+ prTitle: opts.prTitle,
2162
+ prBody: opts.prBody,
2163
+ author: opts.author,
2164
+ autoArchive: opts.archive !== false,
2165
+ json: opts.json,
2166
+ format: opts.format
2167
+ });
2168
+ process.exit(passed ? 0 : 1);
2169
+ });
2170
+ program.command("init [directory]").description("Initialize a new repository with AI-SDLC guidelines, schemas, and policies").option("-d, --dry-run", "Simulate file and directory creation without writing to disk").option("--ci <provider>", "CI/CD provider for pipeline generation (github, gitlab, azure, bitbucket)").option("--agents [targets]", "AI agent environments to configure (all, cursor, claude, antigravity, copilot, mcp, or comma-separated combination)").option("--arch, --architecture <granularity>", "Architecture templates granularity level (minimal, full, complete, none)").option("--json", "Structured JSON format output").option("-F, --format <format>", "Output format: text or json").action(async (directory, opts) => {
2171
+ let agents = opts.agents;
2172
+ let arch = opts.architecture || opts.arch;
2173
+ const isJson = opts.json || opts.format === "json" || process.env.AISDLC_FORMAT === "json" || process.env.AISDLC_OUTPUT === "json";
2174
+ if (arch === void 0 && process.stdin.isTTY && !opts.dryRun && !isJson) {
2175
+ arch = await promptForArchitecture();
2176
+ }
2177
+ if (agents === void 0 && process.stdin.isTTY && !opts.dryRun && !isJson) {
2178
+ agents = await promptForAgents();
2179
+ }
2180
+ const passed = runInit(directory, {
2181
+ dryRun: opts.dryRun,
2182
+ ci: opts.ci,
2183
+ agents,
2184
+ architecture: arch,
2185
+ json: opts.json,
2186
+ format: opts.format
2187
+ });
2188
+ process.exit(passed ? 0 : 1);
2189
+ });
2190
+ program.command("mcp").description("Start native AI-SDLC Model Context Protocol (MCP) server (stdio)").option("-r, --root <path>", "Project root directory").action(async (opts) => {
2191
+ await runMcpServer({ root: opts.root });
2192
+ });
2193
+ program.on("command:*", () => {
2194
+ console.error(pc10.red(`
2195
+ [ERROR] Unrecognized command: ${program.args.join(" ")}`));
2196
+ console.log(pc10.yellow("Run `aisdlc --help` to see available commands.\n"));
2197
+ process.exit(1);
2198
+ });
2199
+ program.parse(process.argv);
2200
+ //# sourceMappingURL=index.js.map