@aisdlc/cli 1.3.2 → 1.4.1

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 CHANGED
@@ -7,12 +7,14 @@ import pc10 from "picocolors";
7
7
  // src/commands/check.ts
8
8
  import pc2 from "picocolors";
9
9
  import {
10
- checkGherkinInSync,
10
+ checkGherkinInSync as checkGherkinInSync2,
11
11
  extractGherkinFeatures,
12
12
  syncPdacDigests,
13
+ verifyArtifactDuplicates as verifyArtifactDuplicates2,
13
14
  verifyArtifactsSchemas as verifyArtifactsSchemas2,
14
15
  verifyLicenses as verifyLicenses2,
15
16
  verifyPdacGraph as verifyPdacGraph2,
17
+ verifyProgressiveFriction as verifyProgressiveFriction2,
16
18
  verifyQualityGate as verifyQualityGate2,
17
19
  verifySast as verifySast2,
18
20
  verifySecrets as verifySecrets2,
@@ -24,6 +26,7 @@ import {
24
26
  // src/commands/verify.ts
25
27
  import pc from "picocolors";
26
28
  import {
29
+ checkGherkinInSync,
27
30
  verifyArtifactDuplicates,
28
31
  verifyArtifactsSchemas,
29
32
  verifyLicenses,
@@ -46,71 +49,126 @@ function isJsonOutput(options = {}) {
46
49
  const env = process.env.AISDLC_FORMAT?.trim().toLowerCase() || process.env.AISDLC_OUTPUT?.trim().toLowerCase();
47
50
  return env === "json";
48
51
  }
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)...")));
52
+ function buildQualityViolations(results) {
53
+ return results.filter((r) => r.status === "FAIL").flatMap(
54
+ (r) => r.violations.map((v) => ({
55
+ file: r.relPath,
56
+ function: r.functionName,
57
+ metric: "quality",
58
+ message: v,
59
+ metrics: {
60
+ loc: r.loc,
61
+ cyclomatic: r.cyclomatic,
62
+ cognitive: r.cognitive,
63
+ maintainability: r.maintainability
64
+ }
65
+ }))
66
+ );
67
+ }
68
+ function emitQualityJson(result) {
69
+ const violations = buildQualityViolations(result.results);
70
+ const payload = {
71
+ gate: "quality",
72
+ success: result.success,
73
+ exitCode: result.success ? 0 : 1,
74
+ summary: {
75
+ totalFiles: result.totalFiles,
76
+ totalFunctions: result.totalFunctions,
77
+ passCount: result.passCount,
78
+ failCount: result.failCount
79
+ },
80
+ violations
81
+ };
82
+ console.log(JSON.stringify(payload, null, 2));
83
+ }
84
+ function printQualityFailingDetails(failing, isPermissive) {
85
+ const colorFn = isPermissive ? pc.yellow : pc.red;
86
+ const label = isPermissive ? "\n Detected warnings (PERMISSIVE mode):" : "\n Detected violations:";
87
+ console.log(colorFn(label));
88
+ const maxToShow = 15;
89
+ for (const f of failing.slice(0, maxToShow)) {
90
+ console.log(` ${colorFn(isPermissive ? "\u26A0" : "\u2716")} ${pc.bold(f.relPath)} [${f.functionName}]: ${f.violations.join(", ")}`);
55
91
  }
56
- const thresholds = {
92
+ if (failing.length > maxToShow) {
93
+ console.log(colorFn(` ... and ${failing.length - maxToShow} more functions exceeding thresholds.`));
94
+ }
95
+ }
96
+ function printQualityConsole(result) {
97
+ const isPermissive = result.policy.enforce_mode === "PERMISSIVE";
98
+ console.log(
99
+ ` 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}`
100
+ );
101
+ console.log(` Analyzed files: ${pc.bold(String(result.totalFiles))}`);
102
+ console.log(` Evaluated functions: ${pc.bold(String(result.totalFunctions))}`);
103
+ console.log(` Compliant functions: ${pc.green(String(result.passCount))}`);
104
+ console.log(` Failing functions: ${result.failCount > 0 ? isPermissive ? pc.yellow(String(result.failCount)) : pc.red(String(result.failCount)) : pc.green("0")}`);
105
+ if (result.failCount > 0) {
106
+ printQualityFailingDetails(result.results.filter((r) => r.status === "FAIL"), isPermissive);
107
+ }
108
+ const tag = isPermissive && result.failCount > 0 ? " (PERMISSIVE mode)" : "";
109
+ console.log(result.success ? pc.green(`
110
+ \u2714 Release Gate PASSED${tag}
111
+ `) : pc.red("\n\u2716 Release Gate BLOCKED\n"));
112
+ }
113
+ function buildQualityThresholds(options) {
114
+ return {
57
115
  max_cyclomatic: options.maxCyclomatic !== void 0 ? Number(options.maxCyclomatic) : void 0,
58
116
  max_cognitive: options.maxCognitive !== void 0 ? Number(options.maxCognitive) : void 0,
59
117
  min_maintainability: options.minMaintainability !== void 0 ? Number(options.minMaintainability) : void 0,
60
118
  max_function_lines: options.maxLines !== void 0 ? Number(options.maxLines) : void 0,
61
119
  enforce_mode: options.enforceMode
62
120
  };
63
- const result = verifyQualityGate({ rootDir, policyPath: options.policy, thresholds });
121
+ }
122
+ function runVerifyQuality(options = {}) {
123
+ const rootDir = options.root || process.cwd();
124
+ const useJson = isJsonOutput(options);
125
+ if (!options.silent && !useJson) {
126
+ console.log(pc.bold(pc.cyan("\n\u{1F50D} [AI-SDLC] Verifying Quality Gate (Complexity & Maintainability)...")));
127
+ }
128
+ const result = verifyQualityGate({
129
+ rootDir,
130
+ policyPath: options.policy,
131
+ thresholds: buildQualityThresholds(options)
132
+ });
64
133
  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;
134
+ emitQualityJson(result);
135
+ } else if (!options.silent) {
136
+ printQualityConsole(result);
93
137
  }
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
- }
138
+ return result.success;
139
+ }
140
+ function emitTraceabilityJson(result) {
141
+ const payload = {
142
+ gate: "traceability",
143
+ success: result.success,
144
+ exitCode: result.success ? 0 : 1,
145
+ summary: {
146
+ totalRequirements: result.totalRequirements,
147
+ conformingCount: result.totalRequirements - result.orphanCount,
148
+ orphanCount: result.orphanCount
149
+ },
150
+ violations: result.orphans.map((o) => ({
151
+ id: o.id,
152
+ title: o.title,
153
+ productStatus: o.productStatus,
154
+ archStatus: o.archStatus,
155
+ testStatus: o.testStatus,
156
+ message: `Orphan requirement [${o.id}]`
157
+ }))
158
+ };
159
+ console.log(JSON.stringify(payload, null, 2));
160
+ }
161
+ function printTraceabilityConsole(result) {
162
+ console.log(` Total requirements: ${pc.bold(String(result.totalRequirements))}`);
163
+ console.log(` Compliant requirements: ${pc.green(String(result.totalRequirements - result.orphanCount))}`);
164
+ console.log(` Orphan requirements: ${result.orphanCount > 0 ? pc.red(String(result.orphanCount)) : pc.green("0")}`);
165
+ if (result.orphanCount > 0) {
166
+ console.log(pc.red("\n Traceability gaps:"));
167
+ for (const o of result.orphans) {
168
+ console.log(` ${pc.red("\u2716")} [${o.id}] Product: ${o.productStatus}, Architecture: ${o.archStatus}, Testing: ${o.testStatus}`);
107
169
  }
108
170
  }
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;
171
+ console.log(result.success ? pc.green("\n\u2714 360\xB0 Traceability COMPLIANT (100%)\n") : pc.red("\n\u2716 Traceability BLOCKED\n"));
114
172
  }
115
173
  function runVerifyTraceability(options = {}) {
116
174
  const rootDir = options.root || process.cwd();
@@ -121,43 +179,46 @@ function runVerifyTraceability(options = {}) {
121
179
  }
122
180
  const result = verifyTraceability({ rootDir });
123
181
  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));
182
+ emitTraceabilityJson(result);
143
183
  return result.success;
144
184
  }
145
185
  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
- }
186
+ printTraceabilityConsole(result);
155
187
  }
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"));
188
+ return result.success;
189
+ }
190
+ function emitGovernanceJson(result) {
191
+ const payload = {
192
+ gate: "governance",
193
+ success: result.success,
194
+ exitCode: result.success ? 0 : 1,
195
+ summary: {
196
+ totalTasks: result.totalTasks,
197
+ verifiedCount: result.verifiedCount,
198
+ unverifiedCount: result.unverifiedCount,
199
+ modeCounts: result.modeCounts,
200
+ riskCounts: result.riskCounts
201
+ },
202
+ violations: result.violations.map((v) => ({ message: v }))
203
+ };
204
+ console.log(JSON.stringify(payload, null, 2));
205
+ }
206
+ function printGovernanceConsole(result) {
207
+ console.log(` Total audited tasks: ${pc.bold(String(result.totalTasks))}`);
208
+ console.log(` Tasks with verification: ${pc.green(String(result.verifiedCount))}`);
209
+ console.log(` Tasks without verif.: ${result.unverifiedCount > 0 ? pc.red(String(result.unverifiedCount)) : pc.green("0")}`);
210
+ console.log(` Autonomy distribution:`);
211
+ console.log(` \u{1F7E2} AUTONOMOUS: ${result.modeCounts["AUTONOMOUS"] || 0}`);
212
+ console.log(` \u{1F7E1} HUMAN_REVIEW_PLAN: ${result.modeCounts["HUMAN_REVIEW_PLAN"] || 0}`);
213
+ console.log(` \u{1F7E0} AMBIGUOUS: ${result.modeCounts["AMBIGUOUS"] || 0}`);
214
+ console.log(` \u{1F534} HIGH_RISK_MANUAL: ${result.modeCounts["HIGH_RISK_MANUAL"] || 0}`);
215
+ if (result.violations.length > 0) {
216
+ console.log(pc.red("\n Governance violations:"));
217
+ for (const v of result.violations) {
218
+ console.log(` ${pc.red("\u2716")} ${v}`);
219
+ }
159
220
  }
160
- return isOk;
221
+ console.log(result.success ? pc.green("\n\u2714 Tasks Governance COMPLIANT\n") : pc.red("\n\u2716 Tasks Governance BLOCKED\n"));
161
222
  }
162
223
  function runVerifyGovernance(options = {}) {
163
224
  const rootDir = options.root || process.cwd();
@@ -168,43 +229,61 @@ function runVerifyGovernance(options = {}) {
168
229
  }
169
230
  const result = verifyTasksGovernance({ rootDir });
170
231
  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));
232
+ emitGovernanceJson(result);
185
233
  return result.success;
186
234
  }
187
235
  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
- }
236
+ printGovernanceConsole(result);
202
237
  }
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"));
238
+ return result.success;
239
+ }
240
+ function buildTestingViolations(result) {
241
+ const reqViolations = result.requirements.filter((r) => r.status !== "VERIFICADO_CON_PRUEBA").map((r) => ({
242
+ type: "REQUIREMENT",
243
+ id: r.id,
244
+ title: r.title,
245
+ file: r.file,
246
+ message: `Requirement without verifiable test [${r.id}]`
247
+ }));
248
+ const taskViolations = result.tasks.filter((t) => t.status !== "VERIFICADO_CON_PRUEBA").map((t) => ({
249
+ type: "TASK",
250
+ id: t.id,
251
+ title: t.title,
252
+ file: t.file,
253
+ message: `Task without test verification [${t.id}]`
254
+ }));
255
+ return [...reqViolations, ...taskViolations];
256
+ }
257
+ function emitTestingJson(result) {
258
+ const payload = {
259
+ gate: "testing",
260
+ success: result.success,
261
+ exitCode: result.success ? 0 : 1,
262
+ summary: {
263
+ totalRequirements: result.totalRequirements,
264
+ passedRequirements: result.passedRequirements,
265
+ failedRequirements: result.failedRequirements,
266
+ totalTasks: result.totalTasks,
267
+ passedTasks: result.passedTasks,
268
+ failedTasks: result.failedTasks
269
+ },
270
+ violations: buildTestingViolations(result)
271
+ };
272
+ console.log(JSON.stringify(payload, null, 2));
273
+ }
274
+ function printTestingConsole(result) {
275
+ console.log(` Verified requirements: ${pc.green(`${result.passedRequirements}/${result.totalRequirements}`)}`);
276
+ console.log(` Verified tasks: ${pc.green(`${result.passedTasks}/${result.totalTasks}`)}`);
277
+ if (result.failedRequirements > 0 || result.failedTasks > 0) {
278
+ console.log(pc.red("\n Items lacking executable tests:"));
279
+ for (const r of result.requirements.filter((r2) => r2.status !== "VERIFICADO_CON_PRUEBA")) {
280
+ console.log(` ${pc.red("\u2716")} [Requirement: ${r.id}] ${r.title} (${r.file})`);
281
+ }
282
+ for (const t of result.tasks.filter((t2) => t2.status !== "VERIFICADO_CON_PRUEBA")) {
283
+ console.log(` ${pc.red("\u2716")} [Task: ${t.id}] ${t.title} (${t.file})`);
284
+ }
206
285
  }
207
- return isOk;
286
+ console.log(result.success ? pc.green("\n\u2714 Test Coverage COMPLIANT (100%)\n") : pc.red("\n\u2716 Test Coverage INSUFFICIENT\n"));
208
287
  }
209
288
  function runVerifyTesting(options = {}) {
210
289
  const rootDir = options.root || process.cwd();
@@ -215,126 +294,116 @@ function runVerifyTesting(options = {}) {
215
294
  }
216
295
  const result = verifyTestingCoverage({ rootDir });
217
296
  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));
297
+ emitTestingJson(result);
247
298
  return result.success;
248
299
  }
249
300
  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"));
301
+ printTestingConsole(result);
265
302
  }
266
- return isOk;
303
+ return result.success;
267
304
  }
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)...")));
305
+ function emitLicensesJson(result) {
306
+ const payload = {
307
+ gate: "licenses",
308
+ success: result.success,
309
+ exitCode: result.success ? 0 : 1,
310
+ summary: {
311
+ totalEvaluated: result.totalEvaluated,
312
+ permittedCount: result.permittedCount,
313
+ violationsCount: result.violations.length
314
+ },
315
+ violations: result.violations.map((v) => ({
316
+ package: v.packageName,
317
+ version: v.version,
318
+ license: v.license,
319
+ category: v.category,
320
+ message: v.reason
321
+ })),
322
+ artifacts: {
323
+ sbomPath: result.sbomPath,
324
+ noticesPath: result.noticesPath
325
+ }
326
+ };
327
+ console.log(JSON.stringify(payload, null, 2));
328
+ }
329
+ function printLicensesConsole(result) {
330
+ console.log(` Evaluated dependencies: ${pc.bold(String(result.totalEvaluated))}`);
331
+ console.log(` Compliant dependencies: ${pc.green(String(result.permittedCount))}`);
332
+ console.log(` License violations: ${result.violations.length > 0 ? pc.red(String(result.violations.length)) : pc.green("0")}`);
333
+ if (result.sbomPath) {
334
+ console.log(` CycloneDX SBOM generated: ${pc.cyan(result.sbomPath)}`);
335
+ }
336
+ if (result.noticesPath) {
337
+ console.log(` Legal notices generated: ${pc.cyan(result.noticesPath)}`);
338
+ }
339
+ if (result.violations.length > 0) {
340
+ console.log(pc.red("\n Detected license violations:"));
341
+ for (const v of result.violations) {
342
+ console.log(` ${pc.red("\u2716")} [${v.category}] ${v.packageName} (${v.license}): ${v.reason}`);
343
+ }
274
344
  }
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({
345
+ console.log(result.success ? pc.green("\n\u2714 OSS License Governance COMPLIANT\n") : pc.red("\n\u2716 OSS License Governance BLOCKED\n"));
346
+ }
347
+ function buildLicenseVerifyInput(options, rootDir) {
348
+ return {
280
349
  rootDir,
281
350
  policyPath: options.policy,
282
351
  manifestPath: options.manifest,
283
352
  dynamic: options.dynamic,
284
353
  tool: options.tool,
285
354
  depth: options.depth,
286
- generateSbom,
287
- sbomPath,
288
- generateNotices,
289
- noticesPath
290
- });
355
+ generateSbom: options.sbom !== void 0 ? Boolean(options.sbom) : void 0,
356
+ sbomPath: typeof options.sbom === "string" ? options.sbom : void 0,
357
+ generateNotices: options.notices !== void 0 ? Boolean(options.notices) : void 0,
358
+ noticesPath: typeof options.notices === "string" ? options.notices : void 0
359
+ };
360
+ }
361
+ function runVerifyLicenses(options = {}) {
362
+ const rootDir = options.root || process.cwd();
363
+ const useJson = isJsonOutput(options);
364
+ if (!options.silent && !useJson) {
365
+ console.log(pc.bold(pc.cyan("\n\u{1F50D} [AI-SDLC] Verifying Open Source License Compliance (SCA)...")));
366
+ }
367
+ const result = verifyLicenses(buildLicenseVerifyInput(options, rootDir));
291
368
  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;
369
+ emitLicensesJson(result);
370
+ } else if (!options.silent) {
371
+ printLicensesConsole(result);
315
372
  }
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
- }
373
+ return result.success;
374
+ }
375
+ function emitPdacJson(result) {
376
+ const payload = {
377
+ gate: "pdac",
378
+ success: result.success,
379
+ exitCode: result.success ? 0 : 1,
380
+ summary: {
381
+ totalNodes: result.totalNodes,
382
+ totalEdges: result.totalEdges,
383
+ driftCount: result.drifts.length
384
+ },
385
+ violations: result.drifts.map((d) => ({
386
+ sourceId: d.sourceId,
387
+ targetId: d.targetId,
388
+ sourceFile: d.sourceFile,
389
+ expectedDigest: d.expectedDigest,
390
+ actualDigest: d.actualDigest,
391
+ message: `Cryptographic drift in ${d.sourceFile} citing ${d.targetId}`
392
+ }))
393
+ };
394
+ console.log(JSON.stringify(payload, null, 2));
395
+ }
396
+ function printPdacConsole(result) {
397
+ console.log(` PDaC baseline nodes: ${pc.bold(String(result.totalNodes))}`);
398
+ console.log(` Evaluated citations: ${pc.bold(String(result.totalEdges))}`);
399
+ console.log(` Cryptographic drifts: ${result.drifts.length > 0 ? pc.red(String(result.drifts.length)) : pc.green("0")}`);
400
+ if (result.drifts.length > 0) {
401
+ console.log(pc.red("\n Detected drifts (Status: STALE):"));
402
+ for (const d of result.drifts) {
403
+ console.log(` ${pc.red("\u2716")} In ${d.sourceFile} citing ${d.targetId}: misaligned digest.`);
331
404
  }
332
405
  }
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;
406
+ console.log(result.success ? pc.green("\n\u2714 PDaC Graph Free of Drift\n") : pc.red("\n\u2716 Cryptographic Drift Detected\n"));
338
407
  }
339
408
  function runVerifyPdac(options = {}) {
340
409
  const rootDir = options.root || process.cwd();
@@ -345,43 +414,45 @@ function runVerifyPdac(options = {}) {
345
414
  }
346
415
  const result = verifyPdacGraph({ rootDir });
347
416
  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));
417
+ emitPdacJson(result);
367
418
  return result.success;
368
419
  }
369
420
  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
- }
421
+ printPdacConsole(result);
379
422
  }
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"));
423
+ return result.success;
424
+ }
425
+ function emitSchemasJson(result) {
426
+ const payload = {
427
+ gate: "schemas",
428
+ success: result.success,
429
+ exitCode: result.success ? 0 : 1,
430
+ summary: {
431
+ totalEvaluated: result.totalEvaluated,
432
+ validCount: result.validCount,
433
+ invalidCount: result.invalidCount
434
+ },
435
+ violations: result.violations.map((v) => ({
436
+ file: v.filePath,
437
+ id: v.id,
438
+ schemaId: v.schemaId,
439
+ property: v.property,
440
+ message: v.message
441
+ }))
442
+ };
443
+ console.log(JSON.stringify(payload, null, 2));
444
+ }
445
+ function printSchemasConsole(result) {
446
+ console.log(` Evaluated artifacts: ${pc.bold(String(result.totalEvaluated))}`);
447
+ console.log(` Compliant artifacts: ${pc.green(String(result.validCount))}`);
448
+ console.log(` Schema violations: ${result.invalidCount > 0 ? pc.red(String(result.invalidCount)) : pc.green("0")}`);
449
+ if (result.violations.length > 0) {
450
+ console.log(pc.red("\n Detected JSON schema violations:"));
451
+ for (const v of result.violations) {
452
+ console.log(` ${pc.red("\u2716")} [${v.id || v.filePath}] (${v.schemaId || "schema"}): ${v.message}`);
453
+ }
383
454
  }
384
- return isOk;
455
+ console.log(result.success ? pc.green("\n\u2714 Artifact Schemas COMPLIANT (100%)\n") : pc.red("\n\u2716 Artifact Schemas BLOCKED\n"));
385
456
  }
386
457
  function runVerifySchemas(options = {}) {
387
458
  const rootDir = options.root || process.cwd();
@@ -392,42 +463,50 @@ function runVerifySchemas(options = {}) {
392
463
  }
393
464
  const result = verifyArtifactsSchemas({ rootDir, targetPath: options.path });
394
465
  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));
466
+ emitSchemasJson(result);
413
467
  return result.success;
414
468
  }
415
469
  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
- }
470
+ printSchemasConsole(result);
471
+ }
472
+ return result.success;
473
+ }
474
+ function emitFrictionJson(result) {
475
+ const violations = [
476
+ ...result.bypassedRules.map((rule) => ({ type: "ANTI_BYPASS", message: rule })),
477
+ ...result.errors.map((err) => ({ type: "PROFILE_ERROR", message: err }))
478
+ ];
479
+ const payload = {
480
+ gate: "friction",
481
+ success: result.success,
482
+ exitCode: result.success ? 0 : 1,
483
+ summary: {
484
+ profile: result.profile,
485
+ evaluatedFilesCount: result.evaluatedFiles.length,
486
+ bypassed: result.bypassed
487
+ },
488
+ violations
489
+ };
490
+ console.log(JSON.stringify(payload, null, 2));
491
+ }
492
+ function printFrictionConsole(result) {
493
+ console.log(` Detected profile: ${pc.magenta(result.profile)}`);
494
+ console.log(` Evaluated files: ${pc.bold(String(result.evaluatedFiles.length))}`);
495
+ if (result.bypassedRules.length > 0) {
496
+ console.log(pc.red("\n Anti-Bypass violations detected:"));
497
+ for (const rule of result.bypassedRules) {
498
+ console.log(` ${pc.red("\u2716")} ${rule}`);
424
499
  }
425
500
  }
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"));
501
+ if (result.errors.length > 0) {
502
+ console.log(pc.red("\n Profile validation errors:"));
503
+ for (const err of result.errors) {
504
+ console.log(` ${pc.red("\u2716")} ${err}`);
505
+ }
429
506
  }
430
- return isOk;
507
+ console.log(
508
+ result.success ? pc.green("\n\u2714 Progressive Friction COMPLIANT (EXIT 0)\n") : pc.red("\n\u2716 Progressive Friction BLOCKED (EXIT 1)\n")
509
+ );
431
510
  }
432
511
  function runVerifyFriction(options = {}) {
433
512
  const rootDir = options.root || process.cwd();
@@ -442,47 +521,50 @@ function runVerifyFriction(options = {}) {
442
521
  diffFiles: options.diffFiles
443
522
  });
444
523
  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));
524
+ emitFrictionJson(result);
461
525
  return result.success;
462
526
  }
463
527
  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
- }
528
+ printFrictionConsole(result);
478
529
  }
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
- );
530
+ return result.success;
531
+ }
532
+ function emitDuplicatesJson(result) {
533
+ const payload = {
534
+ gate: "duplicates",
535
+ success: result.success,
536
+ exitCode: result.success ? 0 : 1,
537
+ summary: {
538
+ totalRequirements: result.totalRequirements,
539
+ errorCount: result.errorCount,
540
+ warningCount: result.warningCount
541
+ },
542
+ violations: result.issues.map((i) => ({
543
+ type: i.type,
544
+ severity: i.severity,
545
+ id: i.id,
546
+ file: i.file,
547
+ conflictingId: i.conflictingId,
548
+ message: i.message
549
+ }))
550
+ };
551
+ console.log(JSON.stringify(payload, null, 2));
552
+ }
553
+ function printDuplicatesConsole(result) {
554
+ console.log(` Evaluated requirements: ${pc.bold(String(result.totalRequirements))}`);
555
+ console.log(` Duplication errors: ${result.errorCount > 0 ? pc.red(String(result.errorCount)) : pc.green("0")}`);
556
+ console.log(` Warnings: ${result.warningCount > 0 ? pc.yellow(String(result.warningCount)) : pc.green("0")}`);
557
+ if (result.issues.length > 0) {
558
+ console.log(pc.red("\n Detected issues:"));
559
+ for (const issue of result.issues) {
560
+ const icon = issue.severity === "ERROR" ? pc.red("\u2716") : pc.yellow("\u26A0");
561
+ const badge = issue.severity === "ERROR" ? pc.red(`[${issue.type}]`) : pc.yellow(`[${issue.type}]`);
562
+ console.log(` ${icon} ${badge} [${issue.id}] in ${issue.file}: ${issue.message}`);
563
+ }
484
564
  }
485
- return isOk;
565
+ console.log(
566
+ result.success ? pc.green("\n\u2714 Duplicates Verification COMPLIANT (0 Collisions)\n") : pc.red("\n\u2716 Duplicates Verification BLOCKED (Collisions Detected)\n")
567
+ );
486
568
  }
487
569
  function runVerifyDuplicates(options = {}) {
488
570
  const rootDir = options.root || process.cwd();
@@ -490,64 +572,53 @@ function runVerifyDuplicates(options = {}) {
490
572
  const useJson = isJsonOutput(options);
491
573
  const isSilent = Boolean(options.silent || useJson);
492
574
  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
- );
575
+ console.log(pc.bold(pc.cyan("\n\u{1F50D} [AI-SDLC] Verifying Duplicate Requirements and Redundancy (Shift-Left Pre-Flight)...")));
500
576
  }
501
577
  const result = verifyArtifactDuplicates({
502
578
  rootDir,
503
579
  titleSimilarityThreshold: similarityThreshold
504
580
  });
505
581
  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));
582
+ emitDuplicatesJson(result);
525
583
  return result.success;
526
584
  }
527
585
  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
- }
586
+ printDuplicatesConsole(result);
543
587
  }
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
- );
588
+ return result.success;
589
+ }
590
+ function emitSecretsJson(result) {
591
+ const payload = {
592
+ gate: "secrets",
593
+ success: result.success,
594
+ exitCode: result.success ? 0 : 4,
595
+ summary: {
596
+ totalFilesScanned: result.totalFilesScanned,
597
+ findingsCount: result.findingsCount,
598
+ scannedWithGitleaks: result.scannedWithGitleaks
599
+ },
600
+ violations: result.findings.map((f) => ({
601
+ ruleId: f.ruleId,
602
+ file: f.relPath,
603
+ line: f.lineNumber,
604
+ type: f.type,
605
+ maskedMatch: f.maskedMatch,
606
+ message: f.message
607
+ }))
608
+ };
609
+ console.log(JSON.stringify(payload, null, 2));
610
+ }
611
+ function printSecretsConsole(result) {
612
+ console.log(` Analyzed files: ${pc.bold(String(result.totalFilesScanned))}`);
613
+ console.log(` Credential leaks: ${result.findingsCount > 0 ? pc.red(String(result.findingsCount)) : pc.green("0")}`);
614
+ console.log(` Native Gitleaks engine: ${result.scannedWithGitleaks ? pc.cyan("Active / Integrated") : pc.dim("Deterministic Scanner (@aisdlc/core)")}`);
615
+ if (result.findings.length > 0) {
616
+ console.log(pc.red("\n Detected exposed credentials:"));
617
+ for (const f of result.findings) {
618
+ console.log(` ${pc.red("\u2716")} [${f.ruleId}] ${pc.bold(`${f.relPath}:${f.lineNumber}`)}: ${f.maskedMatch} - ${f.message}`);
619
+ }
549
620
  }
550
- return isOk;
621
+ console.log(result.success ? pc.green("\n\u2714 Secrets Detection COMPLIANT (0 Credential Leaks)\n") : pc.red("\n\u2716 Secrets Detection BLOCKED (Exit Code 4: Exposed Secret)\n"));
551
622
  }
552
623
  function runVerifySecrets(options = {}) {
553
624
  const rootDir = options.root || process.cwd();
@@ -555,13 +626,7 @@ function runVerifySecrets(options = {}) {
555
626
  const useJson = isJsonOutput(options);
556
627
  const isSilent = Boolean(options.silent || useJson);
557
628
  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
- );
629
+ console.log(pc.bold(pc.cyan("\n\u{1F510} [AI-SDLC] Verifying Deterministic Secrets and Credentials Detection (Gitleaks Gate)...")));
565
630
  }
566
631
  const result = verifySecrets({
567
632
  rootDir,
@@ -571,64 +636,51 @@ function runVerifySecrets(options = {}) {
571
636
  entropyThreshold
572
637
  });
573
638
  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));
639
+ emitSecretsJson(result);
593
640
  return result.success;
594
641
  }
595
642
  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
- }
643
+ printSecretsConsole(result);
611
644
  }
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
- );
645
+ return result.success;
646
+ }
647
+ function emitSastJson(result) {
648
+ const payload = {
649
+ gate: "sast",
650
+ success: result.success,
651
+ exitCode: result.success ? 0 : 1,
652
+ summary: {
653
+ totalFilesScanned: result.totalFilesScanned,
654
+ violationsCount: result.violationsCount
655
+ },
656
+ violations: result.violations.map((v) => ({
657
+ ruleId: v.ruleId,
658
+ file: v.relPath,
659
+ line: v.lineNumber,
660
+ type: v.type,
661
+ severity: v.severity,
662
+ message: v.message
663
+ }))
664
+ };
665
+ console.log(JSON.stringify(payload, null, 2));
666
+ }
667
+ function printSastConsole(result) {
668
+ console.log(` Evaluated files: ${pc.bold(String(result.totalFilesScanned))}`);
669
+ console.log(` SAST vulnerabilities: ${result.violationsCount > 0 ? pc.red(String(result.violationsCount)) : pc.green("0")}`);
670
+ if (result.violations.length > 0) {
671
+ console.log(pc.red("\n Detected vulnerabilities:"));
672
+ for (const v of result.violations) {
673
+ console.log(` ${pc.red("\u2716")} [${v.severity}] [${v.ruleId}] ${pc.bold(`${v.relPath}:${v.lineNumber}`)}: ${v.message}`);
674
+ }
617
675
  }
618
- return isOk;
676
+ console.log(result.success ? pc.green("\n\u2714 SAST Analysis COMPLIANT (0 Critical Vulnerabilities)\n") : pc.red("\n\u2716 SAST Analysis BLOCKED (Vulnerabilities Detected)\n"));
619
677
  }
620
678
  function runVerifySast(options = {}) {
621
679
  const rootDir = options.root || process.cwd();
622
680
  const useJson = isJsonOutput(options);
623
681
  const isSilent = Boolean(options.silent || useJson);
624
682
  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
- );
683
+ console.log(pc.bold(pc.cyan("\n\u{1F6E1}\uFE0F [AI-SDLC] Verifying Shift-Left SAST Security (Injections & OWASP Top 10)...")));
632
684
  }
633
685
  const result = verifySast({
634
686
  rootDir,
@@ -636,47 +688,47 @@ function runVerifySast(options = {}) {
636
688
  minSeverity: options.minSeverity
637
689
  });
638
690
  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));
691
+ emitSastJson(result);
657
692
  return result.success;
658
693
  }
659
694
  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
- );
695
+ printSastConsole(result);
678
696
  }
679
- return isOk;
697
+ return result.success;
698
+ }
699
+ function buildSecurityViolations(resultSecrets, resultSast) {
700
+ const secretViolations = resultSecrets.findings.map((f) => ({
701
+ type: "SECRET",
702
+ ruleId: f.ruleId,
703
+ file: f.relPath,
704
+ line: f.lineNumber,
705
+ message: f.message
706
+ }));
707
+ const sastViolations = resultSast.violations.map((v) => ({
708
+ type: "SAST",
709
+ ruleId: v.ruleId,
710
+ file: v.relPath,
711
+ line: v.lineNumber,
712
+ severity: v.severity,
713
+ message: v.message
714
+ }));
715
+ return [...secretViolations, ...sastViolations];
716
+ }
717
+ function emitSecurityJson(resultSecrets, resultSast, isOk) {
718
+ const exitCode = isOk ? 0 : !resultSecrets.success ? 4 : 1;
719
+ const payload = {
720
+ gate: "security",
721
+ success: isOk,
722
+ exitCode,
723
+ summary: {
724
+ secretsScanned: resultSecrets.totalFilesScanned,
725
+ secretFindings: resultSecrets.findingsCount,
726
+ sastScanned: resultSast.totalFilesScanned,
727
+ sastViolations: resultSast.violationsCount
728
+ },
729
+ violations: buildSecurityViolations(resultSecrets, resultSast)
730
+ };
731
+ console.log(JSON.stringify(payload, null, 2));
680
732
  }
681
733
  function runVerifySecurity(options = {}) {
682
734
  const rootDir = options.root || process.cwd();
@@ -694,46 +746,129 @@ function runVerifySecurity(options = {}) {
694
746
  semgrep: options.semgrep,
695
747
  minSeverity: options.minSeverity
696
748
  });
697
- const okSecrets = resultSecrets.success;
698
- const okSast = resultSast.success;
699
- const isOk = okSecrets && okSast;
749
+ const isOk = resultSecrets.success && resultSast.success;
700
750
  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));
751
+ emitSecurityJson(resultSecrets, resultSast, isOk);
731
752
  return isOk;
732
753
  }
733
754
  const okS = runVerifySecrets({ ...options, silent: options.silent });
734
755
  const okA = runVerifySast({ ...options, silent: options.silent });
735
756
  return okS && okA;
736
757
  }
758
+ function emitGherkinVerifyJson(result) {
759
+ const violations = [
760
+ ...result.missingFiles.map((f) => ({
761
+ type: "MISSING_FEATURE",
762
+ file: f,
763
+ message: `Missing .feature file: ${f}`
764
+ })),
765
+ ...result.outOfSyncFiles.map((f) => ({
766
+ type: "OUT_OF_SYNC_FEATURE",
767
+ file: f,
768
+ message: `Out-of-sync .feature file: ${f}`
769
+ }))
770
+ ];
771
+ const payload = {
772
+ gate: "gherkin",
773
+ success: result.inSync,
774
+ exitCode: result.inSync ? 0 : 1,
775
+ summary: {
776
+ totalFeatures: result.totalFeatures,
777
+ missingCount: result.missingFiles.length,
778
+ outOfSyncCount: result.outOfSyncFiles.length
779
+ },
780
+ violations
781
+ };
782
+ console.log(JSON.stringify(payload, null, 2));
783
+ }
784
+ function printGherkinVerifyConsole(result) {
785
+ const totalOut = result.missingFiles.length + result.outOfSyncFiles.length;
786
+ console.log(` Evaluated features: ${pc.bold(String(result.totalFeatures))}`);
787
+ console.log(` Out-of-sync / missing: ${totalOut > 0 ? pc.red(String(totalOut)) : pc.green("0")}`);
788
+ for (const f of result.missingFiles) {
789
+ console.log(` ${pc.red("\u2716")} [MISSING] ${f}`);
790
+ }
791
+ for (const f of result.outOfSyncFiles) {
792
+ console.log(` ${pc.red("\u2716")} [OUT_OF_SYNC] ${f}`);
793
+ }
794
+ console.log(result.inSync ? pc.green("\n\u2714 BDD Synchronization COMPLIANT\n") : pc.red("\n\u2716 BDD Synchronization BLOCKED\n"));
795
+ }
796
+ function runVerifyGherkin(options = {}) {
797
+ const rootDir = options.root || process.cwd();
798
+ const useJson = isJsonOutput(options);
799
+ const isSilent = Boolean(options.silent || useJson);
800
+ if (!isSilent) {
801
+ console.log(pc.bold(pc.cyan("\n\u{1F952} [AI-SDLC] Verifying BDD Synchronization (Gherkin -> .feature)...")));
802
+ }
803
+ const result = checkGherkinInSync({ rootDir });
804
+ if (useJson) {
805
+ emitGherkinVerifyJson(result);
806
+ return result.inSync;
807
+ }
808
+ if (!options.silent) {
809
+ printGherkinVerifyConsole(result);
810
+ }
811
+ return result.inSync;
812
+ }
813
+ function collectAllGates(options, root, isSilent) {
814
+ return {
815
+ quality: { success: runVerifyQuality({ ...options, root, silent: isSilent, json: false }) },
816
+ traceability: { success: runVerifyTraceability({ root, silent: isSilent, json: false }) },
817
+ governance: { success: runVerifyGovernance({ root, silent: isSilent, json: false }) },
818
+ testing: { success: runVerifyTesting({ root, silent: isSilent, json: false }) },
819
+ gherkin: { success: runVerifyGherkin({ root, silent: isSilent, json: false }) },
820
+ licenses: { success: runVerifyLicenses({ root, silent: isSilent, json: false }) },
821
+ pdac: { success: runVerifyPdac({ root, silent: isSilent, json: false }) },
822
+ schemas: { success: runVerifySchemas({ root, silent: isSilent, json: false }) },
823
+ duplicates: { success: runVerifyDuplicates({ root, silent: isSilent, json: false }) },
824
+ friction: { success: runVerifyFriction({ root, silent: isSilent, json: false }) },
825
+ security: { success: runVerifySecurity({ root, silent: isSilent, json: false }) }
826
+ };
827
+ }
828
+ function emitVerifyAllJson(gatesSummary, allPassed) {
829
+ const totalGates = Object.keys(gatesSummary).length;
830
+ const passedCount = Object.values(gatesSummary).filter((g) => g.success).length;
831
+ const failedCount = totalGates - passedCount;
832
+ const okSecurity = gatesSummary.security.success;
833
+ const exitCode = allPassed ? 0 : !okSecurity ? 4 : 1;
834
+ const violations = Object.entries(gatesSummary).filter(([, g]) => !g.success).map(([name]) => ({ gate: name, message: `Gate ${name} failed verification criteria` }));
835
+ const payload = {
836
+ gate: "all",
837
+ success: allPassed,
838
+ exitCode,
839
+ summary: { totalGates, passedGates: passedCount, failedGates: failedCount },
840
+ gates: gatesSummary,
841
+ violations
842
+ };
843
+ console.log(JSON.stringify(payload, null, 2));
844
+ }
845
+ var VERIFY_ALL_GATES_LIST = [
846
+ { key: "quality", title: " 1. Quality Gate (Complexity/Maintainability): " },
847
+ { key: "traceability", title: " 2. 360\xB0 Traceability (RTM): " },
848
+ { key: "governance", title: " 3. Governance and Autonomy Modes: " },
849
+ { key: "testing", title: " 4. Test Coverage (Reqs & Tasks): " },
850
+ { key: "gherkin", title: " 5. BDD Synchronization (Gherkin -> .feature): " },
851
+ { key: "licenses", title: " 6. Open Source Licenses: " },
852
+ { key: "pdac", title: " 7. PDaC & Cryptographic Drift: " },
853
+ { key: "schemas", title: " 8. Artifact JSON Schemas (+ Handoff YAML): " },
854
+ { key: "duplicates", title: " 9. Duplicate Requirements (Shift-Left Gate): " },
855
+ { key: "friction", title: " 10. Progressive Friction & Anti-Bypass: " },
856
+ { key: "security", title: " 11. Shift-Left Security (Secrets & SAST): " }
857
+ ];
858
+ function printVerifyAllSummaryTable(gatesSummary, allPassed) {
859
+ console.log(pc.bold(pc.magenta("================================================================")));
860
+ console.log(pc.bold("CI/CD EVALUATION SUMMARY:"));
861
+ for (const item of VERIFY_ALL_GATES_LIST) {
862
+ const passed = Boolean(gatesSummary[item.key]?.success);
863
+ console.log(`${item.title}${passed ? pc.green("PASSED") : pc.red("FAILED")}`);
864
+ }
865
+ console.log(pc.bold(pc.magenta("================================================================")));
866
+ if (allPassed) {
867
+ console.log(pc.bold(pc.green("\n\u2728 FINAL VERDICT: REPOSITORY COMPLIANT WITH AI-SDLC STANDARD (EXIT 0)\n")));
868
+ } else {
869
+ console.log(pc.bold(pc.red("\n\u26D4 FINAL VERDICT: BLOCKED BY DETECTED VIOLATIONS (EXIT 1)\n")));
870
+ }
871
+ }
737
872
  function runVerifyAll(options = {}) {
738
873
  const useJson = isJsonOutput(options);
739
874
  const isSilent = Boolean(options.silent || useJson);
@@ -743,65 +878,14 @@ function runVerifyAll(options = {}) {
743
878
  console.log(pc.bold(pc.magenta("================================================================")));
744
879
  }
745
880
  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;
881
+ const gatesSummary = collectAllGates(options, root, isSilent);
882
+ const allPassed = Object.values(gatesSummary).every((g) => g.success);
756
883
  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));
884
+ emitVerifyAllJson(gatesSummary, allPassed);
785
885
  return allPassed;
786
886
  }
787
887
  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
- }
888
+ printVerifyAllSummaryTable(gatesSummary, allPassed);
805
889
  }
806
890
  return allPassed;
807
891
  }
@@ -821,7 +905,7 @@ function runAutoFix(rootDir, silent) {
821
905
  return { gherkinCount: gherkinRes.features.length, digestsCount: pdacRes.syncedCount };
822
906
  }
823
907
  function auditGherkinGate(rootDir, wasAutoFixed) {
824
- const syncCheck = checkGherkinInSync({ rootDir });
908
+ const syncCheck = checkGherkinInSync2({ rootDir });
825
909
  if (wasAutoFixed) {
826
910
  return {
827
911
  name: "BDD Synchronization (Gherkin -> .feature)",
@@ -961,6 +1045,18 @@ function auditSchemasGate(rootDir) {
961
1045
  remediation: "Run 'aisdlc verify schemas' to audit and fix required fields."
962
1046
  };
963
1047
  }
1048
+ function formatSecurityErrors(secRes, sastRes) {
1049
+ const errors = [];
1050
+ if (!secRes.success) {
1051
+ const f = secRes.findings[0];
1052
+ errors.push(`${secRes.findingsCount} secret(s) (e.g. ${f.ruleId} in ${f.relPath}:${f.lineNumber})`);
1053
+ }
1054
+ if (!sastRes.success) {
1055
+ const v = sastRes.violations[0];
1056
+ errors.push(`${sastRes.violationsCount} SAST violation(s) (e.g. ${v.ruleId} in ${v.relPath}:${v.lineNumber})`);
1057
+ }
1058
+ return errors.join("; ");
1059
+ }
964
1060
  function auditSecurityGate(rootDir) {
965
1061
  const secRes = verifySecrets2({ rootDir });
966
1062
  const sastRes = verifySast2({ rootDir });
@@ -971,75 +1067,131 @@ function auditSecurityGate(rootDir) {
971
1067
  message: `${secRes.totalFilesScanned} clean files (0 secrets, 0 vulnerabilities)`
972
1068
  };
973
1069
  }
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
1070
  return {
984
1071
  name: "Shift-Left Security (Gitleaks Secrets & SAST)",
985
1072
  status: "FAILED",
986
- message: errors.join("; "),
1073
+ message: formatSecurityErrors(secRes, sastRes),
987
1074
  remediation: "Run 'aisdlc verify security' and resolve credentials or vulnerable patterns."
988
1075
  };
989
1076
  }
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))}
1077
+ function auditDuplicatesGate(rootDir) {
1078
+ const res = verifyArtifactDuplicates2({ rootDir });
1079
+ if (res.success) {
1080
+ return {
1081
+ name: "Duplicate Requirements & Redundancy",
1082
+ status: "PASSED",
1083
+ message: `${res.totalRequirements} requirements evaluated (0 collisions, ${res.warningCount} warnings)`
1084
+ };
1085
+ }
1086
+ const firstErr = res.issues.find((i) => i.severity === "ERROR")?.message || "Collision detected";
1087
+ return {
1088
+ name: "Duplicate Requirements & Redundancy",
1089
+ status: "FAILED",
1090
+ message: `${res.errorCount} duplication error(s): ${firstErr}`,
1091
+ remediation: "Run 'aisdlc verify duplicates' and resolve duplicate requirement IDs or statements."
1092
+ };
1093
+ }
1094
+ function auditFrictionGate(rootDir) {
1095
+ const res = verifyProgressiveFriction2({ rootDir });
1096
+ if (res.success) {
1097
+ return {
1098
+ name: "Progressive Friction & Anti-Bypass Guardrails",
1099
+ status: "PASSED",
1100
+ message: `Profile '${res.profile}' compliant (${res.evaluatedFiles.length} evaluated paths)`
1101
+ };
1102
+ }
1103
+ const firstViolation = res.bypassedRules[0] || res.errors[0] || "Anti-bypass guardrail triggered";
1104
+ return {
1105
+ name: "Progressive Friction & Anti-Bypass Guardrails",
1106
+ status: "FAILED",
1107
+ message: firstViolation,
1108
+ remediation: "Reclassify change profile to 'standard' or 'critical', or revert protected path changes."
1109
+ };
1110
+ }
1111
+ function renderGateBadge(status) {
1112
+ if (status === "PASSED") return pc2.green("\u2714 PASSED ");
1113
+ if (status === "FIXED") return pc2.cyan("\u{1F527} AUTO-FIX ");
1114
+ return pc2.red("\u2716 FAILED ");
1115
+ }
1116
+ function renderRemediations(failedGates) {
1117
+ console.log(pc2.bold(pc2.red("\n------------------------------------------------------------------------------")));
1118
+ console.log(pc2.bold(pc2.red(" REQUIRED ACTIONS TO RESOLVE BLOCKING ERRORS:")));
1119
+ console.log(pc2.bold(pc2.red("------------------------------------------------------------------------------")));
1120
+ failedGates.forEach((g, idx) => {
1121
+ console.log(` ${pc2.bold(String(idx + 1))}. ${pc2.yellow(g.name)}:`);
1122
+ console.log(` \u{1F449} ${pc2.bold(g.remediation || "Review affected files.")}`);
1123
+ });
1124
+ console.log(pc2.bold(pc2.red("\n\u26D4 VERDICT: PRE-FLIGHT BLOCKED (EXIT 1)\n")));
1125
+ }
1126
+ function printDashboardHeader(autoFixExecuted, gherkinCount, digestsCount) {
1127
+ console.log(pc2.bold(pc2.cyan("\n==============================================================================")));
1128
+ console.log(pc2.bold(pc2.cyan(" AI-SDLC: CONSOLIDATED PRE-FLIGHT DASHBOARD (aisdlc check) ")));
1129
+ console.log(pc2.bold(pc2.cyan("==============================================================================\n")));
1130
+ if (autoFixExecuted) {
1131
+ console.log(pc2.bold(` ${pc2.magenta("AUTO-FIX MODE ACTIVE:")} Non-destructive preliminary syncs applied:`));
1132
+ console.log(` - Gherkin scenarios synchronized: ${pc2.bold(String(gherkinCount))}`);
1133
+ console.log(` - SHA-256 digests synchronized: ${pc2.bold(String(digestsCount))}
998
1134
  `);
999
1135
  }
1136
+ }
1137
+ function printDashboardFooter(isPassed) {
1138
+ if (isPassed) {
1139
+ console.log(pc2.bold(pc2.green("\n==============================================================================")));
1140
+ console.log(pc2.bold(pc2.green("\u2728 VERDICT: PRE-FLIGHT PASSED (EXIT 0) - Repository ready for Pull Request")));
1141
+ console.log(pc2.bold(pc2.green("==============================================================================\n")));
1142
+ }
1143
+ }
1144
+ function renderDashboard(gates, autoFixExecuted, gherkinCount, digestsCount) {
1145
+ printDashboardHeader(autoFixExecuted, gherkinCount, digestsCount);
1000
1146
  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)}`);
1147
+ console.log(` [${renderGateBadge(gate.status)}] ${pc2.bold(gate.name)}`);
1003
1148
  console.log(` ${pc2.dim(gate.message)}`);
1004
1149
  }
1005
1150
  const failedGates = gates.filter((g) => g.status === "FAILED");
1006
1151
  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")));
1152
+ renderRemediations(failedGates);
1015
1153
  } 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")));
1154
+ printDashboardFooter(true);
1019
1155
  }
1020
1156
  }
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),
1157
+ function collectPreflightGates(rootDir, fix, gherkinCount, digestsCount) {
1158
+ return [
1159
+ auditGherkinGate(rootDir, fix && gherkinCount > 0),
1160
+ auditPdacGate(rootDir, fix && digestsCount > 0),
1035
1161
  auditQualityGate(rootDir),
1036
1162
  auditTraceabilityGate(rootDir),
1037
1163
  auditGovernanceGate(rootDir),
1038
1164
  auditTestingGate(rootDir),
1039
1165
  auditLicensesGate(rootDir),
1040
1166
  auditSchemasGate(rootDir),
1167
+ auditDuplicatesGate(rootDir),
1168
+ auditFrictionGate(rootDir),
1041
1169
  auditSecurityGate(rootDir)
1042
1170
  ];
1171
+ }
1172
+ function emitCheckJson(result) {
1173
+ const payload = {
1174
+ command: "check",
1175
+ success: result.success,
1176
+ exitCode: result.success ? 0 : 1,
1177
+ autoFixExecuted: result.autoFixExecuted,
1178
+ gherkinSynced: result.gherkinSynced,
1179
+ digestsSynced: result.digestsSynced,
1180
+ gates: result.gates
1181
+ };
1182
+ console.log(JSON.stringify(payload, null, 2));
1183
+ }
1184
+ function applyAutoFix(rootDir, isSilent, fix) {
1185
+ if (!fix) return { gherkinCount: 0, digestsCount: 0 };
1186
+ const res = runAutoFix(rootDir, isSilent);
1187
+ return { gherkinCount: res.gherkinCount, digestsCount: res.digestsCount };
1188
+ }
1189
+ function executePreflightCheck(options = {}) {
1190
+ const rootDir = options.root || process.cwd();
1191
+ const useJson = isJsonOutput(options);
1192
+ const isSilent = Boolean(options.silent || useJson);
1193
+ const { gherkinCount, digestsCount } = applyAutoFix(rootDir, isSilent, options.fix);
1194
+ const gates = collectPreflightGates(rootDir, Boolean(options.fix), gherkinCount, digestsCount);
1043
1195
  const success = gates.every((g) => g.status === "PASSED" || g.status === "FIXED");
1044
1196
  if (!isSilent) {
1045
1197
  renderDashboard(gates, Boolean(options.fix), gherkinCount, digestsCount);
@@ -1052,16 +1204,7 @@ function executePreflightCheck(options = {}) {
1052
1204
  gates
1053
1205
  };
1054
1206
  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));
1207
+ emitCheckJson(result);
1065
1208
  }
1066
1209
  return result;
1067
1210
  }
@@ -1073,6 +1216,24 @@ function runCheck(options = {}) {
1073
1216
  // src/commands/gherkin.ts
1074
1217
  import pc3 from "picocolors";
1075
1218
  import { extractGherkinFeatures as extractGherkinFeatures2 } from "@aisdlc/core";
1219
+ function printGherkinResult(result) {
1220
+ console.log(` Generated .feature files: ${pc3.bold(String(result.features.length))}`);
1221
+ console.log(` Total scenarios: ${pc3.bold(String(result.totalScenarios))}`);
1222
+ for (const f of result.features) {
1223
+ console.log(` ${pc3.green("\u2714")} ${pc3.bold(f.featureName)} \u2794 ${f.outputFile} (${f.scenarioCount} scenarios)`);
1224
+ }
1225
+ console.log(pc3.green("\n\u2714 BDD synchronization completed successfully.\n"));
1226
+ }
1227
+ function emitGherkinJson(result) {
1228
+ const payload = {
1229
+ command: "gherkin:extract",
1230
+ success: result.success,
1231
+ exitCode: result.success ? 0 : 1,
1232
+ totalScenarios: result.totalScenarios,
1233
+ features: result.features
1234
+ };
1235
+ console.log(JSON.stringify(payload, null, 2));
1236
+ }
1076
1237
  function runGherkinExtract(options = {}) {
1077
1238
  const rootDir = options.root || process.cwd();
1078
1239
  const useJson = isJsonOutput(options);
@@ -1086,22 +1247,10 @@ function runGherkinExtract(options = {}) {
1086
1247
  all: options.all
1087
1248
  });
1088
1249
  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"));
1250
+ printGherkinResult(result);
1095
1251
  }
1096
1252
  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));
1253
+ emitGherkinJson(result);
1105
1254
  }
1106
1255
  return result.success;
1107
1256
  }
@@ -1115,6 +1264,15 @@ import {
1115
1264
  installGitHooks,
1116
1265
  detectAuthorIdentity
1117
1266
  } from "@aisdlc/core";
1267
+ function printInvalidBranchError(error) {
1268
+ console.error(pc4.red(`
1269
+ \u2716 [NAMING ERROR] ${error || "Invalid pattern"}`));
1270
+ console.error(pc4.yellow("\nAllowed patterns:"));
1271
+ console.error(" Tier 1: main");
1272
+ console.error(" Tier 2: release/vX.Y.Z");
1273
+ console.error(" Tier 3: feat/<FEAT-ID>-<slug> or bug/<BUG-ID>-<slug>");
1274
+ console.error(" Tier 4: task/<PARENT-ID>/<TSK-ID>-<slug>\n");
1275
+ }
1118
1276
  function runGitValidate(branchName) {
1119
1277
  if (!branchName) {
1120
1278
  console.error(pc4.red("\n[ERROR] Branch name to validate must be specified.\n"));
@@ -1129,16 +1287,9 @@ function runGitValidate(branchName) {
1129
1287
  console.log(` - Target Merge: ${result.targetMerge}
1130
1288
  `);
1131
1289
  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
1290
  }
1291
+ printInvalidBranchError(result.error);
1292
+ return false;
1142
1293
  }
1143
1294
  function runGitPlan(options) {
1144
1295
  const version = options.version || "v1.1.0";
@@ -1149,6 +1300,35 @@ function runGitPlan(options) {
1149
1300
  console.log(pc4.cyan("\n" + plan.planText));
1150
1301
  return true;
1151
1302
  }
1303
+ function printCheckoutFailure(result) {
1304
+ console.error(pc4.red(`
1305
+ \u2716 [ERROR] ${result.error}`));
1306
+ if (result.availableTasks && result.availableTasks.length > 0) {
1307
+ console.log(pc4.yellow("\nAvailable tasks in active changes:"));
1308
+ for (const t of result.availableTasks) {
1309
+ console.log(` - [${pc4.cyan(t.changeId)}] ${pc4.bold(t.id)}${t.title ? `: ${t.title}` : ""}`);
1310
+ }
1311
+ }
1312
+ console.log();
1313
+ }
1314
+ function printCheckoutSuccess(result) {
1315
+ console.log(` - Detected change: ${pc4.bold(result.changeId || "N/A")}`);
1316
+ console.log(` - Release Branch: ${pc4.green(result.releaseBranch || "")} (Tier 2)`);
1317
+ console.log(` - Feature Branch: ${pc4.green(result.featureBranch || "")} (Tier 3)`);
1318
+ console.log(` - Task Branch: ${pc4.green(result.taskBranch || "")} (Tier 4)`);
1319
+ if (result.createdBranches && result.createdBranches.length > 0) {
1320
+ console.log(pc4.green(`
1321
+ \u2714 Cascading branches created:`));
1322
+ for (const b of result.createdBranches) {
1323
+ console.log(` \u251C\u2500\u2500 ${pc4.bold(b)}`);
1324
+ }
1325
+ }
1326
+ const switched = result.switchedBranch || result.taskBranch || "";
1327
+ console.log(pc4.green(`
1328
+ \u2714 [CHECKOUT] Successfully switched to working branch:`));
1329
+ console.log(` \u{1F449} ${pc4.bold(pc4.cyan(switched))}
1330
+ `);
1331
+ }
1152
1332
  function runGitCheckout(taskId, options = {}) {
1153
1333
  if (!taskId) {
1154
1334
  if (!options.silent) {
@@ -1163,36 +1343,10 @@ function runGitCheckout(taskId, options = {}) {
1163
1343
  }
1164
1344
  const result = checkoutTaskBranch(taskId, { rootDir });
1165
1345
  if (!result.success) {
1166
- if (!options.silent) {
1167
- console.error(pc4.red(`
1168
- \u2716 [ERROR] ${result.error}`));
1169
- if (result.availableTasks && result.availableTasks.length > 0) {
1170
- console.log(pc4.yellow("\nAvailable tasks in active changes:"));
1171
- for (const t of result.availableTasks) {
1172
- console.log(` - [${pc4.cyan(t.changeId)}] ${pc4.bold(t.id)}${t.title ? `: ${t.title}` : ""}`);
1173
- }
1174
- }
1175
- console.log();
1176
- }
1346
+ if (!options.silent) printCheckoutFailure(result);
1177
1347
  return false;
1178
1348
  }
1179
- if (!options.silent) {
1180
- console.log(` - Detected change: ${pc4.bold(result.changeId || "N/A")}`);
1181
- console.log(` - Release Branch: ${pc4.green(result.releaseBranch || "")} (Tier 2)`);
1182
- console.log(` - Feature Branch: ${pc4.green(result.featureBranch || "")} (Tier 3)`);
1183
- console.log(` - Task Branch: ${pc4.green(result.taskBranch || "")} (Tier 4)`);
1184
- if (result.createdBranches && result.createdBranches.length > 0) {
1185
- console.log(pc4.green(`
1186
- \u2714 Cascading branches created:`));
1187
- for (const b of result.createdBranches) {
1188
- console.log(` \u251C\u2500\u2500 ${pc4.bold(b)}`);
1189
- }
1190
- }
1191
- console.log(pc4.green(`
1192
- \u2714 [CHECKOUT] Successfully switched to working branch:`));
1193
- console.log(` \u{1F449} ${pc4.bold(pc4.cyan(result.switchedBranch || result.taskBranch || ""))}
1194
- `);
1195
- }
1349
+ if (!options.silent) printCheckoutSuccess(result);
1196
1350
  return true;
1197
1351
  }
1198
1352
  function runGitHookInstall(options = {}) {
@@ -1227,152 +1381,156 @@ function runGitDetectAuthor(options = {}) {
1227
1381
  import * as readline from "readline/promises";
1228
1382
  import { initProject } from "@aisdlc/core";
1229
1383
  import pc5 from "picocolors";
1384
+ function parseArchitectureChoice(answer) {
1385
+ const trimmed = answer.trim().toLowerCase();
1386
+ if (!trimmed || trimmed === "1" || trimmed === "minimal") return "minimal";
1387
+ if (trimmed === "2" || trimmed === "full" || trimmed === "complete") return "full";
1388
+ if (trimmed === "3" || trimmed === "none") return "none";
1389
+ return trimmed;
1390
+ }
1391
+ var ARCH_MENU = [
1392
+ pc5.bold(pc5.cyan("\n\u{1F3DB}\uFE0F [AI-SDLC] Architecture Granularity Level:")),
1393
+ " 1) " + pc5.green("Minimal / Baseline") + " (ARCH-INTRO-* Vision, CMP-* Decisions) " + pc5.yellow("[Recommended]"),
1394
+ " 2) " + pc5.cyan("Full / arc42 + NAF v4") + " (12 complete architecture sections)",
1395
+ " 3) " + pc5.gray("None") + " (No architecture templates)"
1396
+ ].join("\n");
1230
1397
  async function promptForArchitecture() {
1231
- const rl = readline.createInterface({
1232
- input: process.stdin,
1233
- output: process.stdout
1234
- });
1235
- console.log(pc5.bold(pc5.cyan("\n\u{1F3DB}\uFE0F [AI-SDLC] Architecture Granularity Level:")));
1236
- console.log(" 1) " + pc5.green("Minimal / Baseline") + " (ARCH-INTRO-* Vision, CMP-* Components, and ADR-* Decisions) " + pc5.yellow("[Recommended for microservices and CLI]"));
1237
- console.log(" 2) " + pc5.cyan("Full / arc42 + NAF v4") + " (12 complete architecture sections)");
1238
- console.log(" 3) " + pc5.gray("None") + " (No architecture templates)");
1398
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1399
+ console.log(ARCH_MENU);
1239
1400
  try {
1240
- const answer = await rl.question(
1241
- pc5.bold("\nWhich architecture granularity level do you wish to configure? [1-3] (default 1): ")
1242
- );
1243
- const trimmed = answer.trim().toLowerCase();
1244
- if (!trimmed || trimmed === "1" || trimmed === "minimal") return "minimal";
1245
- if (trimmed === "2" || trimmed === "full" || trimmed === "complete") return "full";
1246
- if (trimmed === "3" || trimmed === "none") return "none";
1247
- return trimmed;
1401
+ const answer = await rl.question(pc5.bold("\nWhich architecture granularity level do you wish to configure? [1-3] (default 1): "));
1402
+ return parseArchitectureChoice(answer);
1248
1403
  } finally {
1249
1404
  rl.close();
1250
1405
  }
1251
1406
  }
1407
+ var AGENTS_MENU = [
1408
+ pc5.bold(pc5.cyan("\n\u{1F916} [AI-SDLC] Project AI Agents Configuration:")),
1409
+ " 1) " + pc5.green("All") + " (Cursor, Claude Code, Antigravity, Copilot, MCP) " + pc5.yellow("[Recommended]"),
1410
+ " 2) Cursor (.cursor/rules and .cursor/mcp.json)",
1411
+ " 3) Claude Code (CLAUDE.md)",
1412
+ " 4) Google Antigravity / Gemini CLI (.agent/rules and antigravity.mcp.json)",
1413
+ " 5) GitHub Copilot (.github/copilot-instructions.md)",
1414
+ " 6) MCP connectors only (.cursor/mcp.json, antigravity.mcp.json, .vscode/mcp.json)",
1415
+ " 7) None (only core policies and base templates)"
1416
+ ].join("\n");
1417
+ function parseAgentsChoice(answer) {
1418
+ const map = {
1419
+ "1": "all",
1420
+ "2": "cursor",
1421
+ "3": "claude",
1422
+ "4": "antigravity",
1423
+ "5": "copilot",
1424
+ "6": "mcp",
1425
+ "7": "none"
1426
+ };
1427
+ const trimmed = answer.trim();
1428
+ return !trimmed ? "all" : map[trimmed] || trimmed;
1429
+ }
1252
1430
  async function promptForAgents() {
1253
- const rl = readline.createInterface({
1254
- input: process.stdin,
1255
- output: process.stdout
1256
- });
1257
- console.log(pc5.bold(pc5.cyan("\n\u{1F916} [AI-SDLC] Project AI Agents Configuration:")));
1258
- console.log(" 1) " + pc5.green("All") + " (Cursor, Claude Code, Antigravity, Copilot, MCP) " + pc5.yellow("[Recommended]"));
1259
- console.log(" 2) Cursor (.cursor/rules and .cursor/mcp.json)");
1260
- console.log(" 3) Claude Code (CLAUDE.md)");
1261
- console.log(" 4) Google Antigravity / Gemini CLI (.agent/rules and antigravity.mcp.json)");
1262
- console.log(" 5) GitHub Copilot (.github/copilot-instructions.md)");
1263
- console.log(" 6) MCP connectors only (.cursor/mcp.json, antigravity.mcp.json, .vscode/mcp.json)");
1264
- console.log(" 7) None (only core policies and base templates)");
1431
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1432
+ console.log(AGENTS_MENU);
1265
1433
  try {
1266
- const answer = await rl.question(
1267
- pc5.bold("\nWhich agents do you wish to deploy? [1-7 or comma-separated list] (default 1): ")
1268
- );
1269
- const trimmed = answer.trim();
1270
- if (!trimmed || trimmed === "1") return "all";
1271
- if (trimmed === "2") return "cursor";
1272
- if (trimmed === "3") return "claude";
1273
- if (trimmed === "4") return "antigravity";
1274
- if (trimmed === "5") return "copilot";
1275
- if (trimmed === "6") return "mcp";
1276
- if (trimmed === "7") return "none";
1277
- return trimmed;
1434
+ const answer = await rl.question(pc5.bold("\nWhich agents do you wish to deploy? [1-7 or comma-separated list] (default 1): "));
1435
+ return parseAgentsChoice(answer);
1278
1436
  } finally {
1279
1437
  rl.close();
1280
1438
  }
1281
1439
  }
1282
- function runInit(targetDir = ".", options = {}) {
1283
- const useJson = isJsonOutput(options);
1284
- const isSilent = Boolean(options.silent || useJson);
1285
- const result = initProject({
1286
- rootDir: process.cwd(),
1287
- targetDir,
1288
- ci: options.ci,
1289
- agents: options.agents === "none" ? false : options.agents,
1290
- architecture: options.architecture,
1291
- dryRun: options.dryRun
1292
- });
1440
+ function emitInitJson(result, isSuccess, dryRun) {
1441
+ const payload = {
1442
+ command: "init",
1443
+ success: isSuccess,
1444
+ exitCode: isSuccess ? 0 : 1,
1445
+ targetDir: result.targetDir,
1446
+ directoriesCreated: result.directoriesCreated,
1447
+ filesCreated: result.filesCreated,
1448
+ ciProvider: result.ciProvider,
1449
+ agentsConfigured: result.agentsConfigured,
1450
+ architectureGranularity: result.architectureGranularity,
1451
+ gitHookInstalled: result.gitHookInstalled,
1452
+ dryRun,
1453
+ ...isSuccess ? {} : { error: result.error || "Error initializing project." }
1454
+ };
1455
+ console.log(JSON.stringify(payload, null, 2));
1456
+ }
1457
+ function formatGranularityLabel(granularity) {
1458
+ if (granularity === "full" || granularity === "complete") return "Full (arc42 + NAF v4, 12 sections)";
1459
+ if (granularity === "minimal") return "Minimal / Baseline (ARCH-INTRO-*, CMP-* and ADR-*)";
1460
+ return "None";
1461
+ }
1462
+ function printGitHookStatus(dryRun, installed) {
1463
+ if (dryRun) {
1464
+ console.log(` ${pc5.blue("DRY-RUN")} Install Git Hook: .git/hooks/prepare-commit-msg`);
1465
+ } else if (installed) {
1466
+ console.log(` ${pc5.green("\u2714")} Git Hook installed: ${pc5.bold("prepare-commit-msg")}`);
1467
+ } else {
1468
+ console.log(` ${pc5.yellow("\u2139")} Git repository not detected at target.`);
1469
+ console.log(` ${pc5.gray("Run 'git init' and then 'aisdlc git hook install' to activate commit hooks.")}`);
1470
+ }
1471
+ }
1472
+ function printCreatedItems(items, type, dryRun) {
1473
+ const isDir = type === "directory";
1474
+ for (const item of items) {
1475
+ const prefix = dryRun ? pc5.blue("DRY-RUN") + ` ${isDir ? "Create directory:" : "Create file:"}` : pc5.green("\u2714") + ` ${isDir ? "Directory created:" : "File generated:"}`;
1476
+ console.log(` ${prefix} ${item}`);
1477
+ }
1478
+ }
1479
+ function printInitSuccess(result, dryRun) {
1480
+ console.log(pc5.bold(pc5.cyan(`
1481
+ \u{1F680} [AI-SDLC] Initializing governance structure in: ${result.targetDir}
1482
+ `)));
1483
+ printCreatedItems(result.directoriesCreated, "directory", dryRun);
1484
+ printCreatedItems(result.filesCreated, "file", dryRun);
1485
+ if (result.ciProvider) {
1486
+ console.log(pc5.cyan(`
1487
+ \u2714 CI/CD configuration generated for provider: ${pc5.bold(result.ciProvider)}`));
1488
+ }
1489
+ if (result.agentsConfigured && result.agentsConfigured.length > 0) {
1490
+ console.log(pc5.cyan(`
1491
+ \u2714 Configured AI agents: ${pc5.bold(result.agentsConfigured.join(", "))}`));
1492
+ }
1493
+ if (result.architectureGranularity) {
1494
+ console.log(pc5.cyan(`
1495
+ \u2714 Architecture granularity: ${pc5.bold(formatGranularityLabel(result.architectureGranularity))}`));
1496
+ }
1497
+ printGitHookStatus(dryRun, result.gitHookInstalled);
1498
+ console.log(pc5.green("\n\u2714 Repository configured with AI-SDLC policies and templates.\n"));
1499
+ }
1500
+ function handleInitResult(result, ctx) {
1293
1501
  if (!result.success) {
1294
- if (!isSilent) {
1502
+ if (!ctx.isSilent) {
1295
1503
  console.error(pc5.red(`
1296
1504
  \u2716 [ERROR] ${result.error || "Error initializing project."}
1297
1505
  `));
1298
1506
  }
1299
- if (useJson) {
1300
- const payload = {
1301
- command: "init",
1302
- success: false,
1303
- exitCode: 1,
1304
- targetDir: result.targetDir,
1305
- directoriesCreated: result.directoriesCreated,
1306
- filesCreated: result.filesCreated,
1307
- ciProvider: result.ciProvider,
1308
- agentsConfigured: result.agentsConfigured,
1309
- gitHookInstalled: result.gitHookInstalled,
1310
- dryRun: Boolean(options.dryRun),
1311
- error: result.error || "Error initializing project."
1312
- };
1313
- console.log(JSON.stringify(payload, null, 2));
1507
+ if (ctx.useJson) {
1508
+ emitInitJson(result, false, ctx.dryRun);
1314
1509
  }
1315
1510
  return false;
1316
1511
  }
1317
- if (!isSilent) {
1318
- console.log(pc5.bold(pc5.cyan(`
1319
- \u{1F680} [AI-SDLC] Initializing governance structure in: ${result.targetDir}
1320
- `)));
1321
- for (const d of result.directoriesCreated) {
1322
- if (options.dryRun) {
1323
- console.log(` ${pc5.blue("DRY-RUN")} Create directory: ${d}`);
1324
- } else {
1325
- console.log(` ${pc5.green("\u2714")} Directory created: ${d}`);
1326
- }
1327
- }
1328
- for (const f of result.filesCreated) {
1329
- if (options.dryRun) {
1330
- console.log(` ${pc5.blue("DRY-RUN")} Create file: ${f}`);
1331
- } else {
1332
- console.log(` ${pc5.green("\u2714")} File generated: ${f}`);
1333
- }
1334
- }
1335
- if (result.ciProvider) {
1336
- console.log(pc5.cyan(`
1337
- \u2714 CI/CD configuration generated for provider: ${pc5.bold(result.ciProvider)}`));
1338
- }
1339
- if (result.agentsConfigured && result.agentsConfigured.length > 0) {
1340
- console.log(pc5.cyan(`
1341
- \u2714 Configured AI agents: ${pc5.bold(result.agentsConfigured.join(", "))}`));
1342
- }
1343
- if (result.architectureGranularity) {
1344
- const label = result.architectureGranularity === "full" || result.architectureGranularity === "complete" ? "Full (arc42 + NAF v4, 12 sections)" : result.architectureGranularity === "minimal" ? "Minimal / Baseline (ARCH-INTRO-*, CMP-* and ADR-*)" : "None";
1345
- console.log(pc5.cyan(`
1346
- \u2714 Architecture granularity: ${pc5.bold(label)}`));
1347
- }
1348
- if (options.dryRun) {
1349
- console.log(` ${pc5.blue("DRY-RUN")} Install Git Hook: .git/hooks/prepare-commit-msg`);
1350
- } else if (result.gitHookInstalled) {
1351
- console.log(` ${pc5.green("\u2714")} Git Hook installed: ${pc5.bold("prepare-commit-msg")}`);
1352
- } else {
1353
- console.log(` ${pc5.yellow("\u2139")} Git repository not detected at target.`);
1354
- console.log(` ${pc5.gray("Run 'git init' and then 'aisdlc git hook install' to activate commit hooks.")}`);
1355
- }
1356
- console.log(pc5.green("\n\u2714 Repository configured with AI-SDLC policies and templates.\n"));
1512
+ if (!ctx.isSilent) {
1513
+ printInitSuccess(result, ctx.dryRun);
1357
1514
  }
1358
- if (useJson) {
1359
- const payload = {
1360
- command: "init",
1361
- success: true,
1362
- exitCode: 0,
1363
- targetDir: result.targetDir,
1364
- directoriesCreated: result.directoriesCreated,
1365
- filesCreated: result.filesCreated,
1366
- ciProvider: result.ciProvider,
1367
- agentsConfigured: result.agentsConfigured,
1368
- architectureGranularity: result.architectureGranularity,
1369
- gitHookInstalled: result.gitHookInstalled,
1370
- dryRun: Boolean(options.dryRun)
1371
- };
1372
- console.log(JSON.stringify(payload, null, 2));
1515
+ if (ctx.useJson) {
1516
+ emitInitJson(result, true, ctx.dryRun);
1373
1517
  }
1374
1518
  return true;
1375
1519
  }
1520
+ function runInit(targetDir = ".", options = {}) {
1521
+ const useJson = isJsonOutput(options);
1522
+ const isSilent = Boolean(options.silent || useJson);
1523
+ const dryRun = Boolean(options.dryRun);
1524
+ const result = initProject({
1525
+ rootDir: process.cwd(),
1526
+ targetDir,
1527
+ ci: options.ci,
1528
+ agents: options.agents === "none" ? false : options.agents,
1529
+ architecture: options.architecture,
1530
+ dryRun
1531
+ });
1532
+ return handleInitResult(result, { isSilent, useJson, dryRun });
1533
+ }
1376
1534
 
1377
1535
  // src/commands/kpi.ts
1378
1536
  import * as fs from "fs";
@@ -1384,6 +1542,23 @@ import {
1384
1542
  aggregateReleaseKpis,
1385
1543
  writeReleaseKpiReport
1386
1544
  } from "@aisdlc/core";
1545
+ function applyKpiPrOutput(options, markdown) {
1546
+ if (options.updateFile) {
1547
+ if (!fs.existsSync(options.updateFile)) {
1548
+ console.error(pc6.red(`
1549
+ \u2716 [ERROR] Target file '${options.updateFile}' does not exist.
1550
+ `));
1551
+ return false;
1552
+ }
1553
+ const original = fs.readFileSync(options.updateFile, "utf-8");
1554
+ const updated = injectKpisIntoPrBody(original, markdown);
1555
+ fs.writeFileSync(options.updateFile, updated, "utf-8");
1556
+ console.log(pc6.green(`\u2714 [UPDATED] KPI summary injected into '${options.updateFile}'.`));
1557
+ } else {
1558
+ console.log("\n" + markdown + "\n");
1559
+ }
1560
+ return true;
1561
+ }
1387
1562
  function runKpiPr(options) {
1388
1563
  const baseRef = options.base || "main";
1389
1564
  const headRef = options.head || "HEAD";
@@ -1395,21 +1570,7 @@ function runKpiPr(options) {
1395
1570
  return true;
1396
1571
  }
1397
1572
  const markdown = formatPrKpiMarkdown(kpi);
1398
- if (options.updateFile) {
1399
- if (!fs.existsSync(options.updateFile)) {
1400
- console.error(pc6.red(`
1401
- \u2716 [ERROR] Target file '${options.updateFile}' does not exist.
1402
- `));
1403
- return false;
1404
- }
1405
- const original = fs.readFileSync(options.updateFile, "utf-8");
1406
- const updated = injectKpisIntoPrBody(original, markdown);
1407
- fs.writeFileSync(options.updateFile, updated, "utf-8");
1408
- console.log(pc6.green(`\u2714 [UPDATED] KPI summary injected into '${options.updateFile}'.`));
1409
- } else {
1410
- console.log("\n" + markdown + "\n");
1411
- }
1412
- return true;
1573
+ return applyKpiPrOutput(options, markdown);
1413
1574
  } catch (err) {
1414
1575
  const msg = err instanceof Error ? err.message : String(err);
1415
1576
  console.error(pc6.red(`
@@ -1418,6 +1579,33 @@ function runKpiPr(options) {
1418
1579
  return false;
1419
1580
  }
1420
1581
  }
1582
+ function printReleaseKpiSummary(report, markdownPath, jsonPath) {
1583
+ console.log(pc6.green(`\u2714 [COMPLIANT] Consolidated report successfully generated:`));
1584
+ console.log(` - Markdown: ${pc6.bold(markdownPath)}`);
1585
+ console.log(` - JSON: ${pc6.bold(jsonPath)}`);
1586
+ console.log(` - KLoC: ${report.totalKloc} (${report.totalCommits} commits)`);
1587
+ console.log(` - Bugs: ${report.totalBugs} (Density: ${report.globalDefectDensity} bugs/KLoC)`);
1588
+ console.log(` - Rework: ${report.reworkTimePercent}% time | ${report.reworkTokensPercent}% tokens
1589
+ `);
1590
+ }
1591
+ function printKpiReleaseError(err) {
1592
+ const msg = err instanceof Error ? err.message : String(err);
1593
+ console.error(pc6.red(`
1594
+ \u2716 [ERROR] Failed to calculate Release KPIs: ${msg}
1595
+ `));
1596
+ }
1597
+ function executeKpiReleaseReport(release, baseBranch, rootDir, outputDir) {
1598
+ const report = aggregateReleaseKpis(release, baseBranch, { cwd: rootDir });
1599
+ const { markdownPath, jsonPath } = writeReleaseKpiReport(report, {
1600
+ outputDir,
1601
+ rootDir
1602
+ });
1603
+ if (report.totalCommits === 0) {
1604
+ console.warn(pc6.yellow(`
1605
+ \u26A0 [WARNING] No commits found between '${baseBranch}' and '${release}'.`));
1606
+ }
1607
+ printReleaseKpiSummary(report, markdownPath, jsonPath);
1608
+ }
1421
1609
  function runKpiRelease(options) {
1422
1610
  if (!options.release) {
1423
1611
  console.error(pc6.red("\n\u2716 [ERROR] Release branch must be specified (--release <branch>).\n"));
@@ -1428,25 +1616,15 @@ function runKpiRelease(options) {
1428
1616
  try {
1429
1617
  console.log(pc6.cyan(`
1430
1618
  \u{1F4CA} [AI-SDLC Release KPI] Consolidating metrics for '${pc6.bold(options.release)}'...`));
1431
- const report = aggregateReleaseKpis(options.release, baseBranch, { cwd: rootDir });
1432
1619
  if (options.json) {
1620
+ const report = aggregateReleaseKpis(options.release, baseBranch, { cwd: rootDir });
1433
1621
  console.log(JSON.stringify(report, null, 2));
1434
1622
  return true;
1435
1623
  }
1436
- const { markdownPath, jsonPath } = writeReleaseKpiReport(report, { outputDir: options.output });
1437
- console.log(pc6.green(`\u2714 [COMPLIANT] Consolidated report successfully generated:`));
1438
- console.log(` - Markdown: ${pc6.bold(markdownPath)}`);
1439
- console.log(` - JSON: ${pc6.bold(jsonPath)}`);
1440
- console.log(` - KLoC: ${report.totalKloc} (${report.totalCommits} commits)`);
1441
- console.log(` - Bugs: ${report.totalBugs} (Density: ${report.globalDefectDensity} bugs/KLoC)`);
1442
- console.log(` - Rework: ${report.reworkTimePercent}% time | ${report.reworkTokensPercent}% tokens
1443
- `);
1624
+ executeKpiReleaseReport(options.release, baseBranch, rootDir, options.output);
1444
1625
  return true;
1445
1626
  } catch (err) {
1446
- const msg = err instanceof Error ? err.message : String(err);
1447
- console.error(pc6.red(`
1448
- \u2716 [ERROR] Failed to calculate Release KPIs: ${msg}
1449
- `));
1627
+ printKpiReleaseError(err);
1450
1628
  return false;
1451
1629
  }
1452
1630
  }
@@ -1483,6 +1661,25 @@ function openInBrowser(filePath) {
1483
1661
  } catch {
1484
1662
  }
1485
1663
  }
1664
+ function printDashboardMetrics(result, rootDir) {
1665
+ console.log(` Compiled nodes: ${pc8.bold(String(result.totalNodes))}`);
1666
+ console.log(` Connections (edges): ${pc8.bold(String(result.totalEdges))}`);
1667
+ console.log(` Compliant nodes: ${pc8.green(String(result.conformingCount))}`);
1668
+ console.log(` Nodes with issues: ${result.issueCount > 0 ? pc8.red(String(result.issueCount)) : pc8.green("0")}`);
1669
+ console.log(` Global traceability: ${pc8.green(String(result.metrics.traceabilityRatio) + "%")}`);
1670
+ console.log(` Maintainability: ${pc8.bold(String(result.metrics.avgMaintainability) + " / 100")}`);
1671
+ console.log(` Gate verdict: ${result.metrics.qualityVerdict === "PASS" ? pc8.green("PASS") : pc8.red("FAIL")}`);
1672
+ const relPath = path.relative(rootDir, result.outputPath);
1673
+ console.log(pc8.green(`
1674
+ \u2714 Self-contained HTML dashboard successfully generated at: ${pc8.bold(relPath)}
1675
+ `));
1676
+ }
1677
+ function printDashboardError(err) {
1678
+ const msg = err instanceof Error ? err.message : String(err);
1679
+ console.error(pc8.red(`
1680
+ \u2716 [ERROR] Failed to generate web dashboard: ${msg}
1681
+ `));
1682
+ }
1486
1683
  function runReportDashboard(options = {}) {
1487
1684
  const rootDir = options.root || process.cwd();
1488
1685
  console.log(pc8.bold(pc8.cyan("\n\u{1F310} [AI-SDLC] Generating Interactive Web Dashboard and PDaC / RTM Graph...")));
@@ -1492,40 +1689,17 @@ function runReportDashboard(options = {}) {
1492
1689
  outputPath: options.output,
1493
1690
  title: options.title
1494
1691
  });
1495
- console.log(` Compiled nodes: ${pc8.bold(String(result.totalNodes))}`);
1496
- console.log(` Connections (edges): ${pc8.bold(String(result.totalEdges))}`);
1497
- console.log(` Compliant nodes: ${pc8.green(String(result.conformingCount))}`);
1498
- console.log(` Nodes with issues: ${result.issueCount > 0 ? pc8.red(String(result.issueCount)) : pc8.green("0")}`);
1499
- console.log(` Global traceability: ${pc8.green(String(result.metrics.traceabilityRatio) + "%")}`);
1500
- console.log(` Maintainability: ${pc8.bold(String(result.metrics.avgMaintainability) + " / 100")}`);
1501
- console.log(` Gate verdict: ${result.metrics.qualityVerdict === "PASS" ? pc8.green("PASS") : pc8.red("FAIL")}`);
1502
- const relPath = path.relative(rootDir, result.outputPath);
1503
- console.log(pc8.green(`
1504
- \u2714 Self-contained HTML dashboard successfully generated at: ${pc8.bold(relPath)}
1505
- `));
1692
+ printDashboardMetrics(result, rootDir);
1506
1693
  if (options.open) {
1507
1694
  openInBrowser(result.outputPath);
1508
1695
  }
1509
1696
  return true;
1510
1697
  } catch (err) {
1511
- const msg = err instanceof Error ? err.message : String(err);
1512
- console.error(pc8.red(`
1513
- \u2716 [ERROR] Failed to generate web dashboard: ${msg}
1514
- `));
1698
+ printDashboardError(err);
1515
1699
  return false;
1516
1700
  }
1517
1701
  }
1518
- function runReportQuality(options = {}) {
1519
- const rootDir = options.root || process.cwd();
1520
- console.log(pc8.bold(pc8.cyan("\n\u{1F4CA} Generating Formal Quality Report...")));
1521
- const thresholds = {
1522
- max_cyclomatic: options.maxCyclomatic !== void 0 ? Number(options.maxCyclomatic) : void 0,
1523
- max_cognitive: options.maxCognitive !== void 0 ? Number(options.maxCognitive) : void 0,
1524
- min_maintainability: options.minMaintainability !== void 0 ? Number(options.minMaintainability) : void 0,
1525
- max_function_lines: options.maxLines !== void 0 ? Number(options.maxLines) : void 0,
1526
- enforce_mode: options.enforceMode
1527
- };
1528
- const result = generateQualityReport({ rootDir, policyPath: options.policy, thresholds });
1702
+ function printQualityReportMetrics(result, rootDir) {
1529
1703
  console.log(` Analyzed files: ${pc8.bold(String(result.totalFiles))}`);
1530
1704
  console.log(` Evaluated functions: ${pc8.bold(String(result.totalFunctions))}`);
1531
1705
  console.log(` Average maintainability: ${pc8.green(String(result.avgMaintainability) + " / 100")}`);
@@ -1538,6 +1712,19 @@ function runReportQuality(options = {}) {
1538
1712
  console.log(pc8.green(`
1539
1713
  \u2714 Report successfully generated at: ${pc8.bold(reportRelPath)}
1540
1714
  `));
1715
+ }
1716
+ function runReportQuality(options = {}) {
1717
+ const rootDir = options.root || process.cwd();
1718
+ console.log(pc8.bold(pc8.cyan("\n\u{1F4CA} Generating Formal Quality Report...")));
1719
+ const thresholds = {
1720
+ max_cyclomatic: options.maxCyclomatic !== void 0 ? Number(options.maxCyclomatic) : void 0,
1721
+ max_cognitive: options.maxCognitive !== void 0 ? Number(options.maxCognitive) : void 0,
1722
+ min_maintainability: options.minMaintainability !== void 0 ? Number(options.minMaintainability) : void 0,
1723
+ max_function_lines: options.maxLines !== void 0 ? Number(options.maxLines) : void 0,
1724
+ enforce_mode: options.enforceMode
1725
+ };
1726
+ const result = generateQualityReport({ rootDir, policyPath: options.policy, thresholds });
1727
+ printQualityReportMetrics(result, rootDir);
1541
1728
  return result.verdict === "PASS";
1542
1729
  }
1543
1730
 
@@ -1550,22 +1737,9 @@ import {
1550
1737
  integrateSddChange,
1551
1738
  scaffoldSddChange,
1552
1739
  scanAllProductHandoffs,
1553
- verifyArtifactDuplicates as verifyArtifactDuplicates2
1740
+ verifyArtifactDuplicates as verifyArtifactDuplicates3
1554
1741
  } from "@aisdlc/core";
1555
- function runSddDeposit(options) {
1556
- const rootDir = options.root || process.cwd();
1557
- const changeId = options.change;
1558
- const framework = options.framework || "openspec";
1559
- const useJson = isJsonOutput(options);
1560
- const isSilent = Boolean(options.silent || useJson);
1561
- if (!isSilent) {
1562
- console.log(
1563
- pc9.bold(
1564
- pc9.cyan(`
1565
- \u{1F4E6} [AI-SDLC SDD] Depositing PDaC Handoff Sidecar for '${changeId}' (${framework})...`)
1566
- )
1567
- );
1568
- }
1742
+ function buildHandoffPayload(options, changeId) {
1569
1743
  const reqList = options.requirements ? options.requirements.split(",").map((r) => r.trim()) : ["FR-001"];
1570
1744
  const ucList = options.useCases ? options.useCases.split(",").map((u) => u.trim()) : ["UC-001"];
1571
1745
  const handoff = {
@@ -1580,274 +1754,314 @@ function runSddDeposit(options) {
1580
1754
  useCases: ucList
1581
1755
  }
1582
1756
  };
1583
- try {
1584
- const depositedPath = depositProductHandoffSidecar({
1585
- rootDir,
1586
- changeId,
1587
- framework,
1588
- handoff
1589
- });
1590
- if (!isSilent) {
1591
- console.log(` ${pc9.green("\u2714")} Sidecar successfully deposited: ${pc9.bold(depositedPath)}`);
1592
- console.log(` Handoff ID: ${pc9.cyan(handoff.id)}`);
1593
- console.log(` Delivered requirements: ${reqList.join(", ")}
1757
+ return { handoff, reqList };
1758
+ }
1759
+ function printDepositSuccess(depositedPath, handoffId, reqList) {
1760
+ console.log(` ${pc9.green("\u2714")} Sidecar successfully deposited: ${pc9.bold(depositedPath)}`);
1761
+ console.log(` Handoff ID: ${pc9.cyan(handoffId)}`);
1762
+ console.log(` Delivered requirements: ${reqList.join(", ")}
1594
1763
  `);
1595
- }
1596
- if (useJson) {
1597
- const payload = {
1598
- command: "sdd:deposit",
1599
- success: true,
1600
- exitCode: 0,
1601
- changeId,
1602
- framework,
1603
- depositedPath,
1604
- handoff
1605
- };
1606
- console.log(JSON.stringify(payload, null, 2));
1607
- }
1608
- return true;
1609
- } catch (err) {
1610
- if (!isSilent) {
1611
- console.error(pc9.red(` \u2716 Error depositing sidecar: ${err?.message || err}
1764
+ }
1765
+ function emitDepositJson(success, changeId, framework, depositedPath, handoff, err) {
1766
+ const payload = {
1767
+ command: "sdd:deposit",
1768
+ success,
1769
+ exitCode: success ? 0 : 1,
1770
+ changeId,
1771
+ framework,
1772
+ ...depositedPath ? { depositedPath, handoff } : { error: err instanceof Error ? err.message : String(err) }
1773
+ };
1774
+ console.log(JSON.stringify(payload, null, 2));
1775
+ }
1776
+ function printDepositHeader(changeId, framework) {
1777
+ console.log(pc9.bold(pc9.cyan(`
1778
+ \u{1F4E6} [AI-SDLC SDD] Depositing PDaC Handoff Sidecar for '${changeId}' (${framework})...`)));
1779
+ }
1780
+ function printDepositError(err) {
1781
+ const errMessage = err instanceof Error ? err.message : String(err);
1782
+ console.error(pc9.red(` \u2716 Error depositing sidecar: ${errMessage}
1612
1783
  `));
1613
- }
1614
- if (useJson) {
1615
- const payload = {
1616
- command: "sdd:deposit",
1617
- success: false,
1618
- exitCode: 1,
1619
- changeId,
1620
- framework,
1621
- error: err?.message || String(err)
1622
- };
1623
- console.log(JSON.stringify(payload, null, 2));
1624
- }
1625
- return false;
1626
- }
1627
1784
  }
1628
- function runSddVerify(options = {}) {
1785
+ function runSddDeposit(options) {
1629
1786
  const rootDir = options.root || process.cwd();
1787
+ const changeId = options.change;
1788
+ const framework = options.framework || "openspec";
1630
1789
  const useJson = isJsonOutput(options);
1631
1790
  const isSilent = Boolean(options.silent || useJson);
1632
1791
  if (!isSilent) {
1633
- console.log(
1634
- pc9.bold(
1635
- pc9.cyan("\n\u{1F50D} [AI-SDLC SDD] Verifying SDD Workspaces and Handoff Sidecars (HOF-*)...")
1636
- )
1637
- );
1792
+ printDepositHeader(changeId, framework);
1638
1793
  }
1639
- const handoffsMap = scanAllProductHandoffs(rootDir);
1640
- const totalFound = handoffsMap.size;
1794
+ const { handoff, reqList } = buildHandoffPayload(options, changeId);
1795
+ try {
1796
+ const depositedPath = depositProductHandoffSidecar({ rootDir, changeId, framework, handoff });
1797
+ if (!isSilent) printDepositSuccess(depositedPath, handoff.id, reqList);
1798
+ if (useJson) emitDepositJson(true, changeId, framework, depositedPath, handoff);
1799
+ return true;
1800
+ } catch (err) {
1801
+ if (!isSilent) printDepositError(err);
1802
+ if (useJson) emitDepositJson(false, changeId, framework, void 0, void 0, err);
1803
+ return false;
1804
+ }
1805
+ }
1806
+ function printHandoffEntry(isValid, id, relDir, reqCount) {
1807
+ if (isValid) {
1808
+ console.log(` ${pc9.green("\u2714")} [${pc9.bold(id)}] in ${relDir} (Requirements: ${reqCount})`);
1809
+ } else {
1810
+ console.log(` ${pc9.red("\u2716")} [${pc9.bold(id)}] in ${relDir} - Invalid handoff schema or subgraph.`);
1811
+ }
1812
+ }
1813
+ function processHandoffEntry(handoff, changeDir, rootDir, isSilent) {
1814
+ const relDir = path2.relative(rootDir, changeDir).replace(/\\/g, "/");
1815
+ const reqCount = handoff.subgraph && Array.isArray(handoff.subgraph.requirements) ? handoff.subgraph.requirements.length : 0;
1816
+ const isValid = Boolean(handoff.id && handoff.id.startsWith("HOF-") && reqCount > 0);
1817
+ const id = handoff.id || "UNKNOWN";
1641
1818
  if (!isSilent) {
1642
- console.log(` Found PDaC sidecars: ${pc9.bold(String(totalFound))}`);
1819
+ printHandoffEntry(isValid, id, relDir, reqCount);
1643
1820
  }
1644
- let validCount = 0;
1645
- let invalidCount = 0;
1646
- const handoffItems = [];
1647
- if (totalFound === 0) {
1821
+ return { id, changeDir: relDir, isValid, requirementsCount: reqCount };
1822
+ }
1823
+ function auditHandoffsMap(handoffsMap, rootDir, isSilent) {
1824
+ if (handoffsMap.size === 0) {
1648
1825
  if (!isSilent) {
1649
1826
  console.log(pc9.yellow(" [NOTICE] No handoff.yaml sidecar companion files found in specs/."));
1650
1827
  }
1651
- } else {
1652
- for (const [, { handoff, changeDir }] of handoffsMap.entries()) {
1653
- const relDir = path2.relative(rootDir, changeDir).replace(/\\/g, "/");
1654
- const reqCount = handoff.subgraph && Array.isArray(handoff.subgraph.requirements) ? handoff.subgraph.requirements.length : 0;
1655
- const isValid = Boolean(handoff.id && handoff.id.startsWith("HOF-") && reqCount > 0);
1656
- handoffItems.push({
1657
- id: handoff.id || "UNKNOWN",
1658
- changeDir: relDir,
1659
- isValid,
1660
- requirementsCount: reqCount
1661
- });
1662
- if (isValid) {
1663
- validCount++;
1664
- if (!isSilent) {
1665
- console.log(
1666
- ` ${pc9.green("\u2714")} [${pc9.bold(handoff.id)}] in ${relDir} (Requirements: ${reqCount})`
1667
- );
1668
- }
1669
- } else {
1670
- invalidCount++;
1671
- if (!isSilent) {
1672
- console.log(
1673
- ` ${pc9.red("\u2716")} [${pc9.bold(handoff.id || "UNKNOWN")}] in ${relDir} - Invalid handoff schema or subgraph.`
1674
- );
1675
- }
1676
- }
1828
+ return { handoffItems: [], validCount: 0, invalidCount: 0 };
1829
+ }
1830
+ const handoffItems = [];
1831
+ let validCount = 0;
1832
+ let invalidCount = 0;
1833
+ for (const [, { handoff, changeDir }] of handoffsMap.entries()) {
1834
+ const item = processHandoffEntry(handoff, changeDir, rootDir, isSilent);
1835
+ handoffItems.push(item);
1836
+ if (item.isValid) {
1837
+ validCount++;
1838
+ } else {
1839
+ invalidCount++;
1677
1840
  }
1678
1841
  }
1679
- let duplicateErrors = 0;
1680
- let duplicateIssues = [];
1681
- if (options.checkDuplicates !== false) {
1682
- const dupResult = verifyArtifactDuplicates2({ rootDir });
1683
- duplicateErrors = dupResult.errorCount;
1684
- duplicateIssues = dupResult.issues;
1685
- if (duplicateErrors > 0 && !isSilent) {
1686
- console.log(
1687
- pc9.red(
1688
- `
1689
- \u2716 [Shift-Left Gate] Detected ${duplicateErrors} requirement collision(s)/duplicate(s) in workspace:`
1690
- )
1691
- );
1692
- for (const issue of dupResult.issues.filter((i) => i.severity === "ERROR")) {
1693
- console.log(` ${pc9.red("\u2716")} [${issue.type}] ${issue.id} in ${issue.file}: ${issue.message}`);
1694
- }
1842
+ return { handoffItems, validCount, invalidCount };
1843
+ }
1844
+ function auditDuplicatesShiftLeft(rootDir, checkDuplicates, isSilent) {
1845
+ if (checkDuplicates === false) {
1846
+ return { duplicateErrors: 0, duplicateIssues: [] };
1847
+ }
1848
+ const dupResult = verifyArtifactDuplicates3({ rootDir });
1849
+ if (dupResult.errorCount > 0 && !isSilent) {
1850
+ console.log(pc9.red(`
1851
+ \u2716 [Shift-Left Gate] Detected ${dupResult.errorCount} requirement collision(s)/duplicate(s) in workspace:`));
1852
+ for (const issue of dupResult.issues.filter((i) => i.severity === "ERROR")) {
1853
+ console.log(` ${pc9.red("\u2716")} [${issue.type}] ${issue.id} in ${issue.file}: ${issue.message}`);
1695
1854
  }
1696
1855
  }
1856
+ return { duplicateErrors: dupResult.errorCount, duplicateIssues: dupResult.issues };
1857
+ }
1858
+ function emitSddVerifyJson(payload) {
1859
+ const jsonOutput = {
1860
+ command: "sdd:verify",
1861
+ success: payload.isOk,
1862
+ exitCode: payload.isOk ? 0 : 1,
1863
+ totalHandoffs: payload.totalFound,
1864
+ validHandoffs: payload.validCount,
1865
+ invalidHandoffs: payload.invalidCount,
1866
+ duplicateErrors: payload.duplicateErrors,
1867
+ handoffs: payload.handoffItems,
1868
+ duplicateIssues: payload.duplicateIssues
1869
+ };
1870
+ console.log(JSON.stringify(jsonOutput, null, 2));
1871
+ }
1872
+ function printSddVerifyVerdict(isOk) {
1873
+ console.log(
1874
+ 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")
1875
+ );
1876
+ }
1877
+ function printSddVerifyHeader(totalFound) {
1878
+ console.log(pc9.bold(pc9.cyan("\n\u{1F50D} [AI-SDLC SDD] Verifying SDD Workspaces and Handoff Sidecars (HOF-*)...")));
1879
+ console.log(` Found PDaC sidecars: ${pc9.bold(String(totalFound))}`);
1880
+ }
1881
+ function runSddVerify(options = {}) {
1882
+ const rootDir = options.root || process.cwd();
1883
+ const useJson = isJsonOutput(options);
1884
+ const isSilent = Boolean(options.silent || useJson);
1885
+ const handoffsMap = scanAllProductHandoffs(rootDir);
1886
+ const totalFound = handoffsMap.size;
1887
+ if (!isSilent) {
1888
+ printSddVerifyHeader(totalFound);
1889
+ }
1890
+ const { handoffItems, validCount, invalidCount } = auditHandoffsMap(handoffsMap, rootDir, isSilent);
1891
+ const { duplicateErrors, duplicateIssues } = auditDuplicatesShiftLeft(rootDir, options.checkDuplicates, isSilent);
1697
1892
  const isOk = invalidCount === 0 && duplicateErrors === 0;
1698
1893
  if (!isSilent) {
1699
- console.log(
1700
- 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")
1701
- );
1894
+ printSddVerifyVerdict(isOk);
1702
1895
  }
1703
1896
  if (useJson) {
1704
- const payload = {
1705
- command: "sdd:verify",
1706
- success: isOk,
1707
- exitCode: isOk ? 0 : 1,
1708
- totalHandoffs: totalFound,
1709
- validHandoffs: validCount,
1710
- invalidHandoffs: invalidCount,
1711
- duplicateErrors,
1712
- handoffs: handoffItems,
1713
- duplicateIssues
1714
- };
1715
- console.log(JSON.stringify(payload, null, 2));
1897
+ emitSddVerifyJson({ isOk, totalFound, validCount, invalidCount, duplicateErrors, handoffItems, duplicateIssues });
1716
1898
  }
1717
1899
  return isOk;
1718
1900
  }
1719
- function runSddIntegrate(options) {
1720
- const rootDir = options.root || process.cwd();
1721
- const useJson = isJsonOutput(options);
1722
- const isSilent = Boolean(options.silent || useJson);
1723
- let changeId = options.change;
1724
- if (!changeId && options.auto) {
1725
- const detection = detectActiveChangeForIntegration({
1726
- rootDir,
1727
- headRef: options.headRef,
1728
- prTitle: options.prTitle,
1729
- prBody: options.prBody
1730
- });
1731
- if (!detection.detected || !detection.changeId) {
1732
- if (!isSilent) {
1733
- console.log(pc9.yellow("\n\u2139 [AI-SDLC SDD] No active SDD change detected to integrate:"));
1734
- for (const r of detection.reasons) {
1735
- console.log(` - ${r}`);
1736
- }
1737
- console.log("");
1738
- }
1739
- if (useJson) {
1740
- const payload = {
1741
- command: "sdd:integrate",
1742
- success: false,
1743
- exitCode: 1,
1744
- reasons: detection.reasons,
1745
- error: "No active SDD change detected to integrate"
1746
- };
1747
- console.log(JSON.stringify(payload, null, 2));
1748
- }
1749
- return false;
1750
- }
1751
- if (!detection.allTasksCompleted) {
1752
- if (!isSilent) {
1753
- console.log(
1754
- pc9.red(
1755
- `
1756
- \u2716 [AI-SDLC SDD] Detected change '${detection.changeId}' has pending tasks (${detection.completedTasksCount}/${detection.totalTasksCount} completed). All tasks must be in COMPLETED status.
1757
- `
1758
- )
1759
- );
1760
- }
1761
- if (useJson) {
1762
- const payload = {
1763
- command: "sdd:integrate",
1764
- success: false,
1765
- exitCode: 1,
1766
- changeId: detection.changeId,
1767
- completedTasksCount: detection.completedTasksCount,
1768
- totalTasksCount: detection.totalTasksCount,
1769
- error: `Detected change '${detection.changeId}' has pending tasks (${detection.completedTasksCount}/${detection.totalTasksCount} completed).`
1770
- };
1771
- console.log(JSON.stringify(payload, null, 2));
1772
- }
1773
- return false;
1774
- }
1775
- changeId = detection.changeId;
1776
- if (!isSilent) {
1777
- console.log(
1778
- pc9.cyan(` \u2714 Automatically detected SDD change: ${pc9.bold(changeId)} (via ${detection.source})`)
1779
- );
1780
- }
1901
+ function handleUndetectedChange(detection, isSilent, useJson) {
1902
+ if (!isSilent) {
1903
+ console.log(pc9.yellow("\n\u2139 [AI-SDLC SDD] No active SDD change detected to integrate:"));
1904
+ for (const r of detection.reasons) console.log(` - ${r}`);
1905
+ console.log("");
1781
1906
  }
1782
- if (!changeId) {
1783
- if (!isSilent) {
1784
- console.error(pc9.red("\n\u2716 Change identifier (--change <id>) or --auto option must be specified.\n"));
1785
- }
1786
- if (useJson) {
1787
- const payload = {
1788
- command: "sdd:integrate",
1789
- success: false,
1790
- exitCode: 1,
1791
- error: "Change identifier (--change <id>) or --auto option must be specified."
1792
- };
1793
- console.log(JSON.stringify(payload, null, 2));
1794
- }
1795
- return false;
1907
+ if (useJson) {
1908
+ const payload = { command: "sdd:integrate", success: false, exitCode: 1, reasons: detection.reasons, error: "No active SDD change detected to integrate" };
1909
+ console.log(JSON.stringify(payload, null, 2));
1796
1910
  }
1911
+ return null;
1912
+ }
1913
+ function handlePendingTasks(detection, isSilent, useJson) {
1797
1914
  if (!isSilent) {
1798
- console.log(
1799
- pc9.bold(
1800
- pc9.cyan(`
1801
- \u{1F504} [AI-SDLC SDD] Integrating change '${changeId}' into canonical specification...`)
1802
- )
1803
- );
1804
- }
1805
- const result = integrateSddChange({
1806
- rootDir,
1807
- changeId,
1808
- author: options.author,
1809
- autoArchive: options.autoArchive
1810
- });
1811
- if (!isSilent) {
1812
- if (result.success) {
1813
- console.log(` ${pc9.green("\u2714")} Change '${changeId}' successfully processed:`);
1814
- console.log(` - Completed tasks: ${pc9.bold(String(result.completedTasks.length))}`);
1815
- console.log(` - Integrated requirements: ${pc9.green(result.integratedRequirements.join(", ") || "None")}`);
1816
- console.log(` - Created canonical artifacts: ${pc9.green(result.createdCanonicalArtifacts?.join(", ") || "None")}`);
1817
- console.log(` - Updated product artifacts: ${pc9.green(result.updatedProductArtifacts.join(", ") || "None")}`);
1818
- console.log(` - Updated arc42 architecture: ${pc9.green(result.updatedArchitectureArtifacts.join(", ") || "None")}`);
1819
- if (result.archived) {
1820
- console.log(` - Archived to: ${pc9.cyan(result.archivedPath || "specs/changes/completed")}`);
1821
- }
1822
- console.log(pc9.green("\n\u2714 Canonical specification integration COMPLETED (EXIT 0)\n"));
1823
- } else {
1824
- console.log(pc9.red(`
1825
- \u2716 Failed to integrate change '${changeId}':`));
1826
- for (const err of result.errors) {
1827
- console.log(` ${pc9.red("\u2716")} ${err}`);
1828
- }
1829
- console.log(pc9.red("\n\u2716 Integration BLOCKED (EXIT 1)\n"));
1830
- }
1915
+ console.log(pc9.red(`
1916
+ \u2716 [AI-SDLC SDD] Detected change '${detection.changeId}' has pending tasks (${detection.completedTasksCount}/${detection.totalTasksCount} completed). All tasks must be in COMPLETED status.
1917
+ `));
1831
1918
  }
1832
1919
  if (useJson) {
1833
1920
  const payload = {
1834
1921
  command: "sdd:integrate",
1835
- success: result.success,
1836
- exitCode: result.success ? 0 : 1,
1837
- changeId,
1838
- completedTasks: result.completedTasks,
1839
- integratedRequirements: result.integratedRequirements,
1840
- createdCanonicalArtifacts: result.createdCanonicalArtifacts ?? [],
1841
- updatedProductArtifacts: result.updatedProductArtifacts,
1842
- updatedArchitectureArtifacts: result.updatedArchitectureArtifacts,
1843
- archived: result.archived,
1844
- archivedPath: result.archivedPath,
1845
- errors: result.errors
1922
+ success: false,
1923
+ exitCode: 1,
1924
+ changeId: detection.changeId,
1925
+ completedTasksCount: detection.completedTasksCount,
1926
+ totalTasksCount: detection.totalTasksCount,
1927
+ error: `Detected change '${detection.changeId}' has pending tasks (${detection.completedTasksCount}/${detection.totalTasksCount} completed).`
1846
1928
  };
1847
1929
  console.log(JSON.stringify(payload, null, 2));
1848
1930
  }
1931
+ return null;
1932
+ }
1933
+ function resolveAutoChange(options, rootDir, isSilent, useJson) {
1934
+ const detection = detectActiveChangeForIntegration({
1935
+ rootDir,
1936
+ headRef: options.headRef,
1937
+ prTitle: options.prTitle,
1938
+ prBody: options.prBody
1939
+ });
1940
+ if (!detection.detected || !detection.changeId) {
1941
+ return handleUndetectedChange(detection, isSilent, useJson);
1942
+ }
1943
+ if (!detection.allTasksCompleted) {
1944
+ return handlePendingTasks(detection, isSilent, useJson);
1945
+ }
1946
+ if (!isSilent) {
1947
+ console.log(pc9.cyan(` \u2714 Automatically detected SDD change: ${pc9.bold(detection.changeId)} (via ${detection.source})`));
1948
+ }
1949
+ return detection.changeId;
1950
+ }
1951
+ function resolveIntegrationChangeId(options, rootDir, isSilent, useJson) {
1952
+ const changeId = options.change || (options.auto ? resolveAutoChange(options, rootDir, isSilent, useJson) : null);
1953
+ if (!changeId) {
1954
+ if (!options.auto) {
1955
+ if (!isSilent) console.error(pc9.red("\n\u2716 Change identifier (--change <id>) or --auto option must be specified.\n"));
1956
+ if (useJson) {
1957
+ console.log(JSON.stringify({ command: "sdd:integrate", success: false, exitCode: 1, error: "Change identifier (--change <id>) or --auto option must be specified." }, null, 2));
1958
+ }
1959
+ }
1960
+ return null;
1961
+ }
1962
+ return changeId;
1963
+ }
1964
+ function printIntegrationSuccess(changeId, result) {
1965
+ console.log(` ${pc9.green("\u2714")} Change '${changeId}' successfully processed:`);
1966
+ console.log(` - Completed tasks: ${pc9.bold(String(result.completedTasks.length))}`);
1967
+ console.log(` - Integrated requirements: ${pc9.green(result.integratedRequirements.join(", ") || "None")}`);
1968
+ console.log(` - Created canonical artifacts: ${pc9.green(result.createdCanonicalArtifacts?.join(", ") || "None")}`);
1969
+ console.log(` - Updated product artifacts: ${pc9.green(result.updatedProductArtifacts.join(", ") || "None")}`);
1970
+ console.log(` - Updated arc42 architecture: ${pc9.green(result.updatedArchitectureArtifacts.join(", ") || "None")}`);
1971
+ if (result.archived) {
1972
+ console.log(` - Archived to: ${pc9.cyan(result.archivedPath || "specs/changes/completed")}`);
1973
+ }
1974
+ console.log(pc9.green("\n\u2714 Canonical specification integration COMPLETED (EXIT 0)\n"));
1975
+ }
1976
+ function printIntegrationFailure(changeId, errors) {
1977
+ console.log(pc9.red(`
1978
+ \u2716 Failed to integrate change '${changeId}':`));
1979
+ for (const err of errors) console.log(` ${pc9.red("\u2716")} ${err}`);
1980
+ console.log(pc9.red("\n\u2716 Integration BLOCKED (EXIT 1)\n"));
1981
+ }
1982
+ function emitIntegrateJson(changeId, result) {
1983
+ const payload = {
1984
+ command: "sdd:integrate",
1985
+ success: result.success,
1986
+ exitCode: result.success ? 0 : 1,
1987
+ changeId,
1988
+ completedTasks: result.completedTasks,
1989
+ integratedRequirements: result.integratedRequirements,
1990
+ createdCanonicalArtifacts: result.createdCanonicalArtifacts ?? [],
1991
+ updatedProductArtifacts: result.updatedProductArtifacts,
1992
+ updatedArchitectureArtifacts: result.updatedArchitectureArtifacts,
1993
+ archived: result.archived,
1994
+ archivedPath: result.archivedPath,
1995
+ errors: result.errors
1996
+ };
1997
+ console.log(JSON.stringify(payload, null, 2));
1998
+ }
1999
+ function runSddIntegrate(options) {
2000
+ const rootDir = options.root || process.cwd();
2001
+ const useJson = isJsonOutput(options);
2002
+ const isSilent = Boolean(options.silent || useJson);
2003
+ const changeId = resolveIntegrationChangeId(options, rootDir, isSilent, useJson);
2004
+ if (!changeId) return false;
2005
+ if (!isSilent) {
2006
+ console.log(pc9.bold(pc9.cyan(`
2007
+ \u{1F504} [AI-SDLC SDD] Integrating change '${changeId}' into canonical specification...`)));
2008
+ }
2009
+ const result = integrateSddChange({ rootDir, changeId, author: options.author, autoArchive: options.autoArchive });
2010
+ if (!isSilent) {
2011
+ if (result.success) printIntegrationSuccess(changeId, result);
2012
+ else printIntegrationFailure(changeId, result.errors);
2013
+ }
2014
+ if (useJson) emitIntegrateJson(changeId, result);
1849
2015
  return result.success;
1850
2016
  }
2017
+ function printChangeNewSuccess(result) {
2018
+ console.log(` ${pc9.green("\u2714")} Change directory: ${pc9.bold(result.changeDir)}`);
2019
+ console.log(` ${pc9.green("\u2714")} SDD Change ID: ${pc9.cyan(result.canonicalId)} (${result.changeId})`);
2020
+ console.log(` ${pc9.green("\u2714")} Risk profile: ${pc9.magenta(result.profile || "standard")}`);
2021
+ if (result.productArtifactCreated) {
2022
+ console.log(` ${pc9.green("\u2714")} Product artifact: ${pc9.bold(result.productArtifactCreated)} (status: draft)`);
2023
+ }
2024
+ console.log(` ${pc9.green("\u2714")} Cited artifacts: ${result.citedArtifacts.length}`);
2025
+ for (const cite of result.citedArtifacts) {
2026
+ console.log(` - [${pc9.cyan(cite.id)}] ${cite.digest.substring(0, 19)}... (${cite.title || "Untitled"})`);
2027
+ }
2028
+ console.log(` ${pc9.green("\u2714")} Generated files: ${result.createdFiles.length}`);
2029
+ console.log(pc9.green("\n\u2714 SDD change successfully initialized and validated.\n"));
2030
+ }
2031
+ function printChangeNewFailure(name, errors) {
2032
+ console.log(pc9.red(`
2033
+ \u2716 Failed to create SDD change '${name}':`));
2034
+ for (const err of errors) console.log(` ${pc9.red("\u2716")} ${err}`);
2035
+ console.log(pc9.red("\n\u2716 Change creation BLOCKED\n"));
2036
+ }
2037
+ function emitChangeNewJson(name, result) {
2038
+ const payload = {
2039
+ command: "change:new",
2040
+ success: result.success,
2041
+ exitCode: result.success ? 0 : 1,
2042
+ name,
2043
+ canonicalId: result.canonicalId,
2044
+ changeId: result.changeId,
2045
+ changeDir: result.changeDir,
2046
+ profile: result.profile,
2047
+ createdFiles: result.createdFiles,
2048
+ productArtifactCreated: result.productArtifactCreated,
2049
+ citedArtifacts: result.citedArtifacts,
2050
+ errors: result.errors
2051
+ };
2052
+ console.log(JSON.stringify(payload, null, 2));
2053
+ }
2054
+ function printChangeNewHeader(name, framework) {
2055
+ console.log(pc9.bold(pc9.cyan(`
2056
+ \u{1F4E6} [AI-SDLC SDD] Scaffolding new SDD change '${name}' (${framework})...`)));
2057
+ }
2058
+ function handleScaffoldOutput(name, result, isSilent, useJson) {
2059
+ if (!isSilent) {
2060
+ if (result.success) printChangeNewSuccess(result);
2061
+ else printChangeNewFailure(name, result.errors);
2062
+ }
2063
+ if (useJson) emitChangeNewJson(name, result);
2064
+ }
1851
2065
  function runChangeNew(options) {
1852
2066
  const rootDir = options.root || process.cwd();
1853
2067
  const name = options.name;
@@ -1855,12 +2069,7 @@ function runChangeNew(options) {
1855
2069
  const useJson = isJsonOutput(options);
1856
2070
  const isSilent = Boolean(options.silent || useJson);
1857
2071
  if (!isSilent) {
1858
- console.log(
1859
- pc9.bold(
1860
- pc9.cyan(`
1861
- \u{1F4E6} [AI-SDLC SDD] Scaffolding new SDD change '${name}' (${framework})...`)
1862
- )
1863
- );
2072
+ printChangeNewHeader(name, framework);
1864
2073
  }
1865
2074
  const result = scaffoldSddChange({
1866
2075
  rootDir,
@@ -1872,52 +2081,13 @@ function runChangeNew(options) {
1872
2081
  author: options.author,
1873
2082
  silent: isSilent
1874
2083
  });
1875
- if (!isSilent) {
1876
- if (result.success) {
1877
- console.log(` ${pc9.green("\u2714")} Change directory: ${pc9.bold(result.changeDir)}`);
1878
- console.log(` ${pc9.green("\u2714")} SDD Change ID: ${pc9.cyan(result.canonicalId)} (${result.changeId})`);
1879
- console.log(` ${pc9.green("\u2714")} Risk profile: ${pc9.magenta(result.profile || "standard")}`);
1880
- if (result.productArtifactCreated) {
1881
- console.log(` ${pc9.green("\u2714")} Product artifact: ${pc9.bold(result.productArtifactCreated)} (status: draft)`);
1882
- }
1883
- console.log(` ${pc9.green("\u2714")} Cited artifacts: ${result.citedArtifacts.length}`);
1884
- for (const cite of result.citedArtifacts) {
1885
- console.log(` - [${pc9.cyan(cite.id)}] ${cite.digest.substring(0, 19)}... (${cite.title || "Untitled"})`);
1886
- }
1887
- console.log(` ${pc9.green("\u2714")} Generated files: ${result.createdFiles.length}`);
1888
- console.log(pc9.green("\n\u2714 SDD change successfully initialized and validated.\n"));
1889
- } else {
1890
- console.log(pc9.red(`
1891
- \u2716 Failed to create SDD change '${name}':`));
1892
- for (const err of result.errors) {
1893
- console.log(` ${pc9.red("\u2716")} ${err}`);
1894
- }
1895
- console.log(pc9.red("\n\u2716 Change creation BLOCKED\n"));
1896
- }
1897
- }
1898
- if (useJson) {
1899
- const payload = {
1900
- command: "change:new",
1901
- success: result.success,
1902
- exitCode: result.success ? 0 : 1,
1903
- name,
1904
- canonicalId: result.canonicalId,
1905
- changeId: result.changeId,
1906
- changeDir: result.changeDir,
1907
- profile: result.profile,
1908
- createdFiles: result.createdFiles,
1909
- productArtifactCreated: result.productArtifactCreated,
1910
- citedArtifacts: result.citedArtifacts,
1911
- errors: result.errors
1912
- };
1913
- console.log(JSON.stringify(payload, null, 2));
1914
- }
2084
+ handleScaffoldOutput(name, result, isSilent, useJson);
1915
2085
  return result.success;
1916
2086
  }
1917
2087
 
1918
2088
  // src/index.ts
1919
2089
  var program = new Command();
1920
- program.name("aisdlc").description("AI-SDLC: Spec-Driven Development, Governance & Quality Gates for AI & Humans").version("1.3.2");
2090
+ program.name("aisdlc").description("AI-SDLC: Spec-Driven Development, Governance & Quality Gates for AI & Humans").version("1.4.1");
1921
2091
  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) => {
1922
2092
  const passed = runCheck({
1923
2093
  fix: opts.fix,
@@ -1968,6 +2138,10 @@ verifyCommand.command("testing").description("Audit that 100% of requirements an
1968
2138
  const passed = runVerifyTesting({ root: opts.root, json: opts.json, format: opts.format });
1969
2139
  process.exit(passed ? 0 : 1);
1970
2140
  });
2141
+ verifyCommand.command("gherkin").description("Verify BDD synchronization between Markdown Gherkin blocks and .feature files").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) => {
2142
+ const passed = runVerifyGherkin({ root: opts.root, json: opts.json, format: opts.format });
2143
+ process.exit(passed ? 0 : 1);
2144
+ });
1971
2145
  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) => {
1972
2146
  const passed = runVerifyLicenses({
1973
2147
  root: opts.root,