@aisdlc/core 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1687,21 +1687,24 @@ function collectUniqueSteps(doc) {
1687
1687
  return unique;
1688
1688
  }
1689
1689
  function renderTsFallback(relFeature, steps) {
1690
- const lines = [
1690
+ const entries = steps.map((st) => ` ['${mapStepKeyword(st.keyword)}', "${escapeDoubleQuotes(st.text)}"],`);
1691
+ return [
1691
1692
  `// AUTO-GENERATED RED BDD STEP DEFINITIONS (${relFeature})`,
1692
1693
  `import { BddStepRegistry } from '@aisdlc/core';`,
1693
1694
  ``,
1694
- `export function registerSteps(registry: BddStepRegistry): void {`
1695
- ];
1696
- for (const st of steps) {
1697
- const method = mapStepKeyword(st.keyword);
1698
- const escaped = escapeDoubleQuotes(st.text);
1699
- lines.push(` registry.${method}("${escaped}", () => {`);
1700
- lines.push(` throw new Error("RED: Step not implemented: ${escaped}");`);
1701
- lines.push(` });`);
1702
- }
1703
- lines.push(`}`, ``);
1704
- return lines.join("\n");
1695
+ `const STEP_SPECS: ReadonlyArray<readonly ['given' | 'when' | 'then', string]> = [`,
1696
+ ...entries,
1697
+ `];`,
1698
+ ``,
1699
+ `export function registerSteps(registry: BddStepRegistry): void {`,
1700
+ ` for (const [method, text] of STEP_SPECS) {`,
1701
+ ` registry[method](text, () => {`,
1702
+ ` throw new Error(\`RED: Step not implemented: \${text}\`);`,
1703
+ ` });`,
1704
+ ` }`,
1705
+ `}`,
1706
+ ``
1707
+ ].join("\n");
1705
1708
  }
1706
1709
  function renderPyFallback(relFeature, steps) {
1707
1710
  const lines = [
@@ -2045,39 +2048,85 @@ function extractGherkinFeatures(options = {}) {
2045
2048
  }
2046
2049
  return { success: true, features, totalScenarios };
2047
2050
  }
2051
+ function walkFeatureFiles(dir, fileList = []) {
2052
+ if (!fs12.existsSync(dir)) return fileList;
2053
+ for (const entry of fs12.readdirSync(dir).sort(canonicalSort)) {
2054
+ const fullPath = path14.join(dir, entry);
2055
+ if (fs12.statSync(fullPath).isDirectory()) {
2056
+ walkFeatureFiles(fullPath, fileList);
2057
+ } else if (entry.endsWith(".feature")) {
2058
+ fileList.push(fullPath);
2059
+ }
2060
+ }
2061
+ return fileList;
2062
+ }
2063
+ function hasDeterministicStepFile(rootDir, featureFullPath) {
2064
+ return Object.values(GHERKIN_GENERATOR_SPECS).some((spec) => {
2065
+ const stepPath = spec.resolveOutputPath(rootDir, featureFullPath);
2066
+ return fs12.existsSync(stepPath) && fs12.statSync(stepPath).size > 0;
2067
+ });
2068
+ }
2069
+ function findOrphanFeatureFiles(rootDir, expectedRelPaths) {
2070
+ const featuresDir = path14.join(rootDir, "tests", "features");
2071
+ const orphans = [];
2072
+ for (const fp of walkFeatureFiles(featuresDir)) {
2073
+ const rel = path14.relative(rootDir, fp).replace(/\\/g, "/");
2074
+ if (!expectedRelPaths.has(rel)) {
2075
+ orphans.push(rel);
2076
+ }
2077
+ }
2078
+ return orphans;
2079
+ }
2080
+ function verifyExistingFeatureFile(rootDir, targetPath, expectedContent, relTarget, state) {
2081
+ const actualContent = fs12.readFileSync(targetPath, "utf-8");
2082
+ if (actualContent.replace(/\r\n/g, "\n") !== expectedContent.replace(/\r\n/g, "\n")) {
2083
+ state.outOfSyncFiles.push(relTarget);
2084
+ }
2085
+ if (!hasDeterministicStepFile(rootDir, targetPath)) {
2086
+ state.missingStepFiles.push(relTarget);
2087
+ }
2088
+ }
2089
+ function checkSingleMarkdownFeatureSync(rootDir, filePath, state) {
2090
+ const { frontmatter, body } = parseMarkdownFrontmatter(fs12.readFileSync(filePath, "utf-8"));
2091
+ const gherkinBlocks = extractGherkinBlock(body);
2092
+ if (gherkinBlocks.length === 0) return;
2093
+ state.totalFeatures++;
2094
+ const id = frontmatter.id || path14.basename(filePath, path14.extname(filePath));
2095
+ const targetPath = resolveFeatureFilePath(rootDir, filePath, id, frontmatter["cucumber-feature-file"]);
2096
+ const relTarget = path14.relative(rootDir, targetPath).replace(/\\/g, "/");
2097
+ state.expectedRelPaths.add(relTarget);
2098
+ if (!fs12.existsSync(targetPath)) {
2099
+ state.missingFiles.push(relTarget);
2100
+ return;
2101
+ }
2102
+ const expectedContent = buildFeatureFileContent(rootDir, filePath, id, frontmatter.version, gherkinBlocks);
2103
+ verifyExistingFeatureFile(rootDir, targetPath, expectedContent, relTarget, state);
2104
+ }
2048
2105
  function checkGherkinInSync(options = {}) {
2049
2106
  const rootDir = options.rootDir || process.cwd();
2050
2107
  const targetFiles = resolveTargetFiles(rootDir, options.targetPath);
2051
- const outOfSyncFiles = [];
2052
- const missingFiles = [];
2053
- let totalFeatures = 0;
2108
+ const state = {
2109
+ outOfSyncFiles: [],
2110
+ missingFiles: [],
2111
+ missingStepFiles: [],
2112
+ expectedRelPaths: /* @__PURE__ */ new Set(),
2113
+ totalFeatures: 0
2114
+ };
2054
2115
  for (const filePath of targetFiles) {
2055
2116
  try {
2056
- const content = fs12.readFileSync(filePath, "utf-8");
2057
- const { frontmatter, body } = parseMarkdownFrontmatter(content);
2058
- const gherkinBlocks = extractGherkinBlock(body);
2059
- if (gherkinBlocks.length === 0) continue;
2060
- totalFeatures++;
2061
- const id = frontmatter.id || path14.basename(filePath, path14.extname(filePath));
2062
- const targetPath = resolveFeatureFilePath(rootDir, filePath, id, frontmatter["cucumber-feature-file"]);
2063
- const relTarget = path14.relative(rootDir, targetPath).replace(/\\/g, "/");
2064
- if (!fs12.existsSync(targetPath)) {
2065
- missingFiles.push(relTarget);
2066
- continue;
2067
- }
2068
- const expectedContent = buildFeatureFileContent(rootDir, filePath, id, frontmatter.version, gherkinBlocks);
2069
- const actualContent = fs12.readFileSync(targetPath, "utf-8");
2070
- if (actualContent.replace(/\r\n/g, "\n") !== expectedContent.replace(/\r\n/g, "\n")) {
2071
- outOfSyncFiles.push(relTarget);
2072
- }
2117
+ checkSingleMarkdownFeatureSync(rootDir, filePath, state);
2073
2118
  } catch {
2074
2119
  }
2075
2120
  }
2121
+ const orphanFeatureFiles = options.targetPath ? [] : findOrphanFeatureFiles(rootDir, state.expectedRelPaths);
2122
+ const inSync = state.missingFiles.length === 0 && state.outOfSyncFiles.length === 0 && orphanFeatureFiles.length === 0 && state.missingStepFiles.length === 0;
2076
2123
  return {
2077
- inSync: missingFiles.length === 0 && outOfSyncFiles.length === 0,
2078
- outOfSyncFiles,
2079
- missingFiles,
2080
- totalFeatures
2124
+ inSync,
2125
+ outOfSyncFiles: state.outOfSyncFiles,
2126
+ missingFiles: state.missingFiles,
2127
+ orphanFeatureFiles,
2128
+ missingStepFiles: state.missingStepFiles,
2129
+ totalFeatures: state.totalFeatures
2081
2130
  };
2082
2131
  }
2083
2132
 
@@ -6571,11 +6620,13 @@ function sanitizeDlpPayload(payload, policy = createDefaultDlpPolicy()) {
6571
6620
  // src/adapters/sdd/review-report.ts
6572
6621
  var REVIEW_VERDICTS = ["COMPLIANT", "SUGGESTIONS", "BLOCKING"];
6573
6622
  var REVIEWER_ROLES = [
6623
+ "agent-auditor",
6624
+ "agent-adversary",
6625
+ "agent-privacy-officer",
6626
+ "agent-expert-user",
6574
6627
  "agent-code-reviewer",
6575
6628
  "agent-security-auditor",
6576
6629
  "agent-compliance-checker",
6577
- "agent-privacy-officer",
6578
- "agent-expert-user",
6579
6630
  "auditor",
6580
6631
  "reviewer"
6581
6632
  ];
@@ -13825,1326 +13876,1466 @@ function verifyPrivacy(options = {}) {
13825
13876
  writePrivacyOutputsIfNeeded(result, options, policy, rootDir);
13826
13877
  return result;
13827
13878
  }
13828
- function calculateRating(mi, cc) {
13829
- if (mi >= 75 && cc <= 5) return "A";
13830
- if (mi >= 60 && cc <= 10) return "B";
13831
- if (mi >= 50 && cc <= 15) return "C";
13832
- if (mi >= 40 && cc <= 20) return "D";
13833
- return "F";
13879
+ var TRAILER_REGEXES = {
13880
+ taskId: /^\s*Task-ID:\s*(.+)$/im,
13881
+ parentRef: /^\s*Parent-Ref:\s*(.+)$/im,
13882
+ authorType: /^\s*Author-Type:\s*(human|agent)/im,
13883
+ aiModel: /^\s*AI-Model:\s*(.+)$/im,
13884
+ promptTokens: /^\s*Prompt-Tokens:\s*([0-9]+)/im,
13885
+ completionTokens: /^\s*Completion-Tokens:\s*([0-9]+)/im,
13886
+ activeTimeSeconds: /^\s*Active-Time-Seconds:\s*([0-9]+)/im
13887
+ };
13888
+ function parseTrailerInt(match) {
13889
+ if (!match) return 0;
13890
+ const val = parseInt(match[1], 10);
13891
+ return isNaN(val) ? 0 : val;
13834
13892
  }
13835
- function detectLanguage(filePath) {
13836
- const ext = path14.extname(filePath).toLowerCase();
13837
- switch (ext) {
13838
- case ".ts":
13839
- return "TypeScript";
13840
- case ".js":
13841
- return "JavaScript";
13842
- case ".py":
13843
- return "Python";
13844
- case ".java":
13845
- return "Java";
13846
- case ".go":
13847
- return "Go";
13848
- case ".cs":
13849
- return "C#";
13850
- case ".rs":
13851
- return "Rust";
13852
- case ".cpp":
13853
- case ".c":
13854
- return "C/C++";
13855
- default:
13856
- return "Unknown";
13893
+ function resolveAuthorType(authorTypeMatch, aiModelMatch) {
13894
+ if (authorTypeMatch) {
13895
+ return authorTypeMatch[1].toLowerCase();
13857
13896
  }
13858
- }
13859
- function readCodeCoverageSummary(rootDir = process.cwd()) {
13860
- return readNormalizedCoverage(rootDir);
13861
- }
13862
- function formatCoverageRow(label, measured, minThreshold) {
13863
- if (measured === void 0) {
13864
- return `| **${label}** | \`N/A (Run test:coverage)\` | $\\ge ${minThreshold}\\%$ | \u2139\uFE0F NOT MEASURED |`;
13897
+ if (aiModelMatch && aiModelMatch[1].trim() !== "n/a") {
13898
+ return "agent";
13865
13899
  }
13866
- const status = measured >= minThreshold ? "\u2705 COMPLIANT" : "\u26A0\uFE0F BELOW THRESHOLD";
13867
- return `| **${label}** | \`${measured}%\` | $\\ge ${minThreshold}\\%$ | ${status} |`;
13900
+ return "human";
13868
13901
  }
13869
- function buildCoverageRows(coverage, policy) {
13870
- return [
13871
- formatCoverageRow("Line Coverage", coverage?.linesPct, policy.min_line_coverage),
13872
- formatCoverageRow("Branch Coverage", coverage?.branchesPct, policy.min_branch_coverage),
13873
- formatCoverageRow("Function Coverage", coverage?.functionsPct, policy.min_function_coverage)
13874
- ];
13902
+ function resolveTrailerOrScope(match, text, fallbackRegex) {
13903
+ if (match) return match[1].trim();
13904
+ const subMatch = text.match(fallbackRegex);
13905
+ return subMatch ? subMatch[1].toUpperCase() : void 0;
13875
13906
  }
13876
- function updateLangStats(langMap, fn) {
13877
- const lang = detectLanguage(fn.filePath);
13878
- const existing = langMap.get(lang) || { fns: 0, loc: 0, miSum: 0, ccSum: 0 };
13879
- existing.fns++;
13880
- existing.loc += fn.loc;
13881
- existing.miSum += fn.maintainability;
13882
- existing.ccSum += fn.cyclomatic;
13883
- langMap.set(lang, existing);
13907
+ function parseCommitTrailers(rawMessage) {
13908
+ const text = rawMessage || "";
13909
+ const authorTypeMatch = text.match(TRAILER_REGEXES.authorType);
13910
+ const aiModelMatch = text.match(TRAILER_REGEXES.aiModel);
13911
+ const authorType = resolveAuthorType(authorTypeMatch, aiModelMatch);
13912
+ const rawModel = aiModelMatch ? aiModelMatch[1].trim() : void 0;
13913
+ const aiModel = rawModel && rawModel !== "n/a" ? rawModel : void 0;
13914
+ return {
13915
+ taskId: resolveTrailerOrScope(text.match(TRAILER_REGEXES.taskId), text, /\b(TSK-[0-9A-Za-z_-]+)\b/i),
13916
+ parentRef: resolveTrailerOrScope(text.match(TRAILER_REGEXES.parentRef), text, /\b((?:CHG|FEAT|BUG|FIX|PATCH)-[0-9A-Za-z_-]+)\b/i),
13917
+ authorType,
13918
+ aiModel,
13919
+ promptTokens: parseTrailerInt(text.match(TRAILER_REGEXES.promptTokens)),
13920
+ completionTokens: parseTrailerInt(text.match(TRAILER_REGEXES.completionTokens)),
13921
+ activeTimeSeconds: parseTrailerInt(text.match(TRAILER_REGEXES.activeTimeSeconds))
13922
+ };
13884
13923
  }
13885
- function processFunctionMetric(fn, accumulated) {
13886
- accumulated.totalMi += fn.maintainability;
13887
- accumulated.totalCc += fn.cyclomatic;
13888
- accumulated.totalCognitive += fn.cognitive;
13889
- accumulated.totalLoc += fn.loc;
13890
- updateLangStats(accumulated.langMap, fn);
13891
- if (fn.violations.length > 0) {
13892
- accumulated.violationsList.push(`- **\`${fn.relPath}\`** [\`${fn.functionName}\`]: ${fn.violations.join(", ")}`);
13893
- }
13924
+ function formatCommitTrailers(trailers) {
13925
+ const lines = [];
13926
+ if (trailers.taskId) lines.push(`Task-ID: ${trailers.taskId}`);
13927
+ if (trailers.parentRef) lines.push(`Parent-Ref: ${trailers.parentRef}`);
13928
+ lines.push(`Author-Type: ${trailers.authorType || "human"}`);
13929
+ lines.push(`AI-Model: ${trailers.aiModel || "n/a"}`);
13930
+ lines.push(`Prompt-Tokens: ${trailers.promptTokens ?? 0}`);
13931
+ lines.push(`Completion-Tokens: ${trailers.completionTokens ?? 0}`);
13932
+ lines.push(`Active-Time-Seconds: ${trailers.activeTimeSeconds ?? 0}`);
13933
+ return lines.join("\n");
13894
13934
  }
13895
- function accumulateMetrics(results) {
13896
- const accumulated = {
13897
- totalMi: 0,
13898
- totalCc: 0,
13899
- totalCognitive: 0,
13900
- totalLoc: 0,
13901
- langMap: /* @__PURE__ */ new Map(),
13902
- violationsList: []
13903
- };
13904
- for (const fn of results) {
13905
- processFunctionMetric(fn, accumulated);
13935
+ function parseRawLogChunks(rawLog) {
13936
+ const rawCommits = rawLog.split("---AI_SDLC_COMMIT---").filter((c) => c.trim().length > 0);
13937
+ const chunks = [];
13938
+ for (const raw of rawCommits) {
13939
+ const endBodyIdx = raw.indexOf("---AI_SDLC_BODY_END---");
13940
+ if (endBodyIdx === -1) continue;
13941
+ const beforeEnd = raw.slice(0, endBodyIdx).trimStart();
13942
+ const afterEnd = raw.slice(endBodyIdx + "---AI_SDLC_BODY_END---".length);
13943
+ const firstNewline = beforeEnd.indexOf("\n");
13944
+ const header = firstNewline === -1 ? beforeEnd : beforeEnd.slice(0, firstNewline);
13945
+ const body = firstNewline === -1 ? "" : beforeEnd.slice(firstNewline + 1);
13946
+ const numstatLines = afterEnd.split("\n").filter((l) => /^\d+\s+\d+\s+/.test(l.trim()));
13947
+ chunks.push({ header, body, numstatLines });
13906
13948
  }
13907
- return accumulated;
13949
+ return chunks;
13908
13950
  }
13909
- function renderPolyglotRows(langMap) {
13910
- const rows = [];
13911
- for (const [lang, stats] of langMap.entries()) {
13912
- const langMi = Math.round(stats.miSum / stats.fns * 10) / 10;
13913
- const langCc = Math.round(stats.ccSum / stats.fns * 10) / 10;
13914
- const rating = calculateRating(langMi, langCc);
13915
- rows.push(`| **${lang}** | \`${stats.fns}\` | \`${stats.loc}\` | \`${langMi}\` | \`${langCc}\` | \`${rating}\` |`);
13951
+ function sumNumstatLines(lines) {
13952
+ let added = 0;
13953
+ let deleted = 0;
13954
+ const files = [];
13955
+ for (const line of lines) {
13956
+ const parts = line.trim().split(/\s+/);
13957
+ if (parts.length >= 2) {
13958
+ const a = parseInt(parts[0], 10);
13959
+ const d = parseInt(parts[1], 10);
13960
+ if (!isNaN(a)) added += a;
13961
+ if (!isNaN(d)) deleted += d;
13962
+ if (parts.length >= 3) files.push(parts.slice(2).join(" "));
13963
+ }
13916
13964
  }
13917
- return rows;
13965
+ return { added, deleted, files };
13918
13966
  }
13919
- var EVALUATION_STANDARDS_MD = [
13920
- "---",
13921
- "",
13922
- "## 4. Evaluation Criteria and Standards",
13923
- "- **McCabe Cyclomatic Complexity (CC)**: Number of linearly independent paths.",
13924
- "- **Maintainability Index (SEI MI)**: Normalized formula [0 - 100] combining Halstead Volume, CC, and LOC.",
13925
- "- **Automated Test Coverage**: Passively ingested from `coverage/coverage-summary.json` or `lcov.info` when present.",
13926
- "- **Clean Code Guardrails**: Prohibition of implicit `any` typing, function length limits ($\\le 40$ lines), and zero unjustified suppressions."
13927
- ].join("\n");
13928
- function computeQualityAverages(totalFunctions, acc) {
13929
- const avgMaintainability = totalFunctions > 0 ? Math.round(acc.totalMi / totalFunctions * 10) / 10 : 100;
13930
- const avgCyclomatic = totalFunctions > 0 ? Math.round(acc.totalCc / totalFunctions * 10) / 10 : 1;
13931
- const avgCognitive = totalFunctions > 0 ? Math.round(acc.totalCognitive / totalFunctions * 10) / 10 : 0;
13932
- const globalRating = calculateRating(avgMaintainability, avgCyclomatic);
13933
- return { avgMaintainability, avgCyclomatic, avgCognitive, globalRating };
13967
+ function evaluateIsBugFix(subject, parentRef) {
13968
+ if (parentRef && /^(BUG|FIX)-/i.test(parentRef)) return true;
13969
+ return /^(fix|bug)(\([^)]+\))?:/i.test(subject.trim());
13934
13970
  }
13935
- function buildReportHeader3(verdict, rating, mi, cc) {
13936
- const status = verdict === "PASS" ? "\u{1F7E2} APPROVED (RELEASE READY)" : "\u{1F534} BLOCKED (VIOLATIONS DETECTED)";
13937
- return [
13938
- `# \u{1F4CA} Formal Quality and Release Gate Report (AI-SDLC)`,
13939
- "",
13940
- `> **Generation Date:** ${resolveDeterministicDate().toISOString()}`,
13941
- `> **Release Gate Verdict:** ${status}`,
13942
- `> **Global Rating:** **\`${rating}\`** (MI Index: ${mi}/100, Average CC: ${cc})`
13943
- ];
13971
+ function inferAgentTrailers(trailers, linesAdded, linesDeleted) {
13972
+ const res = { ...trailers };
13973
+ const linesChanged = linesAdded + linesDeleted;
13974
+ let estimated = false;
13975
+ if (res.promptTokens === 0 && res.completionTokens === 0) {
13976
+ res.completionTokens = linesChanged > 0 ? Math.max(linesAdded * 10, 50) : 0;
13977
+ res.promptTokens = linesChanged > 0 ? Math.max(2500 + linesChanged * 25, 3e3) : 1e3;
13978
+ estimated = true;
13979
+ }
13980
+ if (res.activeTimeSeconds === 0) {
13981
+ res.activeTimeSeconds = linesChanged > 0 ? Math.round(30 + linesChanged * 0.5) : 30;
13982
+ estimated = true;
13983
+ }
13984
+ res.isTelemetryEstimated = estimated;
13985
+ return res;
13944
13986
  }
13945
- function buildMetricStatus(averages, policy, failCount) {
13946
- return {
13947
- ccStatus: averages.avgCyclomatic <= policy.max_cyclomatic ? "\u2705 COMPLIANT" : "\u274C EXCEEDED",
13948
- cogStatus: averages.avgCognitive <= policy.max_cognitive ? "\u2705 COMPLIANT" : "\u274C EXCEEDED",
13949
- miStatus: averages.avgMaintainability >= policy.min_maintainability ? "\u2705 COMPLIANT" : "\u274C INSUFFICIENT",
13950
- violStatus: failCount === 0 ? "\u2705 0 VIOLATIONS" : "\u274C BLOCKED"
13951
- };
13987
+ function inferHumanTrailers(trailers, linesAdded, linesDeleted) {
13988
+ const res = { ...trailers };
13989
+ const linesChanged = linesAdded + linesDeleted;
13990
+ let estimated = false;
13991
+ if (res.activeTimeSeconds === 0) {
13992
+ res.activeTimeSeconds = linesChanged > 0 ? Math.round(180 + linesChanged * 2) : 120;
13993
+ estimated = true;
13994
+ }
13995
+ res.isTelemetryEstimated = estimated;
13996
+ return res;
13952
13997
  }
13953
- function buildCountRows(totalFiles, totalFunctions, totalLoc) {
13954
- return [
13955
- `| **Analyzed Files** | \`${totalFiles}\` | N/A | \u2139\uFE0F |`,
13956
- `| **Evaluated Functions** | \`${totalFunctions}\` | N/A | \u2139\uFE0F |`,
13957
- `| **Lines of Code (LOC)** | \`${totalLoc}\` | N/A | \u2139\uFE0F |`
13958
- ];
13998
+ function inferMissingTrailers(trailers, linesAdded, linesDeleted) {
13999
+ return trailers.authorType === "agent" ? inferAgentTrailers(trailers, linesAdded, linesDeleted) : inferHumanTrailers(trailers, linesAdded, linesDeleted);
13959
14000
  }
13960
- function buildExecutiveTable(gateResult, totalLoc, averages, coverage) {
13961
- const { policy, totalFiles, totalFunctions, failCount } = gateResult;
13962
- const status = buildMetricStatus(averages, policy, failCount);
13963
- return [
13964
- "## 1. Executive Metric Summary",
13965
- "",
13966
- "| Key Metric | Measured Value | Policy Threshold | Compliance |",
13967
- "| :--- | :---: | :---: | :---: |",
13968
- ...buildCountRows(totalFiles, totalFunctions, totalLoc),
13969
- `| **Cyclomatic Complexity (Average)** | \`${averages.avgCyclomatic}\` | $\\le ${policy.max_cyclomatic}$ | ${status.ccStatus} |`,
13970
- `| **Cognitive Complexity (Average)** | \`${averages.avgCognitive}\` | $\\le ${policy.max_cognitive}$ | ${status.cogStatus} |`,
13971
- `| **Maintainability Index (SEI MI)** | \`${averages.avgMaintainability} / 100\` | $\\ge ${policy.min_maintainability}$ | ${status.miStatus} |`,
13972
- ...buildCoverageRows(coverage, policy),
13973
- `| **Functions in Violation** | \`${failCount}\` | $0$ (Mode ${policy.enforce_mode}) | ${status.violStatus} |`
13974
- ];
13975
- }
13976
- function renderQualityReportMarkdown(gateResult, coverage, accumulated, averages) {
13977
- const verdict = gateResult.success ? "PASS" : "FAIL";
13978
- const header = buildReportHeader3(verdict, averages.globalRating, averages.avgMaintainability, averages.avgCyclomatic);
13979
- const table = buildExecutiveTable(gateResult, accumulated.totalLoc, averages, coverage);
13980
- const polyglot = [
13981
- "## 2. Polyglot Breakdown by Language Ecosystem",
13982
- "",
13983
- "| Language | Functions | Total LOC | Average MI | Average CC | Rating |",
13984
- "| :--- | :---: | :---: | :---: | :---: | :---: |",
13985
- ...renderPolyglotRows(accumulated.langMap)
14001
+ function resolveGitRef(cwd, ref) {
14002
+ if (!ref || ref === "HEAD") return ref;
14003
+ const candidates = [
14004
+ ref,
14005
+ `feat/${ref}`,
14006
+ `release/${ref}`,
14007
+ `bug/${ref}`,
14008
+ `task/${ref}`,
14009
+ `origin/${ref}`,
14010
+ `origin/feat/${ref}`,
14011
+ `origin/release/${ref}`,
14012
+ `origin/bug/${ref}`
13986
14013
  ];
13987
- const violationsSection = accumulated.violationsList.length > 0 ? ["", "---", "", "## 3. Quality Gate Violations Log", "", ...accumulated.violationsList] : [];
13988
- return [...header, "", "---", "", ...table, "", "---", "", ...polyglot, ...violationsSection, "", EVALUATION_STANDARDS_MD].join("\n");
14014
+ for (const cand of candidates) {
14015
+ try {
14016
+ execFileSync("git", ["rev-parse", "--verify", "--quiet", cand], {
14017
+ cwd,
14018
+ stdio: ["pipe", "pipe", "pipe"]
14019
+ });
14020
+ return cand;
14021
+ } catch {
14022
+ }
14023
+ }
14024
+ return ref;
13989
14025
  }
13990
- function writeQualityReportFile(rootDir, markdown) {
13991
- const targetPath = path14.join(rootDir, "reports", "QUALITY_REPORT.md");
13992
- return writeReportFileIfChanged(targetPath, markdown);
14026
+ function fetchGitLogOutput(cwd, baseRef, headRef, format) {
14027
+ const rangeArg = baseRef ? `${baseRef}..${headRef}` : headRef;
14028
+ try {
14029
+ return execFileSync("git", ["log", rangeArg, `--format=${format}`, "--numstat"], {
14030
+ cwd,
14031
+ encoding: "utf-8",
14032
+ stdio: ["pipe", "pipe", "pipe"]
14033
+ });
14034
+ } catch {
14035
+ if (baseRef && !baseRef.includes("/")) {
14036
+ try {
14037
+ return execFileSync("git", ["log", `origin/${baseRef}..${headRef}`, `--format=${format}`, `--numstat`], {
14038
+ cwd,
14039
+ encoding: "utf-8",
14040
+ stdio: ["pipe", "pipe", "pipe"]
14041
+ });
14042
+ } catch {
14043
+ return "";
14044
+ }
14045
+ }
14046
+ return "";
14047
+ }
13993
14048
  }
13994
- function generateQualityReport(options = {}) {
13995
- const rootDir = options.rootDir || process.cwd();
13996
- const gateResult = verifyQualityGate({
13997
- rootDir,
13998
- policyPath: options.policyPath,
13999
- thresholds: options.thresholds
14000
- });
14001
- const coverage = readCodeCoverageSummary(rootDir);
14002
- const accumulated = accumulateMetrics(gateResult.results);
14003
- const averages = computeQualityAverages(gateResult.totalFunctions, accumulated);
14004
- const markdown = renderQualityReportMarkdown(gateResult, coverage, accumulated, averages);
14005
- writeQualityReportFile(rootDir, markdown);
14049
+ function buildCommitKpiRecord(chunk) {
14050
+ const fields = chunk.header.split("");
14051
+ if (fields.length < 5) return null;
14052
+ const rawTrailers = parseCommitTrailers(chunk.body);
14053
+ const { added, deleted, files } = sumNumstatLines(chunk.numstatLines);
14054
+ const trailers = inferMissingTrailers(rawTrailers, added, deleted);
14006
14055
  return {
14007
- markdown,
14008
- totalFiles: gateResult.totalFiles,
14009
- totalFunctions: gateResult.totalFunctions,
14010
- avgMaintainability: averages.avgMaintainability,
14011
- avgCyclomatic: averages.avgCyclomatic,
14012
- verdict: gateResult.success ? "PASS" : "FAIL",
14013
- coverage
14056
+ sha: fields[0],
14057
+ authorName: fields[1],
14058
+ authorEmail: fields[2],
14059
+ date: fields[3],
14060
+ subject: fields[4],
14061
+ trailers,
14062
+ linesAdded: added,
14063
+ linesDeleted: deleted,
14064
+ isBugFix: evaluateIsBugFix(fields[4], trailers.parentRef),
14065
+ touchedFiles: files
14014
14066
  };
14015
14067
  }
14016
-
14017
- // src/git/workflow.ts
14018
- var BRANCH_PATTERNS = {
14019
- MAIN: /^main$/,
14020
- RELEASE: /^release\/v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$/,
14021
- FEATURE: /^(feat|feature)\/(?:v[0-9]+\.[0-9]+\.[0-9]+\/)?([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/,
14022
- BUG: /^(bug|fix)\/(?:v[0-9]+\.[0-9]+\.[0-9]+\/)?([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/,
14023
- PATCH: /^(patch)\/(?:v[0-9]+\.[0-9]+\.[0-9]+\/)?([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/,
14024
- TASK: /^task\/([a-zA-Z0-9]+-[a-zA-Z0-9-]+)\/([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/
14025
- };
14026
- function classifyTier1And2(branchName) {
14027
- if (BRANCH_PATTERNS.MAIN.test(branchName)) {
14028
- return {
14029
- valid: true,
14030
- tier: 1,
14031
- tierName: "Main (Producci\xF3n)",
14032
- parentRequirement: "Ninguno (Rama Ra\xEDz)",
14033
- targetMerge: "Despliegue a Producci\xF3n"
14034
- };
14035
- }
14036
- if (BRANCH_PATTERNS.RELEASE.test(branchName)) {
14037
- return {
14038
- valid: true,
14039
- tier: 2,
14040
- tierName: "Versi\xF3n / Release",
14041
- parentRequirement: "Debe originarse desde main",
14042
- targetMerge: "main"
14043
- };
14044
- }
14045
- return null;
14046
- }
14047
- var TIER_3_CONFIGS = [
14048
- { regex: BRANCH_PATTERNS.FEATURE, tierName: "Feature (Funcionalidad)", parentReq: "Debe originarse desde una rama release/vX.Y.Z activa", merge: "release/vX.Y.Z" },
14049
- { regex: BRANCH_PATTERNS.BUG, tierName: "Bug (Defecto)", parentReq: "Debe originarse desde una rama release/vX.Y.Z activa", merge: "release/vX.Y.Z" },
14050
- { regex: BRANCH_PATTERNS.PATCH, tierName: "Patch (Parche R\xE1pido)", parentReq: "Debe originarse desde una rama release/vX.Y.Z activa o main seg\xFAn criticidad", merge: "release/vX.Y.Z o main" }
14051
- ];
14052
- function classifyTier3(branchName) {
14053
- for (const cfg of TIER_3_CONFIGS) {
14054
- const m = branchName.match(cfg.regex);
14055
- if (m) {
14056
- return {
14057
- valid: true,
14058
- tier: 3,
14059
- tierName: cfg.tierName,
14060
- id: m[2],
14061
- parentRequirement: cfg.parentReq,
14062
- targetMerge: cfg.merge
14063
- };
14064
- }
14068
+ function extractCommitKpisFromRange(baseRef, headRef = "HEAD", options = {}) {
14069
+ const cwd = options.cwd || process.cwd();
14070
+ const resolvedBase = resolveGitRef(cwd, baseRef);
14071
+ const resolvedHead = resolveGitRef(cwd, headRef);
14072
+ const format = "---AI_SDLC_COMMIT---%n%H%x1f%an%x1f%ae%x1f%aI%x1f%s%n%B%n---AI_SDLC_BODY_END---";
14073
+ const rawOutput = fetchGitLogOutput(cwd, resolvedBase, resolvedHead, format);
14074
+ if (!rawOutput) return [];
14075
+ const chunks = parseRawLogChunks(rawOutput);
14076
+ const records = [];
14077
+ for (const chunk of chunks) {
14078
+ const rec = buildCommitKpiRecord(chunk);
14079
+ if (rec) records.push(rec);
14065
14080
  }
14066
- return null;
14081
+ return records;
14067
14082
  }
14068
- function classifyTier4(branchName) {
14069
- const taskMatch = branchName.match(BRANCH_PATTERNS.TASK);
14070
- if (taskMatch) {
14071
- return {
14072
- valid: true,
14073
- tier: 4,
14074
- tierName: "Task (Tarea At\xF3mica)",
14075
- parentId: taskMatch[1],
14076
- taskId: taskMatch[2],
14077
- parentRequirement: `Debe originarse desde la rama de feature, bug o patch: feat/${taskMatch[1]}, bug/${taskMatch[1]} o patch/${taskMatch[1]}`,
14078
- targetMerge: `feat/${taskMatch[1]}, bug/${taskMatch[1]} o patch/${taskMatch[1]}`
14079
- };
14083
+ function extractAllRepoCommitKpis(options = {}) {
14084
+ const cwd = options.cwd || process.cwd();
14085
+ const format = "---AI_SDLC_COMMIT---%n%H%x1f%an%x1f%ae%x1f%aI%x1f%s%n%B%n---AI_SDLC_BODY_END---";
14086
+ let rawOutput = "";
14087
+ try {
14088
+ rawOutput = execFileSync("git", ["log", "--all", `--format=${format}`, "--numstat"], {
14089
+ cwd,
14090
+ encoding: "utf-8",
14091
+ stdio: ["pipe", "pipe", "pipe"]
14092
+ });
14093
+ } catch {
14094
+ return [];
14080
14095
  }
14081
- return null;
14082
- }
14083
- function classifyBranch(branchName) {
14084
- return classifyTier1And2(branchName) || classifyTier3(branchName) || classifyTier4(branchName) || {
14085
- valid: false,
14086
- tier: 0,
14087
- tierName: "Inv\xE1lido",
14088
- error: `El nombre '${branchName}' no cumple con los est\xE1ndares del modelo de 4 tiers.`
14089
- };
14090
- }
14091
- function buildTaskBranchLines(feature, tasks, fBranch) {
14092
- const lines = [];
14093
- const parentSlug = feature.split("-").slice(0, 2).join("-");
14094
- for (const t of tasks) {
14095
- const taskBranch = `task/${parentSlug}/${t.toLowerCase()}`;
14096
- lines.push(` \u251C\u2500\u2500 ${taskBranch}`);
14097
- lines.push(` \u2502 Comando git: git checkout ${fBranch} && git checkout -b ${taskBranch}`);
14096
+ if (!rawOutput) return [];
14097
+ const chunks = parseRawLogChunks(rawOutput);
14098
+ const records = [];
14099
+ for (const chunk of chunks) {
14100
+ const rec = buildCommitKpiRecord(chunk);
14101
+ if (rec) records.push(rec);
14098
14102
  }
14099
- return lines;
14103
+ return records;
14100
14104
  }
14101
- var PLAN_BANNER = "================================================================";
14102
- function buildPlanHeader(vBranch, fBranch) {
14103
- return [
14104
- PLAN_BANNER,
14105
- "AI-SDLC: Plan de Ramificaci\xF3n Jer\xE1rquico",
14106
- `${PLAN_BANNER}
14107
- `,
14108
- `1. [TIER 1] Rama Base Estable: main`,
14109
- `2. [TIER 2] Rama de Versi\xF3n Abierta: ${vBranch} (originada de main)`,
14110
- `3. [TIER 3] Rama de Feature: ${fBranch} (originada de ${vBranch})
14111
- `,
14112
- `4. [TIER 4] Ramas de Tareas At\xF3micas (originadas de ${fBranch}):`
14113
- ];
14105
+
14106
+ // src/reporters/pr-kpis.ts
14107
+ var KPI_SUMMARY_START_TAG = "<!-- AI-SDLC-KPI-SUMMARY-START -->";
14108
+ var KPI_SUMMARY_END_TAG = "<!-- AI-SDLC-KPI-SUMMARY-END -->";
14109
+ function calculateEstimatedCost(promptTokens, completionTokens) {
14110
+ const promptCost = promptTokens / 1e6 * 3;
14111
+ const completionCost = completionTokens / 1e6 * 15;
14112
+ return Math.round((promptCost + completionCost) * 1e4) / 1e4;
14114
14113
  }
14115
- function generateBranchHierarchyPlan(version, feature, tasks) {
14116
- const vBranch = `release/${version}`;
14117
- const fBranch = `feat/${feature}`;
14118
- const header = buildPlanHeader(vBranch, fBranch);
14119
- const taskLines = buildTaskBranchLines(feature, tasks, fBranch);
14120
- const footer = [
14121
- `
14122
- Flujo de Integraci\xF3n (Merges):`,
14123
- ` task/* \u2794 [PR Tarea] \u2794 ${fBranch} \u2794 [PR Feature + Quality Gate] \u2794 ${vBranch} \u2794 [PR Release] \u2794 main
14124
- `
14125
- ];
14114
+ function createEmptySummary() {
14126
14115
  return {
14127
- version,
14128
- feature,
14129
- tasks,
14130
- planText: [...header, ...taskLines, ...footer].join("\n")
14116
+ commits: 0,
14117
+ linesAdded: 0,
14118
+ linesDeleted: 0,
14119
+ activeTimeSeconds: 0,
14120
+ promptTokens: 0,
14121
+ completionTokens: 0,
14122
+ estimatedCostUsd: 0
14131
14123
  };
14132
14124
  }
14133
- function resolveVersionFromProposal(changeDir) {
14134
- const proposalFile = path14.join(changeDir, "proposal.md");
14135
- if (!fs12.existsSync(proposalFile)) return "1.0.0";
14136
- const propContent = fs12.readFileSync(proposalFile, "utf-8");
14137
- const propFm = propContent.match(/^---\r?\n([\s\S]*?)\r?\n---/);
14138
- if (!propFm) return "1.0.0";
14139
- const parsedProp = yaml3.load(propFm[1]);
14140
- return parsedProp?.version ? String(parsedProp.version) : "1.0.0";
14141
- }
14142
- function resolveChangeVersion(fm, changeDir) {
14143
- if (fm.version) return String(fm.version);
14144
- if (fm["target-release"] || fm.release) return String(fm["target-release"] || fm.release);
14145
- return resolveVersionFromProposal(changeDir);
14146
- }
14147
- function isTaskMatchingId(currentId, cleanTaskId) {
14148
- const targetLower = cleanTaskId.toLowerCase();
14149
- const currentLower = currentId.toLowerCase();
14150
- return currentLower === targetLower || currentLower.startsWith(`${targetLower}-`) || targetLower.startsWith(`${currentLower}-`);
14125
+ function accumulateRecord(target, record) {
14126
+ target.commits += 1;
14127
+ target.linesAdded += record.linesAdded;
14128
+ target.linesDeleted += record.linesDeleted;
14129
+ target.activeTimeSeconds += record.trailers.activeTimeSeconds;
14130
+ target.promptTokens += record.trailers.promptTokens;
14131
+ target.completionTokens += record.trailers.completionTokens;
14132
+ target.estimatedCostUsd = calculateEstimatedCost(target.promptTokens, target.completionTokens);
14151
14133
  }
14152
- function parseTasksFrontmatter(tasksFile) {
14153
- if (!fs12.existsSync(tasksFile)) return null;
14154
- try {
14155
- const content = fs12.readFileSync(tasksFile, "utf-8");
14156
- const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
14157
- if (!fmMatch) return null;
14158
- const fm = yaml3.load(fmMatch[1]);
14159
- return fm && Array.isArray(fm.tasks) ? fm : null;
14160
- } catch {
14161
- return null;
14134
+ function accumulateAuthorSummaries(records, humanSummary, byModel) {
14135
+ let linesAdded = 0;
14136
+ let linesDeleted = 0;
14137
+ let activeTime = 0;
14138
+ let prompt = 0;
14139
+ let completion = 0;
14140
+ let isBugPr = false;
14141
+ for (const record of records) {
14142
+ linesAdded += record.linesAdded;
14143
+ linesDeleted += record.linesDeleted;
14144
+ activeTime += record.trailers.activeTimeSeconds;
14145
+ prompt += record.trailers.promptTokens;
14146
+ completion += record.trailers.completionTokens;
14147
+ if (record.isBugFix) isBugPr = true;
14148
+ if (record.trailers.authorType === "agent") {
14149
+ const modelName = record.trailers.aiModel || "agent-generic";
14150
+ if (!byModel[modelName]) byModel[modelName] = createEmptySummary();
14151
+ accumulateRecord(byModel[modelName], record);
14152
+ } else {
14153
+ accumulateRecord(humanSummary, record);
14154
+ }
14162
14155
  }
14156
+ return { linesAdded, linesDeleted, activeTime, prompt, completion, isBugPr };
14163
14157
  }
14164
- function resolveRawChangeId(fm, entryName) {
14165
- return String(fm["change-id"] || fm.changeId || entryName.replace(/^(chg|CHG)-/i, "CHG-").toUpperCase());
14166
- }
14167
- function buildTaskMatch(currentId, currentTitle, rawChangeId, changeDir, versionStr) {
14158
+ function initTaskKpi(taskId) {
14168
14159
  return {
14169
- taskId: currentId,
14170
- taskTitle: currentTitle,
14171
- changeId: rawChangeId,
14172
- changeDir,
14173
- version: versionStr
14160
+ taskId,
14161
+ commits: 0,
14162
+ fixCommits: 0,
14163
+ linesAdded: 0,
14164
+ linesDeleted: 0,
14165
+ codeChurnPercent: 0,
14166
+ totalTokens: 0,
14167
+ activeTimeSeconds: 0,
14168
+ reworkTokens: 0,
14169
+ reworkTokensPercent: 0,
14170
+ reworkTimeSeconds: 0,
14171
+ reworkTimePercent: 0,
14172
+ isFirstTimeRight: true
14174
14173
  };
14175
14174
  }
14176
- function inspectChangeTasks(changeDir, entryName, cleanTaskId, availableTasks) {
14177
- const fm = parseTasksFrontmatter(path14.join(changeDir, "tasks.md"));
14178
- if (!fm || !fm.tasks) return void 0;
14179
- const rawChangeId = resolveRawChangeId(fm, entryName);
14180
- const versionStr = resolveChangeVersion(fm, changeDir);
14181
- let match;
14182
- for (const t of fm.tasks) {
14183
- if (!t?.id) continue;
14184
- const currentId = String(t.id).trim();
14185
- const currentTitle = String(t.title || "").trim();
14186
- availableTasks.push({ id: currentId, title: currentTitle, changeId: rawChangeId });
14187
- if (!match && isTaskMatchingId(currentId, cleanTaskId)) {
14188
- match = buildTaskMatch(currentId, currentTitle, rawChangeId, changeDir, versionStr);
14189
- }
14175
+ function processTaskCommit(tStat, record) {
14176
+ const recTokens = record.trailers.promptTokens + record.trailers.completionTokens;
14177
+ tStat.commits += 1;
14178
+ tStat.linesAdded += record.linesAdded;
14179
+ tStat.linesDeleted += record.linesDeleted;
14180
+ tStat.totalTokens += recTokens;
14181
+ tStat.activeTimeSeconds += record.trailers.activeTimeSeconds;
14182
+ const isRework = record.isBugFix || /^(fix|bug|remediate|refactor)(([^)]+))?:/i.test((record.subject || "").trim());
14183
+ if (isRework) {
14184
+ tStat.fixCommits += 1;
14185
+ tStat.reworkTokens += recTokens;
14186
+ tStat.reworkTimeSeconds += record.trailers.activeTimeSeconds;
14190
14187
  }
14191
- return match;
14192
14188
  }
14193
- function locateTaskInActiveChanges(taskId, rootDir = process.cwd()) {
14194
- const cleanTaskId = (taskId || "").trim();
14195
- if (!cleanTaskId) {
14196
- return { found: false, error: "Debe especificar un identificador de tarea v\xE1lido (ej. TSK-001)." };
14197
- }
14198
- const activeChangesDir = path14.join(rootDir, "specs", "changes", "active");
14199
- if (!fs12.existsSync(activeChangesDir)) {
14200
- return { found: false, error: `No se encontr\xF3 el directorio de cambios activos en '${activeChangesDir}'.` };
14201
- }
14202
- const availableTasks = [];
14203
- const candidateDirs = fs12.readdirSync(activeChangesDir, { withFileTypes: true });
14204
- let matchedTask;
14205
- for (const entry of candidateDirs) {
14206
- if (!entry.isDirectory()) continue;
14207
- const changeDir = path14.join(activeChangesDir, entry.name);
14208
- const m = inspectChangeTasks(changeDir, entry.name, cleanTaskId, availableTasks);
14209
- if (m && !matchedTask) {
14210
- matchedTask = m;
14211
- }
14189
+ function accumulateTaskSummaries(records) {
14190
+ const byTask = {};
14191
+ for (const record of records) {
14192
+ const tid = record.trailers.taskId || record.subject.match(/\b(TSK-[0-9A-Za-z_-]+)\b/i)?.[1]?.toUpperCase();
14193
+ if (!tid) continue;
14194
+ if (!byTask[tid]) byTask[tid] = initTaskKpi(tid);
14195
+ processTaskCommit(byTask[tid], record);
14212
14196
  }
14213
- if (matchedTask) {
14214
- return { found: true, match: matchedTask, availableTasks };
14197
+ for (const t of Object.values(byTask)) {
14198
+ const churn = t.linesAdded > 0 ? t.linesDeleted / t.linesAdded * 100 : 0;
14199
+ t.codeChurnPercent = Math.round(Math.min(churn, 100) * 10) / 10;
14200
+ t.reworkTokensPercent = t.totalTokens > 0 ? Math.round(t.reworkTokens / t.totalTokens * 1e3) / 10 : 0;
14201
+ t.reworkTimePercent = t.activeTimeSeconds > 0 ? Math.round(t.reworkTimeSeconds / t.activeTimeSeconds * 1e3) / 10 : 0;
14202
+ t.isFirstTimeRight = t.fixCommits === 0 && t.codeChurnPercent < 25;
14215
14203
  }
14204
+ return byTask;
14205
+ }
14206
+ function assemblePrKpiAggregation(baseRef, headRef, records, totals, humanSummary, byModel, byTask) {
14207
+ const totalTokens = totals.prompt + totals.completion;
14216
14208
  return {
14217
- found: false,
14218
- availableTasks,
14219
- error: `No se encontr\xF3 la tarea '${cleanTaskId}' en ning\xFAn cambio activo bajo 'specs/changes/active/'.`
14209
+ baseRef,
14210
+ headRef,
14211
+ totalCommits: records.length,
14212
+ linesAdded: totals.linesAdded,
14213
+ linesDeleted: totals.linesDeleted,
14214
+ totalActiveTimeSeconds: totals.activeTime,
14215
+ totalPromptTokens: totals.prompt,
14216
+ totalCompletionTokens: totals.completion,
14217
+ totalTokens,
14218
+ estimatedCostUsd: calculateEstimatedCost(totals.prompt, totals.completion),
14219
+ humanSummary,
14220
+ byModel,
14221
+ isBugPr: totals.isBugPr,
14222
+ commitRecords: records,
14223
+ byTask
14220
14224
  };
14221
14225
  }
14222
- function getGitBranchList(rootDir) {
14223
- try {
14224
- const out = execFileSync("git", ["branch", "-a"], {
14225
- cwd: rootDir,
14226
- encoding: "utf-8",
14227
- stdio: ["pipe", "pipe", "ignore"]
14228
- });
14229
- return out.split("\n").map((l) => l.trim().replace(/^[*+]\s+/, "").replace(/^remotes\/origin\//, ""));
14230
- } catch {
14231
- return [];
14232
- }
14226
+ function aggregateCommitKpiRecords(records, baseRef = "main", headRef = "HEAD") {
14227
+ const humanSummary = createEmptySummary();
14228
+ const byModel = {};
14229
+ const totals = accumulateAuthorSummaries(records, humanSummary, byModel);
14230
+ const byTask = accumulateTaskSummaries(records);
14231
+ return assemblePrKpiAggregation(baseRef, headRef, records, totals, humanSummary, byModel, byTask);
14233
14232
  }
14234
- function detectExistingReleaseBranch(branches, cleanVersion) {
14235
- const candidate = `release/v${cleanVersion}`;
14236
- const existing = branches.find((b) => b.startsWith("release/v") && classifyBranch(b).valid);
14237
- return existing || candidate;
14233
+ function aggregatePrKpis(baseRef, headRef = "HEAD", options = {}) {
14234
+ const records = extractCommitKpisFromRange(baseRef, headRef, options);
14235
+ return aggregateCommitKpiRecords(records, baseRef, headRef);
14238
14236
  }
14239
- function detectExistingFeatureBranch(branches, dirName, changeId, changeSlug) {
14240
- const existing = branches.find(
14241
- (b) => b.startsWith("feat/") && (b.toLowerCase().includes(dirName.toLowerCase()) || b.toLowerCase().includes(changeId.toLowerCase())) && classifyBranch(b).valid
14242
- );
14243
- if (existing) return existing;
14244
- const normalizedName = slugify2(changeSlug).replace(/^(chg|bug|feat)-(\d+)/i, (_, p, n) => `${p.toUpperCase()}-${n}`);
14245
- return `feat/${normalizedName}`;
14237
+ function formatMinutes(seconds) {
14238
+ const mins = Math.round(seconds / 60);
14239
+ return mins > 0 ? `${mins} min` : `${seconds}s`;
14246
14240
  }
14247
- function buildDefaultTaskSuffix(taskId, taskTitle) {
14248
- let taskSuffix = taskId.toLowerCase();
14249
- const hasSlug = taskSuffix.includes("-") && taskSuffix.split("-").length > 2;
14250
- if (!hasSlug && taskTitle) {
14251
- const titleSlug = slugify2(taskTitle).split("-").slice(0, 4).join("-");
14252
- if (titleSlug) {
14253
- taskSuffix = `${taskSuffix}-${titleSlug}`;
14254
- }
14255
- }
14256
- return taskSuffix;
14241
+ function buildPrKpiRows(kpi, models) {
14242
+ const human = kpi.humanSummary;
14243
+ const commitCols = models.map((m) => kpi.byModel[m].commits).join(" | ");
14244
+ const linesCols = models.map((m) => `+${kpi.byModel[m].linesAdded} / -${kpi.byModel[m].linesDeleted}`).join(" | ");
14245
+ const timeCols = models.map((m) => formatMinutes(kpi.byModel[m].activeTimeSeconds)).join(" | ");
14246
+ const tokenCols = models.map((m) => `${(kpi.byModel[m].promptTokens + kpi.byModel[m].completionTokens).toLocaleString("en-US")}`).join(" | ");
14247
+ const costCols = models.map((m) => `$${kpi.byModel[m].estimatedCostUsd.toFixed(2)}`).join(" | ");
14248
+ const totalLines = `+${kpi.linesAdded} / -${kpi.linesDeleted}`;
14249
+ const totalTime = formatMinutes(kpi.totalActiveTimeSeconds);
14250
+ const totalTokensStr = `${kpi.totalTokens.toLocaleString("en-US")} tokens`;
14251
+ const totalCostStr = `$${kpi.estimatedCostUsd.toFixed(2)} USD`;
14252
+ return [
14253
+ `| **Commits** | ${human.commits} |${models.length > 0 ? ` ${commitCols} |` : ""} **${kpi.totalCommits}** |`,
14254
+ `| **Lines Added / Deleted** | +${human.linesAdded} / -${human.linesDeleted} |${models.length > 0 ? ` ${linesCols} |` : ""} **${totalLines}** |`,
14255
+ `| **Active Development Time** | ${formatMinutes(human.activeTimeSeconds)} |${models.length > 0 ? ` ${timeCols} |` : ""} **${totalTime}** |`,
14256
+ `| **Tokens Consumed (In+Out)** | 0 |${models.length > 0 ? ` ${tokenCols} |` : ""} **${totalTokensStr}** |`,
14257
+ `| **Estimated Cost (USD)** | \u2014 (Human labor) |${models.length > 0 ? ` ${costCols} |` : ""} **${totalCostStr}** |`
14258
+ ];
14257
14259
  }
14258
- function detectExistingTaskBranch(branches, parentId, taskId, taskTitle) {
14259
- const prefix = `task/${parentId}/`;
14260
- const existing = branches.find(
14261
- (b) => b.startsWith(prefix) && b.toLowerCase().includes(taskId.toLowerCase()) && classifyBranch(b).valid
14262
- );
14263
- if (existing) return existing;
14264
- return `task/${parentId}/${buildDefaultTaskSuffix(taskId, taskTitle)}`;
14260
+ function formatTaskKpiRows(byTask) {
14261
+ const taskIds = Object.keys(byTask || {});
14262
+ if (taskIds.length === 0) return [];
14263
+ const rows = [
14264
+ "",
14265
+ "#### \u{1F4CB} Task-Level Rework & Code Churn Breakdown",
14266
+ "",
14267
+ "| Task ID | Commits (Total / Fix) | Lines (+ / -) | Code Churn % | Rework Tokens % | Rework Time % | Status |",
14268
+ "| :--- | :---: | :---: | :---: | :---: | :---: | :---: |"
14269
+ ];
14270
+ for (const tid of taskIds) {
14271
+ const t = byTask[tid];
14272
+ const statusLabel = t.isFirstTimeRight ? "\u2714 First-Time-Right" : `\u26A0 ${t.fixCommits} rework commit${t.fixCommits === 1 ? "" : "s"}`;
14273
+ rows.push(
14274
+ `| \`${t.taskId}\` | ${t.commits} (${t.fixCommits} fix) | +${t.linesAdded} / -${t.linesDeleted} | ${t.codeChurnPercent}% | ${t.reworkTokensPercent}% | ${t.reworkTimePercent}% | ${statusLabel} |`
14275
+ );
14276
+ }
14277
+ return rows;
14265
14278
  }
14266
- function resolveBranchHierarchy(match, rootDir = process.cwd()) {
14267
- const baseBranch = "main";
14268
- const branches = getGitBranchList(rootDir);
14269
- const cleanVersion = (match.version || "1.0.0").replace(/^v/, "");
14270
- const releaseBranch = detectExistingReleaseBranch(branches, cleanVersion);
14271
- const dirName = path14.basename(match.changeDir);
14272
- const changeSlug = dirName.replace(/^(chg|CHG)-/i, (m) => m.toUpperCase());
14273
- const featureBranch = detectExistingFeatureBranch(branches, dirName, match.changeId, changeSlug);
14274
- const parentIdMatch = featureBranch.replace(/^(feat|feature)\//i, "").match(/^[a-zA-Z0-9]+-[a-zA-Z0-9]+/);
14275
- const parentId = parentIdMatch ? parentIdMatch[0] : match.changeId.split("-").slice(0, 2).join("-");
14276
- const taskBranch = detectExistingTaskBranch(branches, parentId, match.taskId, match.taskTitle);
14277
- return { baseBranch, releaseBranch, featureBranch, taskBranch };
14278
- }
14279
- function branchExistsLocally(branch, rootDir) {
14280
- try {
14281
- execFileSync("git", ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], {
14282
- cwd: rootDir,
14283
- stdio: ["pipe", "pipe", "pipe"]
14284
- });
14285
- return true;
14286
- } catch {
14287
- return false;
14288
- }
14279
+ function formatPrKpiMarkdown(kpi) {
14280
+ const models = Object.keys(kpi.byModel);
14281
+ const modelHeaders = models.map((m) => `Agent (${m})`).join(" | ");
14282
+ const modelSeparator = models.map(() => ":---:").join(" | ");
14283
+ const headers = `| Metric | Human |${models.length > 0 ? ` ${modelHeaders} |` : ""} Total PR |`;
14284
+ const sep5 = `| :--- | :---: |${models.length > 0 ? ` ${modelSeparator} |` : ""} :---: |`;
14285
+ const rows = buildPrKpiRows(kpi, models);
14286
+ const taskRowsList = formatTaskKpiRows(kpi.byTask);
14287
+ return [
14288
+ KPI_SUMMARY_START_TAG,
14289
+ "### \u{1F4CA} AI-SDLC: Aggregated PR KPI Summary",
14290
+ "",
14291
+ headers,
14292
+ sep5,
14293
+ ...rows,
14294
+ ...taskRowsList,
14295
+ "",
14296
+ `> **Branch Attribution:** ${kpi.isBugPr ? "\u{1F6A8} *Defect Fix / Bugfix*" : "\u2728 *New Feature*"} (Range: \`${kpi.baseRef}..${kpi.headRef}\`)`,
14297
+ KPI_SUMMARY_END_TAG
14298
+ ].join("\n");
14289
14299
  }
14290
- function branchExistsRemotely(branch, rootDir) {
14291
- try {
14292
- execFileSync("git", ["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`], {
14293
- cwd: rootDir,
14294
- stdio: ["pipe", "pipe", "pipe"]
14295
- });
14296
- return true;
14297
- } catch {
14298
- return false;
14300
+ function injectKpisIntoPrBody(originalBody, kpiMarkdown) {
14301
+ const body = originalBody || "";
14302
+ const startIndex = body.indexOf(KPI_SUMMARY_START_TAG);
14303
+ const endIndex = body.indexOf(KPI_SUMMARY_END_TAG);
14304
+ if (startIndex !== -1 && endIndex !== -1) {
14305
+ const before = body.slice(0, startIndex);
14306
+ const after = body.slice(endIndex + KPI_SUMMARY_END_TAG.length);
14307
+ return `${before.trimEnd()}
14308
+
14309
+ ${kpiMarkdown}
14310
+
14311
+ ${after.trimStart()}`.trim();
14299
14312
  }
14313
+ return `${body.trimEnd()}
14314
+
14315
+ ${kpiMarkdown}
14316
+ `;
14300
14317
  }
14301
- function ensureBranchInCascade(branch, parentBranch, rootDir) {
14302
- if (branchExistsLocally(branch, rootDir)) return false;
14303
- if (branchExistsRemotely(branch, rootDir)) {
14304
- execFileSync("git", ["branch", "--track", branch, `origin/${branch}`], { cwd: rootDir, stdio: ["pipe", "pipe", "pipe"] });
14305
- } else {
14306
- execFileSync("git", ["branch", branch, parentBranch], { cwd: rootDir, stdio: ["pipe", "pipe", "pipe"] });
14307
- }
14308
- return true;
14318
+
14319
+ // src/reporters/agent-kpis.ts
14320
+ function roundOneDecimal(value) {
14321
+ return Math.round(value * 10) / 10;
14309
14322
  }
14310
- function switchBranch(branch, rootDir) {
14311
- execFileSync("git", ["checkout", branch], { cwd: rootDir, stdio: ["pipe", "pipe", "pipe"] });
14323
+ function computeAuditedCommitsPercent(records) {
14324
+ if (records.length === 0) return 0;
14325
+ const audited = records.filter((r) => r.trailers.isTelemetryEstimated === false).length;
14326
+ return roundOneDecimal(audited / records.length * 100);
14312
14327
  }
14313
- function cascadeBranchCheckout(hierarchy, rootDir, created, streamlined) {
14314
- if (streamlined) {
14315
- if (ensureBranchInCascade(hierarchy.featureBranch, hierarchy.baseBranch, rootDir)) created.push(hierarchy.featureBranch);
14316
- switchBranch(hierarchy.featureBranch, rootDir);
14317
- return hierarchy.featureBranch;
14328
+ function computeTaskYieldAndRework(records) {
14329
+ const tasks = Object.values(accumulateTaskSummaries(records));
14330
+ if (tasks.length === 0) {
14331
+ return { totalTasks: 0, firstPassYieldPercent: 100, reworkLoopsPerTask: 0 };
14318
14332
  }
14319
- if (ensureBranchInCascade(hierarchy.releaseBranch, hierarchy.baseBranch, rootDir)) created.push(hierarchy.releaseBranch);
14320
- if (ensureBranchInCascade(hierarchy.featureBranch, hierarchy.releaseBranch, rootDir)) created.push(hierarchy.featureBranch);
14321
- if (ensureBranchInCascade(hierarchy.taskBranch, hierarchy.featureBranch, rootDir)) created.push(hierarchy.taskBranch);
14322
- switchBranch(hierarchy.taskBranch, rootDir);
14323
- return hierarchy.taskBranch;
14324
- }
14325
- function buildCheckoutErrorResult(match, hierarchy, created, err) {
14326
- const message = err instanceof Error ? err.message : String(err);
14333
+ const firstPassCount = tasks.filter((t) => t.isFirstTimeRight).length;
14334
+ const totalReworkLoops = tasks.reduce((sum, t) => sum + t.fixCommits, 0);
14327
14335
  return {
14328
- success: false,
14329
- taskId: match.taskId,
14330
- changeId: match.changeId,
14331
- releaseBranch: hierarchy.releaseBranch,
14332
- featureBranch: hierarchy.featureBranch,
14333
- taskBranch: hierarchy.taskBranch,
14334
- createdBranches: created,
14335
- error: `Error durante la creaci\xF3n o checkout de ramas Git: ${message}`
14336
+ totalTasks: tasks.length,
14337
+ firstPassYieldPercent: roundOneDecimal(firstPassCount / tasks.length * 100),
14338
+ reworkLoopsPerTask: Math.round(totalReworkLoops / tasks.length * 100) / 100
14336
14339
  };
14337
14340
  }
14338
- function buildLocateFailureResult(taskId, locateRes) {
14339
- return {
14340
- success: false,
14341
- taskId,
14342
- createdBranches: [],
14343
- error: locateRes.error,
14344
- availableTasks: locateRes.availableTasks
14345
- };
14341
+ function resolveTaskKey(record) {
14342
+ return record.trailers.taskId || record.subject.match(/\b(TSK-[0-9A-Za-z_-]+)\b/i)?.[1]?.toUpperCase();
14346
14343
  }
14347
- function buildCheckoutSuccessResult(match, hierarchy, created, switchedBranch, streamlined) {
14344
+ function computeHumanTakeoverRate(records) {
14345
+ const byTask = /* @__PURE__ */ new Map();
14346
+ for (const r of records) {
14347
+ const tid = resolveTaskKey(r);
14348
+ if (!tid) continue;
14349
+ const state = byTask.get(tid) || { hasAgent: false, hasHumanTakeover: false };
14350
+ if (r.trailers.authorType === "agent") {
14351
+ state.hasAgent = true;
14352
+ } else if (state.hasAgent || r.isBugFix) {
14353
+ state.hasHumanTakeover = true;
14354
+ }
14355
+ byTask.set(tid, state);
14356
+ }
14357
+ const agentTasks = Array.from(byTask.values()).filter((s) => s.hasAgent);
14358
+ if (agentTasks.length === 0) return 0;
14359
+ const takeovers = agentTasks.filter((s) => s.hasHumanTakeover).length;
14360
+ return roundOneDecimal(takeovers / agentTasks.length * 100);
14361
+ }
14362
+ function computeSpecificationAdherence(input) {
14363
+ const cov = input.coverageResult;
14364
+ const trace = input.traceabilityResult;
14365
+ const gate = input.gateResult;
14366
+ const bddRatio = cov && cov.totalRequirements > 0 ? cov.passedRequirements / cov.totalRequirements : 1;
14367
+ const traceRatio = trace && trace.totalRequirements > 0 ? (trace.totalRequirements - trace.orphanCount) / trace.totalRequirements : 1;
14368
+ const gateRatio = gate && gate.totalFunctions > 0 ? (gate.totalFunctions - gate.failCount) / gate.totalFunctions : 1;
14369
+ return roundOneDecimal((bddRatio + traceRatio + gateRatio) / 3 * 100);
14370
+ }
14371
+ function computeTokenCostEfficiency(records, gateResult) {
14372
+ if (!gateResult || gateResult.results.length === 0) return 0;
14373
+ const totalCc = gateResult.results.reduce((sum, fn) => sum + fn.cyclomatic, 0);
14374
+ if (totalCc <= 0) return 0;
14375
+ const totalTokens = records.reduce(
14376
+ (sum, r) => sum + r.trailers.promptTokens + r.trailers.completionTokens,
14377
+ 0
14378
+ );
14379
+ return Math.round(totalTokens / totalCc);
14380
+ }
14381
+ function isComponentContractPath(filePath) {
14382
+ const normalized = filePath.replace(/\\/g, "/").toLowerCase();
14383
+ return normalized.includes("specs/architecture/components/") || /\/?cmp-[^/]+\.md$/i.test(normalized);
14384
+ }
14385
+ function computeArchitectureDriftRate(records) {
14386
+ const cmpCommits = records.filter((r) => (r.touchedFiles || []).some(isComponentContractPath));
14387
+ if (cmpCommits.length === 0) return 0;
14388
+ const unauthorized = cmpCommits.filter((r) => {
14389
+ const ref = r.trailers.parentRef || "";
14390
+ const hasApprovedRef = /^(CHG|ADR)-/i.test(ref) || Boolean(r.trailers.taskId);
14391
+ return !hasApprovedRef;
14392
+ });
14393
+ return roundOneDecimal(unauthorized.length / cmpCommits.length * 100);
14394
+ }
14395
+ function computeAgentPerformanceKpis(input) {
14396
+ const { totalTasks, firstPassYieldPercent, reworkLoopsPerTask } = computeTaskYieldAndRework(input.records);
14348
14397
  return {
14349
- success: true,
14350
- taskId: match.taskId,
14351
- changeId: match.changeId,
14352
- releaseBranch: hierarchy.releaseBranch,
14353
- featureBranch: hierarchy.featureBranch,
14354
- taskBranch: streamlined ? void 0 : hierarchy.taskBranch,
14355
- createdBranches: created,
14356
- switchedBranch
14398
+ totalCommits: input.records.length,
14399
+ totalTasks,
14400
+ auditedCommitsPercent: computeAuditedCommitsPercent(input.records),
14401
+ firstPassYieldPercent,
14402
+ reworkLoopsPerTask,
14403
+ specificationAdherenceIndex: computeSpecificationAdherence(input),
14404
+ humanTakeoverRatePercent: computeHumanTakeoverRate(input.records),
14405
+ tokenCostEfficiency: computeTokenCostEfficiency(input.records, input.gateResult),
14406
+ architectureDriftRatePercent: computeArchitectureDriftRate(input.records)
14357
14407
  };
14358
14408
  }
14359
- function checkoutTaskBranch(taskId, options = {}) {
14360
- const rootDir = options.rootDir || process.cwd();
14361
- const locateRes = locateTaskInActiveChanges(taskId, rootDir);
14362
- if (!locateRes.found || !locateRes.match) {
14363
- return buildLocateFailureResult(taskId, locateRes);
14364
- }
14365
- const match = locateRes.match;
14366
- const hierarchy = resolveBranchHierarchy(match, rootDir);
14367
- const created = [];
14368
- try {
14369
- const switched = cascadeBranchCheckout(hierarchy, rootDir, created, options.streamlined);
14370
- return buildCheckoutSuccessResult(match, hierarchy, created, switched, options.streamlined);
14371
- } catch (err) {
14372
- return buildCheckoutErrorResult(match, hierarchy, created, err);
14373
- }
14409
+ function formatAgentKpisMarkdownSection(kpis) {
14410
+ return [
14411
+ "## 2. AI Agent Performance KPIs (SWE-bench & DORA AI)",
14412
+ "",
14413
+ `> **Evaluated Tasks:** \`${kpis.totalTasks}\` | **Commits:** \`${kpis.totalCommits}\` | **Audited Trailer Coverage:** \`${kpis.auditedCommitsPercent}%\``,
14414
+ "",
14415
+ "| KPI | Measured Value | Benchmark / Target |",
14416
+ "| :--- | :---: | :---: |",
14417
+ `| **First-Pass Yield (FPY)** | \`${kpis.firstPassYieldPercent}%\` | $\\ge 80\\%$ |`,
14418
+ `| **Rework Loops per Task** | \`${kpis.reworkLoopsPerTask}\` | $\\le 0.5$ |`,
14419
+ `| **Specification Adherence Index** | \`${kpis.specificationAdherenceIndex}%\` | $\\ge 95\\%$ |`,
14420
+ `| **Human Takeover / Intervention Rate** | \`${kpis.humanTakeoverRatePercent}%\` | $\\le 15\\%$ |`,
14421
+ `| **Token Cost Efficiency** | \`${kpis.tokenCostEfficiency.toLocaleString("en-US")} tokens/CC\` | Lower is better |`,
14422
+ `| **Architecture Drift Rate** | \`${kpis.architectureDriftRatePercent}%\` | $0\\%$ |`
14423
+ ];
14374
14424
  }
14375
- var TRAILER_REGEXES = {
14376
- taskId: /^\s*Task-ID:\s*(.+)$/im,
14377
- parentRef: /^\s*Parent-Ref:\s*(.+)$/im,
14378
- authorType: /^\s*Author-Type:\s*(human|agent)/im,
14379
- aiModel: /^\s*AI-Model:\s*(.+)$/im,
14380
- promptTokens: /^\s*Prompt-Tokens:\s*([0-9]+)/im,
14381
- completionTokens: /^\s*Completion-Tokens:\s*([0-9]+)/im,
14382
- activeTimeSeconds: /^\s*Active-Time-Seconds:\s*([0-9]+)/im
14383
- };
14384
- function parseTrailerInt(match) {
14385
- if (!match) return 0;
14386
- const val = parseInt(match[1], 10);
14387
- return isNaN(val) ? 0 : val;
14425
+
14426
+ // src/reporters/quality-report.ts
14427
+ function calculateRating(mi, cc) {
14428
+ if (mi >= 75 && cc <= 5) return "A";
14429
+ if (mi >= 60 && cc <= 10) return "B";
14430
+ if (mi >= 50 && cc <= 15) return "C";
14431
+ if (mi >= 40 && cc <= 20) return "D";
14432
+ return "F";
14388
14433
  }
14389
- function resolveAuthorType(authorTypeMatch, aiModelMatch) {
14390
- if (authorTypeMatch) {
14391
- return authorTypeMatch[1].toLowerCase();
14392
- }
14393
- if (aiModelMatch && aiModelMatch[1].trim() !== "n/a") {
14394
- return "agent";
14434
+ function detectLanguage(filePath) {
14435
+ const ext = path14.extname(filePath).toLowerCase();
14436
+ switch (ext) {
14437
+ case ".ts":
14438
+ return "TypeScript";
14439
+ case ".js":
14440
+ return "JavaScript";
14441
+ case ".py":
14442
+ return "Python";
14443
+ case ".java":
14444
+ return "Java";
14445
+ case ".go":
14446
+ return "Go";
14447
+ case ".cs":
14448
+ return "C#";
14449
+ case ".rs":
14450
+ return "Rust";
14451
+ case ".cpp":
14452
+ case ".c":
14453
+ return "C/C++";
14454
+ default:
14455
+ return "Unknown";
14395
14456
  }
14396
- return "human";
14397
14457
  }
14398
- function resolveTrailerOrScope(match, text, fallbackRegex) {
14399
- if (match) return match[1].trim();
14400
- const subMatch = text.match(fallbackRegex);
14401
- return subMatch ? subMatch[1].toUpperCase() : void 0;
14458
+ function readCodeCoverageSummary(rootDir = process.cwd()) {
14459
+ return readNormalizedCoverage(rootDir);
14402
14460
  }
14403
- function parseCommitTrailers(rawMessage) {
14404
- const text = rawMessage || "";
14405
- const authorTypeMatch = text.match(TRAILER_REGEXES.authorType);
14406
- const aiModelMatch = text.match(TRAILER_REGEXES.aiModel);
14407
- const authorType = resolveAuthorType(authorTypeMatch, aiModelMatch);
14408
- const rawModel = aiModelMatch ? aiModelMatch[1].trim() : void 0;
14409
- const aiModel = rawModel && rawModel !== "n/a" ? rawModel : void 0;
14410
- return {
14411
- taskId: resolveTrailerOrScope(text.match(TRAILER_REGEXES.taskId), text, /\b(TSK-[0-9A-Za-z_-]+)\b/i),
14412
- parentRef: resolveTrailerOrScope(text.match(TRAILER_REGEXES.parentRef), text, /\b((?:CHG|FEAT|BUG|FIX|PATCH)-[0-9A-Za-z_-]+)\b/i),
14413
- authorType,
14414
- aiModel,
14415
- promptTokens: parseTrailerInt(text.match(TRAILER_REGEXES.promptTokens)),
14416
- completionTokens: parseTrailerInt(text.match(TRAILER_REGEXES.completionTokens)),
14417
- activeTimeSeconds: parseTrailerInt(text.match(TRAILER_REGEXES.activeTimeSeconds))
14418
- };
14461
+ function formatCoverageRow(label, measured, minThreshold) {
14462
+ if (measured === void 0) {
14463
+ return `| **${label}** | \`N/A (Run test:coverage)\` | $\\ge ${minThreshold}\\%$ | \u2139\uFE0F NOT MEASURED |`;
14464
+ }
14465
+ const status = measured >= minThreshold ? "\u2705 COMPLIANT" : "\u26A0\uFE0F BELOW THRESHOLD";
14466
+ return `| **${label}** | \`${measured}%\` | $\\ge ${minThreshold}\\%$ | ${status} |`;
14419
14467
  }
14420
- function formatCommitTrailers(trailers) {
14421
- const lines = [];
14422
- if (trailers.taskId) lines.push(`Task-ID: ${trailers.taskId}`);
14423
- if (trailers.parentRef) lines.push(`Parent-Ref: ${trailers.parentRef}`);
14424
- lines.push(`Author-Type: ${trailers.authorType || "human"}`);
14425
- lines.push(`AI-Model: ${trailers.aiModel || "n/a"}`);
14426
- lines.push(`Prompt-Tokens: ${trailers.promptTokens ?? 0}`);
14427
- lines.push(`Completion-Tokens: ${trailers.completionTokens ?? 0}`);
14428
- lines.push(`Active-Time-Seconds: ${trailers.activeTimeSeconds ?? 0}`);
14429
- return lines.join("\n");
14468
+ function buildCoverageRows(coverage, policy) {
14469
+ return [
14470
+ formatCoverageRow("Line Coverage", coverage?.linesPct, policy.min_line_coverage),
14471
+ formatCoverageRow("Branch Coverage", coverage?.branchesPct, policy.min_branch_coverage),
14472
+ formatCoverageRow("Function Coverage", coverage?.functionsPct, policy.min_function_coverage)
14473
+ ];
14430
14474
  }
14431
- function parseRawLogChunks(rawLog) {
14432
- const rawCommits = rawLog.split("---AI_SDLC_COMMIT---").filter((c) => c.trim().length > 0);
14433
- const chunks = [];
14434
- for (const raw of rawCommits) {
14435
- const endBodyIdx = raw.indexOf("---AI_SDLC_BODY_END---");
14436
- if (endBodyIdx === -1) continue;
14437
- const beforeEnd = raw.slice(0, endBodyIdx).trimStart();
14438
- const afterEnd = raw.slice(endBodyIdx + "---AI_SDLC_BODY_END---".length);
14439
- const firstNewline = beforeEnd.indexOf("\n");
14440
- const header = firstNewline === -1 ? beforeEnd : beforeEnd.slice(0, firstNewline);
14441
- const body = firstNewline === -1 ? "" : beforeEnd.slice(firstNewline + 1);
14442
- const numstatLines = afterEnd.split("\n").filter((l) => /^\d+\s+\d+\s+/.test(l.trim()));
14443
- chunks.push({ header, body, numstatLines });
14475
+ function updateLangStats(langMap, fn) {
14476
+ const lang = detectLanguage(fn.filePath);
14477
+ const existing = langMap.get(lang) || { fns: 0, loc: 0, miSum: 0, ccSum: 0 };
14478
+ existing.fns++;
14479
+ existing.loc += fn.loc;
14480
+ existing.miSum += fn.maintainability;
14481
+ existing.ccSum += fn.cyclomatic;
14482
+ langMap.set(lang, existing);
14483
+ }
14484
+ function processFunctionMetric(fn, accumulated) {
14485
+ accumulated.totalMi += fn.maintainability;
14486
+ accumulated.totalCc += fn.cyclomatic;
14487
+ accumulated.totalCognitive += fn.cognitive;
14488
+ accumulated.totalLoc += fn.loc;
14489
+ updateLangStats(accumulated.langMap, fn);
14490
+ if (fn.violations.length > 0) {
14491
+ accumulated.violationsList.push(`- **\`${fn.relPath}\`** [\`${fn.functionName}\`]: ${fn.violations.join(", ")}`);
14444
14492
  }
14445
- return chunks;
14446
14493
  }
14447
- function sumNumstatLines(lines) {
14448
- let added = 0;
14449
- let deleted = 0;
14450
- for (const line of lines) {
14451
- const parts = line.trim().split(/\s+/);
14452
- if (parts.length >= 2) {
14453
- const a = parseInt(parts[0], 10);
14454
- const d = parseInt(parts[1], 10);
14455
- if (!isNaN(a)) added += a;
14456
- if (!isNaN(d)) deleted += d;
14457
- }
14458
- }
14459
- return { added, deleted };
14460
- }
14461
- function evaluateIsBugFix(subject, parentRef) {
14462
- if (parentRef && /^(BUG|FIX)-/i.test(parentRef)) return true;
14463
- return /^(fix|bug)(\([^)]+\))?:/i.test(subject.trim());
14464
- }
14465
- function inferAgentTrailers(trailers, linesAdded, linesDeleted) {
14466
- const res = { ...trailers };
14467
- const linesChanged = linesAdded + linesDeleted;
14468
- if (res.promptTokens === 0 && res.completionTokens === 0) {
14469
- res.completionTokens = linesChanged > 0 ? Math.max(linesAdded * 10, 50) : 0;
14470
- res.promptTokens = linesChanged > 0 ? Math.max(2500 + linesChanged * 25, 3e3) : 1e3;
14471
- }
14472
- if (res.activeTimeSeconds === 0) {
14473
- res.activeTimeSeconds = linesChanged > 0 ? Math.round(30 + linesChanged * 0.5) : 30;
14494
+ function accumulateMetrics(results) {
14495
+ const accumulated = {
14496
+ totalMi: 0,
14497
+ totalCc: 0,
14498
+ totalCognitive: 0,
14499
+ totalLoc: 0,
14500
+ langMap: /* @__PURE__ */ new Map(),
14501
+ violationsList: []
14502
+ };
14503
+ for (const fn of results) {
14504
+ processFunctionMetric(fn, accumulated);
14474
14505
  }
14475
- return res;
14506
+ return accumulated;
14476
14507
  }
14477
- function inferHumanTrailers(trailers, linesAdded, linesDeleted) {
14478
- const res = { ...trailers };
14479
- const linesChanged = linesAdded + linesDeleted;
14480
- if (res.activeTimeSeconds === 0) {
14481
- res.activeTimeSeconds = linesChanged > 0 ? Math.round(180 + linesChanged * 2) : 120;
14508
+ function renderPolyglotRows(langMap) {
14509
+ const rows = [];
14510
+ for (const [lang, stats] of langMap.entries()) {
14511
+ const langMi = Math.round(stats.miSum / stats.fns * 10) / 10;
14512
+ const langCc = Math.round(stats.ccSum / stats.fns * 10) / 10;
14513
+ const rating = calculateRating(langMi, langCc);
14514
+ rows.push(`| **${lang}** | \`${stats.fns}\` | \`${stats.loc}\` | \`${langMi}\` | \`${langCc}\` | \`${rating}\` |`);
14482
14515
  }
14483
- return res;
14516
+ return rows;
14484
14517
  }
14485
- function inferMissingTrailers(trailers, linesAdded, linesDeleted) {
14486
- return trailers.authorType === "agent" ? inferAgentTrailers(trailers, linesAdded, linesDeleted) : inferHumanTrailers(trailers, linesAdded, linesDeleted);
14518
+ var EVALUATION_STANDARDS_MD = [
14519
+ "---",
14520
+ "",
14521
+ "## 4. Evaluation Criteria and Standards",
14522
+ "- **McCabe Cyclomatic Complexity (CC)**: Number of linearly independent paths.",
14523
+ "- **Maintainability Index (SEI MI)**: Normalized formula [0 - 100] combining Halstead Volume, CC, and LOC.",
14524
+ "- **Automated Test Coverage**: Passively ingested from `coverage/coverage-summary.json` or `lcov.info` when present.",
14525
+ "- **Clean Code Guardrails**: Prohibition of implicit `any` typing, function length limits ($\\le 40$ lines), and zero unjustified suppressions."
14526
+ ].join("\n");
14527
+ function computeQualityAverages(totalFunctions, acc) {
14528
+ const avgMaintainability = totalFunctions > 0 ? Math.round(acc.totalMi / totalFunctions * 10) / 10 : 100;
14529
+ const avgCyclomatic = totalFunctions > 0 ? Math.round(acc.totalCc / totalFunctions * 10) / 10 : 1;
14530
+ const avgCognitive = totalFunctions > 0 ? Math.round(acc.totalCognitive / totalFunctions * 10) / 10 : 0;
14531
+ const globalRating = calculateRating(avgMaintainability, avgCyclomatic);
14532
+ return { avgMaintainability, avgCyclomatic, avgCognitive, globalRating };
14487
14533
  }
14488
- function resolveGitRef(cwd, ref) {
14489
- if (!ref || ref === "HEAD") return ref;
14490
- const candidates = [
14491
- ref,
14492
- `feat/${ref}`,
14493
- `release/${ref}`,
14494
- `bug/${ref}`,
14495
- `task/${ref}`,
14496
- `origin/${ref}`,
14497
- `origin/feat/${ref}`,
14498
- `origin/release/${ref}`,
14499
- `origin/bug/${ref}`
14534
+ function buildReportHeader3(verdict, rating, mi, cc) {
14535
+ const status = verdict === "PASS" ? "\u{1F7E2} APPROVED (RELEASE READY)" : "\u{1F534} BLOCKED (VIOLATIONS DETECTED)";
14536
+ return [
14537
+ `# \u{1F4CA} Formal Quality and Release Gate Report (AI-SDLC)`,
14538
+ "",
14539
+ `> **Generation Date:** ${resolveDeterministicDate().toISOString()}`,
14540
+ `> **Release Gate Verdict:** ${status}`,
14541
+ `> **Global Rating:** **\`${rating}\`** (MI Index: ${mi}/100, Average CC: ${cc})`
14500
14542
  ];
14501
- for (const cand of candidates) {
14502
- try {
14503
- execFileSync("git", ["rev-parse", "--verify", "--quiet", cand], {
14504
- cwd,
14505
- stdio: ["pipe", "pipe", "pipe"]
14506
- });
14507
- return cand;
14508
- } catch {
14509
- }
14510
- }
14511
- return ref;
14512
- }
14513
- function fetchGitLogOutput(cwd, baseRef, headRef, format) {
14514
- const rangeArg = baseRef ? `${baseRef}..${headRef}` : headRef;
14515
- try {
14516
- return execFileSync("git", ["log", rangeArg, `--format=${format}`, "--numstat"], {
14517
- cwd,
14518
- encoding: "utf-8",
14519
- stdio: ["pipe", "pipe", "pipe"]
14520
- });
14521
- } catch {
14522
- if (baseRef && !baseRef.includes("/")) {
14523
- try {
14524
- return execFileSync("git", ["log", `origin/${baseRef}..${headRef}`, `--format=${format}`, `--numstat`], {
14525
- cwd,
14526
- encoding: "utf-8",
14527
- stdio: ["pipe", "pipe", "pipe"]
14528
- });
14529
- } catch {
14530
- return "";
14531
- }
14532
- }
14533
- return "";
14534
- }
14535
14543
  }
14536
- function buildCommitKpiRecord(chunk) {
14537
- const fields = chunk.header.split("");
14538
- if (fields.length < 5) return null;
14539
- const rawTrailers = parseCommitTrailers(chunk.body);
14540
- const { added, deleted } = sumNumstatLines(chunk.numstatLines);
14541
- const trailers = inferMissingTrailers(rawTrailers, added, deleted);
14544
+ function buildMetricStatus(averages, policy, failCount) {
14542
14545
  return {
14543
- sha: fields[0],
14544
- authorName: fields[1],
14545
- authorEmail: fields[2],
14546
- date: fields[3],
14547
- subject: fields[4],
14548
- trailers,
14549
- linesAdded: added,
14550
- linesDeleted: deleted,
14551
- isBugFix: evaluateIsBugFix(fields[4], trailers.parentRef)
14546
+ ccStatus: averages.avgCyclomatic <= policy.max_cyclomatic ? "\u2705 COMPLIANT" : "\u274C EXCEEDED",
14547
+ cogStatus: averages.avgCognitive <= policy.max_cognitive ? "\u2705 COMPLIANT" : "\u274C EXCEEDED",
14548
+ miStatus: averages.avgMaintainability >= policy.min_maintainability ? "\u2705 COMPLIANT" : "\u274C INSUFFICIENT",
14549
+ violStatus: failCount === 0 ? "\u2705 0 VIOLATIONS" : "\u274C BLOCKED"
14552
14550
  };
14553
14551
  }
14554
- function extractCommitKpisFromRange(baseRef, headRef = "HEAD", options = {}) {
14555
- const cwd = options.cwd || process.cwd();
14556
- const resolvedBase = resolveGitRef(cwd, baseRef);
14557
- const resolvedHead = resolveGitRef(cwd, headRef);
14558
- const format = "---AI_SDLC_COMMIT---%n%H%x1f%an%x1f%ae%x1f%aI%x1f%s%n%B%n---AI_SDLC_BODY_END---";
14559
- const rawOutput = fetchGitLogOutput(cwd, resolvedBase, resolvedHead, format);
14560
- if (!rawOutput) return [];
14561
- const chunks = parseRawLogChunks(rawOutput);
14562
- const records = [];
14563
- for (const chunk of chunks) {
14564
- const rec = buildCommitKpiRecord(chunk);
14565
- if (rec) records.push(rec);
14566
- }
14567
- return records;
14552
+ function buildCountRows(totalFiles, totalFunctions, totalLoc) {
14553
+ return [
14554
+ `| **Analyzed Files** | \`${totalFiles}\` | N/A | \u2139\uFE0F |`,
14555
+ `| **Evaluated Functions** | \`${totalFunctions}\` | N/A | \u2139\uFE0F |`,
14556
+ `| **Lines of Code (LOC)** | \`${totalLoc}\` | N/A | \u2139\uFE0F |`
14557
+ ];
14568
14558
  }
14569
- function extractAllRepoCommitKpis(options = {}) {
14570
- const cwd = options.cwd || process.cwd();
14571
- const format = "---AI_SDLC_COMMIT---%n%H%x1f%an%x1f%ae%x1f%aI%x1f%s%n%B%n---AI_SDLC_BODY_END---";
14572
- let rawOutput = "";
14573
- try {
14574
- rawOutput = execFileSync("git", ["log", "--all", `--format=${format}`, "--numstat"], {
14575
- cwd,
14576
- encoding: "utf-8",
14577
- stdio: ["pipe", "pipe", "pipe"]
14578
- });
14579
- } catch {
14580
- return [];
14581
- }
14582
- if (!rawOutput) return [];
14583
- const chunks = parseRawLogChunks(rawOutput);
14584
- const records = [];
14585
- for (const chunk of chunks) {
14586
- const rec = buildCommitKpiRecord(chunk);
14587
- if (rec) records.push(rec);
14588
- }
14589
- return records;
14559
+ function buildExecutiveTable(gateResult, totalLoc, averages, coverage) {
14560
+ const { policy, totalFiles, totalFunctions, failCount } = gateResult;
14561
+ const status = buildMetricStatus(averages, policy, failCount);
14562
+ return [
14563
+ "## 1. Executive Metric Summary",
14564
+ "",
14565
+ "| Key Metric | Measured Value | Policy Threshold | Compliance |",
14566
+ "| :--- | :---: | :---: | :---: |",
14567
+ ...buildCountRows(totalFiles, totalFunctions, totalLoc),
14568
+ `| **Cyclomatic Complexity (Average)** | \`${averages.avgCyclomatic}\` | $\\le ${policy.max_cyclomatic}$ | ${status.ccStatus} |`,
14569
+ `| **Cognitive Complexity (Average)** | \`${averages.avgCognitive}\` | $\\le ${policy.max_cognitive}$ | ${status.cogStatus} |`,
14570
+ `| **Maintainability Index (SEI MI)** | \`${averages.avgMaintainability} / 100\` | $\\ge ${policy.min_maintainability}$ | ${status.miStatus} |`,
14571
+ ...buildCoverageRows(coverage, policy),
14572
+ `| **Functions in Violation** | \`${failCount}\` | $0$ (Mode ${policy.enforce_mode}) | ${status.violStatus} |`
14573
+ ];
14590
14574
  }
14591
- var AGENT_ENV_MAPPINGS = [
14592
- { envKey: "ANTIGRAVITY_AGENT", defaultModel: "gemini-3.8-flash", source: "antigravity" },
14593
- { envKey: "ANTIGRAVITY_CONVERSATION_ID", defaultModel: "gemini-3.8-flash", source: "antigravity" },
14594
- { envKey: "ANTIGRAVITY_AGENT_ID", defaultModel: "gemini-3.8-flash", source: "antigravity" },
14595
- { envKey: "CORTEX_SESSION_ID", defaultModel: "antigravity-agent", source: "cortex" },
14596
- { envKey: "CLAUDE_CODE", defaultModel: "claude-3-7-sonnet", source: "claude-code" },
14597
- { envKey: "CLAUDE_AGENT", defaultModel: "claude-3-7-sonnet", source: "claude-agent" },
14598
- { envKey: "CURSOR_AGENT", defaultModel: "cursor-agent", source: "cursor" },
14599
- { envKey: "CURSOR_SESSION_ID", defaultModel: "cursor-agent", source: "cursor" },
14600
- { envKey: "WINDSURF_AGENT", defaultModel: "windsurf-cascade", source: "windsurf" },
14601
- { envKey: "CASCADE_AGENT", defaultModel: "windsurf-cascade", source: "cascade" },
14602
- { envKey: "GITHUB_COPILOT_AGENT", defaultModel: "github-copilot", source: "copilot" },
14603
- { envKey: "COPILOT_AGENT_NAME", defaultModel: "github-copilot", source: "copilot" },
14604
- { envKey: "AIDER_MODEL", defaultModel: "aider-agent", source: "aider" },
14605
- { envKey: "GEMINI_CLI", defaultModel: "gemini-1.5-pro", source: "gemini" },
14606
- { envKey: "AI_AGENT_NAME", defaultModel: "agent-developer", source: "ai-sdlc-agent" },
14607
- { envKey: "AI_MODEL", defaultModel: "agent-developer", source: "ai-sdlc-model" }
14608
- ];
14609
- var BOT_NAME_REGEX = /\b(bot|agent|copilot|assistant|llm|claude|gpt|cortex|gemini)\b/i;
14610
- function getGitConfigValue(key, cwd) {
14611
- try {
14612
- const val = execFileSync("git", ["config", "--get", key], {
14613
- cwd,
14614
- encoding: "utf-8",
14615
- stdio: ["pipe", "pipe", "pipe"]
14616
- }).trim();
14617
- return val.length > 0 ? val : void 0;
14618
- } catch {
14619
- return void 0;
14620
- }
14575
+ function buildPolyglotSection(langMap) {
14576
+ return [
14577
+ "## 3. Polyglot Breakdown by Language Ecosystem",
14578
+ "",
14579
+ "| Language | Functions | Total LOC | Average MI | Average CC | Rating |",
14580
+ "| :--- | :---: | :---: | :---: | :---: | :---: |",
14581
+ ...renderPolyglotRows(langMap)
14582
+ ];
14621
14583
  }
14622
- function readSessionTelemetry(cwd) {
14623
- const possiblePaths = [
14624
- path14.join(cwd, ".ai-sdlc", "session-telemetry.json"),
14625
- path14.join(cwd, ".ai-sdlc", "agent-session.json")
14584
+ function renderQualityReportMarkdown(gateResult, coverage, accumulated, averages, agentKpis) {
14585
+ const verdict = gateResult.success ? "PASS" : "FAIL";
14586
+ const sections = [
14587
+ buildReportHeader3(verdict, averages.globalRating, averages.avgMaintainability, averages.avgCyclomatic),
14588
+ buildExecutiveTable(gateResult, accumulated.totalLoc, averages, coverage),
14589
+ formatAgentKpisMarkdownSection(agentKpis),
14590
+ buildPolyglotSection(accumulated.langMap)
14626
14591
  ];
14627
- for (const p of possiblePaths) {
14628
- if (fs12.existsSync(p)) {
14629
- try {
14630
- const raw = fs12.readFileSync(p, "utf-8");
14631
- return JSON.parse(raw);
14632
- } catch {
14633
- }
14634
- }
14635
- }
14636
- return null;
14592
+ if (accumulated.violationsList.length > 0) {
14593
+ sections.push(["## 4. Quality Gate Violations Log", "", ...accumulated.violationsList]);
14594
+ }
14595
+ return [...sections.map((s) => s.join("\n")), EVALUATION_STANDARDS_MD].join("\n\n---\n\n");
14596
+ }
14597
+ function collectAgentKpisForReport(rootDir, gateResult) {
14598
+ const records = extractAllRepoCommitKpis({ cwd: rootDir });
14599
+ const hasSpecs = fs12.existsSync(path14.join(rootDir, "specs"));
14600
+ const coverageResult = hasSpecs ? verifyTestingCoverage({ rootDir }) : void 0;
14601
+ const traceabilityResult = hasSpecs ? verifyTraceability({ rootDir }) : void 0;
14602
+ return computeAgentPerformanceKpis({
14603
+ records,
14604
+ gateResult,
14605
+ coverageResult,
14606
+ traceabilityResult
14607
+ });
14637
14608
  }
14638
- function resolveModelFromBotString(str) {
14639
- if (/claude/i.test(str)) return "claude-3-7-sonnet";
14640
- if (/gpt/i.test(str)) return "gpt-4o";
14641
- if (/copilot/i.test(str)) return "github-copilot";
14642
- if (/gemini/i.test(str)) return "gemini-1.5-pro";
14643
- if (/cortex/i.test(str)) return "antigravity-agent";
14644
- return "agent-developer";
14609
+ function writeQualityReportFile(rootDir, markdown) {
14610
+ const targetPath = path14.join(rootDir, "reports", "QUALITY_REPORT.md");
14611
+ return writeReportFileIfChanged(targetPath, markdown);
14645
14612
  }
14646
- function detectFromEnvOverride(env) {
14647
- const explicitEnv = env.AI_SDLC_AUTHOR_TYPE || env.AUTHOR_TYPE;
14648
- if (explicitEnv === "human" || explicitEnv === "agent") {
14649
- const model = explicitEnv === "agent" ? env.AI_MODEL || "agent-developer" : "n/a";
14613
+ function generateQualityReport(options = {}) {
14614
+ const rootDir = options.rootDir || process.cwd();
14615
+ const gateResult = verifyQualityGate({
14616
+ rootDir,
14617
+ policyPath: options.policyPath,
14618
+ thresholds: options.thresholds
14619
+ });
14620
+ const coverage = readCodeCoverageSummary(rootDir);
14621
+ const accumulated = accumulateMetrics(gateResult.results);
14622
+ const averages = computeQualityAverages(gateResult.totalFunctions, accumulated);
14623
+ const agentKpis = collectAgentKpisForReport(rootDir, gateResult);
14624
+ const markdown = renderQualityReportMarkdown(gateResult, coverage, accumulated, averages, agentKpis);
14625
+ writeQualityReportFile(rootDir, markdown);
14626
+ return {
14627
+ markdown,
14628
+ totalFiles: gateResult.totalFiles,
14629
+ totalFunctions: gateResult.totalFunctions,
14630
+ avgMaintainability: averages.avgMaintainability,
14631
+ avgCyclomatic: averages.avgCyclomatic,
14632
+ verdict: gateResult.success ? "PASS" : "FAIL",
14633
+ coverage
14634
+ };
14635
+ }
14636
+
14637
+ // src/git/workflow.ts
14638
+ var BRANCH_PATTERNS = {
14639
+ MAIN: /^main$/,
14640
+ RELEASE: /^release\/v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$/,
14641
+ FEATURE: /^(feat|feature)\/(?:v[0-9]+\.[0-9]+\.[0-9]+\/)?([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/,
14642
+ BUG: /^(bug|fix)\/(?:v[0-9]+\.[0-9]+\.[0-9]+\/)?([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/,
14643
+ PATCH: /^(patch)\/(?:v[0-9]+\.[0-9]+\.[0-9]+\/)?([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/,
14644
+ TASK: /^task\/([a-zA-Z0-9]+-[a-zA-Z0-9-]+)\/([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/
14645
+ };
14646
+ function classifyTier1And2(branchName) {
14647
+ if (BRANCH_PATTERNS.MAIN.test(branchName)) {
14650
14648
  return {
14651
- authorType: explicitEnv,
14652
- model,
14653
- source: "explicit-env",
14654
- confidence: "HIGH",
14655
- promptTokens: 0,
14656
- completionTokens: 0,
14657
- activeTimeSeconds: 0
14649
+ valid: true,
14650
+ tier: 1,
14651
+ tierName: "Main (Producci\xF3n)",
14652
+ parentRequirement: "Ninguno (Rama Ra\xEDz)",
14653
+ targetMerge: "Despliegue a Producci\xF3n"
14658
14654
  };
14659
14655
  }
14660
- return null;
14661
- }
14662
- function detectFromGitConfig(cwd) {
14663
- const gitConfigType = getGitConfigValue("ai-sdlc.author-type", cwd);
14664
- if (gitConfigType === "human" || gitConfigType === "agent") {
14665
- const gitConfigModel = getGitConfigValue("ai-sdlc.model", cwd) || (gitConfigType === "agent" ? "agent-developer" : "n/a");
14656
+ if (BRANCH_PATTERNS.RELEASE.test(branchName)) {
14666
14657
  return {
14667
- authorType: gitConfigType,
14668
- model: gitConfigModel,
14669
- source: "git-config",
14670
- confidence: "HIGH",
14671
- promptTokens: 0,
14672
- completionTokens: 0,
14673
- activeTimeSeconds: 0
14658
+ valid: true,
14659
+ tier: 2,
14660
+ tierName: "Versi\xF3n / Release",
14661
+ parentRequirement: "Debe originarse desde main",
14662
+ targetMerge: "main"
14674
14663
  };
14675
14664
  }
14676
14665
  return null;
14677
14666
  }
14678
- function detectFromTelemetry(cwd, env) {
14679
- const telemetry = readSessionTelemetry(cwd);
14680
- if (telemetry) {
14681
- const model = telemetry.model || env.AI_MODEL || "agent-developer";
14682
- return {
14683
- authorType: "agent",
14684
- model,
14685
- source: "session-telemetry-file",
14686
- confidence: "HIGH",
14687
- promptTokens: telemetry.promptTokens || 0,
14688
- completionTokens: telemetry.completionTokens || 0,
14689
- activeTimeSeconds: telemetry.activeTimeSeconds || 0
14690
- };
14667
+ var TIER_3_CONFIGS = [
14668
+ { regex: BRANCH_PATTERNS.FEATURE, tierName: "Feature (Funcionalidad)", parentReq: "Debe originarse desde una rama release/vX.Y.Z activa", merge: "release/vX.Y.Z" },
14669
+ { regex: BRANCH_PATTERNS.BUG, tierName: "Bug (Defecto)", parentReq: "Debe originarse desde una rama release/vX.Y.Z activa", merge: "release/vX.Y.Z" },
14670
+ { regex: BRANCH_PATTERNS.PATCH, tierName: "Patch (Parche R\xE1pido)", parentReq: "Debe originarse desde una rama release/vX.Y.Z activa o main seg\xFAn criticidad", merge: "release/vX.Y.Z o main" }
14671
+ ];
14672
+ function classifyTier3(branchName) {
14673
+ for (const cfg of TIER_3_CONFIGS) {
14674
+ const m = branchName.match(cfg.regex);
14675
+ if (m) {
14676
+ return {
14677
+ valid: true,
14678
+ tier: 3,
14679
+ tierName: cfg.tierName,
14680
+ id: m[2],
14681
+ parentRequirement: cfg.parentReq,
14682
+ targetMerge: cfg.merge
14683
+ };
14684
+ }
14691
14685
  }
14692
14686
  return null;
14693
14687
  }
14694
- function parseEnvInt(val) {
14695
- return val ? parseInt(val, 10) || 0 : 0;
14696
- }
14697
- function isEnvActive(val) {
14698
- return Boolean(val && val !== "0" && val !== "false");
14699
- }
14700
- function detectFromAgentEnv(env) {
14701
- for (const mapping of AGENT_ENV_MAPPINGS) {
14702
- const envVal = env[mapping.envKey];
14703
- if (!isEnvActive(envVal)) continue;
14704
- const model = env.AI_MODEL || (mapping.envKey === "AIDER_MODEL" ? envVal : mapping.defaultModel);
14688
+ function classifyTier4(branchName) {
14689
+ const taskMatch = branchName.match(BRANCH_PATTERNS.TASK);
14690
+ if (taskMatch) {
14705
14691
  return {
14706
- authorType: "agent",
14707
- model,
14708
- source: `env-${mapping.source}`,
14709
- confidence: "HIGH",
14710
- promptTokens: parseEnvInt(env.PROMPT_TOKENS),
14711
- completionTokens: parseEnvInt(env.COMPLETION_TOKENS),
14712
- activeTimeSeconds: parseEnvInt(env.ACTIVE_TIME_SECONDS || env.ACTIVE_TIME_SEC)
14692
+ valid: true,
14693
+ tier: 4,
14694
+ tierName: "Task (Tarea At\xF3mica)",
14695
+ parentId: taskMatch[1],
14696
+ taskId: taskMatch[2],
14697
+ parentRequirement: `Debe originarse desde la rama de feature, bug o patch: feat/${taskMatch[1]}, bug/${taskMatch[1]} o patch/${taskMatch[1]}`,
14698
+ targetMerge: `feat/${taskMatch[1]}, bug/${taskMatch[1]} o patch/${taskMatch[1]}`
14713
14699
  };
14714
14700
  }
14715
14701
  return null;
14716
14702
  }
14717
- function detectFromSignature(env, cwd) {
14718
- const authorName = env.GIT_AUTHOR_NAME || getGitConfigValue("user.name", cwd) || "";
14719
- const authorEmail = env.GIT_AUTHOR_EMAIL || getGitConfigValue("user.email", cwd) || "";
14720
- if (BOT_NAME_REGEX.test(authorName) || BOT_NAME_REGEX.test(authorEmail)) {
14721
- const inferredModel = resolveModelFromBotString(`${authorName} ${authorEmail}`);
14722
- return {
14723
- authorType: "agent",
14724
- model: inferredModel,
14725
- source: "git-user-signature",
14726
- confidence: "MEDIUM",
14727
- promptTokens: 0,
14728
- completionTokens: 0,
14729
- activeTimeSeconds: 0
14730
- };
14703
+ function classifyBranch(branchName) {
14704
+ return classifyTier1And2(branchName) || classifyTier3(branchName) || classifyTier4(branchName) || {
14705
+ valid: false,
14706
+ tier: 0,
14707
+ tierName: "Inv\xE1lido",
14708
+ error: `El nombre '${branchName}' no cumple con los est\xE1ndares del modelo de 4 tiers.`
14709
+ };
14710
+ }
14711
+ function buildTaskBranchLines(feature, tasks, fBranch) {
14712
+ const lines = [];
14713
+ const parentSlug = feature.split("-").slice(0, 2).join("-");
14714
+ for (const t of tasks) {
14715
+ const taskBranch = `task/${parentSlug}/${t.toLowerCase()}`;
14716
+ lines.push(` \u251C\u2500\u2500 ${taskBranch}`);
14717
+ lines.push(` \u2502 Comando git: git checkout ${fBranch} && git checkout -b ${taskBranch}`);
14731
14718
  }
14732
- return null;
14719
+ return lines;
14733
14720
  }
14734
- function detectAuthorIdentity(options = {}) {
14735
- const env = options.env || process.env;
14736
- const cwd = options.cwd || process.cwd();
14737
- return detectFromEnvOverride(env) || detectFromGitConfig(cwd) || detectFromTelemetry(cwd, env) || detectFromAgentEnv(env) || detectFromSignature(env, cwd) || {
14738
- authorType: "human",
14739
- model: "n/a",
14740
- source: "default-human",
14741
- confidence: "HIGH",
14742
- promptTokens: 0,
14743
- completionTokens: 0,
14744
- activeTimeSeconds: 0
14721
+ var PLAN_BANNER = "================================================================";
14722
+ function buildPlanHeader(vBranch, fBranch) {
14723
+ return [
14724
+ PLAN_BANNER,
14725
+ "AI-SDLC: Plan de Ramificaci\xF3n Jer\xE1rquico",
14726
+ `${PLAN_BANNER}
14727
+ `,
14728
+ `1. [TIER 1] Rama Base Estable: main`,
14729
+ `2. [TIER 2] Rama de Versi\xF3n Abierta: ${vBranch} (originada de main)`,
14730
+ `3. [TIER 3] Rama de Feature: ${fBranch} (originada de ${vBranch})
14731
+ `,
14732
+ `4. [TIER 4] Ramas de Tareas At\xF3micas (originadas de ${fBranch}):`
14733
+ ];
14734
+ }
14735
+ function generateBranchHierarchyPlan(version, feature, tasks) {
14736
+ const vBranch = `release/${version}`;
14737
+ const fBranch = `feat/${feature}`;
14738
+ const header = buildPlanHeader(vBranch, fBranch);
14739
+ const taskLines = buildTaskBranchLines(feature, tasks, fBranch);
14740
+ const footer = [
14741
+ `
14742
+ Flujo de Integraci\xF3n (Merges):`,
14743
+ ` task/* \u2794 [PR Tarea] \u2794 ${fBranch} \u2794 [PR Feature + Quality Gate] \u2794 ${vBranch} \u2794 [PR Release] \u2794 main
14744
+ `
14745
+ ];
14746
+ return {
14747
+ version,
14748
+ feature,
14749
+ tasks,
14750
+ planText: [...header, ...taskLines, ...footer].join("\n")
14745
14751
  };
14746
14752
  }
14747
- var PRE_COMMIT_SCRIPT = `#!/usr/bin/env bash
14748
- # ==============================================================================
14749
- # AI-SDLC: Universal Protected Branches Guard (pre-commit)
14750
- # ==============================================================================
14751
-
14752
- CURRENT_BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
14753
-
14754
- if [ -z "$CURRENT_BRANCH" ] || [ "$CURRENT_BRANCH" = "HEAD" ]; then
14755
- exit 0
14756
- fi
14757
-
14758
- # Protected branches regex: main, master, release/*, release/v*
14759
- if echo "$CURRENT_BRANCH" | grep -qE "^(main|master|release/.*)$"; then
14760
- echo "" >&2
14761
- echo "\u274C [AI-SDLC Security Guard] BLOCKED: Direct commits to protected branch '$CURRENT_BRANCH' are forbidden!" >&2
14762
- echo "--------------------------------------------------------------------------------" >&2
14763
- echo "Direct commits on protected branches violate the AI-SDLC 4-Tier Branching Policy." >&2
14764
- echo "You must create and switch to a dedicated working branch before committing:" >&2
14765
- echo "" >&2
14766
- echo " git checkout -b feat/<CHG-ID>-<slug>" >&2
14767
- echo " or" >&2
14768
- echo " git checkout -b task/<PARENT-ID>/<TSK-ID>-<slug>" >&2
14769
- echo "--------------------------------------------------------------------------------" >&2
14770
- echo "" >&2
14771
- exit 1
14772
- fi
14773
-
14774
- # Immutable Coding Rules Guard: block AI agents from adding, modifying or deleting coding rules files
14775
- IS_AGENT=0
14776
- if [ -n "$AI_MODEL" ] || [ -n "$AI_AGENT_NAME" ] || [ -n "$ANTIGRAVITY_AGENT" ] || [ -n "$ANTIGRAVITY_AGENT_ID" ] || [ -n "$ANTIGRAVITY_CONVERSATION_ID" ] || [ -n "$CLAUDE_CODE" ] || [ -n "$CURSOR_AGENT" ] || [ -n "$WINDSURF_AGENT" ] || [ -n "$AIDER_MODEL" ] || [ -f ".ai-sdlc/session-telemetry.json" ]; then
14777
- IS_AGENT=1
14778
- fi
14779
-
14780
- if [ "$IS_AGENT" = "1" ]; then
14781
- TAMPERED_RULES=$(git diff --cached --diff-filter=AMDR --name-only 2>/dev/null | grep -E "(^|/)(Directory\\.Build\\.props|tsconfig\\.strict\\.json|eslint\\.config\\.mjs|gradle/init\\.d/aisdlc-strict\\.init\\.gradle\\.kts|config/pmd/aisdlc-ruleset\\.xml|config/detekt/detekt\\.yml|\\.cargo/config\\.toml|\\.clippy\\.toml|\\.golangci\\.yml|\\.clang-tidy|cmake/AisdlcStrictCompiler\\.cmake|\\.github/CODEOWNERS|templates/coding-rules/.+)$" || echo "")
14782
- if [ -n "$TAMPERED_RULES" ]; then
14783
- echo "" >&2
14784
- echo "\u274C [AI-SDLC Immutable Coding Rules Guard] BLOCKED: AI agents are forbidden from adding, modifying or deleting coding rules files:" >&2
14785
- echo "$TAMPERED_RULES" >&2
14786
- echo "Fix the source or test code to comply with the compiler/linter rules instead of altering the rule configuration." >&2
14787
- echo "" >&2
14788
- exit 1
14789
- fi
14790
- fi
14791
-
14792
- exit 0
14793
- `;
14794
- var PREPARE_COMMIT_MSG_SCRIPT = `#!/usr/bin/env bash
14795
- # ==============================================================================
14796
- # AI-SDLC: Automated Commit Trailers Injection Hook
14797
- # ==============================================================================
14798
-
14799
- COMMIT_MSG_FILE=$1
14800
- COMMIT_SOURCE=$2
14801
-
14802
- # Bypass if this is an automated merge commit
14803
- if [ "$COMMIT_SOURCE" = "merge" ]; then
14804
- exit 0
14805
- fi
14806
-
14807
- CURRENT_BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
14808
- if [ -z "$CURRENT_BRANCH" ]; then
14809
- exit 0
14810
- fi
14811
-
14812
- # Extract Task-ID and Parent-Ref from 4-tier branch hierarchy
14813
- # Patterns: task/<PARENT-ID>/<TSK-ID>-slug | feat/<FEAT-ID>-slug | bug/<BUG-ID>-slug
14814
- TASK_ID=$(echo "$CURRENT_BRANCH" | grep -oE "TSK-[0-9A-Za-z-]+" || echo "")
14815
- if [ -z "$TASK_ID" ]; then
14816
- TASK_ID=$(head -n 1 "$COMMIT_MSG_FILE" 2>/dev/null | grep -oE "TSK-[0-9A-Za-z_-]+" | head -n 1 || echo "")
14817
- fi
14818
- if [ -z "$TASK_ID" ] && [ -f "$TELEMETRY_FILE" ]; then
14819
- TASK_ID=$(grep -oE '"taskId"s*:s*"[^"]+"' "$TELEMETRY_FILE" 2>/dev/null | sed -E 's/.*"taskId"s*:s*"([^"]+)".*/\\1/' || echo "")
14820
- fi
14821
-
14822
- PARENT_REF=$(echo "$CURRENT_BRANCH" | grep -oE "(CHG|FEAT|BUG|FIX|PATCH)-[0-9A-Za-z-]+" | head -n 1 || echo "")
14823
- if [ -z "$PARENT_REF" ]; then
14824
- PARENT_REF=$(head -n 1 "$COMMIT_MSG_FILE" 2>/dev/null | grep -oE "(CHG|FEAT|BUG|FIX|PATCH)-[0-9A-Za-z_-]+" | head -n 1 || echo "")
14825
- fi
14826
-
14827
- TELEMETRY_FILE=".ai-sdlc/session-telemetry.json"
14828
- AUTHOR_TYPE="human"
14829
- AI_MODEL_NAME="n/a"
14830
- PROMPT_TOKENS=0
14831
- COMPLETION_TOKENS=0
14832
- ACTIVE_TIME_SEC=0
14833
-
14834
- # Execute universal IDE-agnostic author detection engine
14835
- DETECTED=$(node packages/cli/bin/aisdlc.js git detect-author 2>/dev/null || npx aisdlc git detect-author 2>/dev/null || node -e "try { const { detectAuthorIdentity } = require('@aisdlc/core'); const id = detectAuthorIdentity(); console.log([id.authorType, id.model, id.promptTokens, id.completionTokens, id.activeTimeSeconds].join('|')); } catch {}" 2>/dev/null || echo "")
14836
-
14837
- if [ -n "$DETECTED" ]; then
14838
- IFS='|' read -r DET_AUTHOR DET_MODEL DET_PROMPT DET_COMPL DET_TIME <<< "$DETECTED"
14839
- AUTHOR_TYPE="\${DET_AUTHOR:-$AUTHOR_TYPE}"
14840
- AI_MODEL_NAME="\${DET_MODEL:-$AI_MODEL_NAME}"
14841
- PROMPT_TOKENS="\${DET_PROMPT:-$PROMPT_TOKENS}"
14842
- COMPLETION_TOKENS="\${DET_COMPL:-$COMPLETION_TOKENS}"
14843
- ACTIVE_TIME_SEC="\${DET_TIME:-$ACTIVE_TIME_SEC}"
14844
- else
14845
- if [ -n "$AI_MODEL" ] || [ -n "$AI_AGENT_NAME" ] || [ -n "$ANTIGRAVITY_AGENT" ] || [ -n "$ANTIGRAVITY_AGENT_ID" ] || [ -n "$ANTIGRAVITY_CONVERSATION_ID" ] || [ -n "$CLAUDE_CODE" ] || [ -n "$CURSOR_AGENT" ] || [ -n "$WINDSURF_AGENT" ] || [ -n "$AIDER_MODEL" ] || [ -f "$TELEMETRY_FILE" ]; then
14846
- AUTHOR_TYPE="agent"
14847
- AI_MODEL_NAME="\${AI_MODEL:-\${AI_AGENT_NAME:-\${AIDER_MODEL:-agent-developer}}}"
14848
- fi
14849
- fi
14850
-
14851
- # Estimate tokens and active time if not provided for agent
14852
- if [ "$PROMPT_TOKENS" = "0" ] && [ "$AUTHOR_TYPE" = "agent" ]; then
14853
- CHG_LINES=$(git diff --cached --shortstat 2>/dev/null | grep -oE '[0-9]+ (insertion|deletion)' | awk '{s+=$1} END {print s+0}')
14854
- if [ -n "$CHG_LINES" ] && [ "$CHG_LINES" -gt 0 ]; then
14855
- COMPLETION_TOKENS=$((CHG_LINES * 10))
14856
- PROMPT_TOKENS=$((2500 + CHG_LINES * 25))
14857
- ACTIVE_TIME_SEC=$((30 + CHG_LINES / 2))
14858
- else
14859
- PROMPT_TOKENS=1000
14860
- COMPLETION_TOKENS=0
14861
- ACTIVE_TIME_SEC=30
14862
- fi
14863
- fi
14864
-
14865
- # Inject missing trailers individually into the commit message
14866
- TRAILERS_TO_ADD=""
14867
-
14868
- if [ -n "$TASK_ID" ] && ! grep -qE "^Task-ID:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14869
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Task-ID: $TASK_ID
14870
- "
14871
- fi
14872
- if [ -n "$PARENT_REF" ] && ! grep -qE "^Parent-Ref:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14873
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Parent-Ref: $PARENT_REF
14874
- "
14875
- fi
14876
- if ! grep -qE "^Author-Type:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14877
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Author-Type: $AUTHOR_TYPE
14878
- "
14879
- fi
14880
- if [ "$AUTHOR_TYPE" = "agent" ] && ! grep -qE "^AI-Model:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14881
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}AI-Model: $AI_MODEL_NAME
14882
- "
14883
- fi
14884
- if ! grep -qE "^Prompt-Tokens:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14885
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Prompt-Tokens: $PROMPT_TOKENS
14886
- "
14887
- fi
14888
- if ! grep -qE "^Completion-Tokens:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14889
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Completion-Tokens: $COMPLETION_TOKENS
14890
- "
14891
- fi
14892
- if ! grep -qE "^Active-Time-Seconds:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14893
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Active-Time-Seconds: $ACTIVE_TIME_SEC
14894
- "
14895
- fi
14896
-
14897
- if [ -n "$TRAILERS_TO_ADD" ]; then
14898
- echo "" >> "$COMMIT_MSG_FILE"
14899
- printf "$TRAILERS_TO_ADD" >> "$COMMIT_MSG_FILE"
14900
- fi
14901
-
14902
- if [ -f "$TELEMETRY_FILE" ]; then
14903
- rm -f "$TELEMETRY_FILE" 2>/dev/null || true
14904
- fi
14905
- `;
14906
- function installGitHooks(rootDir = process.cwd()) {
14907
- const gitDir = path14.join(rootDir, ".git");
14908
- if (!fs12.existsSync(gitDir)) {
14909
- return {
14910
- success: false,
14911
- error: `No se encontr\xF3 el directorio Git en '${gitDir}'.`
14912
- };
14753
+ function resolveVersionFromProposal(changeDir) {
14754
+ const proposalFile = path14.join(changeDir, "proposal.md");
14755
+ if (!fs12.existsSync(proposalFile)) return "1.0.0";
14756
+ const propContent = fs12.readFileSync(proposalFile, "utf-8");
14757
+ const propFm = propContent.match(/^---\r?\n([\s\S]*?)\r?\n---/);
14758
+ if (!propFm) return "1.0.0";
14759
+ const parsedProp = yaml3.load(propFm[1]);
14760
+ return parsedProp?.version ? String(parsedProp.version) : "1.0.0";
14761
+ }
14762
+ function resolveChangeVersion(fm, changeDir) {
14763
+ if (fm.version) return String(fm.version);
14764
+ if (fm["target-release"] || fm.release) return String(fm["target-release"] || fm.release);
14765
+ return resolveVersionFromProposal(changeDir);
14766
+ }
14767
+ function isTaskMatchingId(currentId, cleanTaskId) {
14768
+ const targetLower = cleanTaskId.toLowerCase();
14769
+ const currentLower = currentId.toLowerCase();
14770
+ return currentLower === targetLower || currentLower.startsWith(`${targetLower}-`) || targetLower.startsWith(`${currentLower}-`);
14771
+ }
14772
+ function parseTasksFrontmatter(tasksFile) {
14773
+ if (!fs12.existsSync(tasksFile)) return null;
14774
+ try {
14775
+ const content = fs12.readFileSync(tasksFile, "utf-8");
14776
+ const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
14777
+ if (!fmMatch) return null;
14778
+ const fm = yaml3.load(fmMatch[1]);
14779
+ return fm && Array.isArray(fm.tasks) ? fm : null;
14780
+ } catch {
14781
+ return null;
14913
14782
  }
14914
- const hooksDir = path14.join(gitDir, "hooks");
14915
- if (!fs12.existsSync(hooksDir)) {
14916
- fs12.mkdirSync(hooksDir, { recursive: true });
14783
+ }
14784
+ function resolveRawChangeId(fm, entryName) {
14785
+ return String(fm["change-id"] || fm.changeId || entryName.replace(/^(chg|CHG)-/i, "CHG-").toUpperCase());
14786
+ }
14787
+ function buildTaskMatch(currentId, currentTitle, rawChangeId, changeDir, versionStr) {
14788
+ return {
14789
+ taskId: currentId,
14790
+ taskTitle: currentTitle,
14791
+ changeId: rawChangeId,
14792
+ changeDir,
14793
+ version: versionStr
14794
+ };
14795
+ }
14796
+ function inspectChangeTasks(changeDir, entryName, cleanTaskId, availableTasks) {
14797
+ const fm = parseTasksFrontmatter(path14.join(changeDir, "tasks.md"));
14798
+ if (!fm || !fm.tasks) return void 0;
14799
+ const rawChangeId = resolveRawChangeId(fm, entryName);
14800
+ const versionStr = resolveChangeVersion(fm, changeDir);
14801
+ let match;
14802
+ for (const t of fm.tasks) {
14803
+ if (!t?.id) continue;
14804
+ const currentId = String(t.id).trim();
14805
+ const currentTitle = String(t.title || "").trim();
14806
+ availableTasks.push({ id: currentId, title: currentTitle, changeId: rawChangeId });
14807
+ if (!match && isTaskMatchingId(currentId, cleanTaskId)) {
14808
+ match = buildTaskMatch(currentId, currentTitle, rawChangeId, changeDir, versionStr);
14809
+ }
14917
14810
  }
14918
- const prepareCommitMsgPath = path14.join(hooksDir, "prepare-commit-msg");
14919
- const preCommitPath = path14.join(gitDir, "hooks", "pre-commit");
14811
+ return match;
14812
+ }
14813
+ function locateTaskInActiveChanges(taskId, rootDir = process.cwd()) {
14814
+ const cleanTaskId = (taskId || "").trim();
14815
+ if (!cleanTaskId) {
14816
+ return { found: false, error: "Debe especificar un identificador de tarea v\xE1lido (ej. TSK-001)." };
14817
+ }
14818
+ const activeChangesDir = path14.join(rootDir, "specs", "changes", "active");
14819
+ if (!fs12.existsSync(activeChangesDir)) {
14820
+ return { found: false, error: `No se encontr\xF3 el directorio de cambios activos en '${activeChangesDir}'.` };
14821
+ }
14822
+ const availableTasks = [];
14823
+ const candidateDirs = fs12.readdirSync(activeChangesDir, { withFileTypes: true });
14824
+ let matchedTask;
14825
+ for (const entry of candidateDirs) {
14826
+ if (!entry.isDirectory()) continue;
14827
+ const changeDir = path14.join(activeChangesDir, entry.name);
14828
+ const m = inspectChangeTasks(changeDir, entry.name, cleanTaskId, availableTasks);
14829
+ if (m && !matchedTask) {
14830
+ matchedTask = m;
14831
+ }
14832
+ }
14833
+ if (matchedTask) {
14834
+ return { found: true, match: matchedTask, availableTasks };
14835
+ }
14836
+ return {
14837
+ found: false,
14838
+ availableTasks,
14839
+ error: `No se encontr\xF3 la tarea '${cleanTaskId}' en ning\xFAn cambio activo bajo 'specs/changes/active/'.`
14840
+ };
14841
+ }
14842
+ function getGitBranchList(rootDir) {
14920
14843
  try {
14921
- fs12.writeFileSync(prepareCommitMsgPath, PREPARE_COMMIT_MSG_SCRIPT, { encoding: "utf-8", mode: 493 });
14922
- fs12.writeFileSync(preCommitPath, PRE_COMMIT_SCRIPT, { encoding: "utf-8", mode: 493 });
14923
- return {
14924
- success: true,
14925
- hookPath: prepareCommitMsgPath,
14926
- installedHooks: [prepareCommitMsgPath, preCommitPath]
14927
- };
14928
- } catch (err) {
14929
- const msg = err instanceof Error ? err.message : String(err);
14930
- return {
14931
- success: false,
14932
- error: `Error al escribir hooks en '${hooksDir}': ${msg}`
14933
- };
14844
+ const out = execFileSync("git", ["branch", "-a"], {
14845
+ cwd: rootDir,
14846
+ encoding: "utf-8",
14847
+ stdio: ["pipe", "pipe", "ignore"]
14848
+ });
14849
+ return out.split("\n").map((l) => l.trim().replace(/^[*+]\s+/, "").replace(/^remotes\/origin\//, ""));
14850
+ } catch {
14851
+ return [];
14934
14852
  }
14935
14853
  }
14936
-
14937
- // src/reporters/pr-kpis.ts
14938
- var KPI_SUMMARY_START_TAG = "<!-- AI-SDLC-KPI-SUMMARY-START -->";
14939
- var KPI_SUMMARY_END_TAG = "<!-- AI-SDLC-KPI-SUMMARY-END -->";
14940
- function calculateEstimatedCost(promptTokens, completionTokens) {
14941
- const promptCost = promptTokens / 1e6 * 3;
14942
- const completionCost = completionTokens / 1e6 * 15;
14943
- return Math.round((promptCost + completionCost) * 1e4) / 1e4;
14854
+ function detectExistingReleaseBranch(branches, cleanVersion) {
14855
+ const candidate = `release/v${cleanVersion}`;
14856
+ const existing = branches.find((b) => b.startsWith("release/v") && classifyBranch(b).valid);
14857
+ return existing || candidate;
14944
14858
  }
14945
- function createEmptySummary() {
14859
+ function detectExistingFeatureBranch(branches, dirName, changeId, changeSlug) {
14860
+ const existing = branches.find(
14861
+ (b) => b.startsWith("feat/") && (b.toLowerCase().includes(dirName.toLowerCase()) || b.toLowerCase().includes(changeId.toLowerCase())) && classifyBranch(b).valid
14862
+ );
14863
+ if (existing) return existing;
14864
+ const normalizedName = slugify2(changeSlug).replace(/^(chg|bug|feat)-(\d+)/i, (_, p, n) => `${p.toUpperCase()}-${n}`);
14865
+ return `feat/${normalizedName}`;
14866
+ }
14867
+ function buildDefaultTaskSuffix(taskId, taskTitle) {
14868
+ let taskSuffix = taskId.toLowerCase();
14869
+ const hasSlug = taskSuffix.includes("-") && taskSuffix.split("-").length > 2;
14870
+ if (!hasSlug && taskTitle) {
14871
+ const titleSlug = slugify2(taskTitle).split("-").slice(0, 4).join("-");
14872
+ if (titleSlug) {
14873
+ taskSuffix = `${taskSuffix}-${titleSlug}`;
14874
+ }
14875
+ }
14876
+ return taskSuffix;
14877
+ }
14878
+ function detectExistingTaskBranch(branches, parentId, taskId, taskTitle) {
14879
+ const prefix = `task/${parentId}/`;
14880
+ const existing = branches.find(
14881
+ (b) => b.startsWith(prefix) && b.toLowerCase().includes(taskId.toLowerCase()) && classifyBranch(b).valid
14882
+ );
14883
+ if (existing) return existing;
14884
+ return `task/${parentId}/${buildDefaultTaskSuffix(taskId, taskTitle)}`;
14885
+ }
14886
+ function resolveBranchHierarchy(match, rootDir = process.cwd()) {
14887
+ const baseBranch = "main";
14888
+ const branches = getGitBranchList(rootDir);
14889
+ const cleanVersion = (match.version || "1.0.0").replace(/^v/, "");
14890
+ const releaseBranch = detectExistingReleaseBranch(branches, cleanVersion);
14891
+ const dirName = path14.basename(match.changeDir);
14892
+ const changeSlug = dirName.replace(/^(chg|CHG)-/i, (m) => m.toUpperCase());
14893
+ const featureBranch = detectExistingFeatureBranch(branches, dirName, match.changeId, changeSlug);
14894
+ const parentIdMatch = featureBranch.replace(/^(feat|feature)\//i, "").match(/^[a-zA-Z0-9]+-[a-zA-Z0-9]+/);
14895
+ const parentId = parentIdMatch ? parentIdMatch[0] : match.changeId.split("-").slice(0, 2).join("-");
14896
+ const taskBranch = detectExistingTaskBranch(branches, parentId, match.taskId, match.taskTitle);
14897
+ return { baseBranch, releaseBranch, featureBranch, taskBranch };
14898
+ }
14899
+ function branchExistsLocally(branch, rootDir) {
14900
+ try {
14901
+ execFileSync("git", ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], {
14902
+ cwd: rootDir,
14903
+ stdio: ["pipe", "pipe", "pipe"]
14904
+ });
14905
+ return true;
14906
+ } catch {
14907
+ return false;
14908
+ }
14909
+ }
14910
+ function branchExistsRemotely(branch, rootDir) {
14911
+ try {
14912
+ execFileSync("git", ["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`], {
14913
+ cwd: rootDir,
14914
+ stdio: ["pipe", "pipe", "pipe"]
14915
+ });
14916
+ return true;
14917
+ } catch {
14918
+ return false;
14919
+ }
14920
+ }
14921
+ function ensureBranchInCascade(branch, parentBranch, rootDir) {
14922
+ if (branchExistsLocally(branch, rootDir)) return false;
14923
+ if (branchExistsRemotely(branch, rootDir)) {
14924
+ execFileSync("git", ["branch", "--track", branch, `origin/${branch}`], { cwd: rootDir, stdio: ["pipe", "pipe", "pipe"] });
14925
+ } else {
14926
+ execFileSync("git", ["branch", branch, parentBranch], { cwd: rootDir, stdio: ["pipe", "pipe", "pipe"] });
14927
+ }
14928
+ return true;
14929
+ }
14930
+ function switchBranch(branch, rootDir) {
14931
+ execFileSync("git", ["checkout", branch], { cwd: rootDir, stdio: ["pipe", "pipe", "pipe"] });
14932
+ }
14933
+ function cascadeBranchCheckout(hierarchy, rootDir, created, streamlined) {
14934
+ if (streamlined) {
14935
+ if (ensureBranchInCascade(hierarchy.featureBranch, hierarchy.baseBranch, rootDir)) created.push(hierarchy.featureBranch);
14936
+ switchBranch(hierarchy.featureBranch, rootDir);
14937
+ return hierarchy.featureBranch;
14938
+ }
14939
+ if (ensureBranchInCascade(hierarchy.releaseBranch, hierarchy.baseBranch, rootDir)) created.push(hierarchy.releaseBranch);
14940
+ if (ensureBranchInCascade(hierarchy.featureBranch, hierarchy.releaseBranch, rootDir)) created.push(hierarchy.featureBranch);
14941
+ if (ensureBranchInCascade(hierarchy.taskBranch, hierarchy.featureBranch, rootDir)) created.push(hierarchy.taskBranch);
14942
+ switchBranch(hierarchy.taskBranch, rootDir);
14943
+ return hierarchy.taskBranch;
14944
+ }
14945
+ function buildCheckoutErrorResult(match, hierarchy, created, err) {
14946
+ const message = err instanceof Error ? err.message : String(err);
14946
14947
  return {
14947
- commits: 0,
14948
- linesAdded: 0,
14949
- linesDeleted: 0,
14950
- activeTimeSeconds: 0,
14951
- promptTokens: 0,
14952
- completionTokens: 0,
14953
- estimatedCostUsd: 0
14948
+ success: false,
14949
+ taskId: match.taskId,
14950
+ changeId: match.changeId,
14951
+ releaseBranch: hierarchy.releaseBranch,
14952
+ featureBranch: hierarchy.featureBranch,
14953
+ taskBranch: hierarchy.taskBranch,
14954
+ createdBranches: created,
14955
+ error: `Error durante la creaci\xF3n o checkout de ramas Git: ${message}`
14954
14956
  };
14955
14957
  }
14956
- function accumulateRecord(target, record) {
14957
- target.commits += 1;
14958
- target.linesAdded += record.linesAdded;
14959
- target.linesDeleted += record.linesDeleted;
14960
- target.activeTimeSeconds += record.trailers.activeTimeSeconds;
14961
- target.promptTokens += record.trailers.promptTokens;
14962
- target.completionTokens += record.trailers.completionTokens;
14963
- target.estimatedCostUsd = calculateEstimatedCost(target.promptTokens, target.completionTokens);
14958
+ function buildLocateFailureResult(taskId, locateRes) {
14959
+ return {
14960
+ success: false,
14961
+ taskId,
14962
+ createdBranches: [],
14963
+ error: locateRes.error,
14964
+ availableTasks: locateRes.availableTasks
14965
+ };
14966
+ }
14967
+ function buildCheckoutSuccessResult(match, hierarchy, created, switchedBranch, streamlined) {
14968
+ return {
14969
+ success: true,
14970
+ taskId: match.taskId,
14971
+ changeId: match.changeId,
14972
+ releaseBranch: hierarchy.releaseBranch,
14973
+ featureBranch: hierarchy.featureBranch,
14974
+ taskBranch: streamlined ? void 0 : hierarchy.taskBranch,
14975
+ createdBranches: created,
14976
+ switchedBranch
14977
+ };
14978
+ }
14979
+ function checkoutTaskBranch(taskId, options = {}) {
14980
+ const rootDir = options.rootDir || process.cwd();
14981
+ const locateRes = locateTaskInActiveChanges(taskId, rootDir);
14982
+ if (!locateRes.found || !locateRes.match) {
14983
+ return buildLocateFailureResult(taskId, locateRes);
14984
+ }
14985
+ const match = locateRes.match;
14986
+ const hierarchy = resolveBranchHierarchy(match, rootDir);
14987
+ const created = [];
14988
+ try {
14989
+ const switched = cascadeBranchCheckout(hierarchy, rootDir, created, options.streamlined);
14990
+ return buildCheckoutSuccessResult(match, hierarchy, created, switched, options.streamlined);
14991
+ } catch (err) {
14992
+ return buildCheckoutErrorResult(match, hierarchy, created, err);
14993
+ }
14994
+ }
14995
+ var AGENT_ENV_MAPPINGS = [
14996
+ { envKey: "ANTIGRAVITY_AGENT", defaultModel: "gemini-3.8-flash", source: "antigravity" },
14997
+ { envKey: "ANTIGRAVITY_CONVERSATION_ID", defaultModel: "gemini-3.8-flash", source: "antigravity" },
14998
+ { envKey: "ANTIGRAVITY_AGENT_ID", defaultModel: "gemini-3.8-flash", source: "antigravity" },
14999
+ { envKey: "CORTEX_SESSION_ID", defaultModel: "antigravity-agent", source: "cortex" },
15000
+ { envKey: "CLAUDE_CODE", defaultModel: "claude-3-7-sonnet", source: "claude-code" },
15001
+ { envKey: "CLAUDE_AGENT", defaultModel: "claude-3-7-sonnet", source: "claude-agent" },
15002
+ { envKey: "CURSOR_AGENT", defaultModel: "cursor-agent", source: "cursor" },
15003
+ { envKey: "CURSOR_SESSION_ID", defaultModel: "cursor-agent", source: "cursor" },
15004
+ { envKey: "WINDSURF_AGENT", defaultModel: "windsurf-cascade", source: "windsurf" },
15005
+ { envKey: "CASCADE_AGENT", defaultModel: "windsurf-cascade", source: "cascade" },
15006
+ { envKey: "GITHUB_COPILOT_AGENT", defaultModel: "github-copilot", source: "copilot" },
15007
+ { envKey: "COPILOT_AGENT_NAME", defaultModel: "github-copilot", source: "copilot" },
15008
+ { envKey: "AIDER_MODEL", defaultModel: "aider-agent", source: "aider" },
15009
+ { envKey: "GEMINI_CLI", defaultModel: "gemini-1.5-pro", source: "gemini" },
15010
+ { envKey: "AI_AGENT_NAME", defaultModel: "agent-developer", source: "ai-sdlc-agent" },
15011
+ { envKey: "AI_MODEL", defaultModel: "agent-developer", source: "ai-sdlc-model" }
15012
+ ];
15013
+ var BOT_NAME_REGEX = /\b(bot|agent|copilot|assistant|llm|claude|gpt|cortex|gemini)\b/i;
15014
+ function getGitConfigValue(key, cwd) {
15015
+ try {
15016
+ const val = execFileSync("git", ["config", "--get", key], {
15017
+ cwd,
15018
+ encoding: "utf-8",
15019
+ stdio: ["pipe", "pipe", "pipe"]
15020
+ }).trim();
15021
+ return val.length > 0 ? val : void 0;
15022
+ } catch {
15023
+ return void 0;
15024
+ }
14964
15025
  }
14965
- function accumulateAuthorSummaries(records, humanSummary, byModel) {
14966
- let linesAdded = 0;
14967
- let linesDeleted = 0;
14968
- let activeTime = 0;
14969
- let prompt = 0;
14970
- let completion = 0;
14971
- let isBugPr = false;
14972
- for (const record of records) {
14973
- linesAdded += record.linesAdded;
14974
- linesDeleted += record.linesDeleted;
14975
- activeTime += record.trailers.activeTimeSeconds;
14976
- prompt += record.trailers.promptTokens;
14977
- completion += record.trailers.completionTokens;
14978
- if (record.isBugFix) isBugPr = true;
14979
- if (record.trailers.authorType === "agent") {
14980
- const modelName = record.trailers.aiModel || "agent-generic";
14981
- if (!byModel[modelName]) byModel[modelName] = createEmptySummary();
14982
- accumulateRecord(byModel[modelName], record);
14983
- } else {
14984
- accumulateRecord(humanSummary, record);
15026
+ function readSessionTelemetry(cwd) {
15027
+ const possiblePaths = [
15028
+ path14.join(cwd, ".ai-sdlc", "session-telemetry.json"),
15029
+ path14.join(cwd, ".ai-sdlc", "agent-session.json")
15030
+ ];
15031
+ for (const p of possiblePaths) {
15032
+ if (fs12.existsSync(p)) {
15033
+ try {
15034
+ const raw = fs12.readFileSync(p, "utf-8");
15035
+ return JSON.parse(raw);
15036
+ } catch {
15037
+ }
14985
15038
  }
14986
15039
  }
14987
- return { linesAdded, linesDeleted, activeTime, prompt, completion, isBugPr };
15040
+ return null;
14988
15041
  }
14989
- function initTaskKpi(taskId) {
14990
- return {
14991
- taskId,
14992
- commits: 0,
14993
- fixCommits: 0,
14994
- linesAdded: 0,
14995
- linesDeleted: 0,
14996
- codeChurnPercent: 0,
14997
- totalTokens: 0,
14998
- activeTimeSeconds: 0,
14999
- reworkTokens: 0,
15000
- reworkTokensPercent: 0,
15001
- reworkTimeSeconds: 0,
15002
- reworkTimePercent: 0,
15003
- isFirstTimeRight: true
15004
- };
15042
+ function resolveModelFromBotString(str) {
15043
+ if (/claude/i.test(str)) return "claude-3-7-sonnet";
15044
+ if (/gpt/i.test(str)) return "gpt-4o";
15045
+ if (/copilot/i.test(str)) return "github-copilot";
15046
+ if (/gemini/i.test(str)) return "gemini-1.5-pro";
15047
+ if (/cortex/i.test(str)) return "antigravity-agent";
15048
+ return "agent-developer";
15005
15049
  }
15006
- function processTaskCommit(tStat, record) {
15007
- const recTokens = record.trailers.promptTokens + record.trailers.completionTokens;
15008
- tStat.commits += 1;
15009
- tStat.linesAdded += record.linesAdded;
15010
- tStat.linesDeleted += record.linesDeleted;
15011
- tStat.totalTokens += recTokens;
15012
- tStat.activeTimeSeconds += record.trailers.activeTimeSeconds;
15013
- const isRework = record.isBugFix || /^(fix|bug|remediate|refactor)(([^)]+))?:/i.test((record.subject || "").trim());
15014
- if (isRework) {
15015
- tStat.fixCommits += 1;
15016
- tStat.reworkTokens += recTokens;
15017
- tStat.reworkTimeSeconds += record.trailers.activeTimeSeconds;
15050
+ function detectFromEnvOverride(env) {
15051
+ const explicitEnv = env.AI_SDLC_AUTHOR_TYPE || env.AUTHOR_TYPE;
15052
+ if (explicitEnv === "human" || explicitEnv === "agent") {
15053
+ const model = explicitEnv === "agent" ? env.AI_MODEL || "agent-developer" : "n/a";
15054
+ return {
15055
+ authorType: explicitEnv,
15056
+ model,
15057
+ source: "explicit-env",
15058
+ confidence: "HIGH",
15059
+ promptTokens: 0,
15060
+ completionTokens: 0,
15061
+ activeTimeSeconds: 0
15062
+ };
15018
15063
  }
15064
+ return null;
15019
15065
  }
15020
- function accumulateTaskSummaries(records) {
15021
- const byTask = {};
15022
- for (const record of records) {
15023
- const tid = record.trailers.taskId || record.subject.match(/\b(TSK-[0-9A-Za-z_-]+)\b/i)?.[1]?.toUpperCase();
15024
- if (!tid) continue;
15025
- if (!byTask[tid]) byTask[tid] = initTaskKpi(tid);
15026
- processTaskCommit(byTask[tid], record);
15027
- }
15028
- for (const t of Object.values(byTask)) {
15029
- const churn = t.linesAdded > 0 ? t.linesDeleted / t.linesAdded * 100 : 0;
15030
- t.codeChurnPercent = Math.round(Math.min(churn, 100) * 10) / 10;
15031
- t.reworkTokensPercent = t.totalTokens > 0 ? Math.round(t.reworkTokens / t.totalTokens * 1e3) / 10 : 0;
15032
- t.reworkTimePercent = t.activeTimeSeconds > 0 ? Math.round(t.reworkTimeSeconds / t.activeTimeSeconds * 1e3) / 10 : 0;
15033
- t.isFirstTimeRight = t.fixCommits === 0 && t.codeChurnPercent < 25;
15066
+ function detectFromGitConfig(cwd) {
15067
+ const gitConfigType = getGitConfigValue("ai-sdlc.author-type", cwd);
15068
+ if (gitConfigType === "human" || gitConfigType === "agent") {
15069
+ const gitConfigModel = getGitConfigValue("ai-sdlc.model", cwd) || (gitConfigType === "agent" ? "agent-developer" : "n/a");
15070
+ return {
15071
+ authorType: gitConfigType,
15072
+ model: gitConfigModel,
15073
+ source: "git-config",
15074
+ confidence: "HIGH",
15075
+ promptTokens: 0,
15076
+ completionTokens: 0,
15077
+ activeTimeSeconds: 0
15078
+ };
15034
15079
  }
15035
- return byTask;
15036
- }
15037
- function assemblePrKpiAggregation(baseRef, headRef, records, totals, humanSummary, byModel, byTask) {
15038
- const totalTokens = totals.prompt + totals.completion;
15039
- return {
15040
- baseRef,
15041
- headRef,
15042
- totalCommits: records.length,
15043
- linesAdded: totals.linesAdded,
15044
- linesDeleted: totals.linesDeleted,
15045
- totalActiveTimeSeconds: totals.activeTime,
15046
- totalPromptTokens: totals.prompt,
15047
- totalCompletionTokens: totals.completion,
15048
- totalTokens,
15049
- estimatedCostUsd: calculateEstimatedCost(totals.prompt, totals.completion),
15050
- humanSummary,
15051
- byModel,
15052
- isBugPr: totals.isBugPr,
15053
- commitRecords: records,
15054
- byTask
15055
- };
15056
- }
15057
- function aggregateCommitKpiRecords(records, baseRef = "main", headRef = "HEAD") {
15058
- const humanSummary = createEmptySummary();
15059
- const byModel = {};
15060
- const totals = accumulateAuthorSummaries(records, humanSummary, byModel);
15061
- const byTask = accumulateTaskSummaries(records);
15062
- return assemblePrKpiAggregation(baseRef, headRef, records, totals, humanSummary, byModel, byTask);
15080
+ return null;
15063
15081
  }
15064
- function aggregatePrKpis(baseRef, headRef = "HEAD", options = {}) {
15065
- const records = extractCommitKpisFromRange(baseRef, headRef, options);
15066
- return aggregateCommitKpiRecords(records, baseRef, headRef);
15082
+ function detectFromTelemetry(cwd, env) {
15083
+ const telemetry = readSessionTelemetry(cwd);
15084
+ if (telemetry) {
15085
+ const model = telemetry.model || env.AI_MODEL || "agent-developer";
15086
+ return {
15087
+ authorType: "agent",
15088
+ model,
15089
+ source: "session-telemetry-file",
15090
+ confidence: "HIGH",
15091
+ promptTokens: telemetry.promptTokens || 0,
15092
+ completionTokens: telemetry.completionTokens || 0,
15093
+ activeTimeSeconds: telemetry.activeTimeSeconds || 0
15094
+ };
15095
+ }
15096
+ return null;
15067
15097
  }
15068
- function formatMinutes(seconds) {
15069
- const mins = Math.round(seconds / 60);
15070
- return mins > 0 ? `${mins} min` : `${seconds}s`;
15098
+ function parseEnvInt(val) {
15099
+ return val ? parseInt(val, 10) || 0 : 0;
15071
15100
  }
15072
- function buildPrKpiRows(kpi, models) {
15073
- const human = kpi.humanSummary;
15074
- const commitCols = models.map((m) => kpi.byModel[m].commits).join(" | ");
15075
- const linesCols = models.map((m) => `+${kpi.byModel[m].linesAdded} / -${kpi.byModel[m].linesDeleted}`).join(" | ");
15076
- const timeCols = models.map((m) => formatMinutes(kpi.byModel[m].activeTimeSeconds)).join(" | ");
15077
- const tokenCols = models.map((m) => `${(kpi.byModel[m].promptTokens + kpi.byModel[m].completionTokens).toLocaleString("en-US")}`).join(" | ");
15078
- const costCols = models.map((m) => `$${kpi.byModel[m].estimatedCostUsd.toFixed(2)}`).join(" | ");
15079
- const totalLines = `+${kpi.linesAdded} / -${kpi.linesDeleted}`;
15080
- const totalTime = formatMinutes(kpi.totalActiveTimeSeconds);
15081
- const totalTokensStr = `${kpi.totalTokens.toLocaleString("en-US")} tokens`;
15082
- const totalCostStr = `$${kpi.estimatedCostUsd.toFixed(2)} USD`;
15083
- return [
15084
- `| **Commits** | ${human.commits} |${models.length > 0 ? ` ${commitCols} |` : ""} **${kpi.totalCommits}** |`,
15085
- `| **Lines Added / Deleted** | +${human.linesAdded} / -${human.linesDeleted} |${models.length > 0 ? ` ${linesCols} |` : ""} **${totalLines}** |`,
15086
- `| **Active Development Time** | ${formatMinutes(human.activeTimeSeconds)} |${models.length > 0 ? ` ${timeCols} |` : ""} **${totalTime}** |`,
15087
- `| **Tokens Consumed (In+Out)** | 0 |${models.length > 0 ? ` ${tokenCols} |` : ""} **${totalTokensStr}** |`,
15088
- `| **Estimated Cost (USD)** | \u2014 (Human labor) |${models.length > 0 ? ` ${costCols} |` : ""} **${totalCostStr}** |`
15089
- ];
15101
+ function isEnvActive(val) {
15102
+ return Boolean(val && val !== "0" && val !== "false");
15090
15103
  }
15091
- function formatTaskKpiRows(byTask) {
15092
- const taskIds = Object.keys(byTask || {});
15093
- if (taskIds.length === 0) return [];
15094
- const rows = [
15095
- "",
15096
- "#### \u{1F4CB} Task-Level Rework & Code Churn Breakdown",
15097
- "",
15098
- "| Task ID | Commits (Total / Fix) | Lines (+ / -) | Code Churn % | Rework Tokens % | Rework Time % | Status |",
15099
- "| :--- | :---: | :---: | :---: | :---: | :---: | :---: |"
15100
- ];
15101
- for (const tid of taskIds) {
15102
- const t = byTask[tid];
15103
- const statusLabel = t.isFirstTimeRight ? "\u2714 First-Time-Right" : `\u26A0 ${t.fixCommits} rework commit${t.fixCommits === 1 ? "" : "s"}`;
15104
- rows.push(
15105
- `| \`${t.taskId}\` | ${t.commits} (${t.fixCommits} fix) | +${t.linesAdded} / -${t.linesDeleted} | ${t.codeChurnPercent}% | ${t.reworkTokensPercent}% | ${t.reworkTimePercent}% | ${statusLabel} |`
15106
- );
15104
+ function detectFromAgentEnv(env) {
15105
+ for (const mapping of AGENT_ENV_MAPPINGS) {
15106
+ const envVal = env[mapping.envKey];
15107
+ if (!isEnvActive(envVal)) continue;
15108
+ const model = env.AI_MODEL || (mapping.envKey === "AIDER_MODEL" ? envVal : mapping.defaultModel);
15109
+ return {
15110
+ authorType: "agent",
15111
+ model,
15112
+ source: `env-${mapping.source}`,
15113
+ confidence: "HIGH",
15114
+ promptTokens: parseEnvInt(env.PROMPT_TOKENS),
15115
+ completionTokens: parseEnvInt(env.COMPLETION_TOKENS),
15116
+ activeTimeSeconds: parseEnvInt(env.ACTIVE_TIME_SECONDS || env.ACTIVE_TIME_SEC)
15117
+ };
15107
15118
  }
15108
- return rows;
15119
+ return null;
15109
15120
  }
15110
- function formatPrKpiMarkdown(kpi) {
15111
- const models = Object.keys(kpi.byModel);
15112
- const modelHeaders = models.map((m) => `Agent (${m})`).join(" | ");
15113
- const modelSeparator = models.map(() => ":---:").join(" | ");
15114
- const headers = `| Metric | Human |${models.length > 0 ? ` ${modelHeaders} |` : ""} Total PR |`;
15115
- const sep5 = `| :--- | :---: |${models.length > 0 ? ` ${modelSeparator} |` : ""} :---: |`;
15116
- const rows = buildPrKpiRows(kpi, models);
15117
- const taskRowsList = formatTaskKpiRows(kpi.byTask);
15118
- return [
15119
- KPI_SUMMARY_START_TAG,
15120
- "### \u{1F4CA} AI-SDLC: Aggregated PR KPI Summary",
15121
- "",
15122
- headers,
15123
- sep5,
15124
- ...rows,
15125
- ...taskRowsList,
15126
- "",
15127
- `> **Branch Attribution:** ${kpi.isBugPr ? "\u{1F6A8} *Defect Fix / Bugfix*" : "\u2728 *New Feature*"} (Range: \`${kpi.baseRef}..${kpi.headRef}\`)`,
15128
- KPI_SUMMARY_END_TAG
15129
- ].join("\n");
15121
+ function detectFromSignature(env, cwd) {
15122
+ const authorName = env.GIT_AUTHOR_NAME || getGitConfigValue("user.name", cwd) || "";
15123
+ const authorEmail = env.GIT_AUTHOR_EMAIL || getGitConfigValue("user.email", cwd) || "";
15124
+ if (BOT_NAME_REGEX.test(authorName) || BOT_NAME_REGEX.test(authorEmail)) {
15125
+ const inferredModel = resolveModelFromBotString(`${authorName} ${authorEmail}`);
15126
+ return {
15127
+ authorType: "agent",
15128
+ model: inferredModel,
15129
+ source: "git-user-signature",
15130
+ confidence: "MEDIUM",
15131
+ promptTokens: 0,
15132
+ completionTokens: 0,
15133
+ activeTimeSeconds: 0
15134
+ };
15135
+ }
15136
+ return null;
15130
15137
  }
15131
- function injectKpisIntoPrBody(originalBody, kpiMarkdown) {
15132
- const body = originalBody || "";
15133
- const startIndex = body.indexOf(KPI_SUMMARY_START_TAG);
15134
- const endIndex = body.indexOf(KPI_SUMMARY_END_TAG);
15135
- if (startIndex !== -1 && endIndex !== -1) {
15136
- const before = body.slice(0, startIndex);
15137
- const after = body.slice(endIndex + KPI_SUMMARY_END_TAG.length);
15138
- return `${before.trimEnd()}
15138
+ function detectAuthorIdentity(options = {}) {
15139
+ const env = options.env || process.env;
15140
+ const cwd = options.cwd || process.cwd();
15141
+ return detectFromEnvOverride(env) || detectFromGitConfig(cwd) || detectFromTelemetry(cwd, env) || detectFromAgentEnv(env) || detectFromSignature(env, cwd) || {
15142
+ authorType: "human",
15143
+ model: "n/a",
15144
+ source: "default-human",
15145
+ confidence: "HIGH",
15146
+ promptTokens: 0,
15147
+ completionTokens: 0,
15148
+ activeTimeSeconds: 0
15149
+ };
15150
+ }
15151
+ var PRE_COMMIT_SCRIPT = `#!/usr/bin/env bash
15152
+ # ==============================================================================
15153
+ # AI-SDLC: Universal Protected Branches Guard (pre-commit)
15154
+ # ==============================================================================
15139
15155
 
15140
- ${kpiMarkdown}
15156
+ CURRENT_BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
15141
15157
 
15142
- ${after.trimStart()}`.trim();
15143
- }
15144
- return `${body.trimEnd()}
15158
+ if [ -z "$CURRENT_BRANCH" ] || [ "$CURRENT_BRANCH" = "HEAD" ]; then
15159
+ exit 0
15160
+ fi
15145
15161
 
15146
- ${kpiMarkdown}
15162
+ # Protected branches regex: main, master, release/*, release/v*
15163
+ if echo "$CURRENT_BRANCH" | grep -qE "^(main|master|release/.*)$"; then
15164
+ echo "" >&2
15165
+ echo "\u274C [AI-SDLC Security Guard] BLOCKED: Direct commits to protected branch '$CURRENT_BRANCH' are forbidden!" >&2
15166
+ echo "--------------------------------------------------------------------------------" >&2
15167
+ echo "Direct commits on protected branches violate the AI-SDLC 4-Tier Branching Policy." >&2
15168
+ echo "You must create and switch to a dedicated working branch before committing:" >&2
15169
+ echo "" >&2
15170
+ echo " git checkout -b feat/<CHG-ID>-<slug>" >&2
15171
+ echo " or" >&2
15172
+ echo " git checkout -b task/<PARENT-ID>/<TSK-ID>-<slug>" >&2
15173
+ echo "--------------------------------------------------------------------------------" >&2
15174
+ echo "" >&2
15175
+ exit 1
15176
+ fi
15177
+
15178
+ # Immutable Coding Rules Guard: block AI agents from adding, modifying or deleting coding rules files
15179
+ IS_AGENT=0
15180
+ if [ -n "$AI_MODEL" ] || [ -n "$AI_AGENT_NAME" ] || [ -n "$ANTIGRAVITY_AGENT" ] || [ -n "$ANTIGRAVITY_AGENT_ID" ] || [ -n "$ANTIGRAVITY_CONVERSATION_ID" ] || [ -n "$CLAUDE_CODE" ] || [ -n "$CURSOR_AGENT" ] || [ -n "$WINDSURF_AGENT" ] || [ -n "$AIDER_MODEL" ] || [ -f ".ai-sdlc/session-telemetry.json" ]; then
15181
+ IS_AGENT=1
15182
+ fi
15183
+
15184
+ if [ "$IS_AGENT" = "1" ]; then
15185
+ TAMPERED_RULES=$(git diff --cached --diff-filter=AMDR --name-only 2>/dev/null | grep -E "(^|/)(Directory\\.Build\\.props|tsconfig\\.strict\\.json|eslint\\.config\\.mjs|gradle/init\\.d/aisdlc-strict\\.init\\.gradle\\.kts|config/pmd/aisdlc-ruleset\\.xml|config/detekt/detekt\\.yml|\\.cargo/config\\.toml|\\.clippy\\.toml|\\.golangci\\.yml|\\.clang-tidy|cmake/AisdlcStrictCompiler\\.cmake|\\.github/CODEOWNERS|templates/coding-rules/.+)$" || echo "")
15186
+ if [ -n "$TAMPERED_RULES" ]; then
15187
+ echo "" >&2
15188
+ echo "\u274C [AI-SDLC Immutable Coding Rules Guard] BLOCKED: AI agents are forbidden from adding, modifying or deleting coding rules files:" >&2
15189
+ echo "$TAMPERED_RULES" >&2
15190
+ echo "Fix the source or test code to comply with the compiler/linter rules instead of altering the rule configuration." >&2
15191
+ echo "" >&2
15192
+ exit 1
15193
+ fi
15194
+ fi
15195
+
15196
+ exit 0
15197
+ `;
15198
+ var PREPARE_COMMIT_MSG_SCRIPT = `#!/usr/bin/env bash
15199
+ # ==============================================================================
15200
+ # AI-SDLC: Automated Commit Trailers Injection Hook
15201
+ # ==============================================================================
15202
+
15203
+ COMMIT_MSG_FILE=$1
15204
+ COMMIT_SOURCE=$2
15205
+
15206
+ # Bypass if this is an automated merge commit
15207
+ if [ "$COMMIT_SOURCE" = "merge" ]; then
15208
+ exit 0
15209
+ fi
15210
+
15211
+ CURRENT_BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
15212
+ if [ -z "$CURRENT_BRANCH" ]; then
15213
+ exit 0
15214
+ fi
15215
+
15216
+ # Extract Task-ID and Parent-Ref from 4-tier branch hierarchy
15217
+ # Patterns: task/<PARENT-ID>/<TSK-ID>-slug | feat/<FEAT-ID>-slug | bug/<BUG-ID>-slug
15218
+ TASK_ID=$(echo "$CURRENT_BRANCH" | grep -oE "TSK-[0-9A-Za-z-]+" || echo "")
15219
+ if [ -z "$TASK_ID" ]; then
15220
+ TASK_ID=$(head -n 1 "$COMMIT_MSG_FILE" 2>/dev/null | grep -oE "TSK-[0-9A-Za-z_-]+" | head -n 1 || echo "")
15221
+ fi
15222
+ if [ -z "$TASK_ID" ] && [ -f "$TELEMETRY_FILE" ]; then
15223
+ TASK_ID=$(grep -oE '"taskId"s*:s*"[^"]+"' "$TELEMETRY_FILE" 2>/dev/null | sed -E 's/.*"taskId"s*:s*"([^"]+)".*/\\1/' || echo "")
15224
+ fi
15225
+
15226
+ PARENT_REF=$(echo "$CURRENT_BRANCH" | grep -oE "(CHG|FEAT|BUG|FIX|PATCH)-[0-9A-Za-z-]+" | head -n 1 || echo "")
15227
+ if [ -z "$PARENT_REF" ]; then
15228
+ PARENT_REF=$(head -n 1 "$COMMIT_MSG_FILE" 2>/dev/null | grep -oE "(CHG|FEAT|BUG|FIX|PATCH)-[0-9A-Za-z_-]+" | head -n 1 || echo "")
15229
+ fi
15230
+
15231
+ TELEMETRY_FILE=".ai-sdlc/session-telemetry.json"
15232
+ AUTHOR_TYPE="human"
15233
+ AI_MODEL_NAME="n/a"
15234
+ PROMPT_TOKENS=0
15235
+ COMPLETION_TOKENS=0
15236
+ ACTIVE_TIME_SEC=0
15237
+
15238
+ # Execute universal IDE-agnostic author detection engine
15239
+ DETECTED=$(node packages/cli/bin/aisdlc.js git detect-author 2>/dev/null || npx aisdlc git detect-author 2>/dev/null || node -e "try { const { detectAuthorIdentity } = require('@aisdlc/core'); const id = detectAuthorIdentity(); console.log([id.authorType, id.model, id.promptTokens, id.completionTokens, id.activeTimeSeconds].join('|')); } catch {}" 2>/dev/null || echo "")
15240
+
15241
+ if [ -n "$DETECTED" ]; then
15242
+ IFS='|' read -r DET_AUTHOR DET_MODEL DET_PROMPT DET_COMPL DET_TIME <<< "$DETECTED"
15243
+ AUTHOR_TYPE="\${DET_AUTHOR:-$AUTHOR_TYPE}"
15244
+ AI_MODEL_NAME="\${DET_MODEL:-$AI_MODEL_NAME}"
15245
+ PROMPT_TOKENS="\${DET_PROMPT:-$PROMPT_TOKENS}"
15246
+ COMPLETION_TOKENS="\${DET_COMPL:-$COMPLETION_TOKENS}"
15247
+ ACTIVE_TIME_SEC="\${DET_TIME:-$ACTIVE_TIME_SEC}"
15248
+ else
15249
+ if [ -n "$AI_MODEL" ] || [ -n "$AI_AGENT_NAME" ] || [ -n "$ANTIGRAVITY_AGENT" ] || [ -n "$ANTIGRAVITY_AGENT_ID" ] || [ -n "$ANTIGRAVITY_CONVERSATION_ID" ] || [ -n "$CLAUDE_CODE" ] || [ -n "$CURSOR_AGENT" ] || [ -n "$WINDSURF_AGENT" ] || [ -n "$AIDER_MODEL" ] || [ -f "$TELEMETRY_FILE" ]; then
15250
+ AUTHOR_TYPE="agent"
15251
+ AI_MODEL_NAME="\${AI_MODEL:-\${AI_AGENT_NAME:-\${AIDER_MODEL:-agent-developer}}}"
15252
+ fi
15253
+ fi
15254
+
15255
+ # Estimate tokens and active time if not provided for agent
15256
+ if [ "$PROMPT_TOKENS" = "0" ] && [ "$AUTHOR_TYPE" = "agent" ]; then
15257
+ CHG_LINES=$(git diff --cached --shortstat 2>/dev/null | grep -oE '[0-9]+ (insertion|deletion)' | awk '{s+=$1} END {print s+0}')
15258
+ if [ -n "$CHG_LINES" ] && [ "$CHG_LINES" -gt 0 ]; then
15259
+ COMPLETION_TOKENS=$((CHG_LINES * 10))
15260
+ PROMPT_TOKENS=$((2500 + CHG_LINES * 25))
15261
+ ACTIVE_TIME_SEC=$((30 + CHG_LINES / 2))
15262
+ else
15263
+ PROMPT_TOKENS=1000
15264
+ COMPLETION_TOKENS=0
15265
+ ACTIVE_TIME_SEC=30
15266
+ fi
15267
+ fi
15268
+
15269
+ # Inject missing trailers individually into the commit message
15270
+ TRAILERS_TO_ADD=""
15271
+
15272
+ if [ -n "$TASK_ID" ] && ! grep -qE "^Task-ID:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15273
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Task-ID: $TASK_ID
15274
+ "
15275
+ fi
15276
+ if [ -n "$PARENT_REF" ] && ! grep -qE "^Parent-Ref:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15277
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Parent-Ref: $PARENT_REF
15278
+ "
15279
+ fi
15280
+ if ! grep -qE "^Author-Type:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15281
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Author-Type: $AUTHOR_TYPE
15282
+ "
15283
+ fi
15284
+ if [ "$AUTHOR_TYPE" = "agent" ] && ! grep -qE "^AI-Model:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15285
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}AI-Model: $AI_MODEL_NAME
15286
+ "
15287
+ fi
15288
+ if ! grep -qE "^Prompt-Tokens:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15289
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Prompt-Tokens: $PROMPT_TOKENS
15290
+ "
15291
+ fi
15292
+ if ! grep -qE "^Completion-Tokens:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15293
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Completion-Tokens: $COMPLETION_TOKENS
15294
+ "
15295
+ fi
15296
+ if ! grep -qE "^Active-Time-Seconds:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15297
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Active-Time-Seconds: $ACTIVE_TIME_SEC
15298
+ "
15299
+ fi
15300
+
15301
+ if [ -n "$TRAILERS_TO_ADD" ]; then
15302
+ echo "" >> "$COMMIT_MSG_FILE"
15303
+ printf "$TRAILERS_TO_ADD" >> "$COMMIT_MSG_FILE"
15304
+ fi
15305
+
15306
+ if [ -f "$TELEMETRY_FILE" ]; then
15307
+ rm -f "$TELEMETRY_FILE" 2>/dev/null || true
15308
+ fi
15147
15309
  `;
15310
+ function installGitHooks(rootDir = process.cwd()) {
15311
+ const gitDir = path14.join(rootDir, ".git");
15312
+ if (!fs12.existsSync(gitDir)) {
15313
+ return {
15314
+ success: false,
15315
+ error: `No se encontr\xF3 el directorio Git en '${gitDir}'.`
15316
+ };
15317
+ }
15318
+ const hooksDir = path14.join(gitDir, "hooks");
15319
+ if (!fs12.existsSync(hooksDir)) {
15320
+ fs12.mkdirSync(hooksDir, { recursive: true });
15321
+ }
15322
+ const prepareCommitMsgPath = path14.join(hooksDir, "prepare-commit-msg");
15323
+ const preCommitPath = path14.join(gitDir, "hooks", "pre-commit");
15324
+ try {
15325
+ fs12.writeFileSync(prepareCommitMsgPath, PREPARE_COMMIT_MSG_SCRIPT, { encoding: "utf-8", mode: 493 });
15326
+ fs12.writeFileSync(preCommitPath, PRE_COMMIT_SCRIPT, { encoding: "utf-8", mode: 493 });
15327
+ return {
15328
+ success: true,
15329
+ hookPath: prepareCommitMsgPath,
15330
+ installedHooks: [prepareCommitMsgPath, preCommitPath]
15331
+ };
15332
+ } catch (err) {
15333
+ const msg = err instanceof Error ? err.message : String(err);
15334
+ return {
15335
+ success: false,
15336
+ error: `Error al escribir hooks en '${hooksDir}': ${msg}`
15337
+ };
15338
+ }
15148
15339
  }
15149
15340
  function calculateCost(prompt, completion) {
15150
15341
  const promptCost = prompt / 1e6 * 3;
@@ -17773,16 +17964,35 @@ function resolveBranchFilterKeys(metricsData) {
17773
17964
  }
17774
17965
  return keys;
17775
17966
  }
17967
+ function renderAgentKpisSectionHtml(kpis) {
17968
+ if (!kpis) return "";
17969
+ return [
17970
+ `<div class="chart-container" id="agent-performance-kpis">`,
17971
+ ` <h3>AI Agent Performance KPIs (SWE-bench &amp; DORA AI)</h3>`,
17972
+ ` <p style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 1rem;">Tasks: <strong>${kpis.totalTasks}</strong> | Commits: <strong>${kpis.totalCommits}</strong> | Audited Trailers: <strong>${kpis.auditedCommitsPercent}%</strong></p>`,
17973
+ ` <div class="grid-cards">`,
17974
+ ` <div class="metric-card"><span class="title">First-Pass Yield (FPY)</span><span class="value">${kpis.firstPassYieldPercent}%</span><span class="subtitle">Target &ge; 80%</span></div>`,
17975
+ ` <div class="metric-card"><span class="title">Rework Loops / Task</span><span class="value">${kpis.reworkLoopsPerTask}</span><span class="subtitle">Target &le; 0.5</span></div>`,
17976
+ ` <div class="metric-card"><span class="title">Spec Adherence Index</span><span class="value">${kpis.specificationAdherenceIndex}%</span><span class="subtitle">Target &ge; 95%</span></div>`,
17977
+ ` <div class="metric-card"><span class="title">Human Takeover Rate</span><span class="value">${kpis.humanTakeoverRatePercent}%</span><span class="subtitle">Target &le; 15%</span></div>`,
17978
+ ` <div class="metric-card"><span class="title">Token Cost Efficiency</span><span class="value">${kpis.tokenCostEfficiency.toLocaleString("en-US")}</span><span class="subtitle">tokens / CC</span></div>`,
17979
+ ` <div class="metric-card"><span class="title">Architecture Drift Rate</span><span class="value">${kpis.architectureDriftRatePercent}%</span><span class="subtitle">Target 0%</span></div>`,
17980
+ ` </div>`,
17981
+ `</div>`
17982
+ ].join("\n");
17983
+ }
17776
17984
  function renderKpisTabHtml(metricsData) {
17777
17985
  const displayKpi = metricsData.totalTelemetry || metricsData.activePrKpi;
17778
17986
  const branchKeys = resolveBranchFilterKeys(metricsData);
17779
17987
  const telemetryHtml = displayKpi ? renderActiveTelemetrySection(displayKpi, "Totalizador", branchKeys, metricsData.activeBranch) : '<p style="color: var(--text-muted); font-size: 0.85rem;">No telemetry recorded yet in this workspace.</p>';
17988
+ const agentKpisHtml = renderAgentKpisSectionHtml(metricsData.agentKpis);
17780
17989
  const historyContent = renderHistoricalKpisTable(metricsData.history);
17781
17990
  return [
17782
17991
  ` <div id="tab-kpis" class="tab-panel">`,
17783
17992
  ` <div class="content-container">`,
17784
17993
  ` <h2>Active Telemetry and KPI History</h2>`,
17785
17994
  telemetryHtml,
17995
+ agentKpisHtml,
17786
17996
  ` <div class="chart-container"><h3>Consolidated Release History</h3>${historyContent}</div>`,
17787
17997
  ` </div>`,
17788
17998
  ` </div>`
@@ -18144,6 +18354,12 @@ function collectDashboardMetrics(rootDir) {
18144
18354
  history,
18145
18355
  activePrKpi
18146
18356
  );
18357
+ const agentKpis = computeAgentPerformanceKpis({
18358
+ records: totalTelemetry?.commitRecords || [],
18359
+ gateResult: gate,
18360
+ coverageResult: cov,
18361
+ traceabilityResult: trace
18362
+ });
18147
18363
  return {
18148
18364
  gate,
18149
18365
  gov,
@@ -18156,6 +18372,7 @@ function collectDashboardMetrics(rootDir) {
18156
18372
  activeBranch,
18157
18373
  branchTelemetries,
18158
18374
  totalTelemetry,
18375
+ agentKpis,
18159
18376
  complianceBundle
18160
18377
  };
18161
18378
  }
@@ -18376,7 +18593,7 @@ var SPECIALIZED_AGENT_TEMPLATES = [
18376
18593
 
18377
18594
  ## Phase 0: Greenfield Product Inception (New Product Intent)
18378
18595
  - **Trigger**: When the user expresses intent to create a new product from scratch with the framework (or when \`specs/product/\` has no baseline product model yet), initiate **Phase 0** before any SDD change (\`change:new\`) or implementation:
18379
- 1. **Iterative Discovery Interview (Up to 15 Questions or Until Product is Crystal Clear)**: Conduct an iterative discovery interview (up to 15 questions, grouped logically in conversational rounds until zero product ambiguities remain) before drafting specs, clarifying: (a) core problem and mission statement, (b) primary actors/stakeholders (\`ACT-*\`), authentication/role model, and **target user interface modality** (e.g., Web UI, Desktop GUI, Console/TUI/CLI, Mobile app, or headless API/SDK), (c) **modern visual aesthetic & styling standard** (Bootstrap 5-style clean responsive web design with cards/tables/badges, Fluent/modern desktop aesthetic with rounded corners/elevated panels, or colorized rich terminal console with ANSI palettes/status badges), (d) **User Journeys (\`JRN-*\`) to generate** \u2014 asking in plain, non-technical language which end-to-end user workflows to model and explicitly guiding the user on the 5 pieces of information needed to build each journey properly: *(1) Who is the protagonist user (\`persona\` / \`ACT-*\`) and their main goal, (2) What are the step-by-step stages from start to finish (\`stages\`), (3) Which screens, channels, or interfaces the user interacts with at each step (\`touchpoints\`), (4) What current obstacles, frustrations, or risks they face (\`pain-points\`), and (5) Which concrete actions or capabilities the system must provide along the journey (\`related-use-cases\` / \`UC-*\`)*, (e) foundational master entities/catalogs and CRUD flows required to operate the system, (f) essential MVP capabilities/use cases (\`UC-*\`) and business rules/invariants (\`BR-*\`) vs. future roadmap, and (g) top 3\u20135 priority quality goals and constraints (\`QR-*\`, \`CON-*\`). Do not proceed to draft artifacts until the product scope is completely clear.
18596
+ 1. **Iterative Discovery Interview (Up to 15 Questions or Until Product is Crystal Clear)**: Conduct an iterative discovery interview (up to 15 questions, grouped logically in conversational rounds until zero product ambiguities remain) before drafting specs, clarifying: (a) core problem and mission statement, (b) primary actors/stakeholders (\`ACT-*\`), authentication/role model, and **target user interface modality** (e.g., Web UI, Desktop GUI, Console/TUI/CLI, Mobile app, or headless API/SDK), (c) **modern visual aesthetic & styling standard** (Bootstrap 5-style clean responsive web design with cards/tables/badges, Fluent/modern desktop aesthetic with rounded corners/elevated panels, or colorized rich terminal console with ANSI palettes/status badges), (d) **delivery & operation model** (in plain business terms: Cloud SaaS, Self-Hosted/On-Premise, Local Desktop/CLI binary, or Library/SDK package, plus any data-residency or SLA constraints), (e) **User Journeys (\`JRN-*\`) to generate** \u2014 asking in plain, non-technical language which end-to-end user workflows to model and explicitly guiding the user on the 5 pieces of information needed to build each journey properly: *(1) Who is the protagonist user (\`persona\` / \`ACT-*\`) and their main goal, (2) What are the step-by-step stages from start to finish (\`stages\`), (3) Which screens, channels, or interfaces the user interacts with at each step (\`touchpoints\`), (4) What current obstacles, frustrations, or risks they face (\`pain-points\`), and (5) Which concrete actions or capabilities the system must provide along the journey (\`related-use-cases\` / \`UC-*\`)*, (f) foundational master entities/catalogs and CRUD flows required to operate the system, (g) essential MVP capabilities/use cases (\`UC-*\`) and business rules/invariants (\`BR-*\`) vs. future roadmap, and (h) top 3\u20135 priority quality goals and constraints (\`QR-*\`, \`CON-*\`). Do not proceed to draft artifacts until the product scope is completely clear.
18380
18597
  2. **Enterprise & Capability Vision (\`ARCH-INTRO-001\`)**: Draft the root vision artifact (\`type: architecture-introduction\`, \`naf-perspective: "Enterprise & Capability"\`, \`status: draft\`) using \`templates/architecture/introduction-and-goals.template.md\` (\`schemas/architecture/introduction-and-goals.schema.json\`), explicitly recording the agreed UI/interaction modality.
18381
18598
  3. **ProductShape Derivation**: Derive the initial draft artifacts (\`ACT-*\`, \`JRN-*\`, \`UC-*\`, \`BR-*\`, \`FR-*\`, \`QR-*\` with \`status: draft\`) in \`specs/product/\` linked to \`ARCH-INTRO-001\` for human Product Owner review.
18382
18599
  4. **Mandatory End-to-End Presentation Interface & Master Data Prerequisite Rule (ANTI-LIBRARY-ONLY MVP)**: Whenever primary actors (\`ACT-*\`) are human users, the MVP ProductShape baseline MUST include: (a) an explicit presentation/interaction requirement (\`FR-*\`) or vertical UI/CLI acceptance criteria matching the modality agreed in Step 1 (Web UI, Desktop GUI, or Console/TUI/CLI \u2014 never proposing a library-only/in-memory MVP without a runnable entry point), (b) user authentication/session access when multi-role actors exist, and (c) CRUD/configuration flows for foundational master entities (e.g., rooms, staff, students, catalogs) required to operate the core business flows without manual database intervention.
@@ -18464,6 +18681,7 @@ var SPECIALIZED_AGENT_TEMPLATES = [
18464
18681
  - **Contract-First Full-Stack Integration**: Whenever a feature or change spans Frontend (UI) and Backend (API/services), define an explicit shared typed contract (Zod schemas, shared TypeScript DTOs, or OpenAPI specification) in \`design.md\` before implementation so both layers compile against a single source of truth.
18465
18682
  - **No Orphan Presentation Components (\`CMP-WEB-*\` / \`CMP-UI-*\` / \`CMP-CLI-*\`)**: When modeling architecture for a system with human actors (\`ACT-*\`), never leave the agreed presentation/driving adapter (Web UI, Desktop GUI, or Console/CLI) as an unmapped \`proposed\` spec while scheduling only backend class-library tasks in \`tasks.md\`. Wave 0 (\`CHG-001\`) MUST bootstrap the runnable presentation host shell matching the modality defined in Inception, and every subsequent \`CHG-*\` for a human-facing \`UC-*\` must include tasks (\`TSK-*\`) implementing its corresponding views/screens/commands and E2E tests as a complete vertical slice.
18466
18683
  - Generate interaction and sequence diagrams in native Mermaid syntax.
18684
+ - **Deployment Topology (\`ARCH-DEP-001\`)**: Translate the product delivery and operation model recorded in \`ARCH-INTRO-001\` / \`CON-*\` into an arc42 Section 7 Deployment View (\`templates/architecture/deployment-view.template.md\`) mapping components (\`CMP-*\`) to execution nodes (\`RES-*\`) and network enclaves (\`SEC-ENC-*\`).
18467
18685
  - Document critical technological decisions using immutable \`ADR-*\` records conforming to \`schemas/architecture/adr.schema.json\`.
18468
18686
  - Validate that architectural choices comply with legal constraints in \`license-policy.yaml\` and data protection constraints in \`privacy-policy.yaml\`.
18469
18687
  - **Technical Security & Privacy Feedback Loop**: If architectural decisions (databases, queues, distributed caching, third-party APIs, LLM providers, authentication schemes) introduce new attack vectors or PII data flows, emit a return handoff to \`agent-threat-modeler\` (which chains to \`agent-privacy-officer\`) for technical modeling prior to the testing phase.
@@ -18498,7 +18716,11 @@ var SPECIALIZED_AGENT_TEMPLATES = [
18498
18716
  - **Zero-Mock Integration Rule**: When an \`FR-*\` spans UI and Backend, unit tests mocking \`fetch\`/HTTP in isolation are insufficient; include integration/contract or E2E test scenarios verifying real request/response wiring and UI state transitions (\`Loading\`, \`Empty\`, \`Error\`, \`Nominal\`).
18499
18717
  - Tag all scenarios with \`@<FR-ID> @automated @regression\`.
18500
18718
  - **STRICTLY FORBIDDEN**: Including production code, suggesting implementation, or anticipating technical solutions.
18501
- - Run \`pnpm run verify:testing\` before emitting handoff.
18719
+ - **MANDATORY DETERMINISTIC GHERKIN ENGINES**:
18720
+ 1. **NEVER** author or edit \`.feature\` files in \`tests/features/\` manually, and **NEVER** write boilerplate BDD step definition files in \`tests/steps/\` from scratch.
18721
+ 2. Always author Gherkin scenarios inside the \`\`\`gherkin blocks of the specification Markdown (\`FR-*\`, \`SEC-REQ-*\`, \`PRIV-REQ-*\`, \`spec.md\`) and run \`npx aisdlc gherkin extract\` (or \`npx aisdlc check --fix\`) to deterministically generate \`.feature\` files.
18722
+ 3. Always run \`npx aisdlc gherkin scaffold <feature-file> --lang <ts|py|go|rs|cs> --fallback\` (or without \`--fallback\` when native generator is installed and approved) to deterministically scaffold RED step definition skeletons in \`tests/steps/\`. Implement assertions inside those generated step files and add any extra unit/integration/E2E/UI suites in \`tests/unit/\`, \`tests/e2e/\`, etc.
18723
+ - Run \`npx aisdlc verify gherkin\` and \`pnpm run verify:testing\` before emitting handoff.
18502
18724
  - If autonomy is $\\ge$ \`HUMAN_REVIEW_PLAN\`, conclude by emitting the Workflow Handoff block (\`templates/workflow/agent-handoff.template.md\`) suggesting \`agent-developer\` and opening the Human Action Window. In \`AUTONOMOUS\` mode, omit interactive handoff.`
18503
18725
  },
18504
18726
  {
@@ -18543,42 +18765,7 @@ Execute every implementation task following this strict sequential order:
18543
18765
  - **Mandatory Regression Verification**: Never declare build, typecheck, or bug fixes complete without executing the relevant automated test suite (\`pnpm test\`, \`dotnet test\`) and confirming zero regressions.
18544
18766
  - **Global Styles Protection**: When touching or refactoring frontend views, verify that global stylesheet/asset imports remain intact and that layouts suffer no visual disruption.
18545
18767
  - **Skills-First Implementation Directive**: When authoring or refactoring code (especially frontend, UI, styling, accessibility, or framework-specific logic), proactively inspect and leverage available specialized agent skills (e.g., modern web guidance, accessibility a11y, DevTools, framework skills) to produce standard-compliant, modern implementations rather than guessing ad-hoc patterns.
18546
- - Upon completing green implementation, suggest handoff to \`agent-expert-user\` for Post-Development Functional Validation prior to security and privacy audit.`
18547
- },
18548
- {
18549
- id: "agent-security-auditor",
18550
- title: "Adversarial Code Auditor",
18551
- description: "Examine Pull Requests and source code with an attacker mindset for business logic vulnerabilities, injection vectors, secret leaks, and authorization flaws.",
18552
- globs: "src/**, packages/**, security/**",
18553
- claudeTools: ["View", "GlobTool", "GrepTool", "LS", "Bash"],
18554
- antigravityTools: ["read_file", "run_command", "call_mcp_tool"],
18555
- body: `## Role & Mission
18556
- - **Role**: Adversarial Security Auditor Agent (\`agent-security-auditor\`).
18557
- - **Mission**: Rigorously examine Pull Requests and code diffs for business logic vulnerabilities, injection vectors, secret leaks, and authorization flaws as part of the Pre-Merge Audit Triad.
18558
-
18559
- ## Operational Directives & Guardrails
18560
- - Analyze code diffs with an attacker mindset: How can an unauthenticated user bypass this check? Are there info leaks in exceptions? Is command, SQL, path traversal, or prompt injection possible?
18561
- - Run deterministic security verification: \`pnpm run verify:security\` (secrets + shift-left SAST).
18562
- - Issue a formal audit report with CVSS v3.1 severity scoring and concrete remediation proposals.
18563
- - Immediately block any PR introducing CRITICAL or HIGH security risks.
18564
- - If autonomy is $\\ge$ \`HUMAN_REVIEW_PLAN\`, conclude by emitting the Workflow Handoff block (\`templates/workflow/agent-handoff.template.md\`) to the human Tech Lead, opening the Human Action Window. In \`AUTONOMOUS\` mode, omit interactive handoff.`
18565
- },
18566
- {
18567
- id: "agent-compliance-checker",
18568
- title: "Open Source License Compliance Auditor",
18569
- description: "Audit dependency manifests and SBOMs against license-policy.yaml to block viral copyleft licenses and flag commercial license requirements.",
18570
- globs: "package.json, pnpm-lock.yaml, license-policy.yaml, compliance/**",
18571
- claudeTools: ["View", "GlobTool", "GrepTool", "LS", "Bash"],
18572
- antigravityTools: ["read_file", "run_command", "call_mcp_tool"],
18573
- body: `## Role & Mission
18574
- - **Role**: Open Source License and Intellectual Property Compliance Auditor Agent (\`agent-compliance-checker\`).
18575
- - **Mission**: Audit dependency manifests and ensure every direct and transitive third-party package complies with \`license-policy.yaml\` as part of the Pre-Merge Audit Triad.
18576
-
18577
- ## Operational Directives & Guardrails
18578
- - Verify SPDX identifiers for every direct and transitive dependency via \`pnpm run verify:licenses\`.
18579
- - Immediately block viral copyleft licenses (\`GPL-*\`, \`AGPL-*\`) and unknown/unlicensed packages.
18580
- - If source-available or commercial licenses (\`BSL-1.1\`, \`SSPL-1.0\`) are detected, flag with \`COMMERCIAL_APPROVAL_REQUIRED\` and draft a request using \`templates/compliance/commercial-acquisition-request.template.md\`.
18581
- - If autonomy is $\\ge$ \`HUMAN_REVIEW_PLAN\`, conclude by emitting the Workflow Handoff block (\`templates/workflow/agent-handoff.template.md\`) to the human Tech Lead or Legal counsel, opening the Human Action Window. In \`AUTONOMOUS\` mode, omit interactive handoff.`
18768
+ - Upon completing green implementation, suggest handoff to \`agent-expert-user\` for Post-Development Functional Validation prior to Checkpoint 2 (\`agent-auditor\` $\\parallel$ \`agent-adversary\` + \`agent-privacy-officer\`).`
18582
18769
  },
18583
18770
  {
18584
18771
  id: "agent-expert-user",
@@ -18597,28 +18784,7 @@ Execute every implementation task following this strict sequential order:
18597
18784
  - **FORBIDDEN Library-Only MVP for Human Actors**: Whenever primary actors (\`ACT-*\`) are human users, verify that the target interaction modality (Web UI, Desktop GUI, Console/TUI/CLI, or Mobile) was explicitly defined in \`ARCH-INTRO-*\` / \`specs/product/\`, and reject as \`[BLOCKING_DEFECT]\` any MVP proposal that defers the agreed presentation layer, role authentication (when applicable), or foundational master-entity CRUDs (e.g., creating rooms, teachers, students, schedules) to post-MVP or leaves the system operable only via unit tests/in-memory calls. An MVP for human operators must be end-to-end usable from day one via its agreed interface.
18598
18785
  2. **Functional Validation Mode (Downstream / Pre-PR / Post-Development Functional Validation)**: Inspect \`agent-developer\` deliverables once unit tests pass green by executing the real application (via Playwright or Chrome DevTools MCP when UI is present). Contrast actual UI, CLI, and API behavior against approved \`UC-*\` and \`FR-*\` criteria, verifying real Backend connectivity, the 4 UI usability states (\`Loading\`, \`Empty\`, \`Error\`, \`Nominal\`), keyboard/ARIA accessibility, modern visual appearance (Bootstrap 5-style clean layouts for Web, modern styled panels for Desktop, or colorized rich terminal formatting for Console), and \`0\` browser \`console.error\` / network failures.
18599
18786
  - Formulate decisive questions under \`open-questions\` for the human Product Owner.
18600
- - Emit handoff block suggesting the Pre-Merge Audit Triad (\`agent-code-reviewer\`, \`agent-security-auditor\`, \`agent-privacy-officer\`, \`agent-compliance-checker\`) if compliant, or return to \`agent-developer\` on functional drift, unstyled interfaces, or fake-wiring.`
18601
- },
18602
- {
18603
- id: "agent-code-reviewer",
18604
- title: "Technical and Architectural Code Reviewer",
18605
- description: "Audit Pull Requests for Clean Code, SOLID, DRY, YAGNI, design patterns, and compliance with quality-policy.yaml complexity and maintainability thresholds.",
18606
- globs: "src/**, packages/**, tests/**",
18607
- claudeTools: ["View", "GlobTool", "GrepTool", "LS", "Bash"],
18608
- antigravityTools: ["read_file", "run_command", "call_mcp_tool"],
18609
- body: `## Role & Mission
18610
- - **Role**: Technical and Architectural Code Reviewer Agent (\`agent-code-reviewer\`).
18611
- - **Mission**: Audit Pull Requests evaluating code cleanliness, adherence to SOLID, DRY, YAGNI principles, design patterns, and compliance with complexity and maintainability thresholds (\`quality-policy.yaml\`), forming part of the Pre-Merge Audit Triad.
18612
-
18613
- ## Operational Directives & Guardrails
18614
- - Analyze code diffs against \`quality-policy.yaml\` standards: Cyclomatic Complexity $\\le 10$, Cognitive Complexity $\\le 15$, Maintainability Index $\\ge 50$, Lines per Function $\\le 40$.
18615
- - Detect improper coupling, code smells, magic numbers, ambiguous identifiers, and encapsulation breaches.
18616
- - Flag premature abstractions and speculative code violating YAGNI.
18617
- - **Block Fake-Wiring & Disconnected UI**: Flag as \`[BLOCKING]\` any production UI component containing hardcoded mock data (\`mockData\`), empty event handlers (\`onClick={() => {}}\`), missing error/loading state handling, or API calls bypassing shared contracts.
18618
- - **Block Unstyled & Non-Compliant Interfaces**: Flag as \`[BLOCKING]\` any web view lacking responsive grid and standard styling classes (such as Bootstrap 5 or project design tokens), any desktop window using raw unstyled legacy controls, or any interactive console tool emitting raw monochrome dumps without colorized badges or structured formatting. Also verify that inline manual styles (\`style="..."\`) are not used to bypass design systems.
18619
- - Coordinate Pre-Merge Audit Triad with \`agent-security-auditor\`, \`agent-privacy-officer\`, and \`agent-compliance-checker\`.
18620
- - Categorize findings into: \`[BLOCKING]\` (quality violation or broken pattern), \`[CLEAN_CODE_SUGGESTION]\` (non-blocking improvement), and \`[COMPLIANT]\`.
18621
- - If autonomy is $\\ge$ \`HUMAN_REVIEW_PLAN\`, conclude by emitting the Workflow Handoff block (\`templates/workflow/agent-handoff.template.md\`) to the human Tech Lead for final approval and merge, opening the Human Action Window. In \`AUTONOMOUS\` mode, omit interactive handoff.`
18787
+ - Emit handoff block suggesting Checkpoint 2 (\`agent-auditor\` $\\parallel$ \`agent-adversary\` + \`agent-privacy-officer\`) if compliant, or return to \`agent-developer\` on functional drift, unstyled interfaces, or fake-wiring.`
18622
18788
  },
18623
18789
  {
18624
18790
  id: "agent-devops",
@@ -18626,7 +18792,7 @@ Execute every implementation task following this strict sequential order:
18626
18792
  description: "Maintain, evolve, and audit CI/CD workflows, Dockerfiles, IaC manifests, and support scripts under strict non-invasion guardrails on src/.",
18627
18793
  globs: ".github/workflows/**, templates/ci/**, scripts/**, Dockerfile*",
18628
18794
  claudeTools: ["View", "Edit", "Replace", "GlobTool", "GrepTool", "LS", "Bash"],
18629
- antigravityTools: ["read_file", "edit_file", "write_file", "run_command", "call_mcp_tool"],
18795
+ antigravityTools: ["read_file", "edit_file", "write_file", "run_command", "call_mcp_tool", "ask_question"],
18630
18796
  body: `## Role & Mission
18631
18797
  - **Role**: DevOps and Infrastructure as Code (IaC) Engineer Agent (\`agent-devops\`).
18632
18798
  - **Mission**: Maintain, evolve, and audit automated project infrastructure: CI/CD workflows, Docker containers, deployment manifests, and infrastructure scripts.
@@ -18634,6 +18800,7 @@ Execute every implementation task following this strict sequential order:
18634
18800
  ## Operational Directives & Guardrails
18635
18801
  - **Strict Infrastructure Domain**: Operate exclusively on workflows (\`.github/workflows/\`, \`templates/ci/\`), container files (\`Dockerfile*\`, \`docker-compose*.yml\`), IaC manifests, and support scripts (\`scripts/\`).
18636
18802
  - **NON-INVASION GUARDRAIL**: STRICTLY FORBIDDEN from modifying or refactoring application source code files (\`src/\`, \`packages/*/src/\`). Your responsibility is pipelines and scaffolding, never business logic.
18803
+ - **Deployment & CI/CD Strategy Discovery**: Before scaffolding new pipelines or deployment manifests (e.g., Wave 0 Greenfield or Legacy CI integration), read \`ARCH-INTRO-001\` / \`ARCH-DEP-001\` and clarify with the human Tech Lead: (1) target packaging & CD destination (CI-only Quality Gates, Docker/OCI image to GHCR, package registry \`npm\`/\`NuGet\`/\`PyPI\`/GitHub Releases, or PaaS/Cloud/K8s), (2) CI/CD platform (GitHub Actions, GitLab CI, Azure Pipelines), and (3) release trigger policy (on push to \`main\` vs. manual SemVer tag \`vX.Y.Z\`).
18637
18804
  - **Infrastructure Dependency Policy**: Verify licenses of dependencies, Docker base images, and third-party CI actions against \`license-policy.yaml\`.
18638
18805
  - **Gate Preservation**: Ensure any pipeline optimization keeps all existing deterministic Quality Gates intact.
18639
18806
  - **Cross-Workflow Audit**: When fixing any CI/CD or configuration defect detected in a PR, search all \`.github/workflows/*.yml\` for the same pattern (including release, post-merge, and publishing pipelines) before declaring the fix complete.
@@ -18643,18 +18810,21 @@ Execute every implementation task following this strict sequential order:
18643
18810
  {
18644
18811
  id: "agent-auditor",
18645
18812
  title: "Transversal Quality and Improvement Auditor",
18646
- description: "Polymorphically inspect deliverables from any AI-SDLC specialist agent on demand, identifying structural weaknesses, overengineering, or blind spots, and proposing concrete, minimal solutions adhering strictly to YAGNI.",
18813
+ description: "Polymorphically inspect deliverables from any AI-SDLC specialist agent on demand, enforcing Clean Code, SOLID, DRY, YAGNI, AST thresholds, UI design standards, and SPDX license compliance.",
18647
18814
  globs: "**/*",
18648
18815
  claudeTools: ["View", "GlobTool", "GrepTool", "LS", "Bash"],
18649
18816
  antigravityTools: ["read_file", "run_command", "call_mcp_tool", "ask_question"],
18650
18817
  body: `## Role & Mission
18651
18818
  - **Role**: Transversal Quality and Constructive Auditor Agent (\`agent-auditor\`).
18652
- - **Mission**: Inspect the output deliverables of any upstream specialist agent upon demand across any phase, identifying structural weaknesses, premature abstractions, overengineering, or blind spots, and proposing concrete, minimal, and standard solutions adhering strictly to Simplicity First (YAGNI).
18819
+ - **Mission**: Inspect the output deliverables of any upstream specialist agent upon demand across any phase, identifying structural weaknesses, premature abstractions, overengineering, or blind spots, and enforcing Clean Code, SOLID, DRY, Simplicity First (YAGNI), \`quality-policy.yaml\` AST thresholds, and \`license-policy.yaml\` SPDX compliance.
18653
18820
 
18654
18821
  ## Operational Directives & Guardrails
18655
18822
  - **Polymorphic On-Demand Scope**: May be invoked over deliverables from any role (\`agent-product-analyst\`, \`agent-threat-modeler\`, \`agent-privacy-officer\`, \`agent-system-architect\`, \`agent-qa-engineer\`, \`agent-developer\`, \`agent-devops\`).
18656
- - **Simplicity First (YAGNI)**: Actively challenge speculative parameters, redundant interfaces, unused design patterns, and unrequested flexibility.
18823
+ - **Simplicity First (YAGNI) & Code Quality**: Actively challenge speculative parameters, redundant interfaces, unused design patterns, and unrequested flexibility. In code reviews (Checkpoint 2 / Legacy), enforce \`quality-policy.yaml\` thresholds (Cyclomatic Complexity $\\le 10$, Cognitive Complexity $\\le 15$, Maintainability Index $\\ge 50$, Lines per Function $\\le 40$) and Clean Code / SOLID / DRY principles.
18824
+ - **Block Fake-Wiring & Unstyled Interfaces**: Flag as \`[BLOCKING_DEFECT]\` any production UI component containing hardcoded mock data (\`mockData\`), empty event handlers (\`onClick={() => {}}\`), missing \`Loading\`/\`Empty\`/\`Error\` states, or API calls bypassing shared contracts. Also **Block Unstyled & Non-Compliant Interfaces**: flag as \`[BLOCKING_DEFECT]\` any web view lacking responsive grid and standard styling classes (such as Bootstrap 5 or project design tokens), any desktop window using raw unstyled legacy controls, any interactive console tool emitting raw monochrome dumps, or inline \`style="..."\` bypassing design systems.
18657
18825
  - **End-to-End MVP Completeness Check (Anti-Library-Only Drift)**: When auditing Product (\`specs/product/\`), Architecture (\`specs/architecture/\`), or SDD change plans (\`design.md\`, \`tasks.md\`) involving human actors (\`ACT-*\`), flag as \`[BLOCKING_DEFECT]\` any scope cut that fails to define the target user interface modality at Inception or omits the runnable driving adapter (Web UI, Desktop GUI, or Console/CLI), role access/auth (when applicable), or master-data CRUD flows required to operate the use case end-to-end without manual database manipulation.
18826
+ - **Deterministic Gherkin Engine Enforcement**: Flag as \`[BLOCKING_DEFECT]\` any \`.feature\` file in \`tests/features/\` authored manually outside \`aisdlc gherkin extract\` or any missing step definition file in \`tests/steps/\` not scaffolded via \`aisdlc gherkin scaffold\`.
18827
+ - **License & Dependency Compliance**: Verify dependency manifests via \`pnpm run verify:licenses\` (\`npx aisdlc verify licenses\`), blocking viral copyleft licenses (\`GPL-*\`, \`AGPL-*\`) or unapproved commercial licenses (\`BSL-*\`, \`SSPL-*\`) against \`license-policy.yaml\`.
18658
18828
  - **Classification of Findings**: Label every finding as:
18659
18829
  * \`[BLOCKING_DEFECT]\`: Critical omission, structural debt, or standard violation that must be resolved.
18660
18830
  * \`[SIMPLIFICATION]\`: Opportunity to remove unneeded complexity or reduce code/spec surface without loss of function.
@@ -18666,20 +18836,20 @@ Execute every implementation task following this strict sequential order:
18666
18836
  {
18667
18837
  id: "agent-adversary",
18668
18838
  title: "Transversal Red Team and Chaos Adversary",
18669
- description: "Actively attempt to break, bypass, or invalidate deliverables from any target specialist agent, providing concrete proofs-of-concept (PoC), counterexamples, and reproduction steps for every discovered failure mode.",
18839
+ description: "Actively attempt to break, bypass, or invalidate deliverables from any target specialist agent, auditing diffs for security vulnerabilities (CVSS v3.1) and providing concrete proofs-of-concept (PoC).",
18670
18840
  globs: "**/*",
18671
18841
  claudeTools: ["View", "GlobTool", "GrepTool", "LS", "Bash"],
18672
18842
  antigravityTools: ["read_file", "run_command", "call_mcp_tool", "ask_question"],
18673
18843
  body: `## Role & Mission
18674
18844
  - **Role**: Transversal Red Team and Stress Adversary Agent (\`agent-adversary\`).
18675
- - **Mission**: Actively attempt to break, bypass, or invalidate the deliverables of any target specialist agent across any phase, providing concrete proofs-of-concept (PoC), counterexamples, and reproduction steps for every discovered failure mode.
18845
+ - **Mission**: Actively attempt to break, bypass, or invalidate the deliverables of any target specialist agent across any phase (including Pre-Merge / Checkpoint 2 security diff audits), providing concrete proofs-of-concept (PoC), counterexamples, CVSS v3.1 severity scoring, and reproduction steps for every discovered failure mode.
18676
18846
 
18677
18847
  ## Operational Directives & Guardrails
18678
18848
  - **Polymorphic On-Demand Scope**:
18679
18849
  * **Product**: Uncover contradictory requirements, unreachable business states, and logic traps.
18680
18850
  * **Architecture**: Simulate race conditions, cascading failures, resource exhaustion, and single points of failure (SPOFs).
18681
18851
  * **QA**: Perform conceptual mutation testing; demonstrate how flawed or empty implementations could falsely pass tests green.
18682
- * **Development**: Attack boundary inputs, concurrency race triggers, and memory/type edge breaks.
18852
+ * **Development & Pre-Merge Security Audit**: Attack boundary inputs, concurrency race triggers, memory/type edge breaks, injection vectors (SQL, XSS, command, path traversal, prompt injection), secret leaks, and authorization bypasses. Run \`pnpm run verify:security\` (\`npx aisdlc verify security\`), score findings with **CVSS v3.1**, and block any PR introducing \`CRITICAL\` or \`HIGH\` security risks.
18683
18853
  * **DevOps**: Probe pipeline isolation, credential boundaries, and cold-start/dependency outages.
18684
18854
  - **MANDATORY PROOF-OF-BREAK**: Abstract criticism without reproducible proof is strictly forbidden. Every finding must include: (1) Target Entity ID, (2) Failure Scenario / Attack Vector, (3) Concrete PoC (input vector, sequence breakdown, or mutant code), and (4) Expected Impact.
18685
18855
  - **NON-INVASIVE GUARDRAIL**: You do NOT patch the vulnerabilities or bugs yourself.
@@ -18757,7 +18927,7 @@ var LIFECYCLE_SKILL_TEMPLATES = [
18757
18927
  description: "Orchestrate end-to-end AI-SDLC onboarding and Phase 0 Inception for brand-new (Greenfield) projects, from repository initialization (aisdlc init) and NAF v4 Vision (ARCH-INTRO-*) through ProductShape, STRIDE Threat Modeling, arc42 Architecture, 2-checkpoint transversal auditor/adversary verification, and topological wave SDD delivery.",
18758
18928
  references: "[`process/02_product_definition.md`](../../process/02_product_definition.md), [`process/04b_data_protection_and_privacy.md`](../../process/04b_data_protection_and_privacy.md), [`process/05_architecture_arc42_nafv4.md`](../../process/05_architecture_arc42_nafv4.md), [`process/06_spec_driven_development.md`](../../process/06_spec_driven_development.md), and [`process/09_agent_protocols.md`](../../process/09_agent_protocols.md).",
18759
18929
  globs: "product/**, specs/product/**, architecture/**, templates/**",
18760
- body: '## Purpose & Trigger\nUse this skill when starting a **brand-new software project from scratch (Greenfield)** or when `specs/product/` has no canonical baseline yet. It coordinates the sequential execution of AI-SDLC MCP/CLI tools and specialized role agents so no code is written before product vision, security enclaves, privacy-by-design controls, and architecture contracts exist.\n\n## Consolidated Inception Quality & Adversarial Checkpoint\nAcross Phase 0 and Inception, quality auditing and adversarial stress-testing are concentrated at the completion of Inception design (or after product shaping):\n- **Concurrent Inspection**: Concurrently invoke [`agent-auditor`](../agent-auditor/SKILL.md) (evaluating YAGNI, structural debt, and simplification) and [`agent-adversary`](../agent-adversary/SKILL.md) (stress-testing logic traps, SPOFs, attack vectors, or broken invariants) in clean, isolated context windows.\n- **Non-Invasive Review**: Neither auditor nor adversary modifies deliverables directly; both deliver structured reports citing canonical IDs and SHA-256 digests.\n- **Consolidated Remediation**: Consolidate findings and emit the Workflow Handoff back to authoring agents to resolve blocking defects and apply simplifications (max 2 correction rounds).\n- **Anti-Ping-Pong Guardrail**: Bounded strictly to maximum **1 correction round**. If non-blocking advisories remain, proceed to the downstream phase; if blocking defects persist, escalate immediately to the Human Tech Lead.\n\n## End-to-End Execution Playbook\n\n### Step 1: Repository Turnkey Initialization\n1. If the workspace has not been initialized with AI-SDLC schemas, policies, and templates, run MCP tool `new` (or CLI `npx @aisdlc/cli init`).\n2. Install the Git telemetry hook via `npx aisdlc git hook install` (`pnpm run git:hook:install`).\n3. Verify `quality-policy.yaml`, `license-policy.yaml`, and `privacy-policy.yaml` are present in the repository root.\n\n### Step 2: Phase 0 Product Inception (`agent-product-analyst`)\n1. Delegate to or adopt [`agent-product-analyst`](../agent-product-analyst/SKILL.md).\n2. **Iterative Discovery Interview (Up to 15 Questions or Until Product Scope is 100% Clear)**: Before generating artifacts, clarify with the human Product Owner in rounds of 3\u20135 questions:\n - Core mission statement and business problem.\n - Primary actors (`ACT-*`) and external systems.\n - **Target Interaction & Presentation Modality (`CON-*` / `ARCH-INTRO-001`)**: Explicitly define at inception how human actors will interact with the MVP (e.g., **Web UI**, **Desktop GUI**, **Interactive Console/TUI/CLI**, **Mobile App**, or **Headless API/SDK** if actors are exclusively external systems). Never assume a headless class library when human actors exist.\n - **Modern Aesthetic & Design System Standard (`CON-UI-*` / `ARCH-INTRO-001`)**: Explicitly define a modern, visually attractive styling standard adapted to the chosen presentation modality: (1) **Web UI**: modern responsive layouts using Bootstrap 5 utility classes and components (`card`, `table table-hover`, `badge`, `alert alert-*`, responsive grid) or modern equivalents, (2) **Desktop GUI**: modern clean design (rounded corners, elevated panels, padding, consistent typography) avoiding raw legacy unstyled windows, (3) **Console / TUI**: rich terminal interface with ANSI colors, status badges, formatted tables, and progress indicators (e.g., Spectre.Console, Rich, Ink, or Chalk/Picocolors).\n - **User Journeys (`JRN-*`) to Generate (Plain-Language Elicitation)**: Ask in simple, everyday language which end-to-end user journeys to model, explicitly indicating the 5 pieces of information needed to build each journey properly: (1) protagonist user (`persona` / `ACT-*`) and their main goal, (2) step-by-step stages from start to finish (`stages`), (3) interaction screens/channels at each stage (`touchpoints`), (4) current obstacles or pain points (`pain-points`), and (5) concrete system capabilities/use cases (`related-use-cases` / `UC-*`).\n - Essential MVP capabilities (`UC-*`) vs. future roadmap, ensuring **foundational entity CRUD / master data workflows** are explicitly included in the MVP.\n - Top 3\u20135 quality goals (`QR-*`) and regulatory/technical constraints (`CON-*`).\n3. **Enterprise & Capability Vision**: Create `specs/architecture/ARCH-INTRO-001.md` (`status: draft`, `naf-perspective: "Enterprise & Capability"`) using `templates/architecture/introduction-and-goals.template.md`, explicitly recording the chosen presentation/UI modality.\n4. **ProductShape Baseline**: Derive initial draft artifacts in `specs/product/`:\n - Actors (`ACT-*`), User Journeys (`JRN-*`), Use Cases (`UC-*`), Business Rules (`BR-*`), Functional Requirements (`FR-*` with mandatory `@nominal`, `@boundary`, `@invalid` Gherkin blocks), and Quality Requirements (`QR-*`).\n - **Vertical Slice Completeness Rule**: Every human-triggered `UC-*` in the MVP must specify observable user interaction through the agreed presentation modality and state persistence.\n5. Validate schemas and duplicates via MCP tools `verify_schemas` and `verify_duplicates` (or `npx aisdlc check --fix`).\n6. **Mandatory Upstream UX & MVP Boundary Gate (`agent-expert-user`)**: Invoke [`agent-expert-user`](../agent-expert-user/SKILL.md) in **Design Mode** to stress-test the proposed workflows, enforce strict MVP boundaries, reject any headless/library-only MVP when human actors exist, verify master-data CRUD prerequisites, and separate core MVP `UC-*` from future roadmap backlog.\n\n### Step 3: Shift-Left Cybersecurity & Privacy-by-Design (`agent-threat-modeler` \u2794 `agent-privacy-officer`)\n1. Delegate to or adopt [`agent-threat-modeler`](../agent-threat-modeler/SKILL.md).\n2. Analyze every `UC-*` and `FR-*` using STRIDE and OWASP ASVS to create in `specs/security/`:\n - Threat Actors (`ACT-THREAT-*`), Abuse Cases (`ABUSE-*` targeting `UC-*`), and Security Requirements (`SEC-REQ-*` with `@security @mitigation` negative Gherkin scenarios and `SEC-ENC-*` Zero Trust enclave bindings).\n3. Hand off to [`agent-privacy-officer`](../agent-privacy-officer/SKILL.md) to apply LINDDUN and GDPR/LOPDGDD/ISO 27701 in `specs/privacy/`:\n - Personal Data Assets (`DATA-ASSET-*`), GDPR Art. 30 Records of Processing (`PRIV-ROPA-*`), and Privacy Requirements (`PRIV-REQ-*` with `@privacy @gdpr` Gherkin scenarios).\n4. Run `verify_schemas` and `verify_privacy` (`npx aisdlc verify privacy`).\n\n### Step 4: Modular Systems Architecture (`agent-system-architect`)\n1. Delegate to or adopt [`agent-system-architect`](../agent-system-architect/SKILL.md).\n2. Define building blocks (`CMP-*`) and Architectural Decision Records (`ADR-*`) in `specs/architecture/` using `templates/architecture/`, ensuring every `CMP-*` cites `implements-use-cases` (`UC-*`) and `satisfies-requirements` (`FR-*`, `QR-*`, `SEC-REQ-*`, `PRIV-REQ-*`).\n3. Inspect third-party stack choices against `license-policy.yaml` via `verify_licenses` and subprocessors against `privacy-policy.yaml` via `verify_privacy`.\n4. **Technical Security & Privacy Feedback Loop**: If new infrastructure, persistence, LLM, or auth decisions introduce attack vectors or PII flows, return to `agent-threat-modeler` \u2794 `agent-privacy-officer` to add technical mitigations before coding.\n\n### Checkpoint 1 (Inception Design Checkpoint): `agent-auditor` $\\parallel$ `agent-adversary`\n1. Concurrently invoke `agent-auditor` (evaluating YAGNI, architecture bloat, interface contracts) and `agent-adversary` (simulating SPOFs, race conditions, unhandled threat scenarios) in isolated context windows over all Phase 0 deliverables.\n2. Consolidate findings and remediate in authoring agents (max 2 correction rounds).\n3. **Human Approval Gate**: Present the comprehensive Inception model for Human PO & Tech Lead sign-off.\n\n### Step 5: Release Milestone & Topological Wave SDD Plan (`1 UC-* = 1 CHG-*`)\n1. **Open Release Milestone (`Tier 2: release/v1.0.0` or Streamlined `main`)**: Group approved MVP Use Cases (`UC-001`, `UC-002`, ...) and visualize execution plan.\n2. **Decompose into Topological Waves (DAG Parallelism)**:\n - **Wave 0 \u2014 Foundational Core & Executable Presentation Host (Sequential)**: Scaffold `CHG-001` via [`aisdlc-increment`](../aisdlc-increment/SKILL.md) to establish domain core, shared contracts, auth/config, and the runnable presentation host.\n - **Waves 1..N \u2014 Orthogonal End-to-End Vertical Slices (Parallel Multi-Agent)**: Once Wave 0 contracts are merged, execute independent `CHG-*` increments (`1 UC-* = 1 CHG-*`) in parallel across isolated branches/worktrees (`feat/CHG-002`, `feat/CHG-003`, ...).\n3. **Release Consolidation**: Once all MVP increments are integrated (`sdd_integrate`), run `verify` (`npx aisdlc verify all`), generate SBOM, compute release KPIs (`kpi_release`), and open the Release PR for final human approval and SemVer tagging (`v1.0.0`).\n\n## Non-Negotiable Guardrails\n- **Clean Context Window Isolation per Specialist Agent (Cross-IDE)**: Never execute two distinct specialist roles in the same conversation context window. Always spawn each specialist in a fresh isolated subagent context that reads state strictly from disk.\n- **2-Checkpoint Quality & Adversarial Protocol**: Quality auditing and adversarial testing are concentrated at the completion of Inception design and Pre-PR implementation, avoiding micro-step overhead.\n- **FORBIDDEN Library-Only MVP for Human-Facing Products**: Whenever a product defines human actors (`ACT-*`), no agent may scope the MVP as headless class libraries without an executable presentation host.\n- **FORBIDDEN Greenfield Monolith (`1 UC-* = 1 CHG-*`)**: Never bundle the entire product or multiple `UC-*` into a single SDD change (`CHG-001`). Parallelism is achieved by running **multiple bounded `CHG-*` concurrently** on separate branches/worktrees.\n- Never invoke `sdd_change_new` or write application code in `src/` on a Greenfield project before `ARCH-INTRO-001`, `agent-expert-user` MVP validation, and at least one `UC-*` and `FR-*` exist.\n- All newly drafted specifications must start with `status: draft`.'
18930
+ body: '## Purpose & Trigger\nUse this skill when starting a **brand-new software project from scratch (Greenfield)** or when `specs/product/` has no canonical baseline yet. It coordinates the sequential execution of AI-SDLC MCP/CLI tools and specialized role agents so no code is written before product vision, security enclaves, privacy-by-design controls, and architecture contracts exist.\n\n## Consolidated Inception Quality & Adversarial Checkpoint\nAcross Phase 0 and Inception, quality auditing and adversarial stress-testing are concentrated at the completion of Inception design (or after product shaping):\n- **Concurrent Inspection**: Concurrently invoke [`agent-auditor`](../agent-auditor/SKILL.md) (evaluating YAGNI, structural debt, and simplification) and [`agent-adversary`](../agent-adversary/SKILL.md) (stress-testing logic traps, SPOFs, attack vectors, or broken invariants) in clean, isolated context windows.\n- **Non-Invasive Review**: Neither auditor nor adversary modifies deliverables directly; both deliver structured reports citing canonical IDs and SHA-256 digests.\n- **Consolidated Remediation**: Consolidate findings and emit the Workflow Handoff back to authoring agents to resolve blocking defects and apply simplifications (max 2 correction rounds).\n- **Anti-Ping-Pong Guardrail**: Bounded strictly to maximum **1 correction round**. If non-blocking advisories remain, proceed to the downstream phase; if blocking defects persist, escalate immediately to the Human Tech Lead.\n\n## End-to-End Execution Playbook\n\n### Step 1: Repository Turnkey Initialization\n1. If the workspace has not been initialized with AI-SDLC schemas, policies, and templates, run MCP tool `new` (or CLI `npx @aisdlc/cli init`).\n2. Install the Git telemetry hook via `npx aisdlc git hook install` (`pnpm run git:hook:install`).\n3. Verify `quality-policy.yaml`, `license-policy.yaml`, and `privacy-policy.yaml` are present in the repository root.\n\n### Step 2: Phase 0 Product Inception (`agent-product-analyst`)\n1. Delegate to or adopt [`agent-product-analyst`](../agent-product-analyst/SKILL.md).\n2. **Iterative Discovery Interview (Up to 15 Questions or Until Product Scope is 100% Clear)**: Before generating artifacts, clarify with the human Product Owner in rounds of 3\u20135 questions:\n - Core mission statement and business problem.\n - Primary actors (`ACT-*`) and external systems.\n - **Target Interaction & Presentation Modality (`CON-*` / `ARCH-INTRO-001`)**: Explicitly define at inception how human actors will interact with the MVP (e.g., **Web UI**, **Desktop GUI**, **Interactive Console/TUI/CLI**, **Mobile App**, or **Headless API/SDK** if actors are exclusively external systems). Never assume a headless class library when human actors exist.\n - **Delivery & Deployment Model (`ARCH-INTRO-001` / `CON-*` / `QR-*`)**: Clarify in business terms how the product will be delivered and operated (Cloud SaaS, Self-Hosted/On-Premise, Local Desktop/CLI binary, or Library/SDK package) along with any data-residency or availability requirements.\n - **Modern Aesthetic & Design System Standard (`CON-UI-*` / `ARCH-INTRO-001`)**: Explicitly define a modern, visually attractive styling standard adapted to the chosen presentation modality: (1) **Web UI**: modern responsive layouts using Bootstrap 5 utility classes and components (`card`, `table table-hover`, `badge`, `alert alert-*`, responsive grid) or modern equivalents, (2) **Desktop GUI**: modern clean design (rounded corners, elevated panels, padding, consistent typography) avoiding raw legacy unstyled windows, (3) **Console / TUI**: rich terminal interface with ANSI colors, status badges, formatted tables, and progress indicators (e.g., Spectre.Console, Rich, Ink, or Chalk/Picocolors).\n - **User Journeys (`JRN-*`) to Generate (Plain-Language Elicitation)**: Ask in simple, everyday language which end-to-end user journeys to model, explicitly indicating the 5 pieces of information needed to build each journey properly: (1) protagonist user (`persona` / `ACT-*`) and their main goal, (2) step-by-step stages from start to finish (`stages`), (3) interaction screens/channels at each stage (`touchpoints`), (4) current obstacles or pain points (`pain-points`), and (5) concrete system capabilities/use cases (`related-use-cases` / `UC-*`).\n - Essential MVP capabilities (`UC-*`) vs. future roadmap, ensuring **foundational entity CRUD / master data workflows** are explicitly included in the MVP.\n - Top 3\u20135 quality goals (`QR-*`) and regulatory/technical constraints (`CON-*`).\n3. **Enterprise & Capability Vision**: Create `specs/architecture/ARCH-INTRO-001.md` (`status: draft`, `naf-perspective: "Enterprise & Capability"`) using `templates/architecture/introduction-and-goals.template.md`, explicitly recording the chosen presentation/UI modality.\n4. **ProductShape Baseline**: Derive initial draft artifacts in `specs/product/`:\n - Actors (`ACT-*`), User Journeys (`JRN-*`), Use Cases (`UC-*`), Business Rules (`BR-*`), Functional Requirements (`FR-*` with mandatory `@nominal`, `@boundary`, `@invalid` Gherkin blocks), and Quality Requirements (`QR-*`).\n - **Vertical Slice Completeness Rule**: Every human-triggered `UC-*` in the MVP must specify observable user interaction through the agreed presentation modality and state persistence.\n5. Validate schemas and duplicates via MCP tools `verify_schemas` and `verify_duplicates` (or `npx aisdlc check --fix`).\n6. **Mandatory Upstream UX & MVP Boundary Gate (`agent-expert-user`)**: Invoke [`agent-expert-user`](../agent-expert-user/SKILL.md) in **Design Mode** to stress-test the proposed workflows, enforce strict MVP boundaries, reject any headless/library-only MVP when human actors exist, verify master-data CRUD prerequisites, and separate core MVP `UC-*` from future roadmap backlog.\n\n### Step 3: Shift-Left Cybersecurity & Privacy-by-Design (`agent-threat-modeler` \u2794 `agent-privacy-officer`)\n1. Delegate to or adopt [`agent-threat-modeler`](../agent-threat-modeler/SKILL.md).\n2. Analyze every `UC-*` and `FR-*` using STRIDE and OWASP ASVS to create in `specs/security/`:\n - Threat Actors (`ACT-THREAT-*`), Abuse Cases (`ABUSE-*` targeting `UC-*`), and Security Requirements (`SEC-REQ-*` with `@security @mitigation` negative Gherkin scenarios and `SEC-ENC-*` Zero Trust enclave bindings).\n3. Hand off to [`agent-privacy-officer`](../agent-privacy-officer/SKILL.md) to apply LINDDUN and GDPR/LOPDGDD/ISO 27701 in `specs/privacy/`:\n - Personal Data Assets (`DATA-ASSET-*`), GDPR Art. 30 Records of Processing (`PRIV-ROPA-*`), and Privacy Requirements (`PRIV-REQ-*` with `@privacy @gdpr` Gherkin scenarios).\n4. Run `verify_schemas` and `verify_privacy` (`npx aisdlc verify privacy`).\n\n### Step 4: Modular Systems Architecture (`agent-system-architect`)\n1. Delegate to or adopt [`agent-system-architect`](../agent-system-architect/SKILL.md).\n2. Define building blocks (`CMP-*`), Deployment Topology (`ARCH-DEP-001` translating the delivery model into execution nodes `RES-*` and enclaves `SEC-ENC-*`), and Architectural Decision Records (`ADR-*`) in `specs/architecture/` using `templates/architecture/`, ensuring every `CMP-*` cites `implements-use-cases` (`UC-*`) and `satisfies-requirements` (`FR-*`, `QR-*`, `SEC-REQ-*`, `PRIV-REQ-*`).\n3. Inspect third-party stack choices against `license-policy.yaml` via `verify_licenses` and subprocessors against `privacy-policy.yaml` via `verify_privacy`.\n4. **Technical Security & Privacy Feedback Loop**: If new infrastructure, persistence, LLM, or auth decisions introduce attack vectors or PII flows, return to `agent-threat-modeler` \u2794 `agent-privacy-officer` to add technical mitigations before coding.\n\n### Checkpoint 1 (Inception Design Checkpoint): `agent-auditor` $\\parallel$ `agent-adversary`\n1. Concurrently invoke `agent-auditor` (evaluating YAGNI, architecture bloat, interface contracts) and `agent-adversary` (simulating SPOFs, race conditions, unhandled threat scenarios) in isolated context windows over all Phase 0 deliverables.\n2. Consolidate findings and remediate in authoring agents (max 2 correction rounds).\n3. **Human Approval Gate**: Present the comprehensive Inception model for Human PO & Tech Lead sign-off.\n\n### Step 5: Release Milestone & Topological Wave SDD Plan (`1 UC-* = 1 CHG-*`)\n1. **Open Release Milestone (`Tier 2: release/v1.0.0` or Streamlined `main`)**: Group approved MVP Use Cases (`UC-001`, `UC-002`, ...) and visualize execution plan.\n2. **Decompose into Topological Waves (DAG Parallelism)**:\n - **Wave 0 \u2014 Foundational Core, Executable Presentation Host & CI/CD (`agent-devops`) (Sequential)**: Scaffold `CHG-001` via [`aisdlc-increment`](../aisdlc-increment/SKILL.md) to establish domain core, shared contracts, auth/config, and the runnable presentation host. Invoke [`agent-devops`](../agent-devops/SKILL.md) to clarify the technical CI/CD & packaging strategy (CI Quality Gates, Docker/GHCR, package registry, or PaaS/Cloud) and scaffold `.github/workflows/` and container manifests without modifying `src/`.\n - **Waves 1..N \u2014 Orthogonal End-to-End Vertical Slices (Parallel Multi-Agent)**: Once Wave 0 contracts are merged, execute independent `CHG-*` increments (`1 UC-* = 1 CHG-*`) in parallel across isolated branches/worktrees (`feat/CHG-002`, `feat/CHG-003`, ...).\n3. **Release Consolidation (`agent-devops`)**: Once all MVP increments are integrated (`sdd_integrate`), run `verify` (`npx aisdlc verify all`), generate SBOM, compute release KPIs (`kpi_release`), verify release/publishing workflows via `agent-devops`, and open the Release PR for final human approval and SemVer tagging (`v1.0.0`).\n\n## Non-Negotiable Guardrails\n- **Clean Context Window Isolation per Specialist Agent (Cross-IDE)**: Never execute two distinct specialist roles in the same conversation context window. Always spawn each specialist in a fresh isolated subagent context that reads state strictly from disk.\n- **2-Checkpoint Quality & Adversarial Protocol**: Quality auditing and adversarial testing are concentrated at the completion of Inception design and Pre-PR implementation, avoiding micro-step overhead.\n- **FORBIDDEN Library-Only MVP for Human-Facing Products**: Whenever a product defines human actors (`ACT-*`), no agent may scope the MVP as headless class libraries without an executable presentation host.\n- **FORBIDDEN Greenfield Monolith (`1 UC-* = 1 CHG-*`)**: Never bundle the entire product or multiple `UC-*` into a single SDD change (`CHG-001`). Parallelism is achieved by running **multiple bounded `CHG-*` concurrently** on separate branches/worktrees.\n- Never invoke `sdd_change_new` or write application code in `src/` on a Greenfield project before `ARCH-INTRO-001`, `agent-expert-user` MVP validation, and at least one `UC-*` and `FR-*` exist.\n- All newly drafted specifications must start with `status: draft`.'
18761
18931
  },
18762
18932
  {
18763
18933
  id: "aisdlc-legacy-onboarding",
@@ -18765,7 +18935,7 @@ var LIFECYCLE_SKILL_TEMPLATES = [
18765
18935
  description: "Orchestrate progressive AI-SDLC adoption and Brownfield retro-inception on existing or legacy repositories without breaking production code, reverse-engineering architecture (ARCH-INTRO-*, CMP-*), 2-checkpoint auditor/adversary verification, and establishing baseline quality, security, and license audits before new SDD increments.",
18766
18936
  references: "[`process/02_product_definition.md`](../../process/02_product_definition.md), [`process/05_architecture_arc42_nafv4.md`](../../process/05_architecture_arc42_nafv4.md), [`process/06_spec_driven_development.md`](../../process/06_spec_driven_development.md), [`process/10_quality_management_and_release_gates.md`](../../process/10_quality_management_and_release_gates.md), and [`process/09_agent_protocols.md`](../../process/09_agent_protocols.md).",
18767
18937
  globs: "architecture/**, specs/**, src/**, packages/**",
18768
- body: "## Purpose & Trigger\nUse this skill when onboarding an **existing codebase (Brownfield / Legacy)** that was not built with AI-SDLC. It establishes non-disruptive governance, maps existing code into canonical specifications, inventories debt across all 12 Quality Gates, and creates baseline specifications (`specs/product/`, `specs/architecture/`) before new features or refactorings are introduced.\n\n## Retro-Inception Quality & Adversarial Checkpoint\nAcross Brownfield retro-inception, quality auditing and adversarial stress-testing are concentrated at the completion of retro-inception mapping:\n- **Concurrent Inspection**: Concurrently invoke [`agent-auditor`](../agent-auditor/SKILL.md) (evaluating YAGNI, over-modeling, and debt priorities) and [`agent-adversary`](../agent-adversary/SKILL.md) (uncovering undocumented invariants, hidden failure modes, and security gaps) in clean, isolated context windows.\n- **Non-Invasive Review**: Neither auditor nor adversary modifies deliverables directly; both deliver structured reports citing canonical IDs and SHA-256 digests.\n- **Consolidated Remediation**: Consolidate findings and emit the Workflow Handoff back to authoring agents to resolve blocking defects and apply simplifications (max 2 correction rounds).\n- **Anti-Ping-Pong Guardrail**: Bounded strictly to maximum **1 correction round**. If non-blocking advisories remain, proceed to characterization; if blocking defects persist, escalate to the Human Tech Lead.\n\n## End-to-End Execution Playbook\n\n### Step 1: Turnkey Repository Scaffolding (Non-Destructive)\n1. Initialize AI-SDLC configuration without overwriting existing application files using `npx @aisdlc/cli init` (or MCP tool `new`).\n2. Install the Git telemetry hook via `npx aisdlc git hook install` (`pnpm run git:hook:install`).\n3. Commit initial AI-SDLC schemas and policies (`.github/`, `schemas/`, `templates/`, `*-policy.yaml`).\n\n### Step 2: Automated Baseline Audit & Debt Inventory (Read-Only)\nBefore modifying any code or creating SDD changes, run diagnostic verifiers to quantify existing technical, legal, privacy, and security debt:\n1. **License & Dependency Audit (`agent-compliance-checker`)**: Run MCP tool `verify_licenses` (`npx aisdlc verify licenses`). Identify any viral (`GPL`/`AGPL`) or commercial (`BSL`/`SSPL`) dependencies already present in the lockfile and document exceptions or remediation plans.\n2. **Shift-Left Security Scan (`agent-security-auditor`)**: Run MCP tool `verify_security` (`npx aisdlc verify security`) to detect hardcoded secrets (Gate 11) or OWASP SAST vulnerabilities in legacy files.\n3. **Privacy & PII Scan (`agent-privacy-officer`)**: Run MCP tool `verify_privacy` (`npx aisdlc verify privacy`) to detect PII in logs/telemetry or hardcoded real PII in legacy tests/seeds.\n4. **AST Code Quality Baseline (`agent-code-reviewer`)**: Run MCP tool `report_quality` (`npx aisdlc report quality`) to generate `reports/QUALITY_REPORT.md` and identify legacy hotspots exceeding Cyclomatic Complexity ($\\le 10$), Cognitive Complexity ($\\le 15$), or Maintainability Index ($\\ge 50$).\n\n### Step 3: Brownfield Retro-Inception (`agent-system-architect` & `agent-product-analyst`)\nInstead of attempting to document 100% of a legacy monolith upfront, apply **bounded retro-inception** focused on the system boundary and the domain areas under active evolution:\n1. **System Vision & Context (`ARCH-INTRO-001`)**: Use [`agent-product-analyst`](../agent-product-analyst/SKILL.md) to document the current system's mission, primary actors (`ACT-*`), and top quality goals (`QR-*`) in `specs/architecture/ARCH-INTRO-001.md`.\n2. **As-Is Component Mapping (`CMP-*` & `ADR-*`)**: Use [`agent-system-architect`](../agent-system-architect/SKILL.md) to map existing core modules/services into `specs/architecture/CMP-*.md` and capture historical architectural constraints (`CON-*`, `ADR-*`).\n3. **Core Use Cases Extraction (`UC-*`, `FR-*`)**: Extract canonical `UC-*` and `FR-*` artifacts in `specs/product/` for the specific bounded context or module that will be modified or extended next, including Gherkin acceptance scenarios reflecting current expected behavior (characterization specs).\n4. **Threat & Privacy Boundary Mapping (`agent-threat-modeler` \u2794 `agent-privacy-officer`)**: Map existing trust zones (`SEC-ENC-*`), active threat vectors (`ACT-THREAT-*`, `ABUSE-*`, `SEC-REQ-*`), and personal data inventories (`DATA-ASSET-*`, `PRIV-ROPA-*`, `PRIV-REQ-*`) on the target module.\n5. **Retro-Inception Checkpoint (`agent-auditor` $\\parallel$ `agent-adversary`)**: Concurrently inspect reverse-engineered artifacts, evaluate fidelity vs. unnecessary modeling overhead, and consolidate fixes.\n\n### Step 4: Characterization Testing & Synchronization\n1. Run MCP tool `sdd_check_fix` (`npx aisdlc check --fix`) to extract `.feature` files and compute canonical SHA-256 digests.\n2. Run `verify_schemas` and `verify_pdac` to confirm the reverse-engineered baseline graph is structurally valid and drift-free.\n\n### Step 5: Transition to Governed SDD Increments (Boy Scout / Strangler Rule)\nOnce the target domain's baseline artifacts (`ARCH-INTRO-*`, `UC-*`, `FR-*`, `CMP-*`) are in place, execute all new features, refactorings, or bugfixes via [`aisdlc-increment`](../aisdlc-increment/SKILL.md).\n\n## Non-Negotiable Guardrails\n- **Clean Context Window Isolation per Specialist Agent (Cross-IDE)**: Never execute two distinct specialist roles in the same conversation context window. Always spawn each specialist in a fresh isolated subagent context that reads state strictly from disk.\n- **2-Checkpoint Quality & Adversarial Protocol**: Concentrated review at the retro-inception boundary and before PR delivery prevents process friction while maintaining rigorous defect interception.\n- **Zero Drive-By Rewrites**: Never mass-refactor untouched legacy modules during onboarding. Apply the Strangler / Boy Scout rule: bring touched functions into compliance with `quality-policy.yaml` incrementally via governed SDD tasks (`TSK-*`).\n- **Characterization First**: Never alter legacy business logic without first capturing its current behavior in an `FR-*` Gherkin specification and a verifiable test suite (`agent-qa-engineer`).\n- **Immediate Secret Remediation**: If Step 2 (`verify_security`) uncovers leaked credentials (exit code 4), halt feature work and remediate/rotate secrets immediately."
18938
+ body: "## Purpose & Trigger\nUse this skill when onboarding an **existing codebase (Brownfield / Legacy)** that was not built with AI-SDLC. It establishes non-disruptive governance, maps existing code into canonical specifications, inventories debt across all 12 Quality Gates, and creates baseline specifications (`specs/product/`, `specs/architecture/`) before new features or refactorings are introduced.\n\n## Retro-Inception Quality & Adversarial Checkpoint\nAcross Brownfield retro-inception, quality auditing and adversarial stress-testing are concentrated at the completion of retro-inception mapping:\n- **Concurrent Inspection**: Concurrently invoke [`agent-auditor`](../agent-auditor/SKILL.md) (evaluating YAGNI, over-modeling, and debt priorities) and [`agent-adversary`](../agent-adversary/SKILL.md) (uncovering undocumented invariants, hidden failure modes, and security gaps) in clean, isolated context windows.\n- **Non-Invasive Review**: Neither auditor nor adversary modifies deliverables directly; both deliver structured reports citing canonical IDs and SHA-256 digests.\n- **Consolidated Remediation**: Consolidate findings and emit the Workflow Handoff back to authoring agents to resolve blocking defects and apply simplifications (max 2 correction rounds).\n- **Anti-Ping-Pong Guardrail**: Bounded strictly to maximum **1 correction round**. If non-blocking advisories remain, proceed to characterization; if blocking defects persist, escalate to the Human Tech Lead.\n\n## End-to-End Execution Playbook\n\n### Step 1: Turnkey Repository Scaffolding (Non-Destructive)\n1. Initialize AI-SDLC configuration without overwriting existing application files using `npx @aisdlc/cli init` (or MCP tool `new`).\n2. Install the Git telemetry hook via `npx aisdlc git hook install` (`pnpm run git:hook:install`).\n3. Invoke [`agent-devops`](../agent-devops/SKILL.md) to audit existing CI/CD workflows and container manifests and integrate `aisdlc verify all` into the pipeline without breaking legacy deployments.\n4. Commit initial AI-SDLC schemas and policies (`.github/`, `schemas/`, `templates/`, `*-policy.yaml`).\n\n### Step 2: Automated Baseline Audit & Debt Inventory (Read-Only)\nBefore modifying any code or creating SDD changes, run diagnostic verifiers to quantify existing technical, legal, privacy, and security debt:\n1. **License & AST Code Quality Baseline (`agent-auditor`)**: Run MCP tools `verify_licenses` (`npx aisdlc verify licenses`) and `report_quality` (`npx aisdlc report quality`) to identify viral (`GPL`/`AGPL`) or commercial (`BSL`/`SSPL`) dependencies and legacy hotspots exceeding Cyclomatic Complexity ($\\le 10$), Cognitive Complexity ($\\le 15$), or Maintainability Index ($\\ge 50$).\n2. **Shift-Left Security Scan (`agent-adversary`)**: Run MCP tool `verify_security` (`npx aisdlc verify security`) to detect hardcoded secrets (Gate 11) or OWASP SAST vulnerabilities in legacy files.\n3. **Privacy & PII Scan (`agent-privacy-officer`)**: Run MCP tool `verify_privacy` (`npx aisdlc verify privacy`) to detect PII in logs/telemetry or hardcoded real PII in legacy tests/seeds.\n\n### Step 3: Brownfield Retro-Inception (`agent-system-architect` & `agent-product-analyst`)\nInstead of attempting to document 100% of a legacy monolith upfront, apply **bounded retro-inception** focused on the system boundary and the domain areas under active evolution:\n1. **System Vision & Context (`ARCH-INTRO-001`)**: Use [`agent-product-analyst`](../agent-product-analyst/SKILL.md) to document the current system's mission, primary actors (`ACT-*`), and top quality goals (`QR-*`) in `specs/architecture/ARCH-INTRO-001.md`.\n2. **As-Is Component Mapping (`CMP-*` & `ADR-*`)**: Use [`agent-system-architect`](../agent-system-architect/SKILL.md) to map existing core modules/services into `specs/architecture/CMP-*.md` and capture historical architectural constraints (`CON-*`, `ADR-*`).\n3. **Core Use Cases Extraction (`UC-*`, `FR-*`)**: Extract canonical `UC-*` and `FR-*` artifacts in `specs/product/` for the specific bounded context or module that will be modified or extended next, including Gherkin acceptance scenarios reflecting current expected behavior (characterization specs).\n4. **Threat & Privacy Boundary Mapping (`agent-threat-modeler` \u2794 `agent-privacy-officer`)**: Map existing trust zones (`SEC-ENC-*`), active threat vectors (`ACT-THREAT-*`, `ABUSE-*`, `SEC-REQ-*`), and personal data inventories (`DATA-ASSET-*`, `PRIV-ROPA-*`, `PRIV-REQ-*`) on the target module.\n5. **Retro-Inception Checkpoint (`agent-auditor` $\\parallel$ `agent-adversary`)**: Concurrently inspect reverse-engineered artifacts, evaluate fidelity vs. unnecessary modeling overhead, and consolidate fixes.\n\n### Step 4: Characterization Testing & Synchronization\n1. Run MCP tool `sdd_check_fix` (`npx aisdlc check --fix`) to extract `.feature` files and compute canonical SHA-256 digests.\n2. Run `verify_schemas` and `verify_pdac` to confirm the reverse-engineered baseline graph is structurally valid and drift-free.\n\n### Step 5: Transition to Governed SDD Increments (Boy Scout / Strangler Rule)\nOnce the target domain's baseline artifacts (`ARCH-INTRO-*`, `UC-*`, `FR-*`, `CMP-*`) are in place, execute all new features, refactorings, or bugfixes via [`aisdlc-increment`](../aisdlc-increment/SKILL.md).\n\n## Non-Negotiable Guardrails\n- **Clean Context Window Isolation per Specialist Agent (Cross-IDE)**: Never execute two distinct specialist roles in the same conversation context window. Always spawn each specialist in a fresh isolated subagent context that reads state strictly from disk.\n- **2-Checkpoint Quality & Adversarial Protocol**: Concentrated review at the retro-inception boundary and before PR delivery prevents process friction while maintaining rigorous defect interception.\n- **Zero Drive-By Rewrites**: Never mass-refactor untouched legacy modules during onboarding. Apply the Strangler / Boy Scout rule: bring touched functions into compliance with `quality-policy.yaml` incrementally via governed SDD tasks (`TSK-*`).\n- **Characterization First**: Never alter legacy business logic without first capturing its current behavior in an `FR-*` Gherkin specification and a verifiable test suite (`agent-qa-engineer`).\n- **Immediate Secret Remediation**: If Step 2 (`verify_security`) uncovers leaked credentials (exit code 4), halt feature work and remediate/rotate secrets immediately."
18769
18939
  },
18770
18940
  {
18771
18941
  id: "aisdlc-increment",
@@ -18773,7 +18943,7 @@ var LIFECYCLE_SKILL_TEMPLATES = [
18773
18943
  description: "Orchestrate the complete Spec-Driven Development (SDD) lifecycle for bounded feature increments, enhancements, and bugfixes (CHG-* / TSK-*), from upstream requirement derivation and streamlined Git branching through Red-Green-Refactor TDD, 2-checkpoint transversal auditor/adversary verification, all 12 Quality Gates, and canonical baseline integration.",
18774
18944
  references: "[`process/06_spec_driven_development.md`](../../process/06_spec_driven_development.md), [`process/08_citation_contract_and_drift.md`](../../process/08_citation_contract_and_drift.md), [`process/10_quality_management_and_release_gates.md`](../../process/10_quality_management_and_release_gates.md), [`process/11_git_branching_and_lifecycle.md`](../../process/11_git_branching_and_lifecycle.md), and [`process/09_agent_protocols.md`](../../process/09_agent_protocols.md).",
18775
18945
  globs: "specs/changes/**, src/**, packages/**, tests/**",
18776
- body: '## Purpose & Trigger\nUse this skill for **every evolutionary increment (new feature, enhancement, refactoring, or bugfix)** on a project that already has an AI-SDLC baseline. It enforces strict 360\xB0 traceability from upstream ProductShape (`UC-*`, `FR-*`) through SDD (`CHG-*`, `HOF-*`, `TSK-*`), TDD implementation, the 12 Quality Gates, and baseline promotion under the **streamlined 2-checkpoint architecture**.\n\n## End-to-End Execution Playbook\n\n### Step 1: Upstream Product, Security & Privacy Delta (`agent-product-analyst`, `agent-threat-modeler` & `agent-privacy-officer`)\n1. Inspect active changes via MCP tool `get_active_handoff` and verify whether the target Use Case (`UC-*`) or Requirement (`FR-*`) already exists in `specs/product/`.\n2. If the increment introduces new behavior or modifies business rules:\n - Use [`agent-product-analyst`](../agent-product-analyst/SKILL.md) to create or update the `UC-*`, `BR-*`, and `FR-*` (with `@nominal`, `@boundary`, `@invalid` Gherkin scenarios).\n - Run MCP tool `verify_duplicates` (`npx aisdlc verify duplicates`) to block lexical or functional collisions early.\n - Use [`agent-threat-modeler`](../agent-threat-modeler/SKILL.md) to model any new `ABUSE-*` and `SEC-REQ-*` mitigations.\n - Hand off to [`agent-privacy-officer`](../agent-privacy-officer/SKILL.md) to model any personal data assets (`DATA-ASSET-*`), GDPR Art. 30 processing activities (`PRIV-ROPA-*`), and privacy requirements (`PRIV-REQ-*`).\n3. Run `sdd_check_fix` (`npx aisdlc check --fix`) to sync Gherkin `.feature` files and validate schemas.\n\n### Step 2: SDD Change Scaffolding & Architectural Design (`agent-system-architect`)\n1. Scaffold the bounded change package and its cryptographic `handoff.yaml` sidecar (`HOF-*`) targeting **a single Use Case (`1 UC-* = 1 CHG-*`)** using MCP tool `sdd_change_new` (or CLI `npx aisdlc change new "<Title>" --from <UC-ID> --profile <patch|standard|critical>`).\n2. Use [`agent-system-architect`](../agent-system-architect/SKILL.md) to complete `specs/changes/active/<chg-id>/design.md` and `specs/architecture/CMP-*.md`:\n - Structure `CMP-*` and `design.md` around **Modular & Hexagonal Architecture (Ports & Adapters)** (Domain/Application Core + Inbound/Outbound Ports) and define **Contract-First** shared interfaces/DTOs/schemas when spanning Frontend and Backend.\n - Map 100% of `handoff.yaml` requirements and components to atomic tasks (`TSK-*`) in `tasks.md` with explicit `autonomy-mode` (`AUTONOMOUS`, `HUMAN_REVIEW_PLAN`, `HIGH_RISK_MANUAL`, `AMBIGUOUS`).\n3. Run `verify_governance` and `verify_friction` to validate task governance, 100% design/handoff scope coverage, and anti-monolith limits (`maxUseCasesPerChange = 1`).\n\n### Checkpoint 1: Specification & Design Checkpoint (`agent-auditor` $\\parallel$ `agent-adversary`)\n1. Concurrently invoke `agent-auditor` (evaluating YAGNI, interface bloat, and task completeness) and `agent-adversary` (probing contradictions, race conditions, and architecture SPOFs) in clean, isolated context windows over the combined upstream deliverables.\n2. Consolidate findings and remediate any blocking defects (max 2 correction rounds).\n3. **Human Approval Gate 1**: Present the specification and architectural design for Human Tech Lead / PO sign-off before proceeding to code.\n\n### Step 3: Streamlined Git Branch Navigation & Multi-Agent Parallelism\n1. Navigate to the working branch using `npx aisdlc git checkout <TSK-ID>` (`pnpm run git:checkout <TSK-ID>`).\n - **Default Streamlined Mode**: Switches to the working branch `feat/<CHG-ID>-<slug>` (created from `main`).\n - Granular task traceability is maintained via commit trailers (`Task-ID: TSK-*`, `Parent-Ref: CHG-*`) and commit scopes (`feat(TSK-001): ...`), enabling per-task rework KPIs without branch explosion.\n2. **Parallel Agent Execution Rules (`--parallel`)**:\n - When concurrent multi-agent implementation is configured (e.g. Backend adapter $\\parallel$ Frontend UI), `aisdlc git checkout <TSK-ID> --parallel` creates isolated worktrees (`task/<PARENT-ID>/<TSK-ID>-<slug>`).\n\n### Step 4: Red Phase \u2014 Failing Test Suites (`agent-qa-engineer`)\n1. Delegate to or adopt [`agent-qa-engineer`](../agent-qa-engineer/SKILL.md).\n2. Author FAILING (red) BDD/Gherkin step definitions, integration/contract tests, and mandatory E2E/UI tests (evaluating Happy Path, Sad Path, and Boundary Values for every interactive UI element, plus `UC-*` alternative/exception flows) in `tests/`.\n3. Commit failing test suites with trailer `Task-ID: TSK-YYY`.\n4. Run `verify_testing` (`npx aisdlc verify testing`) to confirm requirement test coverage before writing production code.\n\n### Step 5: Green & Refactor Phase \u2014 Surgical Implementation (`agent-developer`)\n1. Delegate to or adopt [`agent-developer`](../agent-developer/SKILL.md).\n2. Execute the **Mandatory 4-Step Implementation Order**:\n - (1) Modular & Hexagonal Architecture (Ports & Adapters) boundaries, (2) Inter-module interfaces/ports first, (3) Concrete component implementation (zero fake-wiring; all 4 UI states `Loading`, `Empty`, `Error`, `Nominal`), (4) Exhaustive per-function unit tests in `tests/unit/` (Happy Path, Sad Path, Boundary, Null/Empty).\n3. Commit implementations with trailer `Task-ID: TSK-YYY`.\n4. Verify any new dependency against `license-policy.yaml` via `verify_licenses` and PII handling against `privacy-policy.yaml` via `verify_privacy`.\n5. Run `sdd_check_fix` (`npx aisdlc check --fix`) and `verify_quality` (`npx aisdlc verify quality`) until Cyclomatic Complexity $\\le 10$, Cognitive $\\le 15$, Maintainability $\\ge 50$, and Function Length $\\le 40$ lines pass with zero violations.\n6. Run `verify` (`npx aisdlc verify all`) confirming all **12 Quality Gates** pass green.\n\n### Checkpoint 2: Implementation & Pre-PR Checkpoint (`agent-auditor` $\\parallel$ `agent-adversary`)\n1. **Functional Validation (`agent-expert-user`)**: Validate live runtime behavior against `UC-*` and `FR-*` criteria (including `0` browser `console.error`/`pageerror` on UI changes).\n2. Concurrently invoke `agent-auditor` (verifying Clean Code, SOLID, DRY, AST thresholds, and eliminating unnecessary abstractions) and `agent-adversary` (performing conceptual test mutation to verify QA tests catch defects, and attacking boundary inputs with concrete PoC breaks).\n3. Consolidate findings and remediate in `agent-developer` (max 2 correction rounds).\n4. Run `npx aisdlc verify all` to confirm final green status.\n\n### Step 6: Human PR Sign-Off, Baseline Integration & Release Closure\n1. **Feature Merge (`feat/CHG-*` \u2794 `main` or `release/vX.Y.Z`)**:\n - Present the PR, KPI summary (`kpi_pr` including per-task rework metrics), and autogenerated reports (`reports/QUALITY_REPORT.md`, `reports/TRACEABILITY_MATRIX.md`, `reports/ROPA_INVENTORY.md`) to the human Tech Lead for review and approval (never auto-approve or auto-merge).\n2. **Canonical Baseline Promotion**: Once tasks in `tasks.md` are marked `COMPLETED` and approved, promote the change into the canonical baseline via MCP tool `sdd_integrate` (`npx aisdlc sdd integrate --auto`), which synchronizes the normative text and BDD Gherkin scenarios into `FR-*` / `UC-*` / `SEC-REQ-*` / `PRIV-REQ-*`, bumps minor SemVer when updating active specs, resyncs PDaC SHA-256 digests, promotes `FR-*` to `active`, links `CMP-*`, and archives the change under `specs/changes/completed/` (or `npx aisdlc sdd integrate --all` to consolidate all completed changes).\n3. **Semantic Versioning Promotion**: Tag the merge with the computed SemVer bump (`patch`, `minor`, `major`) and refresh the interactive dashboard (`report_dashboard`).\n\n## Non-Negotiable Guardrails\n- **Clean Context Window Isolation per Specialist Agent (Cross-IDE)**: Never execute two distinct specialist roles (e.g., `agent-qa-engineer` and `agent-developer`, or `agent-developer` and `agent-security-auditor`) in the same conversation context window. In subagent-capable IDEs (Antigravity `invoke_subagent`, Claude Code `Task` / `.claude/agents/`, GitHub Copilot `@agent-*`), always spawn each specialist in a fresh isolated subagent context that reads state strictly from disk (`specs/`, `handoff.yaml`, `get_active_handoff`). In chat-based IDEs (Cursor, Windsurf, Aider), persist all artifacts to disk, emit the Workflow Handoff block, and instruct the user to open a **New Chat** (or `/clear`) before running the next specialist.\n- **2-Checkpoint Quality & Adversarial Protocol**: Enforce transversal quality and red-team checks exclusively at **Checkpoint 1 (Specification & Design)** and **Checkpoint 2 (Implementation & Pre-PR)**. Enforce the **Anti-Ping-Pong Guardrail**: maximum 2 correction rounds per checkpoint; if unresolved blocking defects persist, escalate to the Human Tech Lead.\n- **Single-Use-Case Scope (`1 UC-* = 1 CHG-*`)**: Each SDD change (`CHG-*`) must deliver at most 1 Use Case (`UC-*`). Bundling multiple `UC-*` into one `handoff.yaml` is blocked by `verify_governance` (`Greenfield monolith detected`). Scale throughput via parallel `CHG-*` branches/worktrees, not monolithic changes.\n- **100% Design & Handoff Coverage in `tasks.md`**: Every `CMP-*`, `FR-*`, `SEC-REQ-*`, and `PRIV-REQ-*` declared in `design.md` and `handoff.yaml` must be explicitly assigned to at least one `TSK-*` in `tasks.md`.'
18946
+ body: '## Purpose & Trigger\nUse this skill for **every evolutionary increment (new feature, enhancement, refactoring, or bugfix)** on a project that already has an AI-SDLC baseline. It enforces strict 360\xB0 traceability from upstream ProductShape (`UC-*`, `FR-*`) through SDD (`CHG-*`, `HOF-*`, `TSK-*`), TDD implementation, the 12 Quality Gates, and baseline promotion under the **streamlined 2-checkpoint architecture**.\n\n## End-to-End Execution Playbook\n\n### Step 1: Upstream Product, Security & Privacy Delta (`agent-product-analyst`, `agent-threat-modeler` & `agent-privacy-officer`)\n1. Inspect active changes via MCP tool `get_active_handoff` and verify whether the target Use Case (`UC-*`) or Requirement (`FR-*`) already exists in `specs/product/`.\n2. If the increment introduces new behavior or modifies business rules:\n - Use [`agent-product-analyst`](../agent-product-analyst/SKILL.md) to create or update the `UC-*`, `BR-*`, and `FR-*` (with `@nominal`, `@boundary`, `@invalid` Gherkin scenarios).\n - Run MCP tool `verify_duplicates` (`npx aisdlc verify duplicates`) to block lexical or functional collisions early.\n - Use [`agent-threat-modeler`](../agent-threat-modeler/SKILL.md) to model any new `ABUSE-*` and `SEC-REQ-*` mitigations.\n - Hand off to [`agent-privacy-officer`](../agent-privacy-officer/SKILL.md) to model any personal data assets (`DATA-ASSET-*`), GDPR Art. 30 processing activities (`PRIV-ROPA-*`), and privacy requirements (`PRIV-REQ-*`).\n3. Run `sdd_check_fix` (`npx aisdlc check --fix`) to sync Gherkin `.feature` files and validate schemas.\n\n### Step 2: SDD Change Scaffolding & Architectural Design (`agent-system-architect`)\n1. Scaffold the bounded change package and its cryptographic `handoff.yaml` sidecar (`HOF-*`) targeting **a single Use Case (`1 UC-* = 1 CHG-*`)** using MCP tool `sdd_change_new` (or CLI `npx aisdlc change new "<Title>" --from <UC-ID> --profile <patch|standard|critical>`).\n2. Use [`agent-system-architect`](../agent-system-architect/SKILL.md) to complete `specs/changes/active/<chg-id>/design.md` and `specs/architecture/CMP-*.md`:\n - Structure `CMP-*` and `design.md` around **Modular & Hexagonal Architecture (Ports & Adapters)** (Domain/Application Core + Inbound/Outbound Ports) and define **Contract-First** shared interfaces/DTOs/schemas when spanning Frontend and Backend.\n - Map 100% of `handoff.yaml` requirements and components to atomic tasks (`TSK-*`) in `tasks.md` with explicit `autonomy-mode` (`AUTONOMOUS`, `HUMAN_REVIEW_PLAN`, `HIGH_RISK_MANUAL`, `AMBIGUOUS`).\n3. Run `verify_governance` and `verify_friction` to validate task governance, 100% design/handoff scope coverage, and anti-monolith limits (`maxUseCasesPerChange = 1`).\n\n### Checkpoint 1: Specification & Design Checkpoint (`agent-auditor` $\\parallel$ `agent-adversary`)\n1. Concurrently invoke `agent-auditor` (evaluating YAGNI, interface bloat, and task completeness) and `agent-adversary` (probing contradictions, race conditions, and architecture SPOFs) in clean, isolated context windows over the combined upstream deliverables.\n2. Consolidate findings and remediate any blocking defects (max 2 correction rounds).\n3. **Human Approval Gate 1**: Present the specification and architectural design for Human Tech Lead / PO sign-off before proceeding to code.\n\n### Step 3: Streamlined Git Branch Navigation & Multi-Agent Parallelism\n1. Navigate to the working branch using `npx aisdlc git checkout <TSK-ID>` (`pnpm run git:checkout <TSK-ID>`).\n - **Default Streamlined Mode**: Switches to the working branch `feat/<CHG-ID>-<slug>` (created from `main`).\n - Granular task traceability is maintained via commit trailers (`Task-ID: TSK-*`, `Parent-Ref: CHG-*`) and commit scopes (`feat(TSK-001): ...`), enabling per-task rework KPIs without branch explosion.\n2. **Parallel Agent Execution Rules (`--parallel`)**:\n - When concurrent multi-agent implementation is configured (e.g. Backend adapter $\\parallel$ Frontend UI), `aisdlc git checkout <TSK-ID> --parallel` creates isolated worktrees (`task/<PARENT-ID>/<TSK-ID>-<slug>`).\n\n### Step 4: Red Phase \u2014 Failing Test Suites (`agent-qa-engineer`)\n1. Delegate to or adopt [`agent-qa-engineer`](../agent-qa-engineer/SKILL.md).\n2. Run `npx aisdlc gherkin extract` (`sdd_check_fix`) to deterministically extract `.feature` files from Markdown specifications, and run `npx aisdlc gherkin scaffold <feature-file> --lang <lang> --fallback` to scaffold RED step definitions in `tests/steps/` (never hand-author `.feature` or step skeletons).\n3. Author FAILING (red) assertions inside the scaffolded step definitions, plus integration/contract tests and mandatory E2E/UI tests (evaluating Happy Path, Sad Path, and Boundary Values for every interactive UI element, plus `UC-*` alternative/exception flows) in `tests/`.\n4. Commit failing test suites with trailer `Task-ID: TSK-YYY`.\n5. Run `npx aisdlc verify gherkin` and `verify_testing` (`npx aisdlc verify testing`) to confirm deterministic Gherkin/step sync and requirement test coverage before writing production code.\n\n### Step 5: Green & Refactor Phase \u2014 Surgical Implementation (`agent-developer` / `agent-devops`)\n1. Delegate application tasks (`src/`, `tests/`) to [`agent-developer`](../agent-developer/SKILL.md). For tasks (`TSK-*`) targeting CI/CD workflows (`.github/workflows/`), `Dockerfile*`, IaC manifests, or support scripts (`scripts/`), delegate to [`agent-devops`](../agent-devops/SKILL.md) under its strict non-invasion guardrail on `src/`.\n2. Execute the **Mandatory 4-Step Implementation Order**:\n - (1) Modular & Hexagonal Architecture (Ports & Adapters) boundaries, (2) Inter-module interfaces/ports first, (3) Concrete component implementation (zero fake-wiring; all 4 UI states `Loading`, `Empty`, `Error`, `Nominal`), (4) Exhaustive per-function unit tests in `tests/unit/` (Happy Path, Sad Path, Boundary, Null/Empty).\n3. Commit implementations with trailer `Task-ID: TSK-YYY`.\n4. Verify any new dependency against `license-policy.yaml` via `verify_licenses` and PII handling against `privacy-policy.yaml` via `verify_privacy`.\n5. Run `sdd_check_fix` (`npx aisdlc check --fix`) and `verify_quality` (`npx aisdlc verify quality`) until Cyclomatic Complexity $\\le 10$, Cognitive $\\le 15$, Maintainability $\\ge 50$, and Function Length $\\le 40$ lines pass with zero violations.\n6. Run `verify` (`npx aisdlc verify all`) confirming all **12 Quality Gates** pass green.\n\n### Checkpoint 2: Implementation & Pre-PR Checkpoint (`agent-auditor` $\\parallel$ `agent-adversary`)\n1. **Functional Validation (`agent-expert-user`)**: Validate live runtime behavior against `UC-*` and `FR-*` criteria (including `0` browser `console.error`/`pageerror` on UI changes).\n2. Concurrently invoke `agent-auditor` (verifying Clean Code, SOLID, DRY, AST thresholds, and eliminating unnecessary abstractions) and `agent-adversary` (performing conceptual test mutation to verify QA tests catch defects, and attacking boundary inputs with concrete PoC breaks).\n3. Consolidate findings and remediate in `agent-developer` (max 2 correction rounds).\n4. Run `npx aisdlc verify all` to confirm final green status.\n\n### Step 6: Human PR Sign-Off, Baseline Integration & Release Closure\n1. **Feature Merge (`feat/CHG-*` \u2794 `main` or `release/vX.Y.Z`)**:\n - Present the PR, KPI summary (`kpi_pr` including per-task rework metrics), and autogenerated reports (`reports/QUALITY_REPORT.md`, `reports/TRACEABILITY_MATRIX.md`, `reports/ROPA_INVENTORY.md`) to the human Tech Lead for review and approval (never auto-approve or auto-merge).\n2. **Canonical Baseline Promotion**: Once tasks in `tasks.md` are marked `COMPLETED` and approved, promote the change into the canonical baseline via MCP tool `sdd_integrate` (`npx aisdlc sdd integrate --auto`), which synchronizes the normative text and BDD Gherkin scenarios into `FR-*` / `UC-*` / `SEC-REQ-*` / `PRIV-REQ-*`, bumps minor SemVer when updating active specs, resyncs PDaC SHA-256 digests, promotes `FR-*` to `active`, links `CMP-*`, and archives the change under `specs/changes/completed/` (or `npx aisdlc sdd integrate --all` to consolidate all completed changes).\n3. **Semantic Versioning Promotion**: Tag the merge with the computed SemVer bump (`patch`, `minor`, `major`) and refresh the interactive dashboard (`report_dashboard`).\n\n## Non-Negotiable Guardrails\n- **Clean Context Window Isolation per Specialist Agent (Cross-IDE)**: Never execute two distinct specialist roles (e.g., `agent-qa-engineer` and `agent-developer`, or `agent-developer` and `agent-adversary`) in the same conversation context window. In subagent-capable IDEs (Antigravity `invoke_subagent`, Claude Code `Task` / `.claude/agents/`, GitHub Copilot `@agent-*`), always spawn each specialist in a fresh isolated subagent context that reads state strictly from disk (`specs/`, `handoff.yaml`, `get_active_handoff`). In chat-based IDEs (Cursor, Windsurf, Aider), persist all artifacts to disk, emit the Workflow Handoff block, and instruct the user to open a **New Chat** (or `/clear`) before running the next specialist.\n- **2-Checkpoint Quality & Adversarial Protocol**: Enforce transversal quality and red-team checks exclusively at **Checkpoint 1 (Specification & Design)** and **Checkpoint 2 (Implementation & Pre-PR)**. Enforce the **Anti-Ping-Pong Guardrail**: maximum 2 correction rounds per checkpoint; if unresolved blocking defects persist, escalate to the Human Tech Lead.\n- **Single-Use-Case Scope (`1 UC-* = 1 CHG-*`)**: Each SDD change (`CHG-*`) must deliver at most 1 Use Case (`UC-*`). Bundling multiple `UC-*` into one `handoff.yaml` is blocked by `verify_governance` (`Greenfield monolith detected`). Scale throughput via parallel `CHG-*` branches/worktrees, not monolithic changes.\n- **100% Design & Handoff Coverage in `tasks.md`**: Every `CMP-*`, `FR-*`, `SEC-REQ-*`, and `PRIV-REQ-*` declared in `design.md` and `handoff.yaml` must be explicitly assigned to at least one `TSK-*` in `tasks.md`.'
18777
18947
  }
18778
18948
  ];
18779
18949
  function renderAntigravitySkillFile(skill) {
@@ -18912,52 +19082,33 @@ This file defines the operational rules and specialized role mappings for Google
18912
19082
  - **Mandatory Regression Verification**: Never declare build, typecheck, or bug fixes complete without executing the relevant automated test suite (\`pnpm test\`, \`dotnet test\`) and confirming zero regressions.
18913
19083
  - **Global Styles Protection**: When touching or refactoring frontend views, verify that global stylesheet/asset imports remain intact and that layouts suffer no visual disruption.
18914
19084
  - **Skills-First Implementation Directive**: When authoring or refactoring code (especially frontend, UI, styling, accessibility, or framework-specific logic), proactively inspect and leverage available specialized agent skills (e.g., modern web guidance, accessibility a11y, DevTools, framework skills) to produce standard-compliant, modern implementations rather than guessing ad-hoc patterns.
18915
- - Upon completing green implementation, suggest handoff to \`agent-expert-user\` for post-development functional validation prior to security and privacy audit.
18916
-
18917
- ### 7. \`agent-security-auditor\` (Adversarial Code Auditor)
18918
- - **Mission**: Rigorously examine Pull Requests for business logic vulnerabilities, injection vectors, secret leaks, and authorization flaws as part of the Pre-Merge Audit Triad.
18919
- - **Directives**:
18920
- - Analyze code diffs with an attacker mindset and run \`pnpm run verify:security\`.
18921
- - Issue findings with CVSS v3.1 severity scoring and block any PR introducing CRITICAL or HIGH security risks.
18922
-
18923
- ### 8. \`agent-compliance-checker\` (Open Source License Compliance Auditor)
18924
- - **Mission**: Audit dependency manifests and ensure every direct and transitive third-party package complies with \`license-policy.yaml\` as part of the Pre-Merge Audit Triad.
18925
- - **Directives**:
18926
- - Verify SPDX identifiers via \`pnpm run verify:licenses\`, immediately blocking viral (\`GPL\`, \`AGPL\`) or unapproved commercial (\`BSL\`, \`SSPL\`) licenses.
19085
+ - Upon completing green implementation, suggest handoff to \`agent-expert-user\` for post-development functional validation prior to Checkpoint 2 (\`agent-auditor\` $\\parallel$ \`agent-adversary\` + \`agent-privacy-officer\`).
18927
19086
 
18928
- ### 9. \`agent-expert-user\` (Expert User and Domain Evaluator)
19087
+ ### 7. \`agent-expert-user\` (Expert User and Domain Evaluator)
18929
19088
  - **Mission**: Contrast design and specifications (design phase) and functionally validate finished software against \`UC-*\` and \`FR-*\` (post-development phase).
18930
19089
  - **Directives**:
18931
19090
  - Design mode (upstream): Adopt the primary actor's profile under stressful field conditions, applying bimodal discrimination (strict MVP core vs. roadmap suggestion backlog in \`templates/product/user-design-feedback.template.md\`). Reject as \`[BLOCKING_DEFECT]\` any library-only MVP proposal for human actors that fails to define or omits the runnable presentation layer (Web, Desktop, or Console/CLI), role access, or master-data CRUD flows.
18932
- - Functional validation mode (downstream / pre-PR / post-development functional validation): Thoroughly contrast interface and actual CLI execution against \`UC-*\` and \`FR-*\` acceptance criteria before pre-merge security audit.
18933
- - Emit handoff block suggesting \`agent-code-reviewer\` / \`agent-security-auditor\` / \`agent-privacy-officer\` if compliant, or return to \`agent-developer\` on functional drift.
18934
-
18935
- ### 10. \`agent-code-reviewer\` (Technical and Architectural Code Reviewer)
18936
- - **Mission**: Audit Pull Requests evaluating code cleanliness, adherence to SOLID, DRY, YAGNI principles, design patterns, and respect for complexity and maintainability thresholds (\`quality-policy.yaml\`), forming part of the Pre-Merge Audit Triad.
18937
- - **Directives**:
18938
- - Respect \`quality-policy.yaml\` thresholds: CC $\\le 10$, Cognitive $\\le 15$, MI $\\ge 50$, LOC $\\le 40$.
18939
- - Detect improper coupling, code smells, magic numbers, ambiguous names, and encapsulation violations.
18940
- - Flag premature abstractions and speculative code violating YAGNI.
18941
- - Coordinate Pre-Merge Audit Triad with \`agent-security-auditor\`, \`agent-privacy-officer\`, and \`agent-compliance-checker\`.
18942
- - Classify findings into: \`[BLOCKING]\` (quality violation or broken pattern), \`[CLEAN_CODE_SUGGESTION]\` (non-blocking improvement), and \`[COMPLIANT]\`.
19091
+ - Functional validation mode (downstream / pre-PR / post-development functional validation): Thoroughly contrast interface and actual CLI execution against \`UC-*\` and \`FR-*\` acceptance criteria before Checkpoint 2 audit.
19092
+ - Emit handoff block suggesting Checkpoint 2 (\`agent-auditor\` $\\parallel$ \`agent-adversary\` + \`agent-privacy-officer\`) if compliant, or return to \`agent-developer\` on functional drift.
18943
19093
 
18944
- ### 11. \`agent-devops\` (Automation and Infrastructure Engineer)
19094
+ ### 8. \`agent-devops\` (Automation and Infrastructure Engineer)
18945
19095
  - **Mission**: Maintain, evolve, and audit automated project infrastructure: CI/CD workflows, Docker containers, IaC manifests, and support scripts.
18946
19096
  - **Directives**:
18947
19097
  - Strict infrastructure domain: Operates exclusively in \`.github/workflows/\`, \`Dockerfile*\`, \`docker-compose*.yml\`, IaC manifests, and \`scripts/\`.
18948
19098
  - **NON-INVASION GUARDRAIL**: STRICTLY FORBIDDEN from modifying or refactoring application source code files (\`src/\`, \`packages/*/src/\`). Your responsibility is the pipeline and scaffolding, never application business logic.
19099
+ - **Deployment & CI/CD Strategy Discovery**: Before scaffolding new pipelines or containers, read \`ARCH-INTRO-001\` / \`ARCH-DEP-001\` and clarify packaging/CD destination, CI platform, and release trigger policy with the Tech Lead.
18949
19100
  - Infrastructure dependency policy: Verify licenses of dependencies, base images, and third-party actions according to \`license-policy.yaml\`.
18950
19101
  - Gate preservation: Ensure pipeline optimizations preserve all existing deterministic Quality Gates intact.
18951
19102
  - **Cross-Workflow Audit**: When fixing any CI/CD or configuration defect detected in a PR, search all \`.github/workflows/*.yml\` for the same pattern (including release, post-merge, and publishing pipelines) before declaring the fix complete.
18952
19103
  - **Remote Verification**: Creating a PR (\`gh pr create\`) does not equal success; actively verify that remote checks pass (\`gh pr checks\`).
18953
19104
 
18954
- ### 12. \`agent-auditor\` (Transversal Quality and Improvement Auditor)
18955
- - **Mission**: Polymorphically inspect deliverables from any specialist agent on demand, identifying structural weaknesses, overengineering, or blind spots, and proposing minimal solutions adhering strictly to YAGNI.
18956
- - **Directives**: Constructive critique; classify findings into \`[BLOCKING_DEFECT]\`, \`[SIMPLIFICATION]\`, and \`[ADVISORY]\`; non-invasive (never edit files directly); always return handoff to the audited agent (max 1 return round).
19105
+ ### 9. \`agent-auditor\` (Transversal Quality and Improvement Auditor)
19106
+ - **Mission**: Polymorphically inspect deliverables from any specialist agent on demand, enforcing Clean Code, SOLID, DRY, Simplicity First (YAGNI), \`quality-policy.yaml\` AST thresholds, UI design standards, and \`license-policy.yaml\` SPDX compliance.
19107
+ - **Directives**: Constructive critique; block fake-wiring, unstyled interfaces, and manual \`.feature\` files; verify licenses via \`pnpm run verify:licenses\`; classify findings into \`[BLOCKING_DEFECT]\`, \`[SIMPLIFICATION]\`, and \`[ADVISORY]\`; non-invasive (never edit files directly); always return handoff to the audited agent (max 1 return round).
18957
19108
 
18958
- ### 13. \`agent-adversary\` (Transversal Red Team and Chaos Adversary)
18959
- - **Mission**: Actively attempt to break, bypass, or invalidate deliverables from any target specialist agent, providing concrete proofs-of-concept (PoC), counterexamples, and reproduction steps.
18960
- - **Directives**: Expose failure modes across Product (logic traps), Architecture (SPOF/races), QA (mutation testing/false greens), Code (boundary/concurrency), and DevOps (pipeline escape); mandatory proof-of-break; non-invasive; always return handoff to the audited agent (max 1 return round).
19109
+ ### 10. \`agent-adversary\` (Transversal Red Team and Chaos Adversary)
19110
+ - **Mission**: Actively attempt to break, bypass, or invalidate deliverables from any target specialist agent, including Pre-Merge / Checkpoint 2 security diff audits with CVSS v3.1 scoring and concrete proofs-of-concept (PoC).
19111
+ - **Directives**: Expose failure modes across Product (logic traps), Architecture (SPOF/races), QA (mutation testing/false greens), Development & Pre-Merge Security (boundary/concurrency, SAST/secrets via \`pnpm run verify:security\`, CVSS v3.1 blocking CRITICAL/HIGH), and DevOps (pipeline escape); mandatory proof-of-break; non-invasive; always return handoff to the audited agent (max 1 return round).
18961
19112
 
18962
19113
  ---
18963
19114
 
@@ -18978,7 +19129,7 @@ This file defines the operational rules and specialized role mappings for Google
18978
19129
  - **Conditional Activation Rule by Autonomy**:
18979
19130
  - \u{1F7E2} **\`AUTONOMOUS\`** (or exclusive final supervision in PR/CI): **OMITTED**. Do not request or emit interactive handoff to avoid interrupting unattended execution.
18980
19131
  - \u{1F7E1} **Autonomy $\\ge$ \`HUMAN_REVIEW_PLAN\`** (\`HUMAN_REVIEW_PLAN\`, \`AMBIGUOUS\`, \`HIGH_RISK_MANUAL\`): **MANDATORY**. Emit the Workflow Handoff block compliant with [\`templates/workflow/agent-handoff.template.md\`](../../templates/workflow/agent-handoff.template.md) and **STOP**.
18981
- - **Block Contents**: Declare produced deliverables, recommend the next role in workflow (\`agent-threat-modeler\`, \`agent-privacy-officer\`, \`agent-system-architect\`, \`agent-qa-engineer\`, \`agent-developer\`, \`agent-expert-user\`, \`agent-code-reviewer\`, \`agent-security-auditor\`, \`agent-compliance-checker\`, \`agent-devops\`, \`agent-auditor\`, \`agent-adversary\`, etc.), provide suggested invocation prompt, and keep **the Human Action Window open at all times for the human user to take action** (review, edit by hand, pause/reroute, or delegate).
19132
+ - **Block Contents**: Declare produced deliverables, recommend the next role in workflow (\`agent-threat-modeler\`, \`agent-privacy-officer\`, \`agent-system-architect\`, \`agent-qa-engineer\`, \`agent-developer\`, \`agent-expert-user\`, \`agent-devops\`, \`agent-auditor\`, \`agent-adversary\`, etc.), provide suggested invocation prompt, and keep **the Human Action Window open at all times for the human user to take action** (review, edit by hand, pause/reroute, or delegate).
18982
19133
  `;
18983
19134
  var STARTER_CURSOR_CORE_RULES = `---
18984
19135
  description: Global canonical directives, 5 unbreakable commandments, and AI-SDLC pre-flight
@@ -19020,13 +19171,10 @@ Before finalizing changes or proposing commits:
19020
19171
  | \`agent-system-architect\` | Modular arc42 + NAF v4 architecture (\`CMP-*\`, Mermaid diagrams, \`ADR-*\`). |
19021
19172
  | \`agent-qa-engineer\` | FAILING BDD/Gherkin, E2E, and UI suites (using agreed project tech; Happy Path, Sad Path & Boundary Values per interactive UI element) before \`agent-developer\` writes code. |
19022
19173
  | \`agent-developer\` | Atomic tasks from \`tasks.md\`; respects autonomy mode; runs \`pnpm run check:fix\` + \`pnpm run verify:all\`. |
19023
- | \`agent-security-auditor\` | Adversarial PR security audit, SAST, secrets, and CVSS v3.1 evaluation. |
19024
- | \`agent-compliance-checker\` | SPDX license compliance audit against \`license-policy.yaml\`. |
19025
19174
  | \`agent-expert-user\` | Bimodal MVP evaluation (design) and functional validation against \`UC-*\` and \`FR-*\` (pre-PR). |
19026
- | \`agent-code-reviewer\` | PR audit (SOLID, DRY, YAGNI): \`[BLOCKING]\` / \`[CLEAN_CODE_SUGGESTION]\` / \`[COMPLIANT]\`. |
19027
- | \`agent-devops\` | CI/CD, Docker, IaC only \u2014 **FORBIDDEN** to touch \`src/\` or \`packages/*/src/\`. |
19028
- | \`agent-auditor\` | Transversal on-demand constructive auditor; identifies overengineering, blind spots & YAGNI simplifications; returns handoff to audited agent. |
19029
- | \`agent-adversary\` | Transversal on-demand Red Team adversary; breaks deliverables with reproducible PoC & mutation tests; returns handoff to audited agent. |
19175
+ | \`agent-devops\` | CI/CD, Docker, IaC only \u2014 clarifies deployment/CI strategy; **FORBIDDEN** to touch \`src/\` or \`packages/*/src/\`. |
19176
+ | \`agent-auditor\` | Transversal auditor: YAGNI, Clean Code/SOLID/AST thresholds, UI standards, SPDX licenses (\`verify:licenses\`); returns handoff to audited agent. |
19177
+ | \`agent-adversary\` | Transversal Red Team adversary: PoC breaks, mutation testing & Pre-Merge security diff audit (\`verify:security\`, CVSS v3.1); returns handoff to audited agent. |
19030
19178
 
19031
19179
  ## 5. Task Autonomy Modes (\`tasks.md\`)
19032
19180
  - \u{1F7E2} **\`AUTONOMOUS\`**: Low risk. Implement directly, omit handoff block.
@@ -19179,32 +19327,20 @@ npx tsx packages/cli/src/index.ts sdd integrate --change <chg-id>
19179
19327
  - **Mission**: Implement atomic tasks from SDD specifications (\`tasks.md\`) with clean, strictly typed code and thorough tests.
19180
19328
  - **Directives**: Execute the mandatory 4-step order: (1) Modular & Hexagonal Architecture (Ports & Adapters) definition/redefinition, (2) Inter-module interfaces first, (3) Component implementation, (4) Per-function unit tests (Happy Path, Sad Path, Boundary Values, Unexpected/Null/Empty values). Respect the autonomy mode. Make tests delivered by \`agent-qa-engineer\` pass green. Run \`pnpm run check:fix\` and \`pnpm run verify:all\`. Enforce Mandatory Regression Verification (\`pnpm test\`) with zero regressions before declaring completion, and enforce Global Styles Protection on frontend views.
19181
19329
 
19182
- ### 7. \`agent-security-auditor\` (Adversarial Code Auditor)
19183
- - **Mission**: Examine Pull Requests for business logic vulnerabilities, injection vectors, secret leaks, and authorization flaws as part of the Pre-Merge Audit Triad.
19184
- - **Directives**: Run \`pnpm run verify:security\`, evaluate CVSS v3.1 severity, and block CRITICAL/HIGH risks.
19185
-
19186
- ### 8. \`agent-compliance-checker\` (Open Source License Compliance Auditor)
19187
- - **Mission**: Audit dependency manifests against \`license-policy.yaml\` as part of the Pre-Merge Audit Triad.
19188
- - **Directives**: Run \`pnpm run verify:licenses\`, blocking viral (\`GPL\`, \`AGPL\`) or unapproved commercial (\`BSL\`, \`SSPL\`) packages.
19189
-
19190
- ### 9. \`agent-expert-user\` (Expert User and Domain Evaluator)
19330
+ ### 7. \`agent-expert-user\` (Expert User and Domain Evaluator)
19191
19331
  - **Mission**: Contrast design and specifications (design phase) and functionally validate finished software against \`UC-*\` and \`FR-*\` (post-development functional validation phase).
19192
19332
 
19193
- ### 10. \`agent-code-reviewer\` (Technical and Architectural Code Reviewer)
19194
- - **Mission**: Audit Pull Requests evaluating code cleanliness, adherence to SOLID, DRY, YAGNI principles, and respect for \`quality-policy.yaml\` thresholds, forming part of the Pre-Merge Audit Triad.
19195
- - **Findings classification**: \`[BLOCKING]\`, \`[CLEAN_CODE_SUGGESTION]\`, \`[COMPLIANT]\`.
19196
-
19197
- ### 11. \`agent-devops\` (Automation and Infrastructure Engineer)
19198
- - **Mission**: Maintain, evolve, and audit automated project infrastructure: CI/CD workflows, Docker containers, IaC manifests, and support scripts.
19333
+ ### 8. \`agent-devops\` (Automation and Infrastructure Engineer)
19334
+ - **Mission**: Maintain, evolve, and audit automated project infrastructure: CI/CD workflows, Docker containers, IaC manifests, and support scripts. Clarifies packaging/CD strategy against \`ARCH-INTRO-001\` / \`ARCH-DEP-001\`.
19199
19335
  - **NON-INVASION GUARDRAIL**: STRICTLY FORBIDDEN from modifying application source code (\`src/\`, \`packages/*/src/\`).
19200
19336
 
19201
- ### 12. \`agent-auditor\` (Transversal Quality and Improvement Auditor)
19202
- - **Mission**: Polymorphically inspect deliverables from any specialist agent on demand, identifying structural weaknesses, overengineering, or blind spots, and proposing minimal solutions adhering strictly to YAGNI.
19337
+ ### 9. \`agent-auditor\` (Transversal Quality and Improvement Auditor)
19338
+ - **Mission**: Polymorphically inspect deliverables from any specialist agent on demand, enforcing Clean Code, SOLID, DRY, YAGNI, \`quality-policy.yaml\` AST thresholds, UI design standards, and \`license-policy.yaml\` SPDX compliance (\`pnpm run verify:licenses\`).
19203
19339
  - **Directives**: Constructive critique; classify findings into \`[BLOCKING_DEFECT]\`, \`[SIMPLIFICATION]\`, and \`[ADVISORY]\`; non-invasive (never edit files directly); always return handoff to the audited agent (max 1 return round).
19204
19340
 
19205
- ### 13. \`agent-adversary\` (Transversal Red Team and Chaos Adversary)
19206
- - **Mission**: Actively attempt to break, bypass, or invalidate deliverables from any target specialist agent, providing concrete proofs-of-concept (PoC), counterexamples, and reproduction steps.
19207
- - **Directives**: Expose failure modes across Product (logic traps), Architecture (SPOF/races), QA (mutation testing/false greens), Code (boundary/concurrency), and DevOps (pipeline escape); mandatory proof-of-break; non-invasive; always return handoff to the audited agent (max 1 return round).
19341
+ ### 10. \`agent-adversary\` (Transversal Red Team and Chaos Adversary)
19342
+ - **Mission**: Actively attempt to break, bypass, or invalidate deliverables from any target specialist agent, including Pre-Merge / Checkpoint 2 security diff audits (\`pnpm run verify:security\`, CVSS v3.1), providing concrete proofs-of-concept (PoC), counterexamples, and reproduction steps.
19343
+ - **Directives**: Expose failure modes across Product (logic traps), Architecture (SPOF/races), QA (mutation testing/false greens), Development & Pre-Merge Security (boundary/concurrency, CVSS v3.1), and DevOps (pipeline escape); mandatory proof-of-break; non-invasive; always return handoff to the audited agent (max 1 return round).
19208
19344
 
19209
19345
  ---
19210
19346
 
@@ -19321,7 +19457,7 @@ Non-Negotiable Quality Thresholds (\`quality-policy.yaml\`):
19321
19457
  - **Conditional Activation**:
19322
19458
  * \u{1F7E2} **\`AUTONOMOUS\` Mode** (or PR/CI final supervision): **OMITTED**. Do not interrupt unattended execution.
19323
19459
  * \u{1F7E1} **Autonomy $\\ge$ \`HUMAN_REVIEW_PLAN\`** (\`HUMAN_REVIEW_PLAN\`, \`AMBIGUOUS\`, \`HIGH_RISK_MANUAL\`): **MANDATORY**. Emit Workflow Handoff block compliant with [\`templates/workflow/agent-handoff.template.md\`](../templates/workflow/agent-handoff.template.md) and **STOP**.
19324
- - **Components**: Declare completed deliverables, recommend next roles (\`agent-threat-modeler\`, \`agent-privacy-officer\`, \`agent-system-architect\`, \`agent-developer\`, \`agent-security-auditor\`), provide suggested invocation prompt, and **keep the Human Action Window open at all times for the user to take action** (review, edit by hand, pause/reroute, or delegate).
19460
+ - **Components**: Declare completed deliverables, recommend next roles (\`agent-threat-modeler\`, \`agent-privacy-officer\`, \`agent-system-architect\`, \`agent-developer\`, \`agent-devops\`, \`agent-auditor\`, \`agent-adversary\`), provide suggested invocation prompt, and **keep the Human Action Window open at all times for the user to take action** (review, edit by hand, pause/reroute, or delegate).
19325
19461
 
19326
19462
  ---
19327
19463
 
@@ -19329,19 +19465,16 @@ Non-Negotiable Quality Thresholds (\`quality-policy.yaml\`):
19329
19465
 
19330
19466
  | Role | Mission (summary) |
19331
19467
  | :--- | :--- |
19332
- | \`agent-product-analyst\` | Phase 0 NAF v4 Enterprise & Capability Vision (\`ARCH-INTRO-*\`, up to 15-question discovery interview defining UI modality & CRUD prerequisites) + ProductShape artifacts (\`ACT-*\`, \`UC-*\`, \`FR-*\`, \`QR-*\`, \`BR-*\`); \`status\` starts \`draft\`. |
19468
+ | \`agent-product-analyst\` | Phase 0 NAF v4 Enterprise & Capability Vision (\`ARCH-INTRO-*\`, up to 15-question discovery interview defining UI modality, delivery model & CRUD prerequisites) + ProductShape artifacts (\`ACT-*\`, \`UC-*\`, \`FR-*\`, \`QR-*\`, \`BR-*\`); \`status\` starts \`draft\`. |
19333
19469
  | \`agent-threat-modeler\` | STRIDE/OWASP threat triad (\`ACT-THREAT-*\`, \`ABUSE-*\`, \`SEC-REQ-*\`); hands off to \`agent-privacy-officer\`. |
19334
19470
  | \`agent-privacy-officer\` | LINDDUN & GDPR/LOPDGDD privacy triad (\`DATA-ASSET-*\`, \`PRIV-ROPA-*\`, \`PRIV-REQ-*\`) + Pre-Merge \`verify:privacy\`. |
19335
- | \`agent-system-architect\` | Modular arc42 + NAF v4 architecture (\`CMP-*\`, Mermaid diagrams, \`ADR-*\`). |
19471
+ | \`agent-system-architect\` | Modular arc42 + NAF v4 architecture (\`CMP-*\`, \`ARCH-DEP-001\`, Mermaid diagrams, \`ADR-*\`). |
19336
19472
  | \`agent-qa-engineer\` | FAILING BDD/Gherkin, E2E, and UI suites (using agreed project tech; Happy Path, Sad Path & Boundary Values per interactive UI element) before \`agent-developer\` writes production code. |
19337
19473
  | \`agent-developer\` | Atomic tasks from \`tasks.md\`; autonomy mode must be respected; runs \`pnpm run check:fix\` + \`pnpm run verify:all\`. |
19338
- | \`agent-security-auditor\` | Adversarial PR security audit, SAST, secrets, and CVSS v3.1 evaluation. |
19339
- | \`agent-compliance-checker\` | SPDX license compliance audit against \`license-policy.yaml\`. |
19340
19474
  | \`agent-expert-user\` | Bimodal MVP evaluation (design) and functional validation against \`UC-*\` and \`FR-*\` (pre-PR). |
19341
- | \`agent-code-reviewer\` | PR audit (SOLID, DRY, YAGNI): \`[BLOCKING]\` / \`[CLEAN_CODE_SUGGESTION]\` / \`[COMPLIANT]\`. |
19342
- | \`agent-devops\` | CI/CD, Docker, IaC only \u2014 **FORBIDDEN** to touch \`src/\` or \`packages/*/src/\`. |
19343
- | \`agent-auditor\` | Transversal on-demand constructive auditor; identifies overengineering, blind spots & YAGNI simplifications; returns handoff to audited agent. |
19344
- | \`agent-adversary\` | Transversal on-demand Red Team adversary; breaks deliverables with reproducible PoC & mutation tests; returns handoff to audited agent. |
19475
+ | \`agent-devops\` | CI/CD, Docker, IaC only \u2014 clarifies deployment/CI strategy; **FORBIDDEN** to touch \`src/\` or \`packages/*/src/\`. |
19476
+ | \`agent-auditor\` | Transversal auditor: YAGNI, Clean Code/SOLID/AST thresholds, UI standards, SPDX licenses (\`verify:licenses\`); returns handoff to audited agent. |
19477
+ | \`agent-adversary\` | Transversal Red Team adversary: PoC breaks, mutation testing & Pre-Merge security diff audit (\`verify:security\`, CVSS v3.1); returns handoff to audited agent. |
19345
19478
 
19346
19479
  ---
19347
19480
 
@@ -23784,23 +23917,8 @@ var TimestampedBackupManagerAdapter = class {
23784
23917
  fs12.mkdirSync(targetBackupDir, { recursive: true, mode: 448 });
23785
23918
  const manifestEntries = [];
23786
23919
  for (const relPath of filesToBackup) {
23787
- const srcFile = path14.resolve(resolvedRoot, relPath);
23788
- if (fs12.existsSync(srcFile)) {
23789
- const destFile = path14.resolve(targetBackupDir, relPath);
23790
- const destDir = path14.dirname(destFile);
23791
- if (!fs12.existsSync(destDir)) {
23792
- fs12.mkdirSync(destDir, { recursive: true });
23793
- }
23794
- const content = fs12.readFileSync(srcFile, "utf-8");
23795
- fs12.writeFileSync(destFile, content, "utf-8");
23796
- const digest = this.diffDetector.computeDigest(content);
23797
- const stats = fs12.statSync(destFile);
23798
- manifestEntries.push({
23799
- path: relPath,
23800
- sha256: digest,
23801
- bytes: stats.size
23802
- });
23803
- }
23920
+ const entry = this.backupSingleFile(resolvedRoot, targetBackupDir, relPath);
23921
+ if (entry) manifestEntries.push(entry);
23804
23922
  }
23805
23923
  const manifest = {
23806
23924
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -23813,6 +23931,18 @@ var TimestampedBackupManagerAdapter = class {
23813
23931
  );
23814
23932
  return targetBackupDir;
23815
23933
  }
23934
+ backupSingleFile(resolvedRoot, targetBackupDir, relPath) {
23935
+ const srcFile = path14.resolve(resolvedRoot, relPath);
23936
+ if (!fs12.existsSync(srcFile)) return null;
23937
+ const destFile = path14.resolve(targetBackupDir, relPath);
23938
+ const destDir = path14.dirname(destFile);
23939
+ if (!fs12.existsSync(destDir)) fs12.mkdirSync(destDir, { recursive: true });
23940
+ const content = fs12.readFileSync(srcFile, "utf-8");
23941
+ fs12.writeFileSync(destFile, content, "utf-8");
23942
+ const digest = this.diffDetector.computeDigest(content);
23943
+ const stats = fs12.statSync(destFile);
23944
+ return { path: relPath, sha256: digest, bytes: stats.size };
23945
+ }
23816
23946
  async restoreBackup(repoRoot, backupPath) {
23817
23947
  const resolvedRoot = path14.resolve(repoRoot);
23818
23948
  const manifestPath = path14.join(backupPath, "manifest.json");
@@ -24238,6 +24368,6 @@ var MigrationService = class {
24238
24368
  }
24239
24369
  };
24240
24370
 
24241
- export { ALL_ARCHITECTURE_TEMPLATES, ALL_QUALITY_GATES, BRANCH_PATTERNS, BddStepRegistry, BranchSafetyCheck, CPP_CLANG_TIDY, CPP_CMAKE_STRICT, DEFAULT_DLP_RULES, DEFAULT_EXCLUDED_PATTERNS, DEFAULT_EXCLUDES, DEFAULT_EXCLUDE_DIRS, DEFAULT_EXTENSIONS, DEFAULT_PRIVACY_POLICY, DEFAULT_SAST_EXCLUDES, DEFAULT_TEST_ARTIFACT_PATTERNS, DEFAULT_UNIT_TEST_PATTERNS, DOTNET_DIRECTORY_BUILD_PROPS, DiffDetector, DlpSanitizer, DoctorOrchestrator, DoctorReporter, DoctorService, FileSystemJailAdapter, GENERAL_SOURCE_EXTENSIONS, GHERKIN_GENERATOR_SPECS, GO_GOLANGCI_YML, GRADLE_STRICT_INIT_KTS, GitHooksHealthCheck, InTotoAttestationBuilder, JAVA_PMD_RULESET_XML, KOTLIN_DETEKT_YML, KPI_SUMMARY_END_TAG, KPI_SUMMARY_START_TAG, LIFECYCLE_SKILL_TEMPLATES, MAX_SARIF_BYTES, MAX_SARIF_JSON_DEPTH, MAX_SARIF_RESULTS, MigrationOrchestrator, MigrationReporter, MigrationService, NativeFileSystemProbeAdapter, OpenSpecAdapter, OscalAssessmentBuilder, OverrideAnalyzer, PII_SAST_RULES, PREPARE_COMMIT_MSG_SCRIPT, PRE_COMMIT_SCRIPT, PROMPT_INJECTION_SIGNATURES, PROTECTED_BYPASS_PATTERNS, PROTECTED_CODING_RULES_FILES, PolicyRatchetEnforcer, REVIEWER_ROLES, REVIEW_VERDICTS, RUST_CARGO_CONFIG_TOML, RUST_CLIPPY_TOML, RegulatoryControlMapper, SARIF_SCHEMA_2_1_0, SARIF_VERSION, SAST_RULES, SCHEMA_SCHEMAS_ARCHITECTURE_ADR_SCHEMA_JSON, SCHEMA_SCHEMAS_ARCHITECTURE_COMPONENT_SCHEMA_JSON, SCHEMA_SCHEMAS_ARCHITECTURE_INTRODUCTION_AND_GOALS_SCHEMA_JSON, SCHEMA_SCHEMAS_COMPLIANCE_LICENSE_MANIFEST_SCHEMA_JSON, SCHEMA_SCHEMAS_COMPLIANCE_LICENSE_POLICY_SCHEMA_JSON, SCHEMA_SCHEMAS_COMPLIANCE_QUALITY_POLICY_SCHEMA_JSON, SCHEMA_SCHEMAS_IDE_MCP_CONFIG_SCHEMA_JSON, SCHEMA_SCHEMAS_MANUALS_PRODUCTION_MANUAL_SCHEMA_JSON, SCHEMA_SCHEMAS_MANUALS_USER_MANUAL_SCHEMA_JSON, SCHEMA_SCHEMAS_PRIVACY_DATA_ASSET_SCHEMA_JSON, SCHEMA_SCHEMAS_PRIVACY_PRIVACY_POLICY_SCHEMA_JSON, SCHEMA_SCHEMAS_PRIVACY_PRIVACY_REQ_SCHEMA_JSON, SCHEMA_SCHEMAS_PRIVACY_PRIVACY_ROPA_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_ACTOR_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_BOUNDED_CONTEXT_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_BUSINESS_RULE_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_JOURNEY_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_REQUIREMENT_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_TERM_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_USE_CASE_SCHEMA_JSON, SCHEMA_SCHEMAS_SAFETY_HAZARD_SCHEMA_JSON, SCHEMA_SCHEMAS_SAFETY_SAFETY_REQ_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_DESIGN_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_HANDOFF_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_PROPOSAL_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_RELEASE_KPIS_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_SESSION_TELEMETRY_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_SPEC_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_TASKS_SCHEMA_JSON, SCHEMA_SCHEMAS_SECURITY_ABUSE_CASE_SCHEMA_JSON, SCHEMA_SCHEMAS_SECURITY_ENCLAVE_SCHEMA_JSON, SCHEMA_SCHEMAS_SECURITY_SECURITY_REQ_SCHEMA_JSON, SCHEMA_SCHEMAS_SECURITY_THREAT_ACTOR_SCHEMA_JSON, SCHEMA_SCHEMAS_WORKFLOW_AGENT_HANDOFF_SCHEMA_JSON, SECRET_RULES, SEVERITY_RANK2 as SEVERITY_RANK, SPECIALIZED_AGENT_TEMPLATES, STARTER_AGENT_GUARD_WRAPPER_CJS, STARTER_ANTIGRAVITY_HOOKS_JSON, STARTER_ANTIGRAVITY_MCP, STARTER_ANTIGRAVITY_RULES, STARTER_ARCH_ADR, STARTER_ARCH_ARCHITECTURE_CONSTRAINTS, STARTER_ARCH_COMPONENT, STARTER_ARCH_CONTEXT_AND_SCOPE, STARTER_ARCH_CROSS_CUTTING_CONCEPTS, STARTER_ARCH_DEPLOYMENT_VIEW, STARTER_ARCH_GLOSSARY, STARTER_ARCH_INTRODUCTION_AND_GOALS, STARTER_ARCH_LEVEL_1_WHITEBOX, STARTER_ARCH_QUALITY_REQUIREMENTS, STARTER_ARCH_RISKS_AND_TECHNICAL_DEBT, STARTER_ARCH_RUNTIME_VIEW, STARTER_ARCH_SOLUTION_STRATEGY, STARTER_AZURE_PIPELINES, STARTER_BASE_TEMPLATES, STARTER_BITBUCKET_PIPELINES, STARTER_CLAUDE_RULES, STARTER_COMPLIANCE_LICENSE_MANIFEST_YAML, STARTER_COPILOT_RULES, STARTER_CURSOR_CORE_RULES, STARTER_CURSOR_MCP, STARTER_CURSOR_PRODUCT_RULES, STARTER_CURSOR_QUALITY_RULES, STARTER_GITHUB_CI, STARTER_GITHUB_DEPLOY_DASHBOARD, STARTER_GITHUB_PR_KPI, STARTER_GITHUB_PULL_REQUEST_TEMPLATE, STARTER_GITHUB_SDD_INTEGRATE, STARTER_GITLAB_CI, STARTER_GUARD_BRANCH_CJS, STARTER_LICENSE_POLICY, STARTER_PRIVACY_POLICY, STARTER_PROCESS_README, STARTER_PULL_REQUEST_TEMPLATE, STARTER_QUALITY_POLICY, STARTER_REQUIREMENT_TEMPLATE, STARTER_SCHEMAS, STARTER_SCHEMAS_MAP, STARTER_TASK_TEMPLATE, STARTER_TEMPLATES_CI_AZURE_PIPELINES_YML, STARTER_TEMPLATES_CI_BITBUCKET_PIPELINES_YML, STARTER_TEMPLATES_CI_GITHUB_WORKFLOWS_CI_YML, STARTER_TEMPLATES_CI_GITHUB_WORKFLOWS_DEPLOY_DASHBOARD_YML, STARTER_TEMPLATES_CI_GITHUB_WORKFLOWS_PR_KPI_SUMMARY_YML, STARTER_TEMPLATES_CI_GITHUB_WORKFLOWS_SDD_INTEGRATE_ON_MERGE_YML, STARTER_TEMPLATES_CI__GITLAB_CI_YML, STARTER_TEMPLATES_COMPLIANCE_COMMERCIAL_ACQUISITION_REQUEST_TEMPLATE_MD, STARTER_TEMPLATES_MANUALS_PRODUCTION_MANUAL_TEMPLATE_MD, STARTER_TEMPLATES_MANUALS_USER_MANUAL_TEMPLATE_MD, STARTER_TEMPLATES_PRIVACY_DATA_ASSET_TEMPLATE_MD, STARTER_TEMPLATES_PRIVACY_DPIA_REQUEST_TEMPLATE_MD, STARTER_TEMPLATES_PRIVACY_PRIVACY_REQ_TEMPLATE_MD, STARTER_TEMPLATES_PRIVACY_PRIVACY_ROPA_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_ACTOR_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_BOUNDED_CONTEXT_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_BUSINESS_RULE_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_JOURNEY_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_REQUIREMENT_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_TERM_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_USER_DESIGN_FEEDBACK_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_USE_CASE_TEMPLATE_MD, STARTER_TEMPLATES_SAFETY_HAZARD_TEMPLATE_MD, STARTER_TEMPLATES_SAFETY_SAFETY_REQ_TEMPLATE_MD, STARTER_TEMPLATES_SDD_DESIGN_TEMPLATE_MD, STARTER_TEMPLATES_SDD_HANDOFF_TEMPLATE_YAML, STARTER_TEMPLATES_SDD_PROPOSAL_TEMPLATE_MD, STARTER_TEMPLATES_SDD_PULL_REQUEST_TEMPLATE_MD, STARTER_TEMPLATES_SDD_SPEC_TEMPLATE_MD, STARTER_TEMPLATES_SDD_TASKS_TEMPLATE_MD, STARTER_TEMPLATES_SECURITY_ABUSE_CASE_TEMPLATE_MD, STARTER_TEMPLATES_SECURITY_ENCLAVE_TEMPLATE_MD, STARTER_TEMPLATES_SECURITY_SECURITY_REQ_TEMPLATE_MD, STARTER_TEMPLATES_SECURITY_THREAT_ACTOR_TEMPLATE_MD, STARTER_TEMPLATES_WORKFLOW_AGENT_HANDOFF_TEMPLATE_MD, STARTER_VSCODE_MCP, STARTER_WORKFLOW_HANDOFF_TEMPLATE, STARTER__GITHUB_PULL_REQUEST_TEMPLATE_MD, SUPPORTED_COVERAGE_FORMATS_HINT, SafeProcessRunnerAdapter, SarifIngestionError, ScaSbomError, SchemasPdacHealthCheck, SecurityToolsHealthCheck, SignatureReadinessCheck, SpecKitAdapter, TOOL_INSTALL_ALLOWLIST, TS_ESLINT_CONFIG_MJS, TS_STRICT_TSCONFIG, TYPE_TO_SCHEMA_MAP, TimestampedBackupManagerAdapter, ToolchainHealthCheck, TransactionManager, UNIT_TEST_SUFFIXES, VALID_AGENT_TARGETS, VALID_ARCHITECTURE_GRANULARITIES, VALID_AUTONOMY_MODES, VALID_CHANGE_PROFILES, VALID_CI_PROVIDERS, VALID_CODING_RULE_STACKS, WIN_CMD_META_RE, accumulateTaskSummaries, aggregateCommitKpiRecords, aggregatePrKpis, aggregateReleaseKpis, analyzeBddVariantsForRequirement, appendRevisionHistoryRow, applyRatchetMode, buildCycloneDxComponent, buildCycloneDxVulnerabilities, buildFeatureFileContent, buildGraphElements, buildSafeEnvironment, calculateJaccardSimilarity, calculateMetrics, calculateRating, calculateShannonEntropy, canonicalSort, canonicalizeJson, checkGherkinInSync, checkoutTaskBranch, classifyBranch, classifyMetricFromMessage, collectAgentFiles, collectDashboardMetrics, collectHistoricalKpis, compileTestPatterns, computeCanonicalSha256, computeLfSha256, computeRawSha256, computeSha256, computeViolationSignature, createDefaultDlpPolicy, createDefaultQualityPolicy, deduplicateAndSortPrivacyViolations, deduplicateAndSortSastViolations, deduplicateAndSortViolations, depositProductHandoffSidecar, detectActiveChangeForIntegration, detectAuthorIdentity, detectLanguage, detectPolyglotLoggerCall, detectProfileFromChange, detectProjectEcosystems, detectProjectStacks, detectPromptInjection, emitCiOutput, ensureToolAvailable, ensureTrivyAvailable, evaluateCompoundLicense, evaluateSingleDependency, evaluateVulnerabilityThresholds, executeBddFeature, extractAllRepoCommitKpis, extractBaselineEntriesFromResults, extractCitations, extractCommitKpisFromRange, extractDirectDepNames, extractFeatureTags, extractFrontmatter, extractFunctions, extractFunctionsBraceLanguages, extractFunctionsPolyglot, extractFunctionsPython, extractFunctionsPythonAst, extractFunctionsTypeScriptAst, extractGherkinBlock, extractGherkinFeatures, extractNormativeText, extractPythonFunctionsPolyglot, extractSemanticContent, findChangeWorkspaceDir, findLicenseFile, formatCommitTrailers, formatInspectResultMarkdown, formatPrKpiMarkdown, formatReleaseKpiMarkdown, formatTaskKpiRows, generateBranchHierarchyPlan, generateComplianceEvidenceBundle, generateComplianceEvidenceBundleSync, generateCycloneDxSbom, generateDashboardReport, generateDeterministicUuidV5, generateDuplicatesReportMarkdown, generateGovernanceReportMarkdown, generateLicenseReportMarkdown, generatePdacReportMarkdown, generatePrivacyReportMarkdown, generateQualityReport, generateRopaInventoryMarkdown, generateSastReportMarkdown, generateSecretsReportMarkdown, generateSecuritySarifReport, generateSuppressionsAuditReport, generateTestingCoverageReportMarkdown, generateThirdPartyNotices, generateTraceabilityReportMarkdown, getArchitectureTemplates, getCodingRulesFilesForStacks, getCytoscapeScript, getGitDiffLines, getNextCorrelativeNumber, getReferenceCodingRulesTemplates, getSddAdapter, getToolInstallSpec, inferArtifactTypeFromId, inferMissingTrailers, ingestSarifFiles, ingestSbomFile, initProject, injectKpisIntoPrBody, inspectElement, installGitHooks, integrateAllSddChanges, integrateSddChange, isCliInstalled, isFunctionReferencedInTests, isGitleaksInstalled, isMetricWorsened, isPathOutsideRoot, isPathProtectedFromPatch, isPlaceholderOrIgnored, isPolyglotTestArtifact, isPolyglotUnitTestFile, isProtectedCodingRulesFile, isReportContentSemanticallyEqual, isRequirementArtifact2 as isRequirementArtifact, isReviewerRole, isSemgrepInstalled, isToolAvailable, isToolInstalled, isUncOrEmptyPath, loadDlpPolicy, loadPrivacyPolicy, loadProductHandoffSidecar, loadQualityBaseline, locateTaskInActiveChanges, mapSastSeverityToSarifLevel, maskSecret, mergeSbomGaps, normalizeIdentifierToSnakeCase, normalizePath, normalizeScaffoldLanguages, normalizeSpdxLicense, normalizeUri, normalizeWinDrive, orchestrateNativeAstAnalysis, orchestratePolyglotSast, parseCoberturaXmlCoverage, parseCommitTrailers, parseDataAsset, parseDlpPolicy, parseFeatureDocument, parseFrontmatter, parseFrontmatterId, parseGenericDoc, parseGoCoverProfile, parseIngestedSbom, parseIstanbulCoverageSummary, parseJacocoXmlCoverage, parseLcovCoverage, parseLicensePolicy, parseLlvmCovJson, parseMarkdownFrontmatter, parseQualityPolicy, parseRequirementFile, parseSarifDocument, parseSarifDocuments, parseSecuritySuppression, parseSpecCatalogScope, parseStrictPurl, parseSyftOutput, parseTasksDoc, parseTasksFromContent, parseTrivyOutput, parseTrivyVulnerabilities, processPackageDir, readCodeCoverageSummary, readFailOnMissingToolFromQualityPolicy, readNormalizedCoverage, readPackageJson, redactSensitiveDiagnostics, renderAntigravityAgentFile, renderAntigravitySkillFile, renderAutonomyModeSection, renderClaudeAgentFile, renderClaudeSkillFile, renderCopilotAgentFile, renderCopilotSkillFile, renderCursorAgentFile, renderCursorSkillFile, renderDashboardHtml, renderManualsTab, resolveAgentTargets, resolveBranchHierarchy, resolveCiEnvironment, resolveCodingRuleStacks, resolveCurrentGitCommit, resolveCytoscapePath, resolveDefaultBranchBase, resolveDeterministicDate, resolveDisallowedLogFields, resolveFeatureFilePath, resolveGitRef, resolveLicenseFromFile, resolveReleaseBaseBranch, resolveSastCwe, resolveSastOwasp, resolveSchemaForArtifact, resolveTargetFiles, resolveTrustedBinaryPath, resolveWinCmdSpawn, runGitleaksCli, runSemgrepCli, sanitizeDlpPayload, sanitizeDlpText, sanitizeSarifText, sanitizeSbomLicense, sanitizeTestCorpus, scaffoldGherkinSteps, scaffoldSddChange, scanAllProductHandoffs, scanAllTestArtifacts, scanContentForSecrets, scanFileForPrivacyViolations, scanFileForSast, scanGoDependencies, scanInstalledLicenses, scanManualsInWorkspace, scanMavenDependencies, scanPnpmStore, scanPythonDependencies, scanRustDependencies, scanSubdirectories, scanWithNativeFs, scanWithSbom, scanWithSyft, scanWithTrivy, scanWithTrivyAsync, serializeSarifDocument, slugify2 as slugify, spawnTrustedBinary, stripMaskingCalls, stripVolatileReportMetadata, submitReviewReport, syncPdacDigests, tokenizeTitle, updateCitationsInContent, validateAgainstSchema, validateAnchorExistence, validateArtifactSchema, verifyArtifactDuplicates, verifyArtifactsSchemas, verifyBddReportAttestation, verifyLicenses, verifyLicensesAsync, verifyManuals, verifyPdacGraph, verifyPrivacy, verifyProgressiveFriction, verifyQualityGate, verifySast, verifySastAsync, verifySddIntegration, verifySecrets, verifyTasksGovernance, verifyTestingCoverage, verifyTraceability, walkDir, walkMdFiles, walkProjectFiles, walkSourceFiles, walkTaskFiles, writeCucumberJsonReport, writeCycloneDxSbom, writeQualityBaseline, writeReleaseKpiReport, writeReportFileIfChanged, writeSecuritySarifReport, writeThirdPartyNotices };
24371
+ export { ALL_ARCHITECTURE_TEMPLATES, ALL_QUALITY_GATES, BRANCH_PATTERNS, BddStepRegistry, BranchSafetyCheck, CPP_CLANG_TIDY, CPP_CMAKE_STRICT, DEFAULT_DLP_RULES, DEFAULT_EXCLUDED_PATTERNS, DEFAULT_EXCLUDES, DEFAULT_EXCLUDE_DIRS, DEFAULT_EXTENSIONS, DEFAULT_PRIVACY_POLICY, DEFAULT_SAST_EXCLUDES, DEFAULT_TEST_ARTIFACT_PATTERNS, DEFAULT_UNIT_TEST_PATTERNS, DOTNET_DIRECTORY_BUILD_PROPS, DiffDetector, DlpSanitizer, DoctorOrchestrator, DoctorReporter, DoctorService, FileSystemJailAdapter, GENERAL_SOURCE_EXTENSIONS, GHERKIN_GENERATOR_SPECS, GO_GOLANGCI_YML, GRADLE_STRICT_INIT_KTS, GitHooksHealthCheck, InTotoAttestationBuilder, JAVA_PMD_RULESET_XML, KOTLIN_DETEKT_YML, KPI_SUMMARY_END_TAG, KPI_SUMMARY_START_TAG, LIFECYCLE_SKILL_TEMPLATES, MAX_SARIF_BYTES, MAX_SARIF_JSON_DEPTH, MAX_SARIF_RESULTS, MigrationOrchestrator, MigrationReporter, MigrationService, NativeFileSystemProbeAdapter, OpenSpecAdapter, OscalAssessmentBuilder, OverrideAnalyzer, PII_SAST_RULES, PREPARE_COMMIT_MSG_SCRIPT, PRE_COMMIT_SCRIPT, PROMPT_INJECTION_SIGNATURES, PROTECTED_BYPASS_PATTERNS, PROTECTED_CODING_RULES_FILES, PolicyRatchetEnforcer, REVIEWER_ROLES, REVIEW_VERDICTS, RUST_CARGO_CONFIG_TOML, RUST_CLIPPY_TOML, RegulatoryControlMapper, SARIF_SCHEMA_2_1_0, SARIF_VERSION, SAST_RULES, SCHEMA_SCHEMAS_ARCHITECTURE_ADR_SCHEMA_JSON, SCHEMA_SCHEMAS_ARCHITECTURE_COMPONENT_SCHEMA_JSON, SCHEMA_SCHEMAS_ARCHITECTURE_INTRODUCTION_AND_GOALS_SCHEMA_JSON, SCHEMA_SCHEMAS_COMPLIANCE_LICENSE_MANIFEST_SCHEMA_JSON, SCHEMA_SCHEMAS_COMPLIANCE_LICENSE_POLICY_SCHEMA_JSON, SCHEMA_SCHEMAS_COMPLIANCE_QUALITY_POLICY_SCHEMA_JSON, SCHEMA_SCHEMAS_IDE_MCP_CONFIG_SCHEMA_JSON, SCHEMA_SCHEMAS_MANUALS_PRODUCTION_MANUAL_SCHEMA_JSON, SCHEMA_SCHEMAS_MANUALS_USER_MANUAL_SCHEMA_JSON, SCHEMA_SCHEMAS_PRIVACY_DATA_ASSET_SCHEMA_JSON, SCHEMA_SCHEMAS_PRIVACY_PRIVACY_POLICY_SCHEMA_JSON, SCHEMA_SCHEMAS_PRIVACY_PRIVACY_REQ_SCHEMA_JSON, SCHEMA_SCHEMAS_PRIVACY_PRIVACY_ROPA_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_ACTOR_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_BOUNDED_CONTEXT_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_BUSINESS_RULE_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_JOURNEY_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_REQUIREMENT_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_TERM_SCHEMA_JSON, SCHEMA_SCHEMAS_PRODUCT_USE_CASE_SCHEMA_JSON, SCHEMA_SCHEMAS_SAFETY_HAZARD_SCHEMA_JSON, SCHEMA_SCHEMAS_SAFETY_SAFETY_REQ_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_DESIGN_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_HANDOFF_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_PROPOSAL_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_RELEASE_KPIS_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_SESSION_TELEMETRY_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_SPEC_SCHEMA_JSON, SCHEMA_SCHEMAS_SDD_TASKS_SCHEMA_JSON, SCHEMA_SCHEMAS_SECURITY_ABUSE_CASE_SCHEMA_JSON, SCHEMA_SCHEMAS_SECURITY_ENCLAVE_SCHEMA_JSON, SCHEMA_SCHEMAS_SECURITY_SECURITY_REQ_SCHEMA_JSON, SCHEMA_SCHEMAS_SECURITY_THREAT_ACTOR_SCHEMA_JSON, SCHEMA_SCHEMAS_WORKFLOW_AGENT_HANDOFF_SCHEMA_JSON, SECRET_RULES, SEVERITY_RANK2 as SEVERITY_RANK, SPECIALIZED_AGENT_TEMPLATES, STARTER_AGENT_GUARD_WRAPPER_CJS, STARTER_ANTIGRAVITY_HOOKS_JSON, STARTER_ANTIGRAVITY_MCP, STARTER_ANTIGRAVITY_RULES, STARTER_ARCH_ADR, STARTER_ARCH_ARCHITECTURE_CONSTRAINTS, STARTER_ARCH_COMPONENT, STARTER_ARCH_CONTEXT_AND_SCOPE, STARTER_ARCH_CROSS_CUTTING_CONCEPTS, STARTER_ARCH_DEPLOYMENT_VIEW, STARTER_ARCH_GLOSSARY, STARTER_ARCH_INTRODUCTION_AND_GOALS, STARTER_ARCH_LEVEL_1_WHITEBOX, STARTER_ARCH_QUALITY_REQUIREMENTS, STARTER_ARCH_RISKS_AND_TECHNICAL_DEBT, STARTER_ARCH_RUNTIME_VIEW, STARTER_ARCH_SOLUTION_STRATEGY, STARTER_AZURE_PIPELINES, STARTER_BASE_TEMPLATES, STARTER_BITBUCKET_PIPELINES, STARTER_CLAUDE_RULES, STARTER_COMPLIANCE_LICENSE_MANIFEST_YAML, STARTER_COPILOT_RULES, STARTER_CURSOR_CORE_RULES, STARTER_CURSOR_MCP, STARTER_CURSOR_PRODUCT_RULES, STARTER_CURSOR_QUALITY_RULES, STARTER_GITHUB_CI, STARTER_GITHUB_DEPLOY_DASHBOARD, STARTER_GITHUB_PR_KPI, STARTER_GITHUB_PULL_REQUEST_TEMPLATE, STARTER_GITHUB_SDD_INTEGRATE, STARTER_GITLAB_CI, STARTER_GUARD_BRANCH_CJS, STARTER_LICENSE_POLICY, STARTER_PRIVACY_POLICY, STARTER_PROCESS_README, STARTER_PULL_REQUEST_TEMPLATE, STARTER_QUALITY_POLICY, STARTER_REQUIREMENT_TEMPLATE, STARTER_SCHEMAS, STARTER_SCHEMAS_MAP, STARTER_TASK_TEMPLATE, STARTER_TEMPLATES_CI_AZURE_PIPELINES_YML, STARTER_TEMPLATES_CI_BITBUCKET_PIPELINES_YML, STARTER_TEMPLATES_CI_GITHUB_WORKFLOWS_CI_YML, STARTER_TEMPLATES_CI_GITHUB_WORKFLOWS_DEPLOY_DASHBOARD_YML, STARTER_TEMPLATES_CI_GITHUB_WORKFLOWS_PR_KPI_SUMMARY_YML, STARTER_TEMPLATES_CI_GITHUB_WORKFLOWS_SDD_INTEGRATE_ON_MERGE_YML, STARTER_TEMPLATES_CI__GITLAB_CI_YML, STARTER_TEMPLATES_COMPLIANCE_COMMERCIAL_ACQUISITION_REQUEST_TEMPLATE_MD, STARTER_TEMPLATES_MANUALS_PRODUCTION_MANUAL_TEMPLATE_MD, STARTER_TEMPLATES_MANUALS_USER_MANUAL_TEMPLATE_MD, STARTER_TEMPLATES_PRIVACY_DATA_ASSET_TEMPLATE_MD, STARTER_TEMPLATES_PRIVACY_DPIA_REQUEST_TEMPLATE_MD, STARTER_TEMPLATES_PRIVACY_PRIVACY_REQ_TEMPLATE_MD, STARTER_TEMPLATES_PRIVACY_PRIVACY_ROPA_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_ACTOR_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_BOUNDED_CONTEXT_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_BUSINESS_RULE_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_JOURNEY_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_REQUIREMENT_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_TERM_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_USER_DESIGN_FEEDBACK_TEMPLATE_MD, STARTER_TEMPLATES_PRODUCT_USE_CASE_TEMPLATE_MD, STARTER_TEMPLATES_SAFETY_HAZARD_TEMPLATE_MD, STARTER_TEMPLATES_SAFETY_SAFETY_REQ_TEMPLATE_MD, STARTER_TEMPLATES_SDD_DESIGN_TEMPLATE_MD, STARTER_TEMPLATES_SDD_HANDOFF_TEMPLATE_YAML, STARTER_TEMPLATES_SDD_PROPOSAL_TEMPLATE_MD, STARTER_TEMPLATES_SDD_PULL_REQUEST_TEMPLATE_MD, STARTER_TEMPLATES_SDD_SPEC_TEMPLATE_MD, STARTER_TEMPLATES_SDD_TASKS_TEMPLATE_MD, STARTER_TEMPLATES_SECURITY_ABUSE_CASE_TEMPLATE_MD, STARTER_TEMPLATES_SECURITY_ENCLAVE_TEMPLATE_MD, STARTER_TEMPLATES_SECURITY_SECURITY_REQ_TEMPLATE_MD, STARTER_TEMPLATES_SECURITY_THREAT_ACTOR_TEMPLATE_MD, STARTER_TEMPLATES_WORKFLOW_AGENT_HANDOFF_TEMPLATE_MD, STARTER_VSCODE_MCP, STARTER_WORKFLOW_HANDOFF_TEMPLATE, STARTER__GITHUB_PULL_REQUEST_TEMPLATE_MD, SUPPORTED_COVERAGE_FORMATS_HINT, SafeProcessRunnerAdapter, SarifIngestionError, ScaSbomError, SchemasPdacHealthCheck, SecurityToolsHealthCheck, SignatureReadinessCheck, SpecKitAdapter, TOOL_INSTALL_ALLOWLIST, TS_ESLINT_CONFIG_MJS, TS_STRICT_TSCONFIG, TYPE_TO_SCHEMA_MAP, TimestampedBackupManagerAdapter, ToolchainHealthCheck, TransactionManager, UNIT_TEST_SUFFIXES, VALID_AGENT_TARGETS, VALID_ARCHITECTURE_GRANULARITIES, VALID_AUTONOMY_MODES, VALID_CHANGE_PROFILES, VALID_CI_PROVIDERS, VALID_CODING_RULE_STACKS, WIN_CMD_META_RE, accumulateTaskSummaries, aggregateCommitKpiRecords, aggregatePrKpis, aggregateReleaseKpis, analyzeBddVariantsForRequirement, appendRevisionHistoryRow, applyRatchetMode, buildCycloneDxComponent, buildCycloneDxVulnerabilities, buildFeatureFileContent, buildGraphElements, buildSafeEnvironment, calculateJaccardSimilarity, calculateMetrics, calculateRating, calculateShannonEntropy, canonicalSort, canonicalizeJson, checkGherkinInSync, checkoutTaskBranch, classifyBranch, classifyMetricFromMessage, collectAgentFiles, collectDashboardMetrics, collectHistoricalKpis, compileTestPatterns, computeAgentPerformanceKpis, computeCanonicalSha256, computeLfSha256, computeRawSha256, computeSha256, computeViolationSignature, createDefaultDlpPolicy, createDefaultQualityPolicy, deduplicateAndSortPrivacyViolations, deduplicateAndSortSastViolations, deduplicateAndSortViolations, depositProductHandoffSidecar, detectActiveChangeForIntegration, detectAuthorIdentity, detectLanguage, detectPolyglotLoggerCall, detectProfileFromChange, detectProjectEcosystems, detectProjectStacks, detectPromptInjection, emitCiOutput, ensureToolAvailable, ensureTrivyAvailable, evaluateCompoundLicense, evaluateSingleDependency, evaluateVulnerabilityThresholds, executeBddFeature, extractAllRepoCommitKpis, extractBaselineEntriesFromResults, extractCitations, extractCommitKpisFromRange, extractDirectDepNames, extractFeatureTags, extractFrontmatter, extractFunctions, extractFunctionsBraceLanguages, extractFunctionsPolyglot, extractFunctionsPython, extractFunctionsPythonAst, extractFunctionsTypeScriptAst, extractGherkinBlock, extractGherkinFeatures, extractNormativeText, extractPythonFunctionsPolyglot, extractSemanticContent, findChangeWorkspaceDir, findLicenseFile, formatAgentKpisMarkdownSection, formatCommitTrailers, formatInspectResultMarkdown, formatPrKpiMarkdown, formatReleaseKpiMarkdown, formatTaskKpiRows, generateBranchHierarchyPlan, generateComplianceEvidenceBundle, generateComplianceEvidenceBundleSync, generateCycloneDxSbom, generateDashboardReport, generateDeterministicUuidV5, generateDuplicatesReportMarkdown, generateGovernanceReportMarkdown, generateLicenseReportMarkdown, generatePdacReportMarkdown, generatePrivacyReportMarkdown, generateQualityReport, generateRopaInventoryMarkdown, generateSastReportMarkdown, generateSecretsReportMarkdown, generateSecuritySarifReport, generateSuppressionsAuditReport, generateTestingCoverageReportMarkdown, generateThirdPartyNotices, generateTraceabilityReportMarkdown, getArchitectureTemplates, getCodingRulesFilesForStacks, getCytoscapeScript, getGitDiffLines, getNextCorrelativeNumber, getReferenceCodingRulesTemplates, getSddAdapter, getToolInstallSpec, inferArtifactTypeFromId, inferMissingTrailers, ingestSarifFiles, ingestSbomFile, initProject, injectKpisIntoPrBody, inspectElement, installGitHooks, integrateAllSddChanges, integrateSddChange, isCliInstalled, isFunctionReferencedInTests, isGitleaksInstalled, isMetricWorsened, isPathOutsideRoot, isPathProtectedFromPatch, isPlaceholderOrIgnored, isPolyglotTestArtifact, isPolyglotUnitTestFile, isProtectedCodingRulesFile, isReportContentSemanticallyEqual, isRequirementArtifact2 as isRequirementArtifact, isReviewerRole, isSemgrepInstalled, isToolAvailable, isToolInstalled, isUncOrEmptyPath, loadDlpPolicy, loadPrivacyPolicy, loadProductHandoffSidecar, loadQualityBaseline, locateTaskInActiveChanges, mapSastSeverityToSarifLevel, maskSecret, mergeSbomGaps, normalizeIdentifierToSnakeCase, normalizePath, normalizeScaffoldLanguages, normalizeSpdxLicense, normalizeUri, normalizeWinDrive, orchestrateNativeAstAnalysis, orchestratePolyglotSast, parseCoberturaXmlCoverage, parseCommitTrailers, parseDataAsset, parseDlpPolicy, parseFeatureDocument, parseFrontmatter, parseFrontmatterId, parseGenericDoc, parseGoCoverProfile, parseIngestedSbom, parseIstanbulCoverageSummary, parseJacocoXmlCoverage, parseLcovCoverage, parseLicensePolicy, parseLlvmCovJson, parseMarkdownFrontmatter, parseQualityPolicy, parseRequirementFile, parseSarifDocument, parseSarifDocuments, parseSecuritySuppression, parseSpecCatalogScope, parseStrictPurl, parseSyftOutput, parseTasksDoc, parseTasksFromContent, parseTrivyOutput, parseTrivyVulnerabilities, processPackageDir, readCodeCoverageSummary, readFailOnMissingToolFromQualityPolicy, readNormalizedCoverage, readPackageJson, redactSensitiveDiagnostics, renderAntigravityAgentFile, renderAntigravitySkillFile, renderAutonomyModeSection, renderClaudeAgentFile, renderClaudeSkillFile, renderCopilotAgentFile, renderCopilotSkillFile, renderCursorAgentFile, renderCursorSkillFile, renderDashboardHtml, renderManualsTab, resolveAgentTargets, resolveBranchHierarchy, resolveCiEnvironment, resolveCodingRuleStacks, resolveCurrentGitCommit, resolveCytoscapePath, resolveDefaultBranchBase, resolveDeterministicDate, resolveDisallowedLogFields, resolveFeatureFilePath, resolveGitRef, resolveLicenseFromFile, resolveReleaseBaseBranch, resolveSastCwe, resolveSastOwasp, resolveSchemaForArtifact, resolveTargetFiles, resolveTrustedBinaryPath, resolveWinCmdSpawn, runGitleaksCli, runSemgrepCli, sanitizeDlpPayload, sanitizeDlpText, sanitizeSarifText, sanitizeSbomLicense, sanitizeTestCorpus, scaffoldGherkinSteps, scaffoldSddChange, scanAllProductHandoffs, scanAllTestArtifacts, scanContentForSecrets, scanFileForPrivacyViolations, scanFileForSast, scanGoDependencies, scanInstalledLicenses, scanManualsInWorkspace, scanMavenDependencies, scanPnpmStore, scanPythonDependencies, scanRustDependencies, scanSubdirectories, scanWithNativeFs, scanWithSbom, scanWithSyft, scanWithTrivy, scanWithTrivyAsync, serializeSarifDocument, slugify2 as slugify, spawnTrustedBinary, stripMaskingCalls, stripVolatileReportMetadata, submitReviewReport, syncPdacDigests, tokenizeTitle, updateCitationsInContent, validateAgainstSchema, validateAnchorExistence, validateArtifactSchema, verifyArtifactDuplicates, verifyArtifactsSchemas, verifyBddReportAttestation, verifyLicenses, verifyLicensesAsync, verifyManuals, verifyPdacGraph, verifyPrivacy, verifyProgressiveFriction, verifyQualityGate, verifySast, verifySastAsync, verifySddIntegration, verifySecrets, verifyTasksGovernance, verifyTestingCoverage, verifyTraceability, walkDir, walkMdFiles, walkProjectFiles, walkSourceFiles, walkTaskFiles, writeCucumberJsonReport, writeCycloneDxSbom, writeQualityBaseline, writeReleaseKpiReport, writeReportFileIfChanged, writeSecuritySarifReport, writeThirdPartyNotices };
24242
24372
  //# sourceMappingURL=index.js.map
24243
24373
  //# sourceMappingURL=index.js.map