@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.cjs CHANGED
@@ -1717,21 +1717,24 @@ function collectUniqueSteps(doc) {
1717
1717
  return unique;
1718
1718
  }
1719
1719
  function renderTsFallback(relFeature, steps) {
1720
- const lines = [
1720
+ const entries = steps.map((st) => ` ['${mapStepKeyword(st.keyword)}', "${escapeDoubleQuotes(st.text)}"],`);
1721
+ return [
1721
1722
  `// AUTO-GENERATED RED BDD STEP DEFINITIONS (${relFeature})`,
1722
1723
  `import { BddStepRegistry } from '@aisdlc/core';`,
1723
1724
  ``,
1724
- `export function registerSteps(registry: BddStepRegistry): void {`
1725
- ];
1726
- for (const st of steps) {
1727
- const method = mapStepKeyword(st.keyword);
1728
- const escaped = escapeDoubleQuotes(st.text);
1729
- lines.push(` registry.${method}("${escaped}", () => {`);
1730
- lines.push(` throw new Error("RED: Step not implemented: ${escaped}");`);
1731
- lines.push(` });`);
1732
- }
1733
- lines.push(`}`, ``);
1734
- return lines.join("\n");
1725
+ `const STEP_SPECS: ReadonlyArray<readonly ['given' | 'when' | 'then', string]> = [`,
1726
+ ...entries,
1727
+ `];`,
1728
+ ``,
1729
+ `export function registerSteps(registry: BddStepRegistry): void {`,
1730
+ ` for (const [method, text] of STEP_SPECS) {`,
1731
+ ` registry[method](text, () => {`,
1732
+ ` throw new Error(\`RED: Step not implemented: \${text}\`);`,
1733
+ ` });`,
1734
+ ` }`,
1735
+ `}`,
1736
+ ``
1737
+ ].join("\n");
1735
1738
  }
1736
1739
  function renderPyFallback(relFeature, steps) {
1737
1740
  const lines = [
@@ -2075,39 +2078,85 @@ function extractGherkinFeatures(options = {}) {
2075
2078
  }
2076
2079
  return { success: true, features, totalScenarios };
2077
2080
  }
2081
+ function walkFeatureFiles(dir, fileList = []) {
2082
+ if (!fs12__namespace.existsSync(dir)) return fileList;
2083
+ for (const entry of fs12__namespace.readdirSync(dir).sort(canonicalSort)) {
2084
+ const fullPath = path14__namespace.join(dir, entry);
2085
+ if (fs12__namespace.statSync(fullPath).isDirectory()) {
2086
+ walkFeatureFiles(fullPath, fileList);
2087
+ } else if (entry.endsWith(".feature")) {
2088
+ fileList.push(fullPath);
2089
+ }
2090
+ }
2091
+ return fileList;
2092
+ }
2093
+ function hasDeterministicStepFile(rootDir, featureFullPath) {
2094
+ return Object.values(GHERKIN_GENERATOR_SPECS).some((spec) => {
2095
+ const stepPath = spec.resolveOutputPath(rootDir, featureFullPath);
2096
+ return fs12__namespace.existsSync(stepPath) && fs12__namespace.statSync(stepPath).size > 0;
2097
+ });
2098
+ }
2099
+ function findOrphanFeatureFiles(rootDir, expectedRelPaths) {
2100
+ const featuresDir = path14__namespace.join(rootDir, "tests", "features");
2101
+ const orphans = [];
2102
+ for (const fp of walkFeatureFiles(featuresDir)) {
2103
+ const rel = path14__namespace.relative(rootDir, fp).replace(/\\/g, "/");
2104
+ if (!expectedRelPaths.has(rel)) {
2105
+ orphans.push(rel);
2106
+ }
2107
+ }
2108
+ return orphans;
2109
+ }
2110
+ function verifyExistingFeatureFile(rootDir, targetPath, expectedContent, relTarget, state) {
2111
+ const actualContent = fs12__namespace.readFileSync(targetPath, "utf-8");
2112
+ if (actualContent.replace(/\r\n/g, "\n") !== expectedContent.replace(/\r\n/g, "\n")) {
2113
+ state.outOfSyncFiles.push(relTarget);
2114
+ }
2115
+ if (!hasDeterministicStepFile(rootDir, targetPath)) {
2116
+ state.missingStepFiles.push(relTarget);
2117
+ }
2118
+ }
2119
+ function checkSingleMarkdownFeatureSync(rootDir, filePath, state) {
2120
+ const { frontmatter, body } = parseMarkdownFrontmatter(fs12__namespace.readFileSync(filePath, "utf-8"));
2121
+ const gherkinBlocks = extractGherkinBlock(body);
2122
+ if (gherkinBlocks.length === 0) return;
2123
+ state.totalFeatures++;
2124
+ const id = frontmatter.id || path14__namespace.basename(filePath, path14__namespace.extname(filePath));
2125
+ const targetPath = resolveFeatureFilePath(rootDir, filePath, id, frontmatter["cucumber-feature-file"]);
2126
+ const relTarget = path14__namespace.relative(rootDir, targetPath).replace(/\\/g, "/");
2127
+ state.expectedRelPaths.add(relTarget);
2128
+ if (!fs12__namespace.existsSync(targetPath)) {
2129
+ state.missingFiles.push(relTarget);
2130
+ return;
2131
+ }
2132
+ const expectedContent = buildFeatureFileContent(rootDir, filePath, id, frontmatter.version, gherkinBlocks);
2133
+ verifyExistingFeatureFile(rootDir, targetPath, expectedContent, relTarget, state);
2134
+ }
2078
2135
  function checkGherkinInSync(options = {}) {
2079
2136
  const rootDir = options.rootDir || process.cwd();
2080
2137
  const targetFiles = resolveTargetFiles(rootDir, options.targetPath);
2081
- const outOfSyncFiles = [];
2082
- const missingFiles = [];
2083
- let totalFeatures = 0;
2138
+ const state = {
2139
+ outOfSyncFiles: [],
2140
+ missingFiles: [],
2141
+ missingStepFiles: [],
2142
+ expectedRelPaths: /* @__PURE__ */ new Set(),
2143
+ totalFeatures: 0
2144
+ };
2084
2145
  for (const filePath of targetFiles) {
2085
2146
  try {
2086
- const content = fs12__namespace.readFileSync(filePath, "utf-8");
2087
- const { frontmatter, body } = parseMarkdownFrontmatter(content);
2088
- const gherkinBlocks = extractGherkinBlock(body);
2089
- if (gherkinBlocks.length === 0) continue;
2090
- totalFeatures++;
2091
- const id = frontmatter.id || path14__namespace.basename(filePath, path14__namespace.extname(filePath));
2092
- const targetPath = resolveFeatureFilePath(rootDir, filePath, id, frontmatter["cucumber-feature-file"]);
2093
- const relTarget = path14__namespace.relative(rootDir, targetPath).replace(/\\/g, "/");
2094
- if (!fs12__namespace.existsSync(targetPath)) {
2095
- missingFiles.push(relTarget);
2096
- continue;
2097
- }
2098
- const expectedContent = buildFeatureFileContent(rootDir, filePath, id, frontmatter.version, gherkinBlocks);
2099
- const actualContent = fs12__namespace.readFileSync(targetPath, "utf-8");
2100
- if (actualContent.replace(/\r\n/g, "\n") !== expectedContent.replace(/\r\n/g, "\n")) {
2101
- outOfSyncFiles.push(relTarget);
2102
- }
2147
+ checkSingleMarkdownFeatureSync(rootDir, filePath, state);
2103
2148
  } catch {
2104
2149
  }
2105
2150
  }
2151
+ const orphanFeatureFiles = options.targetPath ? [] : findOrphanFeatureFiles(rootDir, state.expectedRelPaths);
2152
+ const inSync = state.missingFiles.length === 0 && state.outOfSyncFiles.length === 0 && orphanFeatureFiles.length === 0 && state.missingStepFiles.length === 0;
2106
2153
  return {
2107
- inSync: missingFiles.length === 0 && outOfSyncFiles.length === 0,
2108
- outOfSyncFiles,
2109
- missingFiles,
2110
- totalFeatures
2154
+ inSync,
2155
+ outOfSyncFiles: state.outOfSyncFiles,
2156
+ missingFiles: state.missingFiles,
2157
+ orphanFeatureFiles,
2158
+ missingStepFiles: state.missingStepFiles,
2159
+ totalFeatures: state.totalFeatures
2111
2160
  };
2112
2161
  }
2113
2162
 
@@ -6601,11 +6650,13 @@ function sanitizeDlpPayload(payload, policy = createDefaultDlpPolicy()) {
6601
6650
  // src/adapters/sdd/review-report.ts
6602
6651
  var REVIEW_VERDICTS = ["COMPLIANT", "SUGGESTIONS", "BLOCKING"];
6603
6652
  var REVIEWER_ROLES = [
6653
+ "agent-auditor",
6654
+ "agent-adversary",
6655
+ "agent-privacy-officer",
6656
+ "agent-expert-user",
6604
6657
  "agent-code-reviewer",
6605
6658
  "agent-security-auditor",
6606
6659
  "agent-compliance-checker",
6607
- "agent-privacy-officer",
6608
- "agent-expert-user",
6609
6660
  "auditor",
6610
6661
  "reviewer"
6611
6662
  ];
@@ -13855,1326 +13906,1466 @@ function verifyPrivacy(options = {}) {
13855
13906
  writePrivacyOutputsIfNeeded(result, options, policy, rootDir);
13856
13907
  return result;
13857
13908
  }
13858
- function calculateRating(mi, cc) {
13859
- if (mi >= 75 && cc <= 5) return "A";
13860
- if (mi >= 60 && cc <= 10) return "B";
13861
- if (mi >= 50 && cc <= 15) return "C";
13862
- if (mi >= 40 && cc <= 20) return "D";
13863
- return "F";
13909
+ var TRAILER_REGEXES = {
13910
+ taskId: /^\s*Task-ID:\s*(.+)$/im,
13911
+ parentRef: /^\s*Parent-Ref:\s*(.+)$/im,
13912
+ authorType: /^\s*Author-Type:\s*(human|agent)/im,
13913
+ aiModel: /^\s*AI-Model:\s*(.+)$/im,
13914
+ promptTokens: /^\s*Prompt-Tokens:\s*([0-9]+)/im,
13915
+ completionTokens: /^\s*Completion-Tokens:\s*([0-9]+)/im,
13916
+ activeTimeSeconds: /^\s*Active-Time-Seconds:\s*([0-9]+)/im
13917
+ };
13918
+ function parseTrailerInt(match) {
13919
+ if (!match) return 0;
13920
+ const val = parseInt(match[1], 10);
13921
+ return isNaN(val) ? 0 : val;
13864
13922
  }
13865
- function detectLanguage(filePath) {
13866
- const ext = path14__namespace.extname(filePath).toLowerCase();
13867
- switch (ext) {
13868
- case ".ts":
13869
- return "TypeScript";
13870
- case ".js":
13871
- return "JavaScript";
13872
- case ".py":
13873
- return "Python";
13874
- case ".java":
13875
- return "Java";
13876
- case ".go":
13877
- return "Go";
13878
- case ".cs":
13879
- return "C#";
13880
- case ".rs":
13881
- return "Rust";
13882
- case ".cpp":
13883
- case ".c":
13884
- return "C/C++";
13885
- default:
13886
- return "Unknown";
13923
+ function resolveAuthorType(authorTypeMatch, aiModelMatch) {
13924
+ if (authorTypeMatch) {
13925
+ return authorTypeMatch[1].toLowerCase();
13887
13926
  }
13888
- }
13889
- function readCodeCoverageSummary(rootDir = process.cwd()) {
13890
- return readNormalizedCoverage(rootDir);
13891
- }
13892
- function formatCoverageRow(label, measured, minThreshold) {
13893
- if (measured === void 0) {
13894
- return `| **${label}** | \`N/A (Run test:coverage)\` | $\\ge ${minThreshold}\\%$ | \u2139\uFE0F NOT MEASURED |`;
13927
+ if (aiModelMatch && aiModelMatch[1].trim() !== "n/a") {
13928
+ return "agent";
13895
13929
  }
13896
- const status = measured >= minThreshold ? "\u2705 COMPLIANT" : "\u26A0\uFE0F BELOW THRESHOLD";
13897
- return `| **${label}** | \`${measured}%\` | $\\ge ${minThreshold}\\%$ | ${status} |`;
13930
+ return "human";
13898
13931
  }
13899
- function buildCoverageRows(coverage, policy) {
13900
- return [
13901
- formatCoverageRow("Line Coverage", coverage?.linesPct, policy.min_line_coverage),
13902
- formatCoverageRow("Branch Coverage", coverage?.branchesPct, policy.min_branch_coverage),
13903
- formatCoverageRow("Function Coverage", coverage?.functionsPct, policy.min_function_coverage)
13904
- ];
13932
+ function resolveTrailerOrScope(match, text, fallbackRegex) {
13933
+ if (match) return match[1].trim();
13934
+ const subMatch = text.match(fallbackRegex);
13935
+ return subMatch ? subMatch[1].toUpperCase() : void 0;
13905
13936
  }
13906
- function updateLangStats(langMap, fn) {
13907
- const lang = detectLanguage(fn.filePath);
13908
- const existing = langMap.get(lang) || { fns: 0, loc: 0, miSum: 0, ccSum: 0 };
13909
- existing.fns++;
13910
- existing.loc += fn.loc;
13911
- existing.miSum += fn.maintainability;
13912
- existing.ccSum += fn.cyclomatic;
13913
- langMap.set(lang, existing);
13937
+ function parseCommitTrailers(rawMessage) {
13938
+ const text = rawMessage || "";
13939
+ const authorTypeMatch = text.match(TRAILER_REGEXES.authorType);
13940
+ const aiModelMatch = text.match(TRAILER_REGEXES.aiModel);
13941
+ const authorType = resolveAuthorType(authorTypeMatch, aiModelMatch);
13942
+ const rawModel = aiModelMatch ? aiModelMatch[1].trim() : void 0;
13943
+ const aiModel = rawModel && rawModel !== "n/a" ? rawModel : void 0;
13944
+ return {
13945
+ taskId: resolveTrailerOrScope(text.match(TRAILER_REGEXES.taskId), text, /\b(TSK-[0-9A-Za-z_-]+)\b/i),
13946
+ parentRef: resolveTrailerOrScope(text.match(TRAILER_REGEXES.parentRef), text, /\b((?:CHG|FEAT|BUG|FIX|PATCH)-[0-9A-Za-z_-]+)\b/i),
13947
+ authorType,
13948
+ aiModel,
13949
+ promptTokens: parseTrailerInt(text.match(TRAILER_REGEXES.promptTokens)),
13950
+ completionTokens: parseTrailerInt(text.match(TRAILER_REGEXES.completionTokens)),
13951
+ activeTimeSeconds: parseTrailerInt(text.match(TRAILER_REGEXES.activeTimeSeconds))
13952
+ };
13914
13953
  }
13915
- function processFunctionMetric(fn, accumulated) {
13916
- accumulated.totalMi += fn.maintainability;
13917
- accumulated.totalCc += fn.cyclomatic;
13918
- accumulated.totalCognitive += fn.cognitive;
13919
- accumulated.totalLoc += fn.loc;
13920
- updateLangStats(accumulated.langMap, fn);
13921
- if (fn.violations.length > 0) {
13922
- accumulated.violationsList.push(`- **\`${fn.relPath}\`** [\`${fn.functionName}\`]: ${fn.violations.join(", ")}`);
13923
- }
13954
+ function formatCommitTrailers(trailers) {
13955
+ const lines = [];
13956
+ if (trailers.taskId) lines.push(`Task-ID: ${trailers.taskId}`);
13957
+ if (trailers.parentRef) lines.push(`Parent-Ref: ${trailers.parentRef}`);
13958
+ lines.push(`Author-Type: ${trailers.authorType || "human"}`);
13959
+ lines.push(`AI-Model: ${trailers.aiModel || "n/a"}`);
13960
+ lines.push(`Prompt-Tokens: ${trailers.promptTokens ?? 0}`);
13961
+ lines.push(`Completion-Tokens: ${trailers.completionTokens ?? 0}`);
13962
+ lines.push(`Active-Time-Seconds: ${trailers.activeTimeSeconds ?? 0}`);
13963
+ return lines.join("\n");
13924
13964
  }
13925
- function accumulateMetrics(results) {
13926
- const accumulated = {
13927
- totalMi: 0,
13928
- totalCc: 0,
13929
- totalCognitive: 0,
13930
- totalLoc: 0,
13931
- langMap: /* @__PURE__ */ new Map(),
13932
- violationsList: []
13933
- };
13934
- for (const fn of results) {
13935
- processFunctionMetric(fn, accumulated);
13965
+ function parseRawLogChunks(rawLog) {
13966
+ const rawCommits = rawLog.split("---AI_SDLC_COMMIT---").filter((c) => c.trim().length > 0);
13967
+ const chunks = [];
13968
+ for (const raw of rawCommits) {
13969
+ const endBodyIdx = raw.indexOf("---AI_SDLC_BODY_END---");
13970
+ if (endBodyIdx === -1) continue;
13971
+ const beforeEnd = raw.slice(0, endBodyIdx).trimStart();
13972
+ const afterEnd = raw.slice(endBodyIdx + "---AI_SDLC_BODY_END---".length);
13973
+ const firstNewline = beforeEnd.indexOf("\n");
13974
+ const header = firstNewline === -1 ? beforeEnd : beforeEnd.slice(0, firstNewline);
13975
+ const body = firstNewline === -1 ? "" : beforeEnd.slice(firstNewline + 1);
13976
+ const numstatLines = afterEnd.split("\n").filter((l) => /^\d+\s+\d+\s+/.test(l.trim()));
13977
+ chunks.push({ header, body, numstatLines });
13936
13978
  }
13937
- return accumulated;
13979
+ return chunks;
13938
13980
  }
13939
- function renderPolyglotRows(langMap) {
13940
- const rows = [];
13941
- for (const [lang, stats] of langMap.entries()) {
13942
- const langMi = Math.round(stats.miSum / stats.fns * 10) / 10;
13943
- const langCc = Math.round(stats.ccSum / stats.fns * 10) / 10;
13944
- const rating = calculateRating(langMi, langCc);
13945
- rows.push(`| **${lang}** | \`${stats.fns}\` | \`${stats.loc}\` | \`${langMi}\` | \`${langCc}\` | \`${rating}\` |`);
13981
+ function sumNumstatLines(lines) {
13982
+ let added = 0;
13983
+ let deleted = 0;
13984
+ const files = [];
13985
+ for (const line of lines) {
13986
+ const parts = line.trim().split(/\s+/);
13987
+ if (parts.length >= 2) {
13988
+ const a = parseInt(parts[0], 10);
13989
+ const d = parseInt(parts[1], 10);
13990
+ if (!isNaN(a)) added += a;
13991
+ if (!isNaN(d)) deleted += d;
13992
+ if (parts.length >= 3) files.push(parts.slice(2).join(" "));
13993
+ }
13946
13994
  }
13947
- return rows;
13995
+ return { added, deleted, files };
13948
13996
  }
13949
- var EVALUATION_STANDARDS_MD = [
13950
- "---",
13951
- "",
13952
- "## 4. Evaluation Criteria and Standards",
13953
- "- **McCabe Cyclomatic Complexity (CC)**: Number of linearly independent paths.",
13954
- "- **Maintainability Index (SEI MI)**: Normalized formula [0 - 100] combining Halstead Volume, CC, and LOC.",
13955
- "- **Automated Test Coverage**: Passively ingested from `coverage/coverage-summary.json` or `lcov.info` when present.",
13956
- "- **Clean Code Guardrails**: Prohibition of implicit `any` typing, function length limits ($\\le 40$ lines), and zero unjustified suppressions."
13957
- ].join("\n");
13958
- function computeQualityAverages(totalFunctions, acc) {
13959
- const avgMaintainability = totalFunctions > 0 ? Math.round(acc.totalMi / totalFunctions * 10) / 10 : 100;
13960
- const avgCyclomatic = totalFunctions > 0 ? Math.round(acc.totalCc / totalFunctions * 10) / 10 : 1;
13961
- const avgCognitive = totalFunctions > 0 ? Math.round(acc.totalCognitive / totalFunctions * 10) / 10 : 0;
13962
- const globalRating = calculateRating(avgMaintainability, avgCyclomatic);
13963
- return { avgMaintainability, avgCyclomatic, avgCognitive, globalRating };
13997
+ function evaluateIsBugFix(subject, parentRef) {
13998
+ if (parentRef && /^(BUG|FIX)-/i.test(parentRef)) return true;
13999
+ return /^(fix|bug)(\([^)]+\))?:/i.test(subject.trim());
13964
14000
  }
13965
- function buildReportHeader3(verdict, rating, mi, cc) {
13966
- const status = verdict === "PASS" ? "\u{1F7E2} APPROVED (RELEASE READY)" : "\u{1F534} BLOCKED (VIOLATIONS DETECTED)";
13967
- return [
13968
- `# \u{1F4CA} Formal Quality and Release Gate Report (AI-SDLC)`,
13969
- "",
13970
- `> **Generation Date:** ${resolveDeterministicDate().toISOString()}`,
13971
- `> **Release Gate Verdict:** ${status}`,
13972
- `> **Global Rating:** **\`${rating}\`** (MI Index: ${mi}/100, Average CC: ${cc})`
13973
- ];
14001
+ function inferAgentTrailers(trailers, linesAdded, linesDeleted) {
14002
+ const res = { ...trailers };
14003
+ const linesChanged = linesAdded + linesDeleted;
14004
+ let estimated = false;
14005
+ if (res.promptTokens === 0 && res.completionTokens === 0) {
14006
+ res.completionTokens = linesChanged > 0 ? Math.max(linesAdded * 10, 50) : 0;
14007
+ res.promptTokens = linesChanged > 0 ? Math.max(2500 + linesChanged * 25, 3e3) : 1e3;
14008
+ estimated = true;
14009
+ }
14010
+ if (res.activeTimeSeconds === 0) {
14011
+ res.activeTimeSeconds = linesChanged > 0 ? Math.round(30 + linesChanged * 0.5) : 30;
14012
+ estimated = true;
14013
+ }
14014
+ res.isTelemetryEstimated = estimated;
14015
+ return res;
13974
14016
  }
13975
- function buildMetricStatus(averages, policy, failCount) {
13976
- return {
13977
- ccStatus: averages.avgCyclomatic <= policy.max_cyclomatic ? "\u2705 COMPLIANT" : "\u274C EXCEEDED",
13978
- cogStatus: averages.avgCognitive <= policy.max_cognitive ? "\u2705 COMPLIANT" : "\u274C EXCEEDED",
13979
- miStatus: averages.avgMaintainability >= policy.min_maintainability ? "\u2705 COMPLIANT" : "\u274C INSUFFICIENT",
13980
- violStatus: failCount === 0 ? "\u2705 0 VIOLATIONS" : "\u274C BLOCKED"
13981
- };
14017
+ function inferHumanTrailers(trailers, linesAdded, linesDeleted) {
14018
+ const res = { ...trailers };
14019
+ const linesChanged = linesAdded + linesDeleted;
14020
+ let estimated = false;
14021
+ if (res.activeTimeSeconds === 0) {
14022
+ res.activeTimeSeconds = linesChanged > 0 ? Math.round(180 + linesChanged * 2) : 120;
14023
+ estimated = true;
14024
+ }
14025
+ res.isTelemetryEstimated = estimated;
14026
+ return res;
13982
14027
  }
13983
- function buildCountRows(totalFiles, totalFunctions, totalLoc) {
13984
- return [
13985
- `| **Analyzed Files** | \`${totalFiles}\` | N/A | \u2139\uFE0F |`,
13986
- `| **Evaluated Functions** | \`${totalFunctions}\` | N/A | \u2139\uFE0F |`,
13987
- `| **Lines of Code (LOC)** | \`${totalLoc}\` | N/A | \u2139\uFE0F |`
13988
- ];
14028
+ function inferMissingTrailers(trailers, linesAdded, linesDeleted) {
14029
+ return trailers.authorType === "agent" ? inferAgentTrailers(trailers, linesAdded, linesDeleted) : inferHumanTrailers(trailers, linesAdded, linesDeleted);
13989
14030
  }
13990
- function buildExecutiveTable(gateResult, totalLoc, averages, coverage) {
13991
- const { policy, totalFiles, totalFunctions, failCount } = gateResult;
13992
- const status = buildMetricStatus(averages, policy, failCount);
13993
- return [
13994
- "## 1. Executive Metric Summary",
13995
- "",
13996
- "| Key Metric | Measured Value | Policy Threshold | Compliance |",
13997
- "| :--- | :---: | :---: | :---: |",
13998
- ...buildCountRows(totalFiles, totalFunctions, totalLoc),
13999
- `| **Cyclomatic Complexity (Average)** | \`${averages.avgCyclomatic}\` | $\\le ${policy.max_cyclomatic}$ | ${status.ccStatus} |`,
14000
- `| **Cognitive Complexity (Average)** | \`${averages.avgCognitive}\` | $\\le ${policy.max_cognitive}$ | ${status.cogStatus} |`,
14001
- `| **Maintainability Index (SEI MI)** | \`${averages.avgMaintainability} / 100\` | $\\ge ${policy.min_maintainability}$ | ${status.miStatus} |`,
14002
- ...buildCoverageRows(coverage, policy),
14003
- `| **Functions in Violation** | \`${failCount}\` | $0$ (Mode ${policy.enforce_mode}) | ${status.violStatus} |`
14004
- ];
14005
- }
14006
- function renderQualityReportMarkdown(gateResult, coverage, accumulated, averages) {
14007
- const verdict = gateResult.success ? "PASS" : "FAIL";
14008
- const header = buildReportHeader3(verdict, averages.globalRating, averages.avgMaintainability, averages.avgCyclomatic);
14009
- const table = buildExecutiveTable(gateResult, accumulated.totalLoc, averages, coverage);
14010
- const polyglot = [
14011
- "## 2. Polyglot Breakdown by Language Ecosystem",
14012
- "",
14013
- "| Language | Functions | Total LOC | Average MI | Average CC | Rating |",
14014
- "| :--- | :---: | :---: | :---: | :---: | :---: |",
14015
- ...renderPolyglotRows(accumulated.langMap)
14031
+ function resolveGitRef(cwd, ref) {
14032
+ if (!ref || ref === "HEAD") return ref;
14033
+ const candidates = [
14034
+ ref,
14035
+ `feat/${ref}`,
14036
+ `release/${ref}`,
14037
+ `bug/${ref}`,
14038
+ `task/${ref}`,
14039
+ `origin/${ref}`,
14040
+ `origin/feat/${ref}`,
14041
+ `origin/release/${ref}`,
14042
+ `origin/bug/${ref}`
14016
14043
  ];
14017
- const violationsSection = accumulated.violationsList.length > 0 ? ["", "---", "", "## 3. Quality Gate Violations Log", "", ...accumulated.violationsList] : [];
14018
- return [...header, "", "---", "", ...table, "", "---", "", ...polyglot, ...violationsSection, "", EVALUATION_STANDARDS_MD].join("\n");
14044
+ for (const cand of candidates) {
14045
+ try {
14046
+ child_process3.execFileSync("git", ["rev-parse", "--verify", "--quiet", cand], {
14047
+ cwd,
14048
+ stdio: ["pipe", "pipe", "pipe"]
14049
+ });
14050
+ return cand;
14051
+ } catch {
14052
+ }
14053
+ }
14054
+ return ref;
14019
14055
  }
14020
- function writeQualityReportFile(rootDir, markdown) {
14021
- const targetPath = path14__namespace.join(rootDir, "reports", "QUALITY_REPORT.md");
14022
- return writeReportFileIfChanged(targetPath, markdown);
14056
+ function fetchGitLogOutput(cwd, baseRef, headRef, format) {
14057
+ const rangeArg = baseRef ? `${baseRef}..${headRef}` : headRef;
14058
+ try {
14059
+ return child_process3.execFileSync("git", ["log", rangeArg, `--format=${format}`, "--numstat"], {
14060
+ cwd,
14061
+ encoding: "utf-8",
14062
+ stdio: ["pipe", "pipe", "pipe"]
14063
+ });
14064
+ } catch {
14065
+ if (baseRef && !baseRef.includes("/")) {
14066
+ try {
14067
+ return child_process3.execFileSync("git", ["log", `origin/${baseRef}..${headRef}`, `--format=${format}`, `--numstat`], {
14068
+ cwd,
14069
+ encoding: "utf-8",
14070
+ stdio: ["pipe", "pipe", "pipe"]
14071
+ });
14072
+ } catch {
14073
+ return "";
14074
+ }
14075
+ }
14076
+ return "";
14077
+ }
14023
14078
  }
14024
- function generateQualityReport(options = {}) {
14025
- const rootDir = options.rootDir || process.cwd();
14026
- const gateResult = verifyQualityGate({
14027
- rootDir,
14028
- policyPath: options.policyPath,
14029
- thresholds: options.thresholds
14030
- });
14031
- const coverage = readCodeCoverageSummary(rootDir);
14032
- const accumulated = accumulateMetrics(gateResult.results);
14033
- const averages = computeQualityAverages(gateResult.totalFunctions, accumulated);
14034
- const markdown = renderQualityReportMarkdown(gateResult, coverage, accumulated, averages);
14035
- writeQualityReportFile(rootDir, markdown);
14079
+ function buildCommitKpiRecord(chunk) {
14080
+ const fields = chunk.header.split("");
14081
+ if (fields.length < 5) return null;
14082
+ const rawTrailers = parseCommitTrailers(chunk.body);
14083
+ const { added, deleted, files } = sumNumstatLines(chunk.numstatLines);
14084
+ const trailers = inferMissingTrailers(rawTrailers, added, deleted);
14036
14085
  return {
14037
- markdown,
14038
- totalFiles: gateResult.totalFiles,
14039
- totalFunctions: gateResult.totalFunctions,
14040
- avgMaintainability: averages.avgMaintainability,
14041
- avgCyclomatic: averages.avgCyclomatic,
14042
- verdict: gateResult.success ? "PASS" : "FAIL",
14043
- coverage
14086
+ sha: fields[0],
14087
+ authorName: fields[1],
14088
+ authorEmail: fields[2],
14089
+ date: fields[3],
14090
+ subject: fields[4],
14091
+ trailers,
14092
+ linesAdded: added,
14093
+ linesDeleted: deleted,
14094
+ isBugFix: evaluateIsBugFix(fields[4], trailers.parentRef),
14095
+ touchedFiles: files
14044
14096
  };
14045
14097
  }
14046
-
14047
- // src/git/workflow.ts
14048
- var BRANCH_PATTERNS = {
14049
- MAIN: /^main$/,
14050
- RELEASE: /^release\/v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$/,
14051
- FEATURE: /^(feat|feature)\/(?:v[0-9]+\.[0-9]+\.[0-9]+\/)?([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/,
14052
- BUG: /^(bug|fix)\/(?:v[0-9]+\.[0-9]+\.[0-9]+\/)?([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/,
14053
- PATCH: /^(patch)\/(?:v[0-9]+\.[0-9]+\.[0-9]+\/)?([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/,
14054
- TASK: /^task\/([a-zA-Z0-9]+-[a-zA-Z0-9-]+)\/([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/
14055
- };
14056
- function classifyTier1And2(branchName) {
14057
- if (BRANCH_PATTERNS.MAIN.test(branchName)) {
14058
- return {
14059
- valid: true,
14060
- tier: 1,
14061
- tierName: "Main (Producci\xF3n)",
14062
- parentRequirement: "Ninguno (Rama Ra\xEDz)",
14063
- targetMerge: "Despliegue a Producci\xF3n"
14064
- };
14065
- }
14066
- if (BRANCH_PATTERNS.RELEASE.test(branchName)) {
14067
- return {
14068
- valid: true,
14069
- tier: 2,
14070
- tierName: "Versi\xF3n / Release",
14071
- parentRequirement: "Debe originarse desde main",
14072
- targetMerge: "main"
14073
- };
14074
- }
14075
- return null;
14076
- }
14077
- var TIER_3_CONFIGS = [
14078
- { regex: BRANCH_PATTERNS.FEATURE, tierName: "Feature (Funcionalidad)", parentReq: "Debe originarse desde una rama release/vX.Y.Z activa", merge: "release/vX.Y.Z" },
14079
- { regex: BRANCH_PATTERNS.BUG, tierName: "Bug (Defecto)", parentReq: "Debe originarse desde una rama release/vX.Y.Z activa", merge: "release/vX.Y.Z" },
14080
- { 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" }
14081
- ];
14082
- function classifyTier3(branchName) {
14083
- for (const cfg of TIER_3_CONFIGS) {
14084
- const m = branchName.match(cfg.regex);
14085
- if (m) {
14086
- return {
14087
- valid: true,
14088
- tier: 3,
14089
- tierName: cfg.tierName,
14090
- id: m[2],
14091
- parentRequirement: cfg.parentReq,
14092
- targetMerge: cfg.merge
14093
- };
14094
- }
14098
+ function extractCommitKpisFromRange(baseRef, headRef = "HEAD", options = {}) {
14099
+ const cwd = options.cwd || process.cwd();
14100
+ const resolvedBase = resolveGitRef(cwd, baseRef);
14101
+ const resolvedHead = resolveGitRef(cwd, headRef);
14102
+ const format = "---AI_SDLC_COMMIT---%n%H%x1f%an%x1f%ae%x1f%aI%x1f%s%n%B%n---AI_SDLC_BODY_END---";
14103
+ const rawOutput = fetchGitLogOutput(cwd, resolvedBase, resolvedHead, format);
14104
+ if (!rawOutput) return [];
14105
+ const chunks = parseRawLogChunks(rawOutput);
14106
+ const records = [];
14107
+ for (const chunk of chunks) {
14108
+ const rec = buildCommitKpiRecord(chunk);
14109
+ if (rec) records.push(rec);
14095
14110
  }
14096
- return null;
14111
+ return records;
14097
14112
  }
14098
- function classifyTier4(branchName) {
14099
- const taskMatch = branchName.match(BRANCH_PATTERNS.TASK);
14100
- if (taskMatch) {
14101
- return {
14102
- valid: true,
14103
- tier: 4,
14104
- tierName: "Task (Tarea At\xF3mica)",
14105
- parentId: taskMatch[1],
14106
- taskId: taskMatch[2],
14107
- parentRequirement: `Debe originarse desde la rama de feature, bug o patch: feat/${taskMatch[1]}, bug/${taskMatch[1]} o patch/${taskMatch[1]}`,
14108
- targetMerge: `feat/${taskMatch[1]}, bug/${taskMatch[1]} o patch/${taskMatch[1]}`
14109
- };
14113
+ function extractAllRepoCommitKpis(options = {}) {
14114
+ const cwd = options.cwd || process.cwd();
14115
+ const format = "---AI_SDLC_COMMIT---%n%H%x1f%an%x1f%ae%x1f%aI%x1f%s%n%B%n---AI_SDLC_BODY_END---";
14116
+ let rawOutput = "";
14117
+ try {
14118
+ rawOutput = child_process3.execFileSync("git", ["log", "--all", `--format=${format}`, "--numstat"], {
14119
+ cwd,
14120
+ encoding: "utf-8",
14121
+ stdio: ["pipe", "pipe", "pipe"]
14122
+ });
14123
+ } catch {
14124
+ return [];
14110
14125
  }
14111
- return null;
14112
- }
14113
- function classifyBranch(branchName) {
14114
- return classifyTier1And2(branchName) || classifyTier3(branchName) || classifyTier4(branchName) || {
14115
- valid: false,
14116
- tier: 0,
14117
- tierName: "Inv\xE1lido",
14118
- error: `El nombre '${branchName}' no cumple con los est\xE1ndares del modelo de 4 tiers.`
14119
- };
14120
- }
14121
- function buildTaskBranchLines(feature, tasks, fBranch) {
14122
- const lines = [];
14123
- const parentSlug = feature.split("-").slice(0, 2).join("-");
14124
- for (const t of tasks) {
14125
- const taskBranch = `task/${parentSlug}/${t.toLowerCase()}`;
14126
- lines.push(` \u251C\u2500\u2500 ${taskBranch}`);
14127
- lines.push(` \u2502 Comando git: git checkout ${fBranch} && git checkout -b ${taskBranch}`);
14126
+ if (!rawOutput) return [];
14127
+ const chunks = parseRawLogChunks(rawOutput);
14128
+ const records = [];
14129
+ for (const chunk of chunks) {
14130
+ const rec = buildCommitKpiRecord(chunk);
14131
+ if (rec) records.push(rec);
14128
14132
  }
14129
- return lines;
14133
+ return records;
14130
14134
  }
14131
- var PLAN_BANNER = "================================================================";
14132
- function buildPlanHeader(vBranch, fBranch) {
14133
- return [
14134
- PLAN_BANNER,
14135
- "AI-SDLC: Plan de Ramificaci\xF3n Jer\xE1rquico",
14136
- `${PLAN_BANNER}
14137
- `,
14138
- `1. [TIER 1] Rama Base Estable: main`,
14139
- `2. [TIER 2] Rama de Versi\xF3n Abierta: ${vBranch} (originada de main)`,
14140
- `3. [TIER 3] Rama de Feature: ${fBranch} (originada de ${vBranch})
14141
- `,
14142
- `4. [TIER 4] Ramas de Tareas At\xF3micas (originadas de ${fBranch}):`
14143
- ];
14135
+
14136
+ // src/reporters/pr-kpis.ts
14137
+ var KPI_SUMMARY_START_TAG = "<!-- AI-SDLC-KPI-SUMMARY-START -->";
14138
+ var KPI_SUMMARY_END_TAG = "<!-- AI-SDLC-KPI-SUMMARY-END -->";
14139
+ function calculateEstimatedCost(promptTokens, completionTokens) {
14140
+ const promptCost = promptTokens / 1e6 * 3;
14141
+ const completionCost = completionTokens / 1e6 * 15;
14142
+ return Math.round((promptCost + completionCost) * 1e4) / 1e4;
14144
14143
  }
14145
- function generateBranchHierarchyPlan(version, feature, tasks) {
14146
- const vBranch = `release/${version}`;
14147
- const fBranch = `feat/${feature}`;
14148
- const header = buildPlanHeader(vBranch, fBranch);
14149
- const taskLines = buildTaskBranchLines(feature, tasks, fBranch);
14150
- const footer = [
14151
- `
14152
- Flujo de Integraci\xF3n (Merges):`,
14153
- ` task/* \u2794 [PR Tarea] \u2794 ${fBranch} \u2794 [PR Feature + Quality Gate] \u2794 ${vBranch} \u2794 [PR Release] \u2794 main
14154
- `
14155
- ];
14144
+ function createEmptySummary() {
14156
14145
  return {
14157
- version,
14158
- feature,
14159
- tasks,
14160
- planText: [...header, ...taskLines, ...footer].join("\n")
14146
+ commits: 0,
14147
+ linesAdded: 0,
14148
+ linesDeleted: 0,
14149
+ activeTimeSeconds: 0,
14150
+ promptTokens: 0,
14151
+ completionTokens: 0,
14152
+ estimatedCostUsd: 0
14161
14153
  };
14162
14154
  }
14163
- function resolveVersionFromProposal(changeDir) {
14164
- const proposalFile = path14__namespace.join(changeDir, "proposal.md");
14165
- if (!fs12__namespace.existsSync(proposalFile)) return "1.0.0";
14166
- const propContent = fs12__namespace.readFileSync(proposalFile, "utf-8");
14167
- const propFm = propContent.match(/^---\r?\n([\s\S]*?)\r?\n---/);
14168
- if (!propFm) return "1.0.0";
14169
- const parsedProp = yaml3__default.default.load(propFm[1]);
14170
- return parsedProp?.version ? String(parsedProp.version) : "1.0.0";
14171
- }
14172
- function resolveChangeVersion(fm, changeDir) {
14173
- if (fm.version) return String(fm.version);
14174
- if (fm["target-release"] || fm.release) return String(fm["target-release"] || fm.release);
14175
- return resolveVersionFromProposal(changeDir);
14176
- }
14177
- function isTaskMatchingId(currentId, cleanTaskId) {
14178
- const targetLower = cleanTaskId.toLowerCase();
14179
- const currentLower = currentId.toLowerCase();
14180
- return currentLower === targetLower || currentLower.startsWith(`${targetLower}-`) || targetLower.startsWith(`${currentLower}-`);
14155
+ function accumulateRecord(target, record) {
14156
+ target.commits += 1;
14157
+ target.linesAdded += record.linesAdded;
14158
+ target.linesDeleted += record.linesDeleted;
14159
+ target.activeTimeSeconds += record.trailers.activeTimeSeconds;
14160
+ target.promptTokens += record.trailers.promptTokens;
14161
+ target.completionTokens += record.trailers.completionTokens;
14162
+ target.estimatedCostUsd = calculateEstimatedCost(target.promptTokens, target.completionTokens);
14181
14163
  }
14182
- function parseTasksFrontmatter(tasksFile) {
14183
- if (!fs12__namespace.existsSync(tasksFile)) return null;
14184
- try {
14185
- const content = fs12__namespace.readFileSync(tasksFile, "utf-8");
14186
- const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
14187
- if (!fmMatch) return null;
14188
- const fm = yaml3__default.default.load(fmMatch[1]);
14189
- return fm && Array.isArray(fm.tasks) ? fm : null;
14190
- } catch {
14191
- return null;
14164
+ function accumulateAuthorSummaries(records, humanSummary, byModel) {
14165
+ let linesAdded = 0;
14166
+ let linesDeleted = 0;
14167
+ let activeTime = 0;
14168
+ let prompt = 0;
14169
+ let completion = 0;
14170
+ let isBugPr = false;
14171
+ for (const record of records) {
14172
+ linesAdded += record.linesAdded;
14173
+ linesDeleted += record.linesDeleted;
14174
+ activeTime += record.trailers.activeTimeSeconds;
14175
+ prompt += record.trailers.promptTokens;
14176
+ completion += record.trailers.completionTokens;
14177
+ if (record.isBugFix) isBugPr = true;
14178
+ if (record.trailers.authorType === "agent") {
14179
+ const modelName = record.trailers.aiModel || "agent-generic";
14180
+ if (!byModel[modelName]) byModel[modelName] = createEmptySummary();
14181
+ accumulateRecord(byModel[modelName], record);
14182
+ } else {
14183
+ accumulateRecord(humanSummary, record);
14184
+ }
14192
14185
  }
14186
+ return { linesAdded, linesDeleted, activeTime, prompt, completion, isBugPr };
14193
14187
  }
14194
- function resolveRawChangeId(fm, entryName) {
14195
- return String(fm["change-id"] || fm.changeId || entryName.replace(/^(chg|CHG)-/i, "CHG-").toUpperCase());
14196
- }
14197
- function buildTaskMatch(currentId, currentTitle, rawChangeId, changeDir, versionStr) {
14188
+ function initTaskKpi(taskId) {
14198
14189
  return {
14199
- taskId: currentId,
14200
- taskTitle: currentTitle,
14201
- changeId: rawChangeId,
14202
- changeDir,
14203
- version: versionStr
14190
+ taskId,
14191
+ commits: 0,
14192
+ fixCommits: 0,
14193
+ linesAdded: 0,
14194
+ linesDeleted: 0,
14195
+ codeChurnPercent: 0,
14196
+ totalTokens: 0,
14197
+ activeTimeSeconds: 0,
14198
+ reworkTokens: 0,
14199
+ reworkTokensPercent: 0,
14200
+ reworkTimeSeconds: 0,
14201
+ reworkTimePercent: 0,
14202
+ isFirstTimeRight: true
14204
14203
  };
14205
14204
  }
14206
- function inspectChangeTasks(changeDir, entryName, cleanTaskId, availableTasks) {
14207
- const fm = parseTasksFrontmatter(path14__namespace.join(changeDir, "tasks.md"));
14208
- if (!fm || !fm.tasks) return void 0;
14209
- const rawChangeId = resolveRawChangeId(fm, entryName);
14210
- const versionStr = resolveChangeVersion(fm, changeDir);
14211
- let match;
14212
- for (const t of fm.tasks) {
14213
- if (!t?.id) continue;
14214
- const currentId = String(t.id).trim();
14215
- const currentTitle = String(t.title || "").trim();
14216
- availableTasks.push({ id: currentId, title: currentTitle, changeId: rawChangeId });
14217
- if (!match && isTaskMatchingId(currentId, cleanTaskId)) {
14218
- match = buildTaskMatch(currentId, currentTitle, rawChangeId, changeDir, versionStr);
14219
- }
14205
+ function processTaskCommit(tStat, record) {
14206
+ const recTokens = record.trailers.promptTokens + record.trailers.completionTokens;
14207
+ tStat.commits += 1;
14208
+ tStat.linesAdded += record.linesAdded;
14209
+ tStat.linesDeleted += record.linesDeleted;
14210
+ tStat.totalTokens += recTokens;
14211
+ tStat.activeTimeSeconds += record.trailers.activeTimeSeconds;
14212
+ const isRework = record.isBugFix || /^(fix|bug|remediate|refactor)(([^)]+))?:/i.test((record.subject || "").trim());
14213
+ if (isRework) {
14214
+ tStat.fixCommits += 1;
14215
+ tStat.reworkTokens += recTokens;
14216
+ tStat.reworkTimeSeconds += record.trailers.activeTimeSeconds;
14220
14217
  }
14221
- return match;
14222
14218
  }
14223
- function locateTaskInActiveChanges(taskId, rootDir = process.cwd()) {
14224
- const cleanTaskId = (taskId || "").trim();
14225
- if (!cleanTaskId) {
14226
- return { found: false, error: "Debe especificar un identificador de tarea v\xE1lido (ej. TSK-001)." };
14227
- }
14228
- const activeChangesDir = path14__namespace.join(rootDir, "specs", "changes", "active");
14229
- if (!fs12__namespace.existsSync(activeChangesDir)) {
14230
- return { found: false, error: `No se encontr\xF3 el directorio de cambios activos en '${activeChangesDir}'.` };
14231
- }
14232
- const availableTasks = [];
14233
- const candidateDirs = fs12__namespace.readdirSync(activeChangesDir, { withFileTypes: true });
14234
- let matchedTask;
14235
- for (const entry of candidateDirs) {
14236
- if (!entry.isDirectory()) continue;
14237
- const changeDir = path14__namespace.join(activeChangesDir, entry.name);
14238
- const m = inspectChangeTasks(changeDir, entry.name, cleanTaskId, availableTasks);
14239
- if (m && !matchedTask) {
14240
- matchedTask = m;
14241
- }
14219
+ function accumulateTaskSummaries(records) {
14220
+ const byTask = {};
14221
+ for (const record of records) {
14222
+ const tid = record.trailers.taskId || record.subject.match(/\b(TSK-[0-9A-Za-z_-]+)\b/i)?.[1]?.toUpperCase();
14223
+ if (!tid) continue;
14224
+ if (!byTask[tid]) byTask[tid] = initTaskKpi(tid);
14225
+ processTaskCommit(byTask[tid], record);
14242
14226
  }
14243
- if (matchedTask) {
14244
- return { found: true, match: matchedTask, availableTasks };
14227
+ for (const t of Object.values(byTask)) {
14228
+ const churn = t.linesAdded > 0 ? t.linesDeleted / t.linesAdded * 100 : 0;
14229
+ t.codeChurnPercent = Math.round(Math.min(churn, 100) * 10) / 10;
14230
+ t.reworkTokensPercent = t.totalTokens > 0 ? Math.round(t.reworkTokens / t.totalTokens * 1e3) / 10 : 0;
14231
+ t.reworkTimePercent = t.activeTimeSeconds > 0 ? Math.round(t.reworkTimeSeconds / t.activeTimeSeconds * 1e3) / 10 : 0;
14232
+ t.isFirstTimeRight = t.fixCommits === 0 && t.codeChurnPercent < 25;
14245
14233
  }
14234
+ return byTask;
14235
+ }
14236
+ function assemblePrKpiAggregation(baseRef, headRef, records, totals, humanSummary, byModel, byTask) {
14237
+ const totalTokens = totals.prompt + totals.completion;
14246
14238
  return {
14247
- found: false,
14248
- availableTasks,
14249
- error: `No se encontr\xF3 la tarea '${cleanTaskId}' en ning\xFAn cambio activo bajo 'specs/changes/active/'.`
14239
+ baseRef,
14240
+ headRef,
14241
+ totalCommits: records.length,
14242
+ linesAdded: totals.linesAdded,
14243
+ linesDeleted: totals.linesDeleted,
14244
+ totalActiveTimeSeconds: totals.activeTime,
14245
+ totalPromptTokens: totals.prompt,
14246
+ totalCompletionTokens: totals.completion,
14247
+ totalTokens,
14248
+ estimatedCostUsd: calculateEstimatedCost(totals.prompt, totals.completion),
14249
+ humanSummary,
14250
+ byModel,
14251
+ isBugPr: totals.isBugPr,
14252
+ commitRecords: records,
14253
+ byTask
14250
14254
  };
14251
14255
  }
14252
- function getGitBranchList(rootDir) {
14253
- try {
14254
- const out = child_process3.execFileSync("git", ["branch", "-a"], {
14255
- cwd: rootDir,
14256
- encoding: "utf-8",
14257
- stdio: ["pipe", "pipe", "ignore"]
14258
- });
14259
- return out.split("\n").map((l) => l.trim().replace(/^[*+]\s+/, "").replace(/^remotes\/origin\//, ""));
14260
- } catch {
14261
- return [];
14262
- }
14256
+ function aggregateCommitKpiRecords(records, baseRef = "main", headRef = "HEAD") {
14257
+ const humanSummary = createEmptySummary();
14258
+ const byModel = {};
14259
+ const totals = accumulateAuthorSummaries(records, humanSummary, byModel);
14260
+ const byTask = accumulateTaskSummaries(records);
14261
+ return assemblePrKpiAggregation(baseRef, headRef, records, totals, humanSummary, byModel, byTask);
14263
14262
  }
14264
- function detectExistingReleaseBranch(branches, cleanVersion) {
14265
- const candidate = `release/v${cleanVersion}`;
14266
- const existing = branches.find((b) => b.startsWith("release/v") && classifyBranch(b).valid);
14267
- return existing || candidate;
14263
+ function aggregatePrKpis(baseRef, headRef = "HEAD", options = {}) {
14264
+ const records = extractCommitKpisFromRange(baseRef, headRef, options);
14265
+ return aggregateCommitKpiRecords(records, baseRef, headRef);
14268
14266
  }
14269
- function detectExistingFeatureBranch(branches, dirName, changeId, changeSlug) {
14270
- const existing = branches.find(
14271
- (b) => b.startsWith("feat/") && (b.toLowerCase().includes(dirName.toLowerCase()) || b.toLowerCase().includes(changeId.toLowerCase())) && classifyBranch(b).valid
14272
- );
14273
- if (existing) return existing;
14274
- const normalizedName = slugify2(changeSlug).replace(/^(chg|bug|feat)-(\d+)/i, (_, p, n) => `${p.toUpperCase()}-${n}`);
14275
- return `feat/${normalizedName}`;
14267
+ function formatMinutes(seconds) {
14268
+ const mins = Math.round(seconds / 60);
14269
+ return mins > 0 ? `${mins} min` : `${seconds}s`;
14276
14270
  }
14277
- function buildDefaultTaskSuffix(taskId, taskTitle) {
14278
- let taskSuffix = taskId.toLowerCase();
14279
- const hasSlug = taskSuffix.includes("-") && taskSuffix.split("-").length > 2;
14280
- if (!hasSlug && taskTitle) {
14281
- const titleSlug = slugify2(taskTitle).split("-").slice(0, 4).join("-");
14282
- if (titleSlug) {
14283
- taskSuffix = `${taskSuffix}-${titleSlug}`;
14284
- }
14285
- }
14286
- return taskSuffix;
14271
+ function buildPrKpiRows(kpi, models) {
14272
+ const human = kpi.humanSummary;
14273
+ const commitCols = models.map((m) => kpi.byModel[m].commits).join(" | ");
14274
+ const linesCols = models.map((m) => `+${kpi.byModel[m].linesAdded} / -${kpi.byModel[m].linesDeleted}`).join(" | ");
14275
+ const timeCols = models.map((m) => formatMinutes(kpi.byModel[m].activeTimeSeconds)).join(" | ");
14276
+ const tokenCols = models.map((m) => `${(kpi.byModel[m].promptTokens + kpi.byModel[m].completionTokens).toLocaleString("en-US")}`).join(" | ");
14277
+ const costCols = models.map((m) => `$${kpi.byModel[m].estimatedCostUsd.toFixed(2)}`).join(" | ");
14278
+ const totalLines = `+${kpi.linesAdded} / -${kpi.linesDeleted}`;
14279
+ const totalTime = formatMinutes(kpi.totalActiveTimeSeconds);
14280
+ const totalTokensStr = `${kpi.totalTokens.toLocaleString("en-US")} tokens`;
14281
+ const totalCostStr = `$${kpi.estimatedCostUsd.toFixed(2)} USD`;
14282
+ return [
14283
+ `| **Commits** | ${human.commits} |${models.length > 0 ? ` ${commitCols} |` : ""} **${kpi.totalCommits}** |`,
14284
+ `| **Lines Added / Deleted** | +${human.linesAdded} / -${human.linesDeleted} |${models.length > 0 ? ` ${linesCols} |` : ""} **${totalLines}** |`,
14285
+ `| **Active Development Time** | ${formatMinutes(human.activeTimeSeconds)} |${models.length > 0 ? ` ${timeCols} |` : ""} **${totalTime}** |`,
14286
+ `| **Tokens Consumed (In+Out)** | 0 |${models.length > 0 ? ` ${tokenCols} |` : ""} **${totalTokensStr}** |`,
14287
+ `| **Estimated Cost (USD)** | \u2014 (Human labor) |${models.length > 0 ? ` ${costCols} |` : ""} **${totalCostStr}** |`
14288
+ ];
14287
14289
  }
14288
- function detectExistingTaskBranch(branches, parentId, taskId, taskTitle) {
14289
- const prefix = `task/${parentId}/`;
14290
- const existing = branches.find(
14291
- (b) => b.startsWith(prefix) && b.toLowerCase().includes(taskId.toLowerCase()) && classifyBranch(b).valid
14292
- );
14293
- if (existing) return existing;
14294
- return `task/${parentId}/${buildDefaultTaskSuffix(taskId, taskTitle)}`;
14290
+ function formatTaskKpiRows(byTask) {
14291
+ const taskIds = Object.keys(byTask || {});
14292
+ if (taskIds.length === 0) return [];
14293
+ const rows = [
14294
+ "",
14295
+ "#### \u{1F4CB} Task-Level Rework & Code Churn Breakdown",
14296
+ "",
14297
+ "| Task ID | Commits (Total / Fix) | Lines (+ / -) | Code Churn % | Rework Tokens % | Rework Time % | Status |",
14298
+ "| :--- | :---: | :---: | :---: | :---: | :---: | :---: |"
14299
+ ];
14300
+ for (const tid of taskIds) {
14301
+ const t = byTask[tid];
14302
+ const statusLabel = t.isFirstTimeRight ? "\u2714 First-Time-Right" : `\u26A0 ${t.fixCommits} rework commit${t.fixCommits === 1 ? "" : "s"}`;
14303
+ rows.push(
14304
+ `| \`${t.taskId}\` | ${t.commits} (${t.fixCommits} fix) | +${t.linesAdded} / -${t.linesDeleted} | ${t.codeChurnPercent}% | ${t.reworkTokensPercent}% | ${t.reworkTimePercent}% | ${statusLabel} |`
14305
+ );
14306
+ }
14307
+ return rows;
14295
14308
  }
14296
- function resolveBranchHierarchy(match, rootDir = process.cwd()) {
14297
- const baseBranch = "main";
14298
- const branches = getGitBranchList(rootDir);
14299
- const cleanVersion = (match.version || "1.0.0").replace(/^v/, "");
14300
- const releaseBranch = detectExistingReleaseBranch(branches, cleanVersion);
14301
- const dirName = path14__namespace.basename(match.changeDir);
14302
- const changeSlug = dirName.replace(/^(chg|CHG)-/i, (m) => m.toUpperCase());
14303
- const featureBranch = detectExistingFeatureBranch(branches, dirName, match.changeId, changeSlug);
14304
- const parentIdMatch = featureBranch.replace(/^(feat|feature)\//i, "").match(/^[a-zA-Z0-9]+-[a-zA-Z0-9]+/);
14305
- const parentId = parentIdMatch ? parentIdMatch[0] : match.changeId.split("-").slice(0, 2).join("-");
14306
- const taskBranch = detectExistingTaskBranch(branches, parentId, match.taskId, match.taskTitle);
14307
- return { baseBranch, releaseBranch, featureBranch, taskBranch };
14308
- }
14309
- function branchExistsLocally(branch, rootDir) {
14310
- try {
14311
- child_process3.execFileSync("git", ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], {
14312
- cwd: rootDir,
14313
- stdio: ["pipe", "pipe", "pipe"]
14314
- });
14315
- return true;
14316
- } catch {
14317
- return false;
14318
- }
14309
+ function formatPrKpiMarkdown(kpi) {
14310
+ const models = Object.keys(kpi.byModel);
14311
+ const modelHeaders = models.map((m) => `Agent (${m})`).join(" | ");
14312
+ const modelSeparator = models.map(() => ":---:").join(" | ");
14313
+ const headers = `| Metric | Human |${models.length > 0 ? ` ${modelHeaders} |` : ""} Total PR |`;
14314
+ const sep5 = `| :--- | :---: |${models.length > 0 ? ` ${modelSeparator} |` : ""} :---: |`;
14315
+ const rows = buildPrKpiRows(kpi, models);
14316
+ const taskRowsList = formatTaskKpiRows(kpi.byTask);
14317
+ return [
14318
+ KPI_SUMMARY_START_TAG,
14319
+ "### \u{1F4CA} AI-SDLC: Aggregated PR KPI Summary",
14320
+ "",
14321
+ headers,
14322
+ sep5,
14323
+ ...rows,
14324
+ ...taskRowsList,
14325
+ "",
14326
+ `> **Branch Attribution:** ${kpi.isBugPr ? "\u{1F6A8} *Defect Fix / Bugfix*" : "\u2728 *New Feature*"} (Range: \`${kpi.baseRef}..${kpi.headRef}\`)`,
14327
+ KPI_SUMMARY_END_TAG
14328
+ ].join("\n");
14319
14329
  }
14320
- function branchExistsRemotely(branch, rootDir) {
14321
- try {
14322
- child_process3.execFileSync("git", ["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`], {
14323
- cwd: rootDir,
14324
- stdio: ["pipe", "pipe", "pipe"]
14325
- });
14326
- return true;
14327
- } catch {
14328
- return false;
14330
+ function injectKpisIntoPrBody(originalBody, kpiMarkdown) {
14331
+ const body = originalBody || "";
14332
+ const startIndex = body.indexOf(KPI_SUMMARY_START_TAG);
14333
+ const endIndex = body.indexOf(KPI_SUMMARY_END_TAG);
14334
+ if (startIndex !== -1 && endIndex !== -1) {
14335
+ const before = body.slice(0, startIndex);
14336
+ const after = body.slice(endIndex + KPI_SUMMARY_END_TAG.length);
14337
+ return `${before.trimEnd()}
14338
+
14339
+ ${kpiMarkdown}
14340
+
14341
+ ${after.trimStart()}`.trim();
14329
14342
  }
14343
+ return `${body.trimEnd()}
14344
+
14345
+ ${kpiMarkdown}
14346
+ `;
14330
14347
  }
14331
- function ensureBranchInCascade(branch, parentBranch, rootDir) {
14332
- if (branchExistsLocally(branch, rootDir)) return false;
14333
- if (branchExistsRemotely(branch, rootDir)) {
14334
- child_process3.execFileSync("git", ["branch", "--track", branch, `origin/${branch}`], { cwd: rootDir, stdio: ["pipe", "pipe", "pipe"] });
14335
- } else {
14336
- child_process3.execFileSync("git", ["branch", branch, parentBranch], { cwd: rootDir, stdio: ["pipe", "pipe", "pipe"] });
14337
- }
14338
- return true;
14348
+
14349
+ // src/reporters/agent-kpis.ts
14350
+ function roundOneDecimal(value) {
14351
+ return Math.round(value * 10) / 10;
14339
14352
  }
14340
- function switchBranch(branch, rootDir) {
14341
- child_process3.execFileSync("git", ["checkout", branch], { cwd: rootDir, stdio: ["pipe", "pipe", "pipe"] });
14353
+ function computeAuditedCommitsPercent(records) {
14354
+ if (records.length === 0) return 0;
14355
+ const audited = records.filter((r) => r.trailers.isTelemetryEstimated === false).length;
14356
+ return roundOneDecimal(audited / records.length * 100);
14342
14357
  }
14343
- function cascadeBranchCheckout(hierarchy, rootDir, created, streamlined) {
14344
- if (streamlined) {
14345
- if (ensureBranchInCascade(hierarchy.featureBranch, hierarchy.baseBranch, rootDir)) created.push(hierarchy.featureBranch);
14346
- switchBranch(hierarchy.featureBranch, rootDir);
14347
- return hierarchy.featureBranch;
14358
+ function computeTaskYieldAndRework(records) {
14359
+ const tasks = Object.values(accumulateTaskSummaries(records));
14360
+ if (tasks.length === 0) {
14361
+ return { totalTasks: 0, firstPassYieldPercent: 100, reworkLoopsPerTask: 0 };
14348
14362
  }
14349
- if (ensureBranchInCascade(hierarchy.releaseBranch, hierarchy.baseBranch, rootDir)) created.push(hierarchy.releaseBranch);
14350
- if (ensureBranchInCascade(hierarchy.featureBranch, hierarchy.releaseBranch, rootDir)) created.push(hierarchy.featureBranch);
14351
- if (ensureBranchInCascade(hierarchy.taskBranch, hierarchy.featureBranch, rootDir)) created.push(hierarchy.taskBranch);
14352
- switchBranch(hierarchy.taskBranch, rootDir);
14353
- return hierarchy.taskBranch;
14354
- }
14355
- function buildCheckoutErrorResult(match, hierarchy, created, err) {
14356
- const message = err instanceof Error ? err.message : String(err);
14363
+ const firstPassCount = tasks.filter((t) => t.isFirstTimeRight).length;
14364
+ const totalReworkLoops = tasks.reduce((sum, t) => sum + t.fixCommits, 0);
14357
14365
  return {
14358
- success: false,
14359
- taskId: match.taskId,
14360
- changeId: match.changeId,
14361
- releaseBranch: hierarchy.releaseBranch,
14362
- featureBranch: hierarchy.featureBranch,
14363
- taskBranch: hierarchy.taskBranch,
14364
- createdBranches: created,
14365
- error: `Error durante la creaci\xF3n o checkout de ramas Git: ${message}`
14366
+ totalTasks: tasks.length,
14367
+ firstPassYieldPercent: roundOneDecimal(firstPassCount / tasks.length * 100),
14368
+ reworkLoopsPerTask: Math.round(totalReworkLoops / tasks.length * 100) / 100
14366
14369
  };
14367
14370
  }
14368
- function buildLocateFailureResult(taskId, locateRes) {
14369
- return {
14370
- success: false,
14371
- taskId,
14372
- createdBranches: [],
14373
- error: locateRes.error,
14374
- availableTasks: locateRes.availableTasks
14375
- };
14371
+ function resolveTaskKey(record) {
14372
+ return record.trailers.taskId || record.subject.match(/\b(TSK-[0-9A-Za-z_-]+)\b/i)?.[1]?.toUpperCase();
14376
14373
  }
14377
- function buildCheckoutSuccessResult(match, hierarchy, created, switchedBranch, streamlined) {
14374
+ function computeHumanTakeoverRate(records) {
14375
+ const byTask = /* @__PURE__ */ new Map();
14376
+ for (const r of records) {
14377
+ const tid = resolveTaskKey(r);
14378
+ if (!tid) continue;
14379
+ const state = byTask.get(tid) || { hasAgent: false, hasHumanTakeover: false };
14380
+ if (r.trailers.authorType === "agent") {
14381
+ state.hasAgent = true;
14382
+ } else if (state.hasAgent || r.isBugFix) {
14383
+ state.hasHumanTakeover = true;
14384
+ }
14385
+ byTask.set(tid, state);
14386
+ }
14387
+ const agentTasks = Array.from(byTask.values()).filter((s) => s.hasAgent);
14388
+ if (agentTasks.length === 0) return 0;
14389
+ const takeovers = agentTasks.filter((s) => s.hasHumanTakeover).length;
14390
+ return roundOneDecimal(takeovers / agentTasks.length * 100);
14391
+ }
14392
+ function computeSpecificationAdherence(input) {
14393
+ const cov = input.coverageResult;
14394
+ const trace = input.traceabilityResult;
14395
+ const gate = input.gateResult;
14396
+ const bddRatio = cov && cov.totalRequirements > 0 ? cov.passedRequirements / cov.totalRequirements : 1;
14397
+ const traceRatio = trace && trace.totalRequirements > 0 ? (trace.totalRequirements - trace.orphanCount) / trace.totalRequirements : 1;
14398
+ const gateRatio = gate && gate.totalFunctions > 0 ? (gate.totalFunctions - gate.failCount) / gate.totalFunctions : 1;
14399
+ return roundOneDecimal((bddRatio + traceRatio + gateRatio) / 3 * 100);
14400
+ }
14401
+ function computeTokenCostEfficiency(records, gateResult) {
14402
+ if (!gateResult || gateResult.results.length === 0) return 0;
14403
+ const totalCc = gateResult.results.reduce((sum, fn) => sum + fn.cyclomatic, 0);
14404
+ if (totalCc <= 0) return 0;
14405
+ const totalTokens = records.reduce(
14406
+ (sum, r) => sum + r.trailers.promptTokens + r.trailers.completionTokens,
14407
+ 0
14408
+ );
14409
+ return Math.round(totalTokens / totalCc);
14410
+ }
14411
+ function isComponentContractPath(filePath) {
14412
+ const normalized = filePath.replace(/\\/g, "/").toLowerCase();
14413
+ return normalized.includes("specs/architecture/components/") || /\/?cmp-[^/]+\.md$/i.test(normalized);
14414
+ }
14415
+ function computeArchitectureDriftRate(records) {
14416
+ const cmpCommits = records.filter((r) => (r.touchedFiles || []).some(isComponentContractPath));
14417
+ if (cmpCommits.length === 0) return 0;
14418
+ const unauthorized = cmpCommits.filter((r) => {
14419
+ const ref = r.trailers.parentRef || "";
14420
+ const hasApprovedRef = /^(CHG|ADR)-/i.test(ref) || Boolean(r.trailers.taskId);
14421
+ return !hasApprovedRef;
14422
+ });
14423
+ return roundOneDecimal(unauthorized.length / cmpCommits.length * 100);
14424
+ }
14425
+ function computeAgentPerformanceKpis(input) {
14426
+ const { totalTasks, firstPassYieldPercent, reworkLoopsPerTask } = computeTaskYieldAndRework(input.records);
14378
14427
  return {
14379
- success: true,
14380
- taskId: match.taskId,
14381
- changeId: match.changeId,
14382
- releaseBranch: hierarchy.releaseBranch,
14383
- featureBranch: hierarchy.featureBranch,
14384
- taskBranch: streamlined ? void 0 : hierarchy.taskBranch,
14385
- createdBranches: created,
14386
- switchedBranch
14428
+ totalCommits: input.records.length,
14429
+ totalTasks,
14430
+ auditedCommitsPercent: computeAuditedCommitsPercent(input.records),
14431
+ firstPassYieldPercent,
14432
+ reworkLoopsPerTask,
14433
+ specificationAdherenceIndex: computeSpecificationAdherence(input),
14434
+ humanTakeoverRatePercent: computeHumanTakeoverRate(input.records),
14435
+ tokenCostEfficiency: computeTokenCostEfficiency(input.records, input.gateResult),
14436
+ architectureDriftRatePercent: computeArchitectureDriftRate(input.records)
14387
14437
  };
14388
14438
  }
14389
- function checkoutTaskBranch(taskId, options = {}) {
14390
- const rootDir = options.rootDir || process.cwd();
14391
- const locateRes = locateTaskInActiveChanges(taskId, rootDir);
14392
- if (!locateRes.found || !locateRes.match) {
14393
- return buildLocateFailureResult(taskId, locateRes);
14394
- }
14395
- const match = locateRes.match;
14396
- const hierarchy = resolveBranchHierarchy(match, rootDir);
14397
- const created = [];
14398
- try {
14399
- const switched = cascadeBranchCheckout(hierarchy, rootDir, created, options.streamlined);
14400
- return buildCheckoutSuccessResult(match, hierarchy, created, switched, options.streamlined);
14401
- } catch (err) {
14402
- return buildCheckoutErrorResult(match, hierarchy, created, err);
14403
- }
14439
+ function formatAgentKpisMarkdownSection(kpis) {
14440
+ return [
14441
+ "## 2. AI Agent Performance KPIs (SWE-bench & DORA AI)",
14442
+ "",
14443
+ `> **Evaluated Tasks:** \`${kpis.totalTasks}\` | **Commits:** \`${kpis.totalCommits}\` | **Audited Trailer Coverage:** \`${kpis.auditedCommitsPercent}%\``,
14444
+ "",
14445
+ "| KPI | Measured Value | Benchmark / Target |",
14446
+ "| :--- | :---: | :---: |",
14447
+ `| **First-Pass Yield (FPY)** | \`${kpis.firstPassYieldPercent}%\` | $\\ge 80\\%$ |`,
14448
+ `| **Rework Loops per Task** | \`${kpis.reworkLoopsPerTask}\` | $\\le 0.5$ |`,
14449
+ `| **Specification Adherence Index** | \`${kpis.specificationAdherenceIndex}%\` | $\\ge 95\\%$ |`,
14450
+ `| **Human Takeover / Intervention Rate** | \`${kpis.humanTakeoverRatePercent}%\` | $\\le 15\\%$ |`,
14451
+ `| **Token Cost Efficiency** | \`${kpis.tokenCostEfficiency.toLocaleString("en-US")} tokens/CC\` | Lower is better |`,
14452
+ `| **Architecture Drift Rate** | \`${kpis.architectureDriftRatePercent}%\` | $0\\%$ |`
14453
+ ];
14404
14454
  }
14405
- var TRAILER_REGEXES = {
14406
- taskId: /^\s*Task-ID:\s*(.+)$/im,
14407
- parentRef: /^\s*Parent-Ref:\s*(.+)$/im,
14408
- authorType: /^\s*Author-Type:\s*(human|agent)/im,
14409
- aiModel: /^\s*AI-Model:\s*(.+)$/im,
14410
- promptTokens: /^\s*Prompt-Tokens:\s*([0-9]+)/im,
14411
- completionTokens: /^\s*Completion-Tokens:\s*([0-9]+)/im,
14412
- activeTimeSeconds: /^\s*Active-Time-Seconds:\s*([0-9]+)/im
14413
- };
14414
- function parseTrailerInt(match) {
14415
- if (!match) return 0;
14416
- const val = parseInt(match[1], 10);
14417
- return isNaN(val) ? 0 : val;
14455
+
14456
+ // src/reporters/quality-report.ts
14457
+ function calculateRating(mi, cc) {
14458
+ if (mi >= 75 && cc <= 5) return "A";
14459
+ if (mi >= 60 && cc <= 10) return "B";
14460
+ if (mi >= 50 && cc <= 15) return "C";
14461
+ if (mi >= 40 && cc <= 20) return "D";
14462
+ return "F";
14418
14463
  }
14419
- function resolveAuthorType(authorTypeMatch, aiModelMatch) {
14420
- if (authorTypeMatch) {
14421
- return authorTypeMatch[1].toLowerCase();
14422
- }
14423
- if (aiModelMatch && aiModelMatch[1].trim() !== "n/a") {
14424
- return "agent";
14464
+ function detectLanguage(filePath) {
14465
+ const ext = path14__namespace.extname(filePath).toLowerCase();
14466
+ switch (ext) {
14467
+ case ".ts":
14468
+ return "TypeScript";
14469
+ case ".js":
14470
+ return "JavaScript";
14471
+ case ".py":
14472
+ return "Python";
14473
+ case ".java":
14474
+ return "Java";
14475
+ case ".go":
14476
+ return "Go";
14477
+ case ".cs":
14478
+ return "C#";
14479
+ case ".rs":
14480
+ return "Rust";
14481
+ case ".cpp":
14482
+ case ".c":
14483
+ return "C/C++";
14484
+ default:
14485
+ return "Unknown";
14425
14486
  }
14426
- return "human";
14427
14487
  }
14428
- function resolveTrailerOrScope(match, text, fallbackRegex) {
14429
- if (match) return match[1].trim();
14430
- const subMatch = text.match(fallbackRegex);
14431
- return subMatch ? subMatch[1].toUpperCase() : void 0;
14488
+ function readCodeCoverageSummary(rootDir = process.cwd()) {
14489
+ return readNormalizedCoverage(rootDir);
14432
14490
  }
14433
- function parseCommitTrailers(rawMessage) {
14434
- const text = rawMessage || "";
14435
- const authorTypeMatch = text.match(TRAILER_REGEXES.authorType);
14436
- const aiModelMatch = text.match(TRAILER_REGEXES.aiModel);
14437
- const authorType = resolveAuthorType(authorTypeMatch, aiModelMatch);
14438
- const rawModel = aiModelMatch ? aiModelMatch[1].trim() : void 0;
14439
- const aiModel = rawModel && rawModel !== "n/a" ? rawModel : void 0;
14440
- return {
14441
- taskId: resolveTrailerOrScope(text.match(TRAILER_REGEXES.taskId), text, /\b(TSK-[0-9A-Za-z_-]+)\b/i),
14442
- parentRef: resolveTrailerOrScope(text.match(TRAILER_REGEXES.parentRef), text, /\b((?:CHG|FEAT|BUG|FIX|PATCH)-[0-9A-Za-z_-]+)\b/i),
14443
- authorType,
14444
- aiModel,
14445
- promptTokens: parseTrailerInt(text.match(TRAILER_REGEXES.promptTokens)),
14446
- completionTokens: parseTrailerInt(text.match(TRAILER_REGEXES.completionTokens)),
14447
- activeTimeSeconds: parseTrailerInt(text.match(TRAILER_REGEXES.activeTimeSeconds))
14448
- };
14491
+ function formatCoverageRow(label, measured, minThreshold) {
14492
+ if (measured === void 0) {
14493
+ return `| **${label}** | \`N/A (Run test:coverage)\` | $\\ge ${minThreshold}\\%$ | \u2139\uFE0F NOT MEASURED |`;
14494
+ }
14495
+ const status = measured >= minThreshold ? "\u2705 COMPLIANT" : "\u26A0\uFE0F BELOW THRESHOLD";
14496
+ return `| **${label}** | \`${measured}%\` | $\\ge ${minThreshold}\\%$ | ${status} |`;
14449
14497
  }
14450
- function formatCommitTrailers(trailers) {
14451
- const lines = [];
14452
- if (trailers.taskId) lines.push(`Task-ID: ${trailers.taskId}`);
14453
- if (trailers.parentRef) lines.push(`Parent-Ref: ${trailers.parentRef}`);
14454
- lines.push(`Author-Type: ${trailers.authorType || "human"}`);
14455
- lines.push(`AI-Model: ${trailers.aiModel || "n/a"}`);
14456
- lines.push(`Prompt-Tokens: ${trailers.promptTokens ?? 0}`);
14457
- lines.push(`Completion-Tokens: ${trailers.completionTokens ?? 0}`);
14458
- lines.push(`Active-Time-Seconds: ${trailers.activeTimeSeconds ?? 0}`);
14459
- return lines.join("\n");
14498
+ function buildCoverageRows(coverage, policy) {
14499
+ return [
14500
+ formatCoverageRow("Line Coverage", coverage?.linesPct, policy.min_line_coverage),
14501
+ formatCoverageRow("Branch Coverage", coverage?.branchesPct, policy.min_branch_coverage),
14502
+ formatCoverageRow("Function Coverage", coverage?.functionsPct, policy.min_function_coverage)
14503
+ ];
14460
14504
  }
14461
- function parseRawLogChunks(rawLog) {
14462
- const rawCommits = rawLog.split("---AI_SDLC_COMMIT---").filter((c) => c.trim().length > 0);
14463
- const chunks = [];
14464
- for (const raw of rawCommits) {
14465
- const endBodyIdx = raw.indexOf("---AI_SDLC_BODY_END---");
14466
- if (endBodyIdx === -1) continue;
14467
- const beforeEnd = raw.slice(0, endBodyIdx).trimStart();
14468
- const afterEnd = raw.slice(endBodyIdx + "---AI_SDLC_BODY_END---".length);
14469
- const firstNewline = beforeEnd.indexOf("\n");
14470
- const header = firstNewline === -1 ? beforeEnd : beforeEnd.slice(0, firstNewline);
14471
- const body = firstNewline === -1 ? "" : beforeEnd.slice(firstNewline + 1);
14472
- const numstatLines = afterEnd.split("\n").filter((l) => /^\d+\s+\d+\s+/.test(l.trim()));
14473
- chunks.push({ header, body, numstatLines });
14505
+ function updateLangStats(langMap, fn) {
14506
+ const lang = detectLanguage(fn.filePath);
14507
+ const existing = langMap.get(lang) || { fns: 0, loc: 0, miSum: 0, ccSum: 0 };
14508
+ existing.fns++;
14509
+ existing.loc += fn.loc;
14510
+ existing.miSum += fn.maintainability;
14511
+ existing.ccSum += fn.cyclomatic;
14512
+ langMap.set(lang, existing);
14513
+ }
14514
+ function processFunctionMetric(fn, accumulated) {
14515
+ accumulated.totalMi += fn.maintainability;
14516
+ accumulated.totalCc += fn.cyclomatic;
14517
+ accumulated.totalCognitive += fn.cognitive;
14518
+ accumulated.totalLoc += fn.loc;
14519
+ updateLangStats(accumulated.langMap, fn);
14520
+ if (fn.violations.length > 0) {
14521
+ accumulated.violationsList.push(`- **\`${fn.relPath}\`** [\`${fn.functionName}\`]: ${fn.violations.join(", ")}`);
14474
14522
  }
14475
- return chunks;
14476
14523
  }
14477
- function sumNumstatLines(lines) {
14478
- let added = 0;
14479
- let deleted = 0;
14480
- for (const line of lines) {
14481
- const parts = line.trim().split(/\s+/);
14482
- if (parts.length >= 2) {
14483
- const a = parseInt(parts[0], 10);
14484
- const d = parseInt(parts[1], 10);
14485
- if (!isNaN(a)) added += a;
14486
- if (!isNaN(d)) deleted += d;
14487
- }
14488
- }
14489
- return { added, deleted };
14490
- }
14491
- function evaluateIsBugFix(subject, parentRef) {
14492
- if (parentRef && /^(BUG|FIX)-/i.test(parentRef)) return true;
14493
- return /^(fix|bug)(\([^)]+\))?:/i.test(subject.trim());
14494
- }
14495
- function inferAgentTrailers(trailers, linesAdded, linesDeleted) {
14496
- const res = { ...trailers };
14497
- const linesChanged = linesAdded + linesDeleted;
14498
- if (res.promptTokens === 0 && res.completionTokens === 0) {
14499
- res.completionTokens = linesChanged > 0 ? Math.max(linesAdded * 10, 50) : 0;
14500
- res.promptTokens = linesChanged > 0 ? Math.max(2500 + linesChanged * 25, 3e3) : 1e3;
14501
- }
14502
- if (res.activeTimeSeconds === 0) {
14503
- res.activeTimeSeconds = linesChanged > 0 ? Math.round(30 + linesChanged * 0.5) : 30;
14524
+ function accumulateMetrics(results) {
14525
+ const accumulated = {
14526
+ totalMi: 0,
14527
+ totalCc: 0,
14528
+ totalCognitive: 0,
14529
+ totalLoc: 0,
14530
+ langMap: /* @__PURE__ */ new Map(),
14531
+ violationsList: []
14532
+ };
14533
+ for (const fn of results) {
14534
+ processFunctionMetric(fn, accumulated);
14504
14535
  }
14505
- return res;
14536
+ return accumulated;
14506
14537
  }
14507
- function inferHumanTrailers(trailers, linesAdded, linesDeleted) {
14508
- const res = { ...trailers };
14509
- const linesChanged = linesAdded + linesDeleted;
14510
- if (res.activeTimeSeconds === 0) {
14511
- res.activeTimeSeconds = linesChanged > 0 ? Math.round(180 + linesChanged * 2) : 120;
14538
+ function renderPolyglotRows(langMap) {
14539
+ const rows = [];
14540
+ for (const [lang, stats] of langMap.entries()) {
14541
+ const langMi = Math.round(stats.miSum / stats.fns * 10) / 10;
14542
+ const langCc = Math.round(stats.ccSum / stats.fns * 10) / 10;
14543
+ const rating = calculateRating(langMi, langCc);
14544
+ rows.push(`| **${lang}** | \`${stats.fns}\` | \`${stats.loc}\` | \`${langMi}\` | \`${langCc}\` | \`${rating}\` |`);
14512
14545
  }
14513
- return res;
14546
+ return rows;
14514
14547
  }
14515
- function inferMissingTrailers(trailers, linesAdded, linesDeleted) {
14516
- return trailers.authorType === "agent" ? inferAgentTrailers(trailers, linesAdded, linesDeleted) : inferHumanTrailers(trailers, linesAdded, linesDeleted);
14548
+ var EVALUATION_STANDARDS_MD = [
14549
+ "---",
14550
+ "",
14551
+ "## 4. Evaluation Criteria and Standards",
14552
+ "- **McCabe Cyclomatic Complexity (CC)**: Number of linearly independent paths.",
14553
+ "- **Maintainability Index (SEI MI)**: Normalized formula [0 - 100] combining Halstead Volume, CC, and LOC.",
14554
+ "- **Automated Test Coverage**: Passively ingested from `coverage/coverage-summary.json` or `lcov.info` when present.",
14555
+ "- **Clean Code Guardrails**: Prohibition of implicit `any` typing, function length limits ($\\le 40$ lines), and zero unjustified suppressions."
14556
+ ].join("\n");
14557
+ function computeQualityAverages(totalFunctions, acc) {
14558
+ const avgMaintainability = totalFunctions > 0 ? Math.round(acc.totalMi / totalFunctions * 10) / 10 : 100;
14559
+ const avgCyclomatic = totalFunctions > 0 ? Math.round(acc.totalCc / totalFunctions * 10) / 10 : 1;
14560
+ const avgCognitive = totalFunctions > 0 ? Math.round(acc.totalCognitive / totalFunctions * 10) / 10 : 0;
14561
+ const globalRating = calculateRating(avgMaintainability, avgCyclomatic);
14562
+ return { avgMaintainability, avgCyclomatic, avgCognitive, globalRating };
14517
14563
  }
14518
- function resolveGitRef(cwd, ref) {
14519
- if (!ref || ref === "HEAD") return ref;
14520
- const candidates = [
14521
- ref,
14522
- `feat/${ref}`,
14523
- `release/${ref}`,
14524
- `bug/${ref}`,
14525
- `task/${ref}`,
14526
- `origin/${ref}`,
14527
- `origin/feat/${ref}`,
14528
- `origin/release/${ref}`,
14529
- `origin/bug/${ref}`
14564
+ function buildReportHeader3(verdict, rating, mi, cc) {
14565
+ const status = verdict === "PASS" ? "\u{1F7E2} APPROVED (RELEASE READY)" : "\u{1F534} BLOCKED (VIOLATIONS DETECTED)";
14566
+ return [
14567
+ `# \u{1F4CA} Formal Quality and Release Gate Report (AI-SDLC)`,
14568
+ "",
14569
+ `> **Generation Date:** ${resolveDeterministicDate().toISOString()}`,
14570
+ `> **Release Gate Verdict:** ${status}`,
14571
+ `> **Global Rating:** **\`${rating}\`** (MI Index: ${mi}/100, Average CC: ${cc})`
14530
14572
  ];
14531
- for (const cand of candidates) {
14532
- try {
14533
- child_process3.execFileSync("git", ["rev-parse", "--verify", "--quiet", cand], {
14534
- cwd,
14535
- stdio: ["pipe", "pipe", "pipe"]
14536
- });
14537
- return cand;
14538
- } catch {
14539
- }
14540
- }
14541
- return ref;
14542
- }
14543
- function fetchGitLogOutput(cwd, baseRef, headRef, format) {
14544
- const rangeArg = baseRef ? `${baseRef}..${headRef}` : headRef;
14545
- try {
14546
- return child_process3.execFileSync("git", ["log", rangeArg, `--format=${format}`, "--numstat"], {
14547
- cwd,
14548
- encoding: "utf-8",
14549
- stdio: ["pipe", "pipe", "pipe"]
14550
- });
14551
- } catch {
14552
- if (baseRef && !baseRef.includes("/")) {
14553
- try {
14554
- return child_process3.execFileSync("git", ["log", `origin/${baseRef}..${headRef}`, `--format=${format}`, `--numstat`], {
14555
- cwd,
14556
- encoding: "utf-8",
14557
- stdio: ["pipe", "pipe", "pipe"]
14558
- });
14559
- } catch {
14560
- return "";
14561
- }
14562
- }
14563
- return "";
14564
- }
14565
14573
  }
14566
- function buildCommitKpiRecord(chunk) {
14567
- const fields = chunk.header.split("");
14568
- if (fields.length < 5) return null;
14569
- const rawTrailers = parseCommitTrailers(chunk.body);
14570
- const { added, deleted } = sumNumstatLines(chunk.numstatLines);
14571
- const trailers = inferMissingTrailers(rawTrailers, added, deleted);
14574
+ function buildMetricStatus(averages, policy, failCount) {
14572
14575
  return {
14573
- sha: fields[0],
14574
- authorName: fields[1],
14575
- authorEmail: fields[2],
14576
- date: fields[3],
14577
- subject: fields[4],
14578
- trailers,
14579
- linesAdded: added,
14580
- linesDeleted: deleted,
14581
- isBugFix: evaluateIsBugFix(fields[4], trailers.parentRef)
14576
+ ccStatus: averages.avgCyclomatic <= policy.max_cyclomatic ? "\u2705 COMPLIANT" : "\u274C EXCEEDED",
14577
+ cogStatus: averages.avgCognitive <= policy.max_cognitive ? "\u2705 COMPLIANT" : "\u274C EXCEEDED",
14578
+ miStatus: averages.avgMaintainability >= policy.min_maintainability ? "\u2705 COMPLIANT" : "\u274C INSUFFICIENT",
14579
+ violStatus: failCount === 0 ? "\u2705 0 VIOLATIONS" : "\u274C BLOCKED"
14582
14580
  };
14583
14581
  }
14584
- function extractCommitKpisFromRange(baseRef, headRef = "HEAD", options = {}) {
14585
- const cwd = options.cwd || process.cwd();
14586
- const resolvedBase = resolveGitRef(cwd, baseRef);
14587
- const resolvedHead = resolveGitRef(cwd, headRef);
14588
- const format = "---AI_SDLC_COMMIT---%n%H%x1f%an%x1f%ae%x1f%aI%x1f%s%n%B%n---AI_SDLC_BODY_END---";
14589
- const rawOutput = fetchGitLogOutput(cwd, resolvedBase, resolvedHead, format);
14590
- if (!rawOutput) return [];
14591
- const chunks = parseRawLogChunks(rawOutput);
14592
- const records = [];
14593
- for (const chunk of chunks) {
14594
- const rec = buildCommitKpiRecord(chunk);
14595
- if (rec) records.push(rec);
14596
- }
14597
- return records;
14582
+ function buildCountRows(totalFiles, totalFunctions, totalLoc) {
14583
+ return [
14584
+ `| **Analyzed Files** | \`${totalFiles}\` | N/A | \u2139\uFE0F |`,
14585
+ `| **Evaluated Functions** | \`${totalFunctions}\` | N/A | \u2139\uFE0F |`,
14586
+ `| **Lines of Code (LOC)** | \`${totalLoc}\` | N/A | \u2139\uFE0F |`
14587
+ ];
14598
14588
  }
14599
- function extractAllRepoCommitKpis(options = {}) {
14600
- const cwd = options.cwd || process.cwd();
14601
- const format = "---AI_SDLC_COMMIT---%n%H%x1f%an%x1f%ae%x1f%aI%x1f%s%n%B%n---AI_SDLC_BODY_END---";
14602
- let rawOutput = "";
14603
- try {
14604
- rawOutput = child_process3.execFileSync("git", ["log", "--all", `--format=${format}`, "--numstat"], {
14605
- cwd,
14606
- encoding: "utf-8",
14607
- stdio: ["pipe", "pipe", "pipe"]
14608
- });
14609
- } catch {
14610
- return [];
14611
- }
14612
- if (!rawOutput) return [];
14613
- const chunks = parseRawLogChunks(rawOutput);
14614
- const records = [];
14615
- for (const chunk of chunks) {
14616
- const rec = buildCommitKpiRecord(chunk);
14617
- if (rec) records.push(rec);
14618
- }
14619
- return records;
14589
+ function buildExecutiveTable(gateResult, totalLoc, averages, coverage) {
14590
+ const { policy, totalFiles, totalFunctions, failCount } = gateResult;
14591
+ const status = buildMetricStatus(averages, policy, failCount);
14592
+ return [
14593
+ "## 1. Executive Metric Summary",
14594
+ "",
14595
+ "| Key Metric | Measured Value | Policy Threshold | Compliance |",
14596
+ "| :--- | :---: | :---: | :---: |",
14597
+ ...buildCountRows(totalFiles, totalFunctions, totalLoc),
14598
+ `| **Cyclomatic Complexity (Average)** | \`${averages.avgCyclomatic}\` | $\\le ${policy.max_cyclomatic}$ | ${status.ccStatus} |`,
14599
+ `| **Cognitive Complexity (Average)** | \`${averages.avgCognitive}\` | $\\le ${policy.max_cognitive}$ | ${status.cogStatus} |`,
14600
+ `| **Maintainability Index (SEI MI)** | \`${averages.avgMaintainability} / 100\` | $\\ge ${policy.min_maintainability}$ | ${status.miStatus} |`,
14601
+ ...buildCoverageRows(coverage, policy),
14602
+ `| **Functions in Violation** | \`${failCount}\` | $0$ (Mode ${policy.enforce_mode}) | ${status.violStatus} |`
14603
+ ];
14620
14604
  }
14621
- var AGENT_ENV_MAPPINGS = [
14622
- { envKey: "ANTIGRAVITY_AGENT", defaultModel: "gemini-3.8-flash", source: "antigravity" },
14623
- { envKey: "ANTIGRAVITY_CONVERSATION_ID", defaultModel: "gemini-3.8-flash", source: "antigravity" },
14624
- { envKey: "ANTIGRAVITY_AGENT_ID", defaultModel: "gemini-3.8-flash", source: "antigravity" },
14625
- { envKey: "CORTEX_SESSION_ID", defaultModel: "antigravity-agent", source: "cortex" },
14626
- { envKey: "CLAUDE_CODE", defaultModel: "claude-3-7-sonnet", source: "claude-code" },
14627
- { envKey: "CLAUDE_AGENT", defaultModel: "claude-3-7-sonnet", source: "claude-agent" },
14628
- { envKey: "CURSOR_AGENT", defaultModel: "cursor-agent", source: "cursor" },
14629
- { envKey: "CURSOR_SESSION_ID", defaultModel: "cursor-agent", source: "cursor" },
14630
- { envKey: "WINDSURF_AGENT", defaultModel: "windsurf-cascade", source: "windsurf" },
14631
- { envKey: "CASCADE_AGENT", defaultModel: "windsurf-cascade", source: "cascade" },
14632
- { envKey: "GITHUB_COPILOT_AGENT", defaultModel: "github-copilot", source: "copilot" },
14633
- { envKey: "COPILOT_AGENT_NAME", defaultModel: "github-copilot", source: "copilot" },
14634
- { envKey: "AIDER_MODEL", defaultModel: "aider-agent", source: "aider" },
14635
- { envKey: "GEMINI_CLI", defaultModel: "gemini-1.5-pro", source: "gemini" },
14636
- { envKey: "AI_AGENT_NAME", defaultModel: "agent-developer", source: "ai-sdlc-agent" },
14637
- { envKey: "AI_MODEL", defaultModel: "agent-developer", source: "ai-sdlc-model" }
14638
- ];
14639
- var BOT_NAME_REGEX = /\b(bot|agent|copilot|assistant|llm|claude|gpt|cortex|gemini)\b/i;
14640
- function getGitConfigValue(key, cwd) {
14641
- try {
14642
- const val = child_process3.execFileSync("git", ["config", "--get", key], {
14643
- cwd,
14644
- encoding: "utf-8",
14645
- stdio: ["pipe", "pipe", "pipe"]
14646
- }).trim();
14647
- return val.length > 0 ? val : void 0;
14648
- } catch {
14649
- return void 0;
14650
- }
14605
+ function buildPolyglotSection(langMap) {
14606
+ return [
14607
+ "## 3. Polyglot Breakdown by Language Ecosystem",
14608
+ "",
14609
+ "| Language | Functions | Total LOC | Average MI | Average CC | Rating |",
14610
+ "| :--- | :---: | :---: | :---: | :---: | :---: |",
14611
+ ...renderPolyglotRows(langMap)
14612
+ ];
14651
14613
  }
14652
- function readSessionTelemetry(cwd) {
14653
- const possiblePaths = [
14654
- path14__namespace.join(cwd, ".ai-sdlc", "session-telemetry.json"),
14655
- path14__namespace.join(cwd, ".ai-sdlc", "agent-session.json")
14614
+ function renderQualityReportMarkdown(gateResult, coverage, accumulated, averages, agentKpis) {
14615
+ const verdict = gateResult.success ? "PASS" : "FAIL";
14616
+ const sections = [
14617
+ buildReportHeader3(verdict, averages.globalRating, averages.avgMaintainability, averages.avgCyclomatic),
14618
+ buildExecutiveTable(gateResult, accumulated.totalLoc, averages, coverage),
14619
+ formatAgentKpisMarkdownSection(agentKpis),
14620
+ buildPolyglotSection(accumulated.langMap)
14656
14621
  ];
14657
- for (const p of possiblePaths) {
14658
- if (fs12__namespace.existsSync(p)) {
14659
- try {
14660
- const raw = fs12__namespace.readFileSync(p, "utf-8");
14661
- return JSON.parse(raw);
14662
- } catch {
14663
- }
14664
- }
14665
- }
14666
- return null;
14622
+ if (accumulated.violationsList.length > 0) {
14623
+ sections.push(["## 4. Quality Gate Violations Log", "", ...accumulated.violationsList]);
14624
+ }
14625
+ return [...sections.map((s) => s.join("\n")), EVALUATION_STANDARDS_MD].join("\n\n---\n\n");
14626
+ }
14627
+ function collectAgentKpisForReport(rootDir, gateResult) {
14628
+ const records = extractAllRepoCommitKpis({ cwd: rootDir });
14629
+ const hasSpecs = fs12__namespace.existsSync(path14__namespace.join(rootDir, "specs"));
14630
+ const coverageResult = hasSpecs ? verifyTestingCoverage({ rootDir }) : void 0;
14631
+ const traceabilityResult = hasSpecs ? verifyTraceability({ rootDir }) : void 0;
14632
+ return computeAgentPerformanceKpis({
14633
+ records,
14634
+ gateResult,
14635
+ coverageResult,
14636
+ traceabilityResult
14637
+ });
14667
14638
  }
14668
- function resolveModelFromBotString(str) {
14669
- if (/claude/i.test(str)) return "claude-3-7-sonnet";
14670
- if (/gpt/i.test(str)) return "gpt-4o";
14671
- if (/copilot/i.test(str)) return "github-copilot";
14672
- if (/gemini/i.test(str)) return "gemini-1.5-pro";
14673
- if (/cortex/i.test(str)) return "antigravity-agent";
14674
- return "agent-developer";
14639
+ function writeQualityReportFile(rootDir, markdown) {
14640
+ const targetPath = path14__namespace.join(rootDir, "reports", "QUALITY_REPORT.md");
14641
+ return writeReportFileIfChanged(targetPath, markdown);
14675
14642
  }
14676
- function detectFromEnvOverride(env) {
14677
- const explicitEnv = env.AI_SDLC_AUTHOR_TYPE || env.AUTHOR_TYPE;
14678
- if (explicitEnv === "human" || explicitEnv === "agent") {
14679
- const model = explicitEnv === "agent" ? env.AI_MODEL || "agent-developer" : "n/a";
14643
+ function generateQualityReport(options = {}) {
14644
+ const rootDir = options.rootDir || process.cwd();
14645
+ const gateResult = verifyQualityGate({
14646
+ rootDir,
14647
+ policyPath: options.policyPath,
14648
+ thresholds: options.thresholds
14649
+ });
14650
+ const coverage = readCodeCoverageSummary(rootDir);
14651
+ const accumulated = accumulateMetrics(gateResult.results);
14652
+ const averages = computeQualityAverages(gateResult.totalFunctions, accumulated);
14653
+ const agentKpis = collectAgentKpisForReport(rootDir, gateResult);
14654
+ const markdown = renderQualityReportMarkdown(gateResult, coverage, accumulated, averages, agentKpis);
14655
+ writeQualityReportFile(rootDir, markdown);
14656
+ return {
14657
+ markdown,
14658
+ totalFiles: gateResult.totalFiles,
14659
+ totalFunctions: gateResult.totalFunctions,
14660
+ avgMaintainability: averages.avgMaintainability,
14661
+ avgCyclomatic: averages.avgCyclomatic,
14662
+ verdict: gateResult.success ? "PASS" : "FAIL",
14663
+ coverage
14664
+ };
14665
+ }
14666
+
14667
+ // src/git/workflow.ts
14668
+ var BRANCH_PATTERNS = {
14669
+ MAIN: /^main$/,
14670
+ RELEASE: /^release\/v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$/,
14671
+ FEATURE: /^(feat|feature)\/(?:v[0-9]+\.[0-9]+\.[0-9]+\/)?([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/,
14672
+ BUG: /^(bug|fix)\/(?:v[0-9]+\.[0-9]+\.[0-9]+\/)?([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/,
14673
+ PATCH: /^(patch)\/(?:v[0-9]+\.[0-9]+\.[0-9]+\/)?([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/,
14674
+ TASK: /^task\/([a-zA-Z0-9]+-[a-zA-Z0-9-]+)\/([a-zA-Z0-9]+-[a-zA-Z0-9-]+)$/
14675
+ };
14676
+ function classifyTier1And2(branchName) {
14677
+ if (BRANCH_PATTERNS.MAIN.test(branchName)) {
14680
14678
  return {
14681
- authorType: explicitEnv,
14682
- model,
14683
- source: "explicit-env",
14684
- confidence: "HIGH",
14685
- promptTokens: 0,
14686
- completionTokens: 0,
14687
- activeTimeSeconds: 0
14679
+ valid: true,
14680
+ tier: 1,
14681
+ tierName: "Main (Producci\xF3n)",
14682
+ parentRequirement: "Ninguno (Rama Ra\xEDz)",
14683
+ targetMerge: "Despliegue a Producci\xF3n"
14688
14684
  };
14689
14685
  }
14690
- return null;
14691
- }
14692
- function detectFromGitConfig(cwd) {
14693
- const gitConfigType = getGitConfigValue("ai-sdlc.author-type", cwd);
14694
- if (gitConfigType === "human" || gitConfigType === "agent") {
14695
- const gitConfigModel = getGitConfigValue("ai-sdlc.model", cwd) || (gitConfigType === "agent" ? "agent-developer" : "n/a");
14686
+ if (BRANCH_PATTERNS.RELEASE.test(branchName)) {
14696
14687
  return {
14697
- authorType: gitConfigType,
14698
- model: gitConfigModel,
14699
- source: "git-config",
14700
- confidence: "HIGH",
14701
- promptTokens: 0,
14702
- completionTokens: 0,
14703
- activeTimeSeconds: 0
14688
+ valid: true,
14689
+ tier: 2,
14690
+ tierName: "Versi\xF3n / Release",
14691
+ parentRequirement: "Debe originarse desde main",
14692
+ targetMerge: "main"
14704
14693
  };
14705
14694
  }
14706
14695
  return null;
14707
14696
  }
14708
- function detectFromTelemetry(cwd, env) {
14709
- const telemetry = readSessionTelemetry(cwd);
14710
- if (telemetry) {
14711
- const model = telemetry.model || env.AI_MODEL || "agent-developer";
14712
- return {
14713
- authorType: "agent",
14714
- model,
14715
- source: "session-telemetry-file",
14716
- confidence: "HIGH",
14717
- promptTokens: telemetry.promptTokens || 0,
14718
- completionTokens: telemetry.completionTokens || 0,
14719
- activeTimeSeconds: telemetry.activeTimeSeconds || 0
14720
- };
14697
+ var TIER_3_CONFIGS = [
14698
+ { regex: BRANCH_PATTERNS.FEATURE, tierName: "Feature (Funcionalidad)", parentReq: "Debe originarse desde una rama release/vX.Y.Z activa", merge: "release/vX.Y.Z" },
14699
+ { regex: BRANCH_PATTERNS.BUG, tierName: "Bug (Defecto)", parentReq: "Debe originarse desde una rama release/vX.Y.Z activa", merge: "release/vX.Y.Z" },
14700
+ { 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" }
14701
+ ];
14702
+ function classifyTier3(branchName) {
14703
+ for (const cfg of TIER_3_CONFIGS) {
14704
+ const m = branchName.match(cfg.regex);
14705
+ if (m) {
14706
+ return {
14707
+ valid: true,
14708
+ tier: 3,
14709
+ tierName: cfg.tierName,
14710
+ id: m[2],
14711
+ parentRequirement: cfg.parentReq,
14712
+ targetMerge: cfg.merge
14713
+ };
14714
+ }
14721
14715
  }
14722
14716
  return null;
14723
14717
  }
14724
- function parseEnvInt(val) {
14725
- return val ? parseInt(val, 10) || 0 : 0;
14726
- }
14727
- function isEnvActive(val) {
14728
- return Boolean(val && val !== "0" && val !== "false");
14729
- }
14730
- function detectFromAgentEnv(env) {
14731
- for (const mapping of AGENT_ENV_MAPPINGS) {
14732
- const envVal = env[mapping.envKey];
14733
- if (!isEnvActive(envVal)) continue;
14734
- const model = env.AI_MODEL || (mapping.envKey === "AIDER_MODEL" ? envVal : mapping.defaultModel);
14718
+ function classifyTier4(branchName) {
14719
+ const taskMatch = branchName.match(BRANCH_PATTERNS.TASK);
14720
+ if (taskMatch) {
14735
14721
  return {
14736
- authorType: "agent",
14737
- model,
14738
- source: `env-${mapping.source}`,
14739
- confidence: "HIGH",
14740
- promptTokens: parseEnvInt(env.PROMPT_TOKENS),
14741
- completionTokens: parseEnvInt(env.COMPLETION_TOKENS),
14742
- activeTimeSeconds: parseEnvInt(env.ACTIVE_TIME_SECONDS || env.ACTIVE_TIME_SEC)
14722
+ valid: true,
14723
+ tier: 4,
14724
+ tierName: "Task (Tarea At\xF3mica)",
14725
+ parentId: taskMatch[1],
14726
+ taskId: taskMatch[2],
14727
+ parentRequirement: `Debe originarse desde la rama de feature, bug o patch: feat/${taskMatch[1]}, bug/${taskMatch[1]} o patch/${taskMatch[1]}`,
14728
+ targetMerge: `feat/${taskMatch[1]}, bug/${taskMatch[1]} o patch/${taskMatch[1]}`
14743
14729
  };
14744
14730
  }
14745
14731
  return null;
14746
14732
  }
14747
- function detectFromSignature(env, cwd) {
14748
- const authorName = env.GIT_AUTHOR_NAME || getGitConfigValue("user.name", cwd) || "";
14749
- const authorEmail = env.GIT_AUTHOR_EMAIL || getGitConfigValue("user.email", cwd) || "";
14750
- if (BOT_NAME_REGEX.test(authorName) || BOT_NAME_REGEX.test(authorEmail)) {
14751
- const inferredModel = resolveModelFromBotString(`${authorName} ${authorEmail}`);
14752
- return {
14753
- authorType: "agent",
14754
- model: inferredModel,
14755
- source: "git-user-signature",
14756
- confidence: "MEDIUM",
14757
- promptTokens: 0,
14758
- completionTokens: 0,
14759
- activeTimeSeconds: 0
14760
- };
14733
+ function classifyBranch(branchName) {
14734
+ return classifyTier1And2(branchName) || classifyTier3(branchName) || classifyTier4(branchName) || {
14735
+ valid: false,
14736
+ tier: 0,
14737
+ tierName: "Inv\xE1lido",
14738
+ error: `El nombre '${branchName}' no cumple con los est\xE1ndares del modelo de 4 tiers.`
14739
+ };
14740
+ }
14741
+ function buildTaskBranchLines(feature, tasks, fBranch) {
14742
+ const lines = [];
14743
+ const parentSlug = feature.split("-").slice(0, 2).join("-");
14744
+ for (const t of tasks) {
14745
+ const taskBranch = `task/${parentSlug}/${t.toLowerCase()}`;
14746
+ lines.push(` \u251C\u2500\u2500 ${taskBranch}`);
14747
+ lines.push(` \u2502 Comando git: git checkout ${fBranch} && git checkout -b ${taskBranch}`);
14761
14748
  }
14762
- return null;
14749
+ return lines;
14763
14750
  }
14764
- function detectAuthorIdentity(options = {}) {
14765
- const env = options.env || process.env;
14766
- const cwd = options.cwd || process.cwd();
14767
- return detectFromEnvOverride(env) || detectFromGitConfig(cwd) || detectFromTelemetry(cwd, env) || detectFromAgentEnv(env) || detectFromSignature(env, cwd) || {
14768
- authorType: "human",
14769
- model: "n/a",
14770
- source: "default-human",
14771
- confidence: "HIGH",
14772
- promptTokens: 0,
14773
- completionTokens: 0,
14774
- activeTimeSeconds: 0
14751
+ var PLAN_BANNER = "================================================================";
14752
+ function buildPlanHeader(vBranch, fBranch) {
14753
+ return [
14754
+ PLAN_BANNER,
14755
+ "AI-SDLC: Plan de Ramificaci\xF3n Jer\xE1rquico",
14756
+ `${PLAN_BANNER}
14757
+ `,
14758
+ `1. [TIER 1] Rama Base Estable: main`,
14759
+ `2. [TIER 2] Rama de Versi\xF3n Abierta: ${vBranch} (originada de main)`,
14760
+ `3. [TIER 3] Rama de Feature: ${fBranch} (originada de ${vBranch})
14761
+ `,
14762
+ `4. [TIER 4] Ramas de Tareas At\xF3micas (originadas de ${fBranch}):`
14763
+ ];
14764
+ }
14765
+ function generateBranchHierarchyPlan(version, feature, tasks) {
14766
+ const vBranch = `release/${version}`;
14767
+ const fBranch = `feat/${feature}`;
14768
+ const header = buildPlanHeader(vBranch, fBranch);
14769
+ const taskLines = buildTaskBranchLines(feature, tasks, fBranch);
14770
+ const footer = [
14771
+ `
14772
+ Flujo de Integraci\xF3n (Merges):`,
14773
+ ` task/* \u2794 [PR Tarea] \u2794 ${fBranch} \u2794 [PR Feature + Quality Gate] \u2794 ${vBranch} \u2794 [PR Release] \u2794 main
14774
+ `
14775
+ ];
14776
+ return {
14777
+ version,
14778
+ feature,
14779
+ tasks,
14780
+ planText: [...header, ...taskLines, ...footer].join("\n")
14775
14781
  };
14776
14782
  }
14777
- var PRE_COMMIT_SCRIPT = `#!/usr/bin/env bash
14778
- # ==============================================================================
14779
- # AI-SDLC: Universal Protected Branches Guard (pre-commit)
14780
- # ==============================================================================
14781
-
14782
- CURRENT_BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
14783
-
14784
- if [ -z "$CURRENT_BRANCH" ] || [ "$CURRENT_BRANCH" = "HEAD" ]; then
14785
- exit 0
14786
- fi
14787
-
14788
- # Protected branches regex: main, master, release/*, release/v*
14789
- if echo "$CURRENT_BRANCH" | grep -qE "^(main|master|release/.*)$"; then
14790
- echo "" >&2
14791
- echo "\u274C [AI-SDLC Security Guard] BLOCKED: Direct commits to protected branch '$CURRENT_BRANCH' are forbidden!" >&2
14792
- echo "--------------------------------------------------------------------------------" >&2
14793
- echo "Direct commits on protected branches violate the AI-SDLC 4-Tier Branching Policy." >&2
14794
- echo "You must create and switch to a dedicated working branch before committing:" >&2
14795
- echo "" >&2
14796
- echo " git checkout -b feat/<CHG-ID>-<slug>" >&2
14797
- echo " or" >&2
14798
- echo " git checkout -b task/<PARENT-ID>/<TSK-ID>-<slug>" >&2
14799
- echo "--------------------------------------------------------------------------------" >&2
14800
- echo "" >&2
14801
- exit 1
14802
- fi
14803
-
14804
- # Immutable Coding Rules Guard: block AI agents from adding, modifying or deleting coding rules files
14805
- IS_AGENT=0
14806
- 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
14807
- IS_AGENT=1
14808
- fi
14809
-
14810
- if [ "$IS_AGENT" = "1" ]; then
14811
- 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 "")
14812
- if [ -n "$TAMPERED_RULES" ]; then
14813
- echo "" >&2
14814
- echo "\u274C [AI-SDLC Immutable Coding Rules Guard] BLOCKED: AI agents are forbidden from adding, modifying or deleting coding rules files:" >&2
14815
- echo "$TAMPERED_RULES" >&2
14816
- echo "Fix the source or test code to comply with the compiler/linter rules instead of altering the rule configuration." >&2
14817
- echo "" >&2
14818
- exit 1
14819
- fi
14820
- fi
14821
-
14822
- exit 0
14823
- `;
14824
- var PREPARE_COMMIT_MSG_SCRIPT = `#!/usr/bin/env bash
14825
- # ==============================================================================
14826
- # AI-SDLC: Automated Commit Trailers Injection Hook
14827
- # ==============================================================================
14828
-
14829
- COMMIT_MSG_FILE=$1
14830
- COMMIT_SOURCE=$2
14831
-
14832
- # Bypass if this is an automated merge commit
14833
- if [ "$COMMIT_SOURCE" = "merge" ]; then
14834
- exit 0
14835
- fi
14836
-
14837
- CURRENT_BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
14838
- if [ -z "$CURRENT_BRANCH" ]; then
14839
- exit 0
14840
- fi
14841
-
14842
- # Extract Task-ID and Parent-Ref from 4-tier branch hierarchy
14843
- # Patterns: task/<PARENT-ID>/<TSK-ID>-slug | feat/<FEAT-ID>-slug | bug/<BUG-ID>-slug
14844
- TASK_ID=$(echo "$CURRENT_BRANCH" | grep -oE "TSK-[0-9A-Za-z-]+" || echo "")
14845
- if [ -z "$TASK_ID" ]; then
14846
- TASK_ID=$(head -n 1 "$COMMIT_MSG_FILE" 2>/dev/null | grep -oE "TSK-[0-9A-Za-z_-]+" | head -n 1 || echo "")
14847
- fi
14848
- if [ -z "$TASK_ID" ] && [ -f "$TELEMETRY_FILE" ]; then
14849
- TASK_ID=$(grep -oE '"taskId"s*:s*"[^"]+"' "$TELEMETRY_FILE" 2>/dev/null | sed -E 's/.*"taskId"s*:s*"([^"]+)".*/\\1/' || echo "")
14850
- fi
14851
-
14852
- PARENT_REF=$(echo "$CURRENT_BRANCH" | grep -oE "(CHG|FEAT|BUG|FIX|PATCH)-[0-9A-Za-z-]+" | head -n 1 || echo "")
14853
- if [ -z "$PARENT_REF" ]; then
14854
- 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 "")
14855
- fi
14856
-
14857
- TELEMETRY_FILE=".ai-sdlc/session-telemetry.json"
14858
- AUTHOR_TYPE="human"
14859
- AI_MODEL_NAME="n/a"
14860
- PROMPT_TOKENS=0
14861
- COMPLETION_TOKENS=0
14862
- ACTIVE_TIME_SEC=0
14863
-
14864
- # Execute universal IDE-agnostic author detection engine
14865
- 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 "")
14866
-
14867
- if [ -n "$DETECTED" ]; then
14868
- IFS='|' read -r DET_AUTHOR DET_MODEL DET_PROMPT DET_COMPL DET_TIME <<< "$DETECTED"
14869
- AUTHOR_TYPE="\${DET_AUTHOR:-$AUTHOR_TYPE}"
14870
- AI_MODEL_NAME="\${DET_MODEL:-$AI_MODEL_NAME}"
14871
- PROMPT_TOKENS="\${DET_PROMPT:-$PROMPT_TOKENS}"
14872
- COMPLETION_TOKENS="\${DET_COMPL:-$COMPLETION_TOKENS}"
14873
- ACTIVE_TIME_SEC="\${DET_TIME:-$ACTIVE_TIME_SEC}"
14874
- else
14875
- 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
14876
- AUTHOR_TYPE="agent"
14877
- AI_MODEL_NAME="\${AI_MODEL:-\${AI_AGENT_NAME:-\${AIDER_MODEL:-agent-developer}}}"
14878
- fi
14879
- fi
14880
-
14881
- # Estimate tokens and active time if not provided for agent
14882
- if [ "$PROMPT_TOKENS" = "0" ] && [ "$AUTHOR_TYPE" = "agent" ]; then
14883
- CHG_LINES=$(git diff --cached --shortstat 2>/dev/null | grep -oE '[0-9]+ (insertion|deletion)' | awk '{s+=$1} END {print s+0}')
14884
- if [ -n "$CHG_LINES" ] && [ "$CHG_LINES" -gt 0 ]; then
14885
- COMPLETION_TOKENS=$((CHG_LINES * 10))
14886
- PROMPT_TOKENS=$((2500 + CHG_LINES * 25))
14887
- ACTIVE_TIME_SEC=$((30 + CHG_LINES / 2))
14888
- else
14889
- PROMPT_TOKENS=1000
14890
- COMPLETION_TOKENS=0
14891
- ACTIVE_TIME_SEC=30
14892
- fi
14893
- fi
14894
-
14895
- # Inject missing trailers individually into the commit message
14896
- TRAILERS_TO_ADD=""
14897
-
14898
- if [ -n "$TASK_ID" ] && ! grep -qE "^Task-ID:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14899
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Task-ID: $TASK_ID
14900
- "
14901
- fi
14902
- if [ -n "$PARENT_REF" ] && ! grep -qE "^Parent-Ref:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14903
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Parent-Ref: $PARENT_REF
14904
- "
14905
- fi
14906
- if ! grep -qE "^Author-Type:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14907
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Author-Type: $AUTHOR_TYPE
14908
- "
14909
- fi
14910
- if [ "$AUTHOR_TYPE" = "agent" ] && ! grep -qE "^AI-Model:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14911
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}AI-Model: $AI_MODEL_NAME
14912
- "
14913
- fi
14914
- if ! grep -qE "^Prompt-Tokens:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14915
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Prompt-Tokens: $PROMPT_TOKENS
14916
- "
14917
- fi
14918
- if ! grep -qE "^Completion-Tokens:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14919
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Completion-Tokens: $COMPLETION_TOKENS
14920
- "
14921
- fi
14922
- if ! grep -qE "^Active-Time-Seconds:" "$COMMIT_MSG_FILE" 2>/dev/null; then
14923
- TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Active-Time-Seconds: $ACTIVE_TIME_SEC
14924
- "
14925
- fi
14926
-
14927
- if [ -n "$TRAILERS_TO_ADD" ]; then
14928
- echo "" >> "$COMMIT_MSG_FILE"
14929
- printf "$TRAILERS_TO_ADD" >> "$COMMIT_MSG_FILE"
14930
- fi
14931
-
14932
- if [ -f "$TELEMETRY_FILE" ]; then
14933
- rm -f "$TELEMETRY_FILE" 2>/dev/null || true
14934
- fi
14935
- `;
14936
- function installGitHooks(rootDir = process.cwd()) {
14937
- const gitDir = path14__namespace.join(rootDir, ".git");
14938
- if (!fs12__namespace.existsSync(gitDir)) {
14939
- return {
14940
- success: false,
14941
- error: `No se encontr\xF3 el directorio Git en '${gitDir}'.`
14942
- };
14783
+ function resolveVersionFromProposal(changeDir) {
14784
+ const proposalFile = path14__namespace.join(changeDir, "proposal.md");
14785
+ if (!fs12__namespace.existsSync(proposalFile)) return "1.0.0";
14786
+ const propContent = fs12__namespace.readFileSync(proposalFile, "utf-8");
14787
+ const propFm = propContent.match(/^---\r?\n([\s\S]*?)\r?\n---/);
14788
+ if (!propFm) return "1.0.0";
14789
+ const parsedProp = yaml3__default.default.load(propFm[1]);
14790
+ return parsedProp?.version ? String(parsedProp.version) : "1.0.0";
14791
+ }
14792
+ function resolveChangeVersion(fm, changeDir) {
14793
+ if (fm.version) return String(fm.version);
14794
+ if (fm["target-release"] || fm.release) return String(fm["target-release"] || fm.release);
14795
+ return resolveVersionFromProposal(changeDir);
14796
+ }
14797
+ function isTaskMatchingId(currentId, cleanTaskId) {
14798
+ const targetLower = cleanTaskId.toLowerCase();
14799
+ const currentLower = currentId.toLowerCase();
14800
+ return currentLower === targetLower || currentLower.startsWith(`${targetLower}-`) || targetLower.startsWith(`${currentLower}-`);
14801
+ }
14802
+ function parseTasksFrontmatter(tasksFile) {
14803
+ if (!fs12__namespace.existsSync(tasksFile)) return null;
14804
+ try {
14805
+ const content = fs12__namespace.readFileSync(tasksFile, "utf-8");
14806
+ const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
14807
+ if (!fmMatch) return null;
14808
+ const fm = yaml3__default.default.load(fmMatch[1]);
14809
+ return fm && Array.isArray(fm.tasks) ? fm : null;
14810
+ } catch {
14811
+ return null;
14943
14812
  }
14944
- const hooksDir = path14__namespace.join(gitDir, "hooks");
14945
- if (!fs12__namespace.existsSync(hooksDir)) {
14946
- fs12__namespace.mkdirSync(hooksDir, { recursive: true });
14813
+ }
14814
+ function resolveRawChangeId(fm, entryName) {
14815
+ return String(fm["change-id"] || fm.changeId || entryName.replace(/^(chg|CHG)-/i, "CHG-").toUpperCase());
14816
+ }
14817
+ function buildTaskMatch(currentId, currentTitle, rawChangeId, changeDir, versionStr) {
14818
+ return {
14819
+ taskId: currentId,
14820
+ taskTitle: currentTitle,
14821
+ changeId: rawChangeId,
14822
+ changeDir,
14823
+ version: versionStr
14824
+ };
14825
+ }
14826
+ function inspectChangeTasks(changeDir, entryName, cleanTaskId, availableTasks) {
14827
+ const fm = parseTasksFrontmatter(path14__namespace.join(changeDir, "tasks.md"));
14828
+ if (!fm || !fm.tasks) return void 0;
14829
+ const rawChangeId = resolveRawChangeId(fm, entryName);
14830
+ const versionStr = resolveChangeVersion(fm, changeDir);
14831
+ let match;
14832
+ for (const t of fm.tasks) {
14833
+ if (!t?.id) continue;
14834
+ const currentId = String(t.id).trim();
14835
+ const currentTitle = String(t.title || "").trim();
14836
+ availableTasks.push({ id: currentId, title: currentTitle, changeId: rawChangeId });
14837
+ if (!match && isTaskMatchingId(currentId, cleanTaskId)) {
14838
+ match = buildTaskMatch(currentId, currentTitle, rawChangeId, changeDir, versionStr);
14839
+ }
14947
14840
  }
14948
- const prepareCommitMsgPath = path14__namespace.join(hooksDir, "prepare-commit-msg");
14949
- const preCommitPath = path14__namespace.join(gitDir, "hooks", "pre-commit");
14841
+ return match;
14842
+ }
14843
+ function locateTaskInActiveChanges(taskId, rootDir = process.cwd()) {
14844
+ const cleanTaskId = (taskId || "").trim();
14845
+ if (!cleanTaskId) {
14846
+ return { found: false, error: "Debe especificar un identificador de tarea v\xE1lido (ej. TSK-001)." };
14847
+ }
14848
+ const activeChangesDir = path14__namespace.join(rootDir, "specs", "changes", "active");
14849
+ if (!fs12__namespace.existsSync(activeChangesDir)) {
14850
+ return { found: false, error: `No se encontr\xF3 el directorio de cambios activos en '${activeChangesDir}'.` };
14851
+ }
14852
+ const availableTasks = [];
14853
+ const candidateDirs = fs12__namespace.readdirSync(activeChangesDir, { withFileTypes: true });
14854
+ let matchedTask;
14855
+ for (const entry of candidateDirs) {
14856
+ if (!entry.isDirectory()) continue;
14857
+ const changeDir = path14__namespace.join(activeChangesDir, entry.name);
14858
+ const m = inspectChangeTasks(changeDir, entry.name, cleanTaskId, availableTasks);
14859
+ if (m && !matchedTask) {
14860
+ matchedTask = m;
14861
+ }
14862
+ }
14863
+ if (matchedTask) {
14864
+ return { found: true, match: matchedTask, availableTasks };
14865
+ }
14866
+ return {
14867
+ found: false,
14868
+ availableTasks,
14869
+ error: `No se encontr\xF3 la tarea '${cleanTaskId}' en ning\xFAn cambio activo bajo 'specs/changes/active/'.`
14870
+ };
14871
+ }
14872
+ function getGitBranchList(rootDir) {
14950
14873
  try {
14951
- fs12__namespace.writeFileSync(prepareCommitMsgPath, PREPARE_COMMIT_MSG_SCRIPT, { encoding: "utf-8", mode: 493 });
14952
- fs12__namespace.writeFileSync(preCommitPath, PRE_COMMIT_SCRIPT, { encoding: "utf-8", mode: 493 });
14953
- return {
14954
- success: true,
14955
- hookPath: prepareCommitMsgPath,
14956
- installedHooks: [prepareCommitMsgPath, preCommitPath]
14957
- };
14958
- } catch (err) {
14959
- const msg = err instanceof Error ? err.message : String(err);
14960
- return {
14961
- success: false,
14962
- error: `Error al escribir hooks en '${hooksDir}': ${msg}`
14963
- };
14874
+ const out = child_process3.execFileSync("git", ["branch", "-a"], {
14875
+ cwd: rootDir,
14876
+ encoding: "utf-8",
14877
+ stdio: ["pipe", "pipe", "ignore"]
14878
+ });
14879
+ return out.split("\n").map((l) => l.trim().replace(/^[*+]\s+/, "").replace(/^remotes\/origin\//, ""));
14880
+ } catch {
14881
+ return [];
14964
14882
  }
14965
14883
  }
14966
-
14967
- // src/reporters/pr-kpis.ts
14968
- var KPI_SUMMARY_START_TAG = "<!-- AI-SDLC-KPI-SUMMARY-START -->";
14969
- var KPI_SUMMARY_END_TAG = "<!-- AI-SDLC-KPI-SUMMARY-END -->";
14970
- function calculateEstimatedCost(promptTokens, completionTokens) {
14971
- const promptCost = promptTokens / 1e6 * 3;
14972
- const completionCost = completionTokens / 1e6 * 15;
14973
- return Math.round((promptCost + completionCost) * 1e4) / 1e4;
14884
+ function detectExistingReleaseBranch(branches, cleanVersion) {
14885
+ const candidate = `release/v${cleanVersion}`;
14886
+ const existing = branches.find((b) => b.startsWith("release/v") && classifyBranch(b).valid);
14887
+ return existing || candidate;
14974
14888
  }
14975
- function createEmptySummary() {
14889
+ function detectExistingFeatureBranch(branches, dirName, changeId, changeSlug) {
14890
+ const existing = branches.find(
14891
+ (b) => b.startsWith("feat/") && (b.toLowerCase().includes(dirName.toLowerCase()) || b.toLowerCase().includes(changeId.toLowerCase())) && classifyBranch(b).valid
14892
+ );
14893
+ if (existing) return existing;
14894
+ const normalizedName = slugify2(changeSlug).replace(/^(chg|bug|feat)-(\d+)/i, (_, p, n) => `${p.toUpperCase()}-${n}`);
14895
+ return `feat/${normalizedName}`;
14896
+ }
14897
+ function buildDefaultTaskSuffix(taskId, taskTitle) {
14898
+ let taskSuffix = taskId.toLowerCase();
14899
+ const hasSlug = taskSuffix.includes("-") && taskSuffix.split("-").length > 2;
14900
+ if (!hasSlug && taskTitle) {
14901
+ const titleSlug = slugify2(taskTitle).split("-").slice(0, 4).join("-");
14902
+ if (titleSlug) {
14903
+ taskSuffix = `${taskSuffix}-${titleSlug}`;
14904
+ }
14905
+ }
14906
+ return taskSuffix;
14907
+ }
14908
+ function detectExistingTaskBranch(branches, parentId, taskId, taskTitle) {
14909
+ const prefix = `task/${parentId}/`;
14910
+ const existing = branches.find(
14911
+ (b) => b.startsWith(prefix) && b.toLowerCase().includes(taskId.toLowerCase()) && classifyBranch(b).valid
14912
+ );
14913
+ if (existing) return existing;
14914
+ return `task/${parentId}/${buildDefaultTaskSuffix(taskId, taskTitle)}`;
14915
+ }
14916
+ function resolveBranchHierarchy(match, rootDir = process.cwd()) {
14917
+ const baseBranch = "main";
14918
+ const branches = getGitBranchList(rootDir);
14919
+ const cleanVersion = (match.version || "1.0.0").replace(/^v/, "");
14920
+ const releaseBranch = detectExistingReleaseBranch(branches, cleanVersion);
14921
+ const dirName = path14__namespace.basename(match.changeDir);
14922
+ const changeSlug = dirName.replace(/^(chg|CHG)-/i, (m) => m.toUpperCase());
14923
+ const featureBranch = detectExistingFeatureBranch(branches, dirName, match.changeId, changeSlug);
14924
+ const parentIdMatch = featureBranch.replace(/^(feat|feature)\//i, "").match(/^[a-zA-Z0-9]+-[a-zA-Z0-9]+/);
14925
+ const parentId = parentIdMatch ? parentIdMatch[0] : match.changeId.split("-").slice(0, 2).join("-");
14926
+ const taskBranch = detectExistingTaskBranch(branches, parentId, match.taskId, match.taskTitle);
14927
+ return { baseBranch, releaseBranch, featureBranch, taskBranch };
14928
+ }
14929
+ function branchExistsLocally(branch, rootDir) {
14930
+ try {
14931
+ child_process3.execFileSync("git", ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], {
14932
+ cwd: rootDir,
14933
+ stdio: ["pipe", "pipe", "pipe"]
14934
+ });
14935
+ return true;
14936
+ } catch {
14937
+ return false;
14938
+ }
14939
+ }
14940
+ function branchExistsRemotely(branch, rootDir) {
14941
+ try {
14942
+ child_process3.execFileSync("git", ["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`], {
14943
+ cwd: rootDir,
14944
+ stdio: ["pipe", "pipe", "pipe"]
14945
+ });
14946
+ return true;
14947
+ } catch {
14948
+ return false;
14949
+ }
14950
+ }
14951
+ function ensureBranchInCascade(branch, parentBranch, rootDir) {
14952
+ if (branchExistsLocally(branch, rootDir)) return false;
14953
+ if (branchExistsRemotely(branch, rootDir)) {
14954
+ child_process3.execFileSync("git", ["branch", "--track", branch, `origin/${branch}`], { cwd: rootDir, stdio: ["pipe", "pipe", "pipe"] });
14955
+ } else {
14956
+ child_process3.execFileSync("git", ["branch", branch, parentBranch], { cwd: rootDir, stdio: ["pipe", "pipe", "pipe"] });
14957
+ }
14958
+ return true;
14959
+ }
14960
+ function switchBranch(branch, rootDir) {
14961
+ child_process3.execFileSync("git", ["checkout", branch], { cwd: rootDir, stdio: ["pipe", "pipe", "pipe"] });
14962
+ }
14963
+ function cascadeBranchCheckout(hierarchy, rootDir, created, streamlined) {
14964
+ if (streamlined) {
14965
+ if (ensureBranchInCascade(hierarchy.featureBranch, hierarchy.baseBranch, rootDir)) created.push(hierarchy.featureBranch);
14966
+ switchBranch(hierarchy.featureBranch, rootDir);
14967
+ return hierarchy.featureBranch;
14968
+ }
14969
+ if (ensureBranchInCascade(hierarchy.releaseBranch, hierarchy.baseBranch, rootDir)) created.push(hierarchy.releaseBranch);
14970
+ if (ensureBranchInCascade(hierarchy.featureBranch, hierarchy.releaseBranch, rootDir)) created.push(hierarchy.featureBranch);
14971
+ if (ensureBranchInCascade(hierarchy.taskBranch, hierarchy.featureBranch, rootDir)) created.push(hierarchy.taskBranch);
14972
+ switchBranch(hierarchy.taskBranch, rootDir);
14973
+ return hierarchy.taskBranch;
14974
+ }
14975
+ function buildCheckoutErrorResult(match, hierarchy, created, err) {
14976
+ const message = err instanceof Error ? err.message : String(err);
14976
14977
  return {
14977
- commits: 0,
14978
- linesAdded: 0,
14979
- linesDeleted: 0,
14980
- activeTimeSeconds: 0,
14981
- promptTokens: 0,
14982
- completionTokens: 0,
14983
- estimatedCostUsd: 0
14978
+ success: false,
14979
+ taskId: match.taskId,
14980
+ changeId: match.changeId,
14981
+ releaseBranch: hierarchy.releaseBranch,
14982
+ featureBranch: hierarchy.featureBranch,
14983
+ taskBranch: hierarchy.taskBranch,
14984
+ createdBranches: created,
14985
+ error: `Error durante la creaci\xF3n o checkout de ramas Git: ${message}`
14984
14986
  };
14985
14987
  }
14986
- function accumulateRecord(target, record) {
14987
- target.commits += 1;
14988
- target.linesAdded += record.linesAdded;
14989
- target.linesDeleted += record.linesDeleted;
14990
- target.activeTimeSeconds += record.trailers.activeTimeSeconds;
14991
- target.promptTokens += record.trailers.promptTokens;
14992
- target.completionTokens += record.trailers.completionTokens;
14993
- target.estimatedCostUsd = calculateEstimatedCost(target.promptTokens, target.completionTokens);
14988
+ function buildLocateFailureResult(taskId, locateRes) {
14989
+ return {
14990
+ success: false,
14991
+ taskId,
14992
+ createdBranches: [],
14993
+ error: locateRes.error,
14994
+ availableTasks: locateRes.availableTasks
14995
+ };
14996
+ }
14997
+ function buildCheckoutSuccessResult(match, hierarchy, created, switchedBranch, streamlined) {
14998
+ return {
14999
+ success: true,
15000
+ taskId: match.taskId,
15001
+ changeId: match.changeId,
15002
+ releaseBranch: hierarchy.releaseBranch,
15003
+ featureBranch: hierarchy.featureBranch,
15004
+ taskBranch: streamlined ? void 0 : hierarchy.taskBranch,
15005
+ createdBranches: created,
15006
+ switchedBranch
15007
+ };
15008
+ }
15009
+ function checkoutTaskBranch(taskId, options = {}) {
15010
+ const rootDir = options.rootDir || process.cwd();
15011
+ const locateRes = locateTaskInActiveChanges(taskId, rootDir);
15012
+ if (!locateRes.found || !locateRes.match) {
15013
+ return buildLocateFailureResult(taskId, locateRes);
15014
+ }
15015
+ const match = locateRes.match;
15016
+ const hierarchy = resolveBranchHierarchy(match, rootDir);
15017
+ const created = [];
15018
+ try {
15019
+ const switched = cascadeBranchCheckout(hierarchy, rootDir, created, options.streamlined);
15020
+ return buildCheckoutSuccessResult(match, hierarchy, created, switched, options.streamlined);
15021
+ } catch (err) {
15022
+ return buildCheckoutErrorResult(match, hierarchy, created, err);
15023
+ }
15024
+ }
15025
+ var AGENT_ENV_MAPPINGS = [
15026
+ { envKey: "ANTIGRAVITY_AGENT", defaultModel: "gemini-3.8-flash", source: "antigravity" },
15027
+ { envKey: "ANTIGRAVITY_CONVERSATION_ID", defaultModel: "gemini-3.8-flash", source: "antigravity" },
15028
+ { envKey: "ANTIGRAVITY_AGENT_ID", defaultModel: "gemini-3.8-flash", source: "antigravity" },
15029
+ { envKey: "CORTEX_SESSION_ID", defaultModel: "antigravity-agent", source: "cortex" },
15030
+ { envKey: "CLAUDE_CODE", defaultModel: "claude-3-7-sonnet", source: "claude-code" },
15031
+ { envKey: "CLAUDE_AGENT", defaultModel: "claude-3-7-sonnet", source: "claude-agent" },
15032
+ { envKey: "CURSOR_AGENT", defaultModel: "cursor-agent", source: "cursor" },
15033
+ { envKey: "CURSOR_SESSION_ID", defaultModel: "cursor-agent", source: "cursor" },
15034
+ { envKey: "WINDSURF_AGENT", defaultModel: "windsurf-cascade", source: "windsurf" },
15035
+ { envKey: "CASCADE_AGENT", defaultModel: "windsurf-cascade", source: "cascade" },
15036
+ { envKey: "GITHUB_COPILOT_AGENT", defaultModel: "github-copilot", source: "copilot" },
15037
+ { envKey: "COPILOT_AGENT_NAME", defaultModel: "github-copilot", source: "copilot" },
15038
+ { envKey: "AIDER_MODEL", defaultModel: "aider-agent", source: "aider" },
15039
+ { envKey: "GEMINI_CLI", defaultModel: "gemini-1.5-pro", source: "gemini" },
15040
+ { envKey: "AI_AGENT_NAME", defaultModel: "agent-developer", source: "ai-sdlc-agent" },
15041
+ { envKey: "AI_MODEL", defaultModel: "agent-developer", source: "ai-sdlc-model" }
15042
+ ];
15043
+ var BOT_NAME_REGEX = /\b(bot|agent|copilot|assistant|llm|claude|gpt|cortex|gemini)\b/i;
15044
+ function getGitConfigValue(key, cwd) {
15045
+ try {
15046
+ const val = child_process3.execFileSync("git", ["config", "--get", key], {
15047
+ cwd,
15048
+ encoding: "utf-8",
15049
+ stdio: ["pipe", "pipe", "pipe"]
15050
+ }).trim();
15051
+ return val.length > 0 ? val : void 0;
15052
+ } catch {
15053
+ return void 0;
15054
+ }
14994
15055
  }
14995
- function accumulateAuthorSummaries(records, humanSummary, byModel) {
14996
- let linesAdded = 0;
14997
- let linesDeleted = 0;
14998
- let activeTime = 0;
14999
- let prompt = 0;
15000
- let completion = 0;
15001
- let isBugPr = false;
15002
- for (const record of records) {
15003
- linesAdded += record.linesAdded;
15004
- linesDeleted += record.linesDeleted;
15005
- activeTime += record.trailers.activeTimeSeconds;
15006
- prompt += record.trailers.promptTokens;
15007
- completion += record.trailers.completionTokens;
15008
- if (record.isBugFix) isBugPr = true;
15009
- if (record.trailers.authorType === "agent") {
15010
- const modelName = record.trailers.aiModel || "agent-generic";
15011
- if (!byModel[modelName]) byModel[modelName] = createEmptySummary();
15012
- accumulateRecord(byModel[modelName], record);
15013
- } else {
15014
- accumulateRecord(humanSummary, record);
15056
+ function readSessionTelemetry(cwd) {
15057
+ const possiblePaths = [
15058
+ path14__namespace.join(cwd, ".ai-sdlc", "session-telemetry.json"),
15059
+ path14__namespace.join(cwd, ".ai-sdlc", "agent-session.json")
15060
+ ];
15061
+ for (const p of possiblePaths) {
15062
+ if (fs12__namespace.existsSync(p)) {
15063
+ try {
15064
+ const raw = fs12__namespace.readFileSync(p, "utf-8");
15065
+ return JSON.parse(raw);
15066
+ } catch {
15067
+ }
15015
15068
  }
15016
15069
  }
15017
- return { linesAdded, linesDeleted, activeTime, prompt, completion, isBugPr };
15070
+ return null;
15018
15071
  }
15019
- function initTaskKpi(taskId) {
15020
- return {
15021
- taskId,
15022
- commits: 0,
15023
- fixCommits: 0,
15024
- linesAdded: 0,
15025
- linesDeleted: 0,
15026
- codeChurnPercent: 0,
15027
- totalTokens: 0,
15028
- activeTimeSeconds: 0,
15029
- reworkTokens: 0,
15030
- reworkTokensPercent: 0,
15031
- reworkTimeSeconds: 0,
15032
- reworkTimePercent: 0,
15033
- isFirstTimeRight: true
15034
- };
15072
+ function resolveModelFromBotString(str) {
15073
+ if (/claude/i.test(str)) return "claude-3-7-sonnet";
15074
+ if (/gpt/i.test(str)) return "gpt-4o";
15075
+ if (/copilot/i.test(str)) return "github-copilot";
15076
+ if (/gemini/i.test(str)) return "gemini-1.5-pro";
15077
+ if (/cortex/i.test(str)) return "antigravity-agent";
15078
+ return "agent-developer";
15035
15079
  }
15036
- function processTaskCommit(tStat, record) {
15037
- const recTokens = record.trailers.promptTokens + record.trailers.completionTokens;
15038
- tStat.commits += 1;
15039
- tStat.linesAdded += record.linesAdded;
15040
- tStat.linesDeleted += record.linesDeleted;
15041
- tStat.totalTokens += recTokens;
15042
- tStat.activeTimeSeconds += record.trailers.activeTimeSeconds;
15043
- const isRework = record.isBugFix || /^(fix|bug|remediate|refactor)(([^)]+))?:/i.test((record.subject || "").trim());
15044
- if (isRework) {
15045
- tStat.fixCommits += 1;
15046
- tStat.reworkTokens += recTokens;
15047
- tStat.reworkTimeSeconds += record.trailers.activeTimeSeconds;
15080
+ function detectFromEnvOverride(env) {
15081
+ const explicitEnv = env.AI_SDLC_AUTHOR_TYPE || env.AUTHOR_TYPE;
15082
+ if (explicitEnv === "human" || explicitEnv === "agent") {
15083
+ const model = explicitEnv === "agent" ? env.AI_MODEL || "agent-developer" : "n/a";
15084
+ return {
15085
+ authorType: explicitEnv,
15086
+ model,
15087
+ source: "explicit-env",
15088
+ confidence: "HIGH",
15089
+ promptTokens: 0,
15090
+ completionTokens: 0,
15091
+ activeTimeSeconds: 0
15092
+ };
15048
15093
  }
15094
+ return null;
15049
15095
  }
15050
- function accumulateTaskSummaries(records) {
15051
- const byTask = {};
15052
- for (const record of records) {
15053
- const tid = record.trailers.taskId || record.subject.match(/\b(TSK-[0-9A-Za-z_-]+)\b/i)?.[1]?.toUpperCase();
15054
- if (!tid) continue;
15055
- if (!byTask[tid]) byTask[tid] = initTaskKpi(tid);
15056
- processTaskCommit(byTask[tid], record);
15057
- }
15058
- for (const t of Object.values(byTask)) {
15059
- const churn = t.linesAdded > 0 ? t.linesDeleted / t.linesAdded * 100 : 0;
15060
- t.codeChurnPercent = Math.round(Math.min(churn, 100) * 10) / 10;
15061
- t.reworkTokensPercent = t.totalTokens > 0 ? Math.round(t.reworkTokens / t.totalTokens * 1e3) / 10 : 0;
15062
- t.reworkTimePercent = t.activeTimeSeconds > 0 ? Math.round(t.reworkTimeSeconds / t.activeTimeSeconds * 1e3) / 10 : 0;
15063
- t.isFirstTimeRight = t.fixCommits === 0 && t.codeChurnPercent < 25;
15096
+ function detectFromGitConfig(cwd) {
15097
+ const gitConfigType = getGitConfigValue("ai-sdlc.author-type", cwd);
15098
+ if (gitConfigType === "human" || gitConfigType === "agent") {
15099
+ const gitConfigModel = getGitConfigValue("ai-sdlc.model", cwd) || (gitConfigType === "agent" ? "agent-developer" : "n/a");
15100
+ return {
15101
+ authorType: gitConfigType,
15102
+ model: gitConfigModel,
15103
+ source: "git-config",
15104
+ confidence: "HIGH",
15105
+ promptTokens: 0,
15106
+ completionTokens: 0,
15107
+ activeTimeSeconds: 0
15108
+ };
15064
15109
  }
15065
- return byTask;
15066
- }
15067
- function assemblePrKpiAggregation(baseRef, headRef, records, totals, humanSummary, byModel, byTask) {
15068
- const totalTokens = totals.prompt + totals.completion;
15069
- return {
15070
- baseRef,
15071
- headRef,
15072
- totalCommits: records.length,
15073
- linesAdded: totals.linesAdded,
15074
- linesDeleted: totals.linesDeleted,
15075
- totalActiveTimeSeconds: totals.activeTime,
15076
- totalPromptTokens: totals.prompt,
15077
- totalCompletionTokens: totals.completion,
15078
- totalTokens,
15079
- estimatedCostUsd: calculateEstimatedCost(totals.prompt, totals.completion),
15080
- humanSummary,
15081
- byModel,
15082
- isBugPr: totals.isBugPr,
15083
- commitRecords: records,
15084
- byTask
15085
- };
15086
- }
15087
- function aggregateCommitKpiRecords(records, baseRef = "main", headRef = "HEAD") {
15088
- const humanSummary = createEmptySummary();
15089
- const byModel = {};
15090
- const totals = accumulateAuthorSummaries(records, humanSummary, byModel);
15091
- const byTask = accumulateTaskSummaries(records);
15092
- return assemblePrKpiAggregation(baseRef, headRef, records, totals, humanSummary, byModel, byTask);
15110
+ return null;
15093
15111
  }
15094
- function aggregatePrKpis(baseRef, headRef = "HEAD", options = {}) {
15095
- const records = extractCommitKpisFromRange(baseRef, headRef, options);
15096
- return aggregateCommitKpiRecords(records, baseRef, headRef);
15112
+ function detectFromTelemetry(cwd, env) {
15113
+ const telemetry = readSessionTelemetry(cwd);
15114
+ if (telemetry) {
15115
+ const model = telemetry.model || env.AI_MODEL || "agent-developer";
15116
+ return {
15117
+ authorType: "agent",
15118
+ model,
15119
+ source: "session-telemetry-file",
15120
+ confidence: "HIGH",
15121
+ promptTokens: telemetry.promptTokens || 0,
15122
+ completionTokens: telemetry.completionTokens || 0,
15123
+ activeTimeSeconds: telemetry.activeTimeSeconds || 0
15124
+ };
15125
+ }
15126
+ return null;
15097
15127
  }
15098
- function formatMinutes(seconds) {
15099
- const mins = Math.round(seconds / 60);
15100
- return mins > 0 ? `${mins} min` : `${seconds}s`;
15128
+ function parseEnvInt(val) {
15129
+ return val ? parseInt(val, 10) || 0 : 0;
15101
15130
  }
15102
- function buildPrKpiRows(kpi, models) {
15103
- const human = kpi.humanSummary;
15104
- const commitCols = models.map((m) => kpi.byModel[m].commits).join(" | ");
15105
- const linesCols = models.map((m) => `+${kpi.byModel[m].linesAdded} / -${kpi.byModel[m].linesDeleted}`).join(" | ");
15106
- const timeCols = models.map((m) => formatMinutes(kpi.byModel[m].activeTimeSeconds)).join(" | ");
15107
- const tokenCols = models.map((m) => `${(kpi.byModel[m].promptTokens + kpi.byModel[m].completionTokens).toLocaleString("en-US")}`).join(" | ");
15108
- const costCols = models.map((m) => `$${kpi.byModel[m].estimatedCostUsd.toFixed(2)}`).join(" | ");
15109
- const totalLines = `+${kpi.linesAdded} / -${kpi.linesDeleted}`;
15110
- const totalTime = formatMinutes(kpi.totalActiveTimeSeconds);
15111
- const totalTokensStr = `${kpi.totalTokens.toLocaleString("en-US")} tokens`;
15112
- const totalCostStr = `$${kpi.estimatedCostUsd.toFixed(2)} USD`;
15113
- return [
15114
- `| **Commits** | ${human.commits} |${models.length > 0 ? ` ${commitCols} |` : ""} **${kpi.totalCommits}** |`,
15115
- `| **Lines Added / Deleted** | +${human.linesAdded} / -${human.linesDeleted} |${models.length > 0 ? ` ${linesCols} |` : ""} **${totalLines}** |`,
15116
- `| **Active Development Time** | ${formatMinutes(human.activeTimeSeconds)} |${models.length > 0 ? ` ${timeCols} |` : ""} **${totalTime}** |`,
15117
- `| **Tokens Consumed (In+Out)** | 0 |${models.length > 0 ? ` ${tokenCols} |` : ""} **${totalTokensStr}** |`,
15118
- `| **Estimated Cost (USD)** | \u2014 (Human labor) |${models.length > 0 ? ` ${costCols} |` : ""} **${totalCostStr}** |`
15119
- ];
15131
+ function isEnvActive(val) {
15132
+ return Boolean(val && val !== "0" && val !== "false");
15120
15133
  }
15121
- function formatTaskKpiRows(byTask) {
15122
- const taskIds = Object.keys(byTask || {});
15123
- if (taskIds.length === 0) return [];
15124
- const rows = [
15125
- "",
15126
- "#### \u{1F4CB} Task-Level Rework & Code Churn Breakdown",
15127
- "",
15128
- "| Task ID | Commits (Total / Fix) | Lines (+ / -) | Code Churn % | Rework Tokens % | Rework Time % | Status |",
15129
- "| :--- | :---: | :---: | :---: | :---: | :---: | :---: |"
15130
- ];
15131
- for (const tid of taskIds) {
15132
- const t = byTask[tid];
15133
- const statusLabel = t.isFirstTimeRight ? "\u2714 First-Time-Right" : `\u26A0 ${t.fixCommits} rework commit${t.fixCommits === 1 ? "" : "s"}`;
15134
- rows.push(
15135
- `| \`${t.taskId}\` | ${t.commits} (${t.fixCommits} fix) | +${t.linesAdded} / -${t.linesDeleted} | ${t.codeChurnPercent}% | ${t.reworkTokensPercent}% | ${t.reworkTimePercent}% | ${statusLabel} |`
15136
- );
15134
+ function detectFromAgentEnv(env) {
15135
+ for (const mapping of AGENT_ENV_MAPPINGS) {
15136
+ const envVal = env[mapping.envKey];
15137
+ if (!isEnvActive(envVal)) continue;
15138
+ const model = env.AI_MODEL || (mapping.envKey === "AIDER_MODEL" ? envVal : mapping.defaultModel);
15139
+ return {
15140
+ authorType: "agent",
15141
+ model,
15142
+ source: `env-${mapping.source}`,
15143
+ confidence: "HIGH",
15144
+ promptTokens: parseEnvInt(env.PROMPT_TOKENS),
15145
+ completionTokens: parseEnvInt(env.COMPLETION_TOKENS),
15146
+ activeTimeSeconds: parseEnvInt(env.ACTIVE_TIME_SECONDS || env.ACTIVE_TIME_SEC)
15147
+ };
15137
15148
  }
15138
- return rows;
15149
+ return null;
15139
15150
  }
15140
- function formatPrKpiMarkdown(kpi) {
15141
- const models = Object.keys(kpi.byModel);
15142
- const modelHeaders = models.map((m) => `Agent (${m})`).join(" | ");
15143
- const modelSeparator = models.map(() => ":---:").join(" | ");
15144
- const headers = `| Metric | Human |${models.length > 0 ? ` ${modelHeaders} |` : ""} Total PR |`;
15145
- const sep5 = `| :--- | :---: |${models.length > 0 ? ` ${modelSeparator} |` : ""} :---: |`;
15146
- const rows = buildPrKpiRows(kpi, models);
15147
- const taskRowsList = formatTaskKpiRows(kpi.byTask);
15148
- return [
15149
- KPI_SUMMARY_START_TAG,
15150
- "### \u{1F4CA} AI-SDLC: Aggregated PR KPI Summary",
15151
- "",
15152
- headers,
15153
- sep5,
15154
- ...rows,
15155
- ...taskRowsList,
15156
- "",
15157
- `> **Branch Attribution:** ${kpi.isBugPr ? "\u{1F6A8} *Defect Fix / Bugfix*" : "\u2728 *New Feature*"} (Range: \`${kpi.baseRef}..${kpi.headRef}\`)`,
15158
- KPI_SUMMARY_END_TAG
15159
- ].join("\n");
15151
+ function detectFromSignature(env, cwd) {
15152
+ const authorName = env.GIT_AUTHOR_NAME || getGitConfigValue("user.name", cwd) || "";
15153
+ const authorEmail = env.GIT_AUTHOR_EMAIL || getGitConfigValue("user.email", cwd) || "";
15154
+ if (BOT_NAME_REGEX.test(authorName) || BOT_NAME_REGEX.test(authorEmail)) {
15155
+ const inferredModel = resolveModelFromBotString(`${authorName} ${authorEmail}`);
15156
+ return {
15157
+ authorType: "agent",
15158
+ model: inferredModel,
15159
+ source: "git-user-signature",
15160
+ confidence: "MEDIUM",
15161
+ promptTokens: 0,
15162
+ completionTokens: 0,
15163
+ activeTimeSeconds: 0
15164
+ };
15165
+ }
15166
+ return null;
15160
15167
  }
15161
- function injectKpisIntoPrBody(originalBody, kpiMarkdown) {
15162
- const body = originalBody || "";
15163
- const startIndex = body.indexOf(KPI_SUMMARY_START_TAG);
15164
- const endIndex = body.indexOf(KPI_SUMMARY_END_TAG);
15165
- if (startIndex !== -1 && endIndex !== -1) {
15166
- const before = body.slice(0, startIndex);
15167
- const after = body.slice(endIndex + KPI_SUMMARY_END_TAG.length);
15168
- return `${before.trimEnd()}
15168
+ function detectAuthorIdentity(options = {}) {
15169
+ const env = options.env || process.env;
15170
+ const cwd = options.cwd || process.cwd();
15171
+ return detectFromEnvOverride(env) || detectFromGitConfig(cwd) || detectFromTelemetry(cwd, env) || detectFromAgentEnv(env) || detectFromSignature(env, cwd) || {
15172
+ authorType: "human",
15173
+ model: "n/a",
15174
+ source: "default-human",
15175
+ confidence: "HIGH",
15176
+ promptTokens: 0,
15177
+ completionTokens: 0,
15178
+ activeTimeSeconds: 0
15179
+ };
15180
+ }
15181
+ var PRE_COMMIT_SCRIPT = `#!/usr/bin/env bash
15182
+ # ==============================================================================
15183
+ # AI-SDLC: Universal Protected Branches Guard (pre-commit)
15184
+ # ==============================================================================
15169
15185
 
15170
- ${kpiMarkdown}
15186
+ CURRENT_BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
15171
15187
 
15172
- ${after.trimStart()}`.trim();
15173
- }
15174
- return `${body.trimEnd()}
15188
+ if [ -z "$CURRENT_BRANCH" ] || [ "$CURRENT_BRANCH" = "HEAD" ]; then
15189
+ exit 0
15190
+ fi
15175
15191
 
15176
- ${kpiMarkdown}
15192
+ # Protected branches regex: main, master, release/*, release/v*
15193
+ if echo "$CURRENT_BRANCH" | grep -qE "^(main|master|release/.*)$"; then
15194
+ echo "" >&2
15195
+ echo "\u274C [AI-SDLC Security Guard] BLOCKED: Direct commits to protected branch '$CURRENT_BRANCH' are forbidden!" >&2
15196
+ echo "--------------------------------------------------------------------------------" >&2
15197
+ echo "Direct commits on protected branches violate the AI-SDLC 4-Tier Branching Policy." >&2
15198
+ echo "You must create and switch to a dedicated working branch before committing:" >&2
15199
+ echo "" >&2
15200
+ echo " git checkout -b feat/<CHG-ID>-<slug>" >&2
15201
+ echo " or" >&2
15202
+ echo " git checkout -b task/<PARENT-ID>/<TSK-ID>-<slug>" >&2
15203
+ echo "--------------------------------------------------------------------------------" >&2
15204
+ echo "" >&2
15205
+ exit 1
15206
+ fi
15207
+
15208
+ # Immutable Coding Rules Guard: block AI agents from adding, modifying or deleting coding rules files
15209
+ IS_AGENT=0
15210
+ 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
15211
+ IS_AGENT=1
15212
+ fi
15213
+
15214
+ if [ "$IS_AGENT" = "1" ]; then
15215
+ 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 "")
15216
+ if [ -n "$TAMPERED_RULES" ]; then
15217
+ echo "" >&2
15218
+ echo "\u274C [AI-SDLC Immutable Coding Rules Guard] BLOCKED: AI agents are forbidden from adding, modifying or deleting coding rules files:" >&2
15219
+ echo "$TAMPERED_RULES" >&2
15220
+ echo "Fix the source or test code to comply with the compiler/linter rules instead of altering the rule configuration." >&2
15221
+ echo "" >&2
15222
+ exit 1
15223
+ fi
15224
+ fi
15225
+
15226
+ exit 0
15227
+ `;
15228
+ var PREPARE_COMMIT_MSG_SCRIPT = `#!/usr/bin/env bash
15229
+ # ==============================================================================
15230
+ # AI-SDLC: Automated Commit Trailers Injection Hook
15231
+ # ==============================================================================
15232
+
15233
+ COMMIT_MSG_FILE=$1
15234
+ COMMIT_SOURCE=$2
15235
+
15236
+ # Bypass if this is an automated merge commit
15237
+ if [ "$COMMIT_SOURCE" = "merge" ]; then
15238
+ exit 0
15239
+ fi
15240
+
15241
+ CURRENT_BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
15242
+ if [ -z "$CURRENT_BRANCH" ]; then
15243
+ exit 0
15244
+ fi
15245
+
15246
+ # Extract Task-ID and Parent-Ref from 4-tier branch hierarchy
15247
+ # Patterns: task/<PARENT-ID>/<TSK-ID>-slug | feat/<FEAT-ID>-slug | bug/<BUG-ID>-slug
15248
+ TASK_ID=$(echo "$CURRENT_BRANCH" | grep -oE "TSK-[0-9A-Za-z-]+" || echo "")
15249
+ if [ -z "$TASK_ID" ]; then
15250
+ TASK_ID=$(head -n 1 "$COMMIT_MSG_FILE" 2>/dev/null | grep -oE "TSK-[0-9A-Za-z_-]+" | head -n 1 || echo "")
15251
+ fi
15252
+ if [ -z "$TASK_ID" ] && [ -f "$TELEMETRY_FILE" ]; then
15253
+ TASK_ID=$(grep -oE '"taskId"s*:s*"[^"]+"' "$TELEMETRY_FILE" 2>/dev/null | sed -E 's/.*"taskId"s*:s*"([^"]+)".*/\\1/' || echo "")
15254
+ fi
15255
+
15256
+ PARENT_REF=$(echo "$CURRENT_BRANCH" | grep -oE "(CHG|FEAT|BUG|FIX|PATCH)-[0-9A-Za-z-]+" | head -n 1 || echo "")
15257
+ if [ -z "$PARENT_REF" ]; then
15258
+ 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 "")
15259
+ fi
15260
+
15261
+ TELEMETRY_FILE=".ai-sdlc/session-telemetry.json"
15262
+ AUTHOR_TYPE="human"
15263
+ AI_MODEL_NAME="n/a"
15264
+ PROMPT_TOKENS=0
15265
+ COMPLETION_TOKENS=0
15266
+ ACTIVE_TIME_SEC=0
15267
+
15268
+ # Execute universal IDE-agnostic author detection engine
15269
+ 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 "")
15270
+
15271
+ if [ -n "$DETECTED" ]; then
15272
+ IFS='|' read -r DET_AUTHOR DET_MODEL DET_PROMPT DET_COMPL DET_TIME <<< "$DETECTED"
15273
+ AUTHOR_TYPE="\${DET_AUTHOR:-$AUTHOR_TYPE}"
15274
+ AI_MODEL_NAME="\${DET_MODEL:-$AI_MODEL_NAME}"
15275
+ PROMPT_TOKENS="\${DET_PROMPT:-$PROMPT_TOKENS}"
15276
+ COMPLETION_TOKENS="\${DET_COMPL:-$COMPLETION_TOKENS}"
15277
+ ACTIVE_TIME_SEC="\${DET_TIME:-$ACTIVE_TIME_SEC}"
15278
+ else
15279
+ 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
15280
+ AUTHOR_TYPE="agent"
15281
+ AI_MODEL_NAME="\${AI_MODEL:-\${AI_AGENT_NAME:-\${AIDER_MODEL:-agent-developer}}}"
15282
+ fi
15283
+ fi
15284
+
15285
+ # Estimate tokens and active time if not provided for agent
15286
+ if [ "$PROMPT_TOKENS" = "0" ] && [ "$AUTHOR_TYPE" = "agent" ]; then
15287
+ CHG_LINES=$(git diff --cached --shortstat 2>/dev/null | grep -oE '[0-9]+ (insertion|deletion)' | awk '{s+=$1} END {print s+0}')
15288
+ if [ -n "$CHG_LINES" ] && [ "$CHG_LINES" -gt 0 ]; then
15289
+ COMPLETION_TOKENS=$((CHG_LINES * 10))
15290
+ PROMPT_TOKENS=$((2500 + CHG_LINES * 25))
15291
+ ACTIVE_TIME_SEC=$((30 + CHG_LINES / 2))
15292
+ else
15293
+ PROMPT_TOKENS=1000
15294
+ COMPLETION_TOKENS=0
15295
+ ACTIVE_TIME_SEC=30
15296
+ fi
15297
+ fi
15298
+
15299
+ # Inject missing trailers individually into the commit message
15300
+ TRAILERS_TO_ADD=""
15301
+
15302
+ if [ -n "$TASK_ID" ] && ! grep -qE "^Task-ID:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15303
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Task-ID: $TASK_ID
15304
+ "
15305
+ fi
15306
+ if [ -n "$PARENT_REF" ] && ! grep -qE "^Parent-Ref:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15307
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Parent-Ref: $PARENT_REF
15308
+ "
15309
+ fi
15310
+ if ! grep -qE "^Author-Type:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15311
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Author-Type: $AUTHOR_TYPE
15312
+ "
15313
+ fi
15314
+ if [ "$AUTHOR_TYPE" = "agent" ] && ! grep -qE "^AI-Model:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15315
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}AI-Model: $AI_MODEL_NAME
15316
+ "
15317
+ fi
15318
+ if ! grep -qE "^Prompt-Tokens:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15319
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Prompt-Tokens: $PROMPT_TOKENS
15320
+ "
15321
+ fi
15322
+ if ! grep -qE "^Completion-Tokens:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15323
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Completion-Tokens: $COMPLETION_TOKENS
15324
+ "
15325
+ fi
15326
+ if ! grep -qE "^Active-Time-Seconds:" "$COMMIT_MSG_FILE" 2>/dev/null; then
15327
+ TRAILERS_TO_ADD="\${TRAILERS_TO_ADD}Active-Time-Seconds: $ACTIVE_TIME_SEC
15328
+ "
15329
+ fi
15330
+
15331
+ if [ -n "$TRAILERS_TO_ADD" ]; then
15332
+ echo "" >> "$COMMIT_MSG_FILE"
15333
+ printf "$TRAILERS_TO_ADD" >> "$COMMIT_MSG_FILE"
15334
+ fi
15335
+
15336
+ if [ -f "$TELEMETRY_FILE" ]; then
15337
+ rm -f "$TELEMETRY_FILE" 2>/dev/null || true
15338
+ fi
15177
15339
  `;
15340
+ function installGitHooks(rootDir = process.cwd()) {
15341
+ const gitDir = path14__namespace.join(rootDir, ".git");
15342
+ if (!fs12__namespace.existsSync(gitDir)) {
15343
+ return {
15344
+ success: false,
15345
+ error: `No se encontr\xF3 el directorio Git en '${gitDir}'.`
15346
+ };
15347
+ }
15348
+ const hooksDir = path14__namespace.join(gitDir, "hooks");
15349
+ if (!fs12__namespace.existsSync(hooksDir)) {
15350
+ fs12__namespace.mkdirSync(hooksDir, { recursive: true });
15351
+ }
15352
+ const prepareCommitMsgPath = path14__namespace.join(hooksDir, "prepare-commit-msg");
15353
+ const preCommitPath = path14__namespace.join(gitDir, "hooks", "pre-commit");
15354
+ try {
15355
+ fs12__namespace.writeFileSync(prepareCommitMsgPath, PREPARE_COMMIT_MSG_SCRIPT, { encoding: "utf-8", mode: 493 });
15356
+ fs12__namespace.writeFileSync(preCommitPath, PRE_COMMIT_SCRIPT, { encoding: "utf-8", mode: 493 });
15357
+ return {
15358
+ success: true,
15359
+ hookPath: prepareCommitMsgPath,
15360
+ installedHooks: [prepareCommitMsgPath, preCommitPath]
15361
+ };
15362
+ } catch (err) {
15363
+ const msg = err instanceof Error ? err.message : String(err);
15364
+ return {
15365
+ success: false,
15366
+ error: `Error al escribir hooks en '${hooksDir}': ${msg}`
15367
+ };
15368
+ }
15178
15369
  }
15179
15370
  function calculateCost(prompt, completion) {
15180
15371
  const promptCost = prompt / 1e6 * 3;
@@ -17803,16 +17994,35 @@ function resolveBranchFilterKeys(metricsData) {
17803
17994
  }
17804
17995
  return keys;
17805
17996
  }
17997
+ function renderAgentKpisSectionHtml(kpis) {
17998
+ if (!kpis) return "";
17999
+ return [
18000
+ `<div class="chart-container" id="agent-performance-kpis">`,
18001
+ ` <h3>AI Agent Performance KPIs (SWE-bench &amp; DORA AI)</h3>`,
18002
+ ` <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>`,
18003
+ ` <div class="grid-cards">`,
18004
+ ` <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>`,
18005
+ ` <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>`,
18006
+ ` <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>`,
18007
+ ` <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>`,
18008
+ ` <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>`,
18009
+ ` <div class="metric-card"><span class="title">Architecture Drift Rate</span><span class="value">${kpis.architectureDriftRatePercent}%</span><span class="subtitle">Target 0%</span></div>`,
18010
+ ` </div>`,
18011
+ `</div>`
18012
+ ].join("\n");
18013
+ }
17806
18014
  function renderKpisTabHtml(metricsData) {
17807
18015
  const displayKpi = metricsData.totalTelemetry || metricsData.activePrKpi;
17808
18016
  const branchKeys = resolveBranchFilterKeys(metricsData);
17809
18017
  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>';
18018
+ const agentKpisHtml = renderAgentKpisSectionHtml(metricsData.agentKpis);
17810
18019
  const historyContent = renderHistoricalKpisTable(metricsData.history);
17811
18020
  return [
17812
18021
  ` <div id="tab-kpis" class="tab-panel">`,
17813
18022
  ` <div class="content-container">`,
17814
18023
  ` <h2>Active Telemetry and KPI History</h2>`,
17815
18024
  telemetryHtml,
18025
+ agentKpisHtml,
17816
18026
  ` <div class="chart-container"><h3>Consolidated Release History</h3>${historyContent}</div>`,
17817
18027
  ` </div>`,
17818
18028
  ` </div>`
@@ -18174,6 +18384,12 @@ function collectDashboardMetrics(rootDir) {
18174
18384
  history,
18175
18385
  activePrKpi
18176
18386
  );
18387
+ const agentKpis = computeAgentPerformanceKpis({
18388
+ records: totalTelemetry?.commitRecords || [],
18389
+ gateResult: gate,
18390
+ coverageResult: cov,
18391
+ traceabilityResult: trace
18392
+ });
18177
18393
  return {
18178
18394
  gate,
18179
18395
  gov,
@@ -18186,6 +18402,7 @@ function collectDashboardMetrics(rootDir) {
18186
18402
  activeBranch,
18187
18403
  branchTelemetries,
18188
18404
  totalTelemetry,
18405
+ agentKpis,
18189
18406
  complianceBundle
18190
18407
  };
18191
18408
  }
@@ -18406,7 +18623,7 @@ var SPECIALIZED_AGENT_TEMPLATES = [
18406
18623
 
18407
18624
  ## Phase 0: Greenfield Product Inception (New Product Intent)
18408
18625
  - **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:
18409
- 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.
18626
+ 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.
18410
18627
  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.
18411
18628
  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.
18412
18629
  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.
@@ -18494,6 +18711,7 @@ var SPECIALIZED_AGENT_TEMPLATES = [
18494
18711
  - **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.
18495
18712
  - **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.
18496
18713
  - Generate interaction and sequence diagrams in native Mermaid syntax.
18714
+ - **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-*\`).
18497
18715
  - Document critical technological decisions using immutable \`ADR-*\` records conforming to \`schemas/architecture/adr.schema.json\`.
18498
18716
  - Validate that architectural choices comply with legal constraints in \`license-policy.yaml\` and data protection constraints in \`privacy-policy.yaml\`.
18499
18717
  - **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.
@@ -18528,7 +18746,11 @@ var SPECIALIZED_AGENT_TEMPLATES = [
18528
18746
  - **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\`).
18529
18747
  - Tag all scenarios with \`@<FR-ID> @automated @regression\`.
18530
18748
  - **STRICTLY FORBIDDEN**: Including production code, suggesting implementation, or anticipating technical solutions.
18531
- - Run \`pnpm run verify:testing\` before emitting handoff.
18749
+ - **MANDATORY DETERMINISTIC GHERKIN ENGINES**:
18750
+ 1. **NEVER** author or edit \`.feature\` files in \`tests/features/\` manually, and **NEVER** write boilerplate BDD step definition files in \`tests/steps/\` from scratch.
18751
+ 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.
18752
+ 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.
18753
+ - Run \`npx aisdlc verify gherkin\` and \`pnpm run verify:testing\` before emitting handoff.
18532
18754
  - 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.`
18533
18755
  },
18534
18756
  {
@@ -18573,42 +18795,7 @@ Execute every implementation task following this strict sequential order:
18573
18795
  - **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.
18574
18796
  - **Global Styles Protection**: When touching or refactoring frontend views, verify that global stylesheet/asset imports remain intact and that layouts suffer no visual disruption.
18575
18797
  - **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.
18576
- - Upon completing green implementation, suggest handoff to \`agent-expert-user\` for Post-Development Functional Validation prior to security and privacy audit.`
18577
- },
18578
- {
18579
- id: "agent-security-auditor",
18580
- title: "Adversarial Code Auditor",
18581
- description: "Examine Pull Requests and source code with an attacker mindset for business logic vulnerabilities, injection vectors, secret leaks, and authorization flaws.",
18582
- globs: "src/**, packages/**, security/**",
18583
- claudeTools: ["View", "GlobTool", "GrepTool", "LS", "Bash"],
18584
- antigravityTools: ["read_file", "run_command", "call_mcp_tool"],
18585
- body: `## Role & Mission
18586
- - **Role**: Adversarial Security Auditor Agent (\`agent-security-auditor\`).
18587
- - **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.
18588
-
18589
- ## Operational Directives & Guardrails
18590
- - 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?
18591
- - Run deterministic security verification: \`pnpm run verify:security\` (secrets + shift-left SAST).
18592
- - Issue a formal audit report with CVSS v3.1 severity scoring and concrete remediation proposals.
18593
- - Immediately block any PR introducing CRITICAL or HIGH security risks.
18594
- - 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.`
18595
- },
18596
- {
18597
- id: "agent-compliance-checker",
18598
- title: "Open Source License Compliance Auditor",
18599
- description: "Audit dependency manifests and SBOMs against license-policy.yaml to block viral copyleft licenses and flag commercial license requirements.",
18600
- globs: "package.json, pnpm-lock.yaml, license-policy.yaml, compliance/**",
18601
- claudeTools: ["View", "GlobTool", "GrepTool", "LS", "Bash"],
18602
- antigravityTools: ["read_file", "run_command", "call_mcp_tool"],
18603
- body: `## Role & Mission
18604
- - **Role**: Open Source License and Intellectual Property Compliance Auditor Agent (\`agent-compliance-checker\`).
18605
- - **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.
18606
-
18607
- ## Operational Directives & Guardrails
18608
- - Verify SPDX identifiers for every direct and transitive dependency via \`pnpm run verify:licenses\`.
18609
- - Immediately block viral copyleft licenses (\`GPL-*\`, \`AGPL-*\`) and unknown/unlicensed packages.
18610
- - 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\`.
18611
- - 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.`
18798
+ - 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\`).`
18612
18799
  },
18613
18800
  {
18614
18801
  id: "agent-expert-user",
@@ -18627,28 +18814,7 @@ Execute every implementation task following this strict sequential order:
18627
18814
  - **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.
18628
18815
  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.
18629
18816
  - Formulate decisive questions under \`open-questions\` for the human Product Owner.
18630
- - 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.`
18631
- },
18632
- {
18633
- id: "agent-code-reviewer",
18634
- title: "Technical and Architectural Code Reviewer",
18635
- description: "Audit Pull Requests for Clean Code, SOLID, DRY, YAGNI, design patterns, and compliance with quality-policy.yaml complexity and maintainability thresholds.",
18636
- globs: "src/**, packages/**, tests/**",
18637
- claudeTools: ["View", "GlobTool", "GrepTool", "LS", "Bash"],
18638
- antigravityTools: ["read_file", "run_command", "call_mcp_tool"],
18639
- body: `## Role & Mission
18640
- - **Role**: Technical and Architectural Code Reviewer Agent (\`agent-code-reviewer\`).
18641
- - **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.
18642
-
18643
- ## Operational Directives & Guardrails
18644
- - 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$.
18645
- - Detect improper coupling, code smells, magic numbers, ambiguous identifiers, and encapsulation breaches.
18646
- - Flag premature abstractions and speculative code violating YAGNI.
18647
- - **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.
18648
- - **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.
18649
- - Coordinate Pre-Merge Audit Triad with \`agent-security-auditor\`, \`agent-privacy-officer\`, and \`agent-compliance-checker\`.
18650
- - Categorize findings into: \`[BLOCKING]\` (quality violation or broken pattern), \`[CLEAN_CODE_SUGGESTION]\` (non-blocking improvement), and \`[COMPLIANT]\`.
18651
- - 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.`
18817
+ - 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.`
18652
18818
  },
18653
18819
  {
18654
18820
  id: "agent-devops",
@@ -18656,7 +18822,7 @@ Execute every implementation task following this strict sequential order:
18656
18822
  description: "Maintain, evolve, and audit CI/CD workflows, Dockerfiles, IaC manifests, and support scripts under strict non-invasion guardrails on src/.",
18657
18823
  globs: ".github/workflows/**, templates/ci/**, scripts/**, Dockerfile*",
18658
18824
  claudeTools: ["View", "Edit", "Replace", "GlobTool", "GrepTool", "LS", "Bash"],
18659
- antigravityTools: ["read_file", "edit_file", "write_file", "run_command", "call_mcp_tool"],
18825
+ antigravityTools: ["read_file", "edit_file", "write_file", "run_command", "call_mcp_tool", "ask_question"],
18660
18826
  body: `## Role & Mission
18661
18827
  - **Role**: DevOps and Infrastructure as Code (IaC) Engineer Agent (\`agent-devops\`).
18662
18828
  - **Mission**: Maintain, evolve, and audit automated project infrastructure: CI/CD workflows, Docker containers, deployment manifests, and infrastructure scripts.
@@ -18664,6 +18830,7 @@ Execute every implementation task following this strict sequential order:
18664
18830
  ## Operational Directives & Guardrails
18665
18831
  - **Strict Infrastructure Domain**: Operate exclusively on workflows (\`.github/workflows/\`, \`templates/ci/\`), container files (\`Dockerfile*\`, \`docker-compose*.yml\`), IaC manifests, and support scripts (\`scripts/\`).
18666
18832
  - **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.
18833
+ - **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\`).
18667
18834
  - **Infrastructure Dependency Policy**: Verify licenses of dependencies, Docker base images, and third-party CI actions against \`license-policy.yaml\`.
18668
18835
  - **Gate Preservation**: Ensure any pipeline optimization keeps all existing deterministic Quality Gates intact.
18669
18836
  - **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.
@@ -18673,18 +18840,21 @@ Execute every implementation task following this strict sequential order:
18673
18840
  {
18674
18841
  id: "agent-auditor",
18675
18842
  title: "Transversal Quality and Improvement Auditor",
18676
- 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.",
18843
+ 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.",
18677
18844
  globs: "**/*",
18678
18845
  claudeTools: ["View", "GlobTool", "GrepTool", "LS", "Bash"],
18679
18846
  antigravityTools: ["read_file", "run_command", "call_mcp_tool", "ask_question"],
18680
18847
  body: `## Role & Mission
18681
18848
  - **Role**: Transversal Quality and Constructive Auditor Agent (\`agent-auditor\`).
18682
- - **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).
18849
+ - **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.
18683
18850
 
18684
18851
  ## Operational Directives & Guardrails
18685
18852
  - **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\`).
18686
- - **Simplicity First (YAGNI)**: Actively challenge speculative parameters, redundant interfaces, unused design patterns, and unrequested flexibility.
18853
+ - **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.
18854
+ - **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.
18687
18855
  - **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.
18856
+ - **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\`.
18857
+ - **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\`.
18688
18858
  - **Classification of Findings**: Label every finding as:
18689
18859
  * \`[BLOCKING_DEFECT]\`: Critical omission, structural debt, or standard violation that must be resolved.
18690
18860
  * \`[SIMPLIFICATION]\`: Opportunity to remove unneeded complexity or reduce code/spec surface without loss of function.
@@ -18696,20 +18866,20 @@ Execute every implementation task following this strict sequential order:
18696
18866
  {
18697
18867
  id: "agent-adversary",
18698
18868
  title: "Transversal Red Team and Chaos Adversary",
18699
- 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.",
18869
+ 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).",
18700
18870
  globs: "**/*",
18701
18871
  claudeTools: ["View", "GlobTool", "GrepTool", "LS", "Bash"],
18702
18872
  antigravityTools: ["read_file", "run_command", "call_mcp_tool", "ask_question"],
18703
18873
  body: `## Role & Mission
18704
18874
  - **Role**: Transversal Red Team and Stress Adversary Agent (\`agent-adversary\`).
18705
- - **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.
18875
+ - **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.
18706
18876
 
18707
18877
  ## Operational Directives & Guardrails
18708
18878
  - **Polymorphic On-Demand Scope**:
18709
18879
  * **Product**: Uncover contradictory requirements, unreachable business states, and logic traps.
18710
18880
  * **Architecture**: Simulate race conditions, cascading failures, resource exhaustion, and single points of failure (SPOFs).
18711
18881
  * **QA**: Perform conceptual mutation testing; demonstrate how flawed or empty implementations could falsely pass tests green.
18712
- * **Development**: Attack boundary inputs, concurrency race triggers, and memory/type edge breaks.
18882
+ * **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.
18713
18883
  * **DevOps**: Probe pipeline isolation, credential boundaries, and cold-start/dependency outages.
18714
18884
  - **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.
18715
18885
  - **NON-INVASIVE GUARDRAIL**: You do NOT patch the vulnerabilities or bugs yourself.
@@ -18787,7 +18957,7 @@ var LIFECYCLE_SKILL_TEMPLATES = [
18787
18957
  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.",
18788
18958
  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).",
18789
18959
  globs: "product/**, specs/product/**, architecture/**, templates/**",
18790
- 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`.'
18960
+ 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`.'
18791
18961
  },
18792
18962
  {
18793
18963
  id: "aisdlc-legacy-onboarding",
@@ -18795,7 +18965,7 @@ var LIFECYCLE_SKILL_TEMPLATES = [
18795
18965
  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.",
18796
18966
  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).",
18797
18967
  globs: "architecture/**, specs/**, src/**, packages/**",
18798
- 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."
18968
+ 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."
18799
18969
  },
18800
18970
  {
18801
18971
  id: "aisdlc-increment",
@@ -18803,7 +18973,7 @@ var LIFECYCLE_SKILL_TEMPLATES = [
18803
18973
  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.",
18804
18974
  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).",
18805
18975
  globs: "specs/changes/**, src/**, packages/**, tests/**",
18806
- 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`.'
18976
+ 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`.'
18807
18977
  }
18808
18978
  ];
18809
18979
  function renderAntigravitySkillFile(skill) {
@@ -18942,52 +19112,33 @@ This file defines the operational rules and specialized role mappings for Google
18942
19112
  - **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.
18943
19113
  - **Global Styles Protection**: When touching or refactoring frontend views, verify that global stylesheet/asset imports remain intact and that layouts suffer no visual disruption.
18944
19114
  - **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.
18945
- - Upon completing green implementation, suggest handoff to \`agent-expert-user\` for post-development functional validation prior to security and privacy audit.
18946
-
18947
- ### 7. \`agent-security-auditor\` (Adversarial Code Auditor)
18948
- - **Mission**: Rigorously examine Pull Requests for business logic vulnerabilities, injection vectors, secret leaks, and authorization flaws as part of the Pre-Merge Audit Triad.
18949
- - **Directives**:
18950
- - Analyze code diffs with an attacker mindset and run \`pnpm run verify:security\`.
18951
- - Issue findings with CVSS v3.1 severity scoring and block any PR introducing CRITICAL or HIGH security risks.
18952
-
18953
- ### 8. \`agent-compliance-checker\` (Open Source License Compliance Auditor)
18954
- - **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.
18955
- - **Directives**:
18956
- - Verify SPDX identifiers via \`pnpm run verify:licenses\`, immediately blocking viral (\`GPL\`, \`AGPL\`) or unapproved commercial (\`BSL\`, \`SSPL\`) licenses.
19115
+ - 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\`).
18957
19116
 
18958
- ### 9. \`agent-expert-user\` (Expert User and Domain Evaluator)
19117
+ ### 7. \`agent-expert-user\` (Expert User and Domain Evaluator)
18959
19118
  - **Mission**: Contrast design and specifications (design phase) and functionally validate finished software against \`UC-*\` and \`FR-*\` (post-development phase).
18960
19119
  - **Directives**:
18961
19120
  - 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.
18962
- - 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.
18963
- - Emit handoff block suggesting \`agent-code-reviewer\` / \`agent-security-auditor\` / \`agent-privacy-officer\` if compliant, or return to \`agent-developer\` on functional drift.
18964
-
18965
- ### 10. \`agent-code-reviewer\` (Technical and Architectural Code Reviewer)
18966
- - **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.
18967
- - **Directives**:
18968
- - Respect \`quality-policy.yaml\` thresholds: CC $\\le 10$, Cognitive $\\le 15$, MI $\\ge 50$, LOC $\\le 40$.
18969
- - Detect improper coupling, code smells, magic numbers, ambiguous names, and encapsulation violations.
18970
- - Flag premature abstractions and speculative code violating YAGNI.
18971
- - Coordinate Pre-Merge Audit Triad with \`agent-security-auditor\`, \`agent-privacy-officer\`, and \`agent-compliance-checker\`.
18972
- - Classify findings into: \`[BLOCKING]\` (quality violation or broken pattern), \`[CLEAN_CODE_SUGGESTION]\` (non-blocking improvement), and \`[COMPLIANT]\`.
19121
+ - 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.
19122
+ - Emit handoff block suggesting Checkpoint 2 (\`agent-auditor\` $\\parallel$ \`agent-adversary\` + \`agent-privacy-officer\`) if compliant, or return to \`agent-developer\` on functional drift.
18973
19123
 
18974
- ### 11. \`agent-devops\` (Automation and Infrastructure Engineer)
19124
+ ### 8. \`agent-devops\` (Automation and Infrastructure Engineer)
18975
19125
  - **Mission**: Maintain, evolve, and audit automated project infrastructure: CI/CD workflows, Docker containers, IaC manifests, and support scripts.
18976
19126
  - **Directives**:
18977
19127
  - Strict infrastructure domain: Operates exclusively in \`.github/workflows/\`, \`Dockerfile*\`, \`docker-compose*.yml\`, IaC manifests, and \`scripts/\`.
18978
19128
  - **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.
19129
+ - **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.
18979
19130
  - Infrastructure dependency policy: Verify licenses of dependencies, base images, and third-party actions according to \`license-policy.yaml\`.
18980
19131
  - Gate preservation: Ensure pipeline optimizations preserve all existing deterministic Quality Gates intact.
18981
19132
  - **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.
18982
19133
  - **Remote Verification**: Creating a PR (\`gh pr create\`) does not equal success; actively verify that remote checks pass (\`gh pr checks\`).
18983
19134
 
18984
- ### 12. \`agent-auditor\` (Transversal Quality and Improvement Auditor)
18985
- - **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.
18986
- - **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).
19135
+ ### 9. \`agent-auditor\` (Transversal Quality and Improvement Auditor)
19136
+ - **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.
19137
+ - **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).
18987
19138
 
18988
- ### 13. \`agent-adversary\` (Transversal Red Team and Chaos Adversary)
18989
- - **Mission**: Actively attempt to break, bypass, or invalidate deliverables from any target specialist agent, providing concrete proofs-of-concept (PoC), counterexamples, and reproduction steps.
18990
- - **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).
19139
+ ### 10. \`agent-adversary\` (Transversal Red Team and Chaos Adversary)
19140
+ - **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).
19141
+ - **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).
18991
19142
 
18992
19143
  ---
18993
19144
 
@@ -19008,7 +19159,7 @@ This file defines the operational rules and specialized role mappings for Google
19008
19159
  - **Conditional Activation Rule by Autonomy**:
19009
19160
  - \u{1F7E2} **\`AUTONOMOUS\`** (or exclusive final supervision in PR/CI): **OMITTED**. Do not request or emit interactive handoff to avoid interrupting unattended execution.
19010
19161
  - \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**.
19011
- - **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).
19162
+ - **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).
19012
19163
  `;
19013
19164
  var STARTER_CURSOR_CORE_RULES = `---
19014
19165
  description: Global canonical directives, 5 unbreakable commandments, and AI-SDLC pre-flight
@@ -19050,13 +19201,10 @@ Before finalizing changes or proposing commits:
19050
19201
  | \`agent-system-architect\` | Modular arc42 + NAF v4 architecture (\`CMP-*\`, Mermaid diagrams, \`ADR-*\`). |
19051
19202
  | \`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. |
19052
19203
  | \`agent-developer\` | Atomic tasks from \`tasks.md\`; respects autonomy mode; runs \`pnpm run check:fix\` + \`pnpm run verify:all\`. |
19053
- | \`agent-security-auditor\` | Adversarial PR security audit, SAST, secrets, and CVSS v3.1 evaluation. |
19054
- | \`agent-compliance-checker\` | SPDX license compliance audit against \`license-policy.yaml\`. |
19055
19204
  | \`agent-expert-user\` | Bimodal MVP evaluation (design) and functional validation against \`UC-*\` and \`FR-*\` (pre-PR). |
19056
- | \`agent-code-reviewer\` | PR audit (SOLID, DRY, YAGNI): \`[BLOCKING]\` / \`[CLEAN_CODE_SUGGESTION]\` / \`[COMPLIANT]\`. |
19057
- | \`agent-devops\` | CI/CD, Docker, IaC only \u2014 **FORBIDDEN** to touch \`src/\` or \`packages/*/src/\`. |
19058
- | \`agent-auditor\` | Transversal on-demand constructive auditor; identifies overengineering, blind spots & YAGNI simplifications; returns handoff to audited agent. |
19059
- | \`agent-adversary\` | Transversal on-demand Red Team adversary; breaks deliverables with reproducible PoC & mutation tests; returns handoff to audited agent. |
19205
+ | \`agent-devops\` | CI/CD, Docker, IaC only \u2014 clarifies deployment/CI strategy; **FORBIDDEN** to touch \`src/\` or \`packages/*/src/\`. |
19206
+ | \`agent-auditor\` | Transversal auditor: YAGNI, Clean Code/SOLID/AST thresholds, UI standards, SPDX licenses (\`verify:licenses\`); returns handoff to audited agent. |
19207
+ | \`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. |
19060
19208
 
19061
19209
  ## 5. Task Autonomy Modes (\`tasks.md\`)
19062
19210
  - \u{1F7E2} **\`AUTONOMOUS\`**: Low risk. Implement directly, omit handoff block.
@@ -19209,32 +19357,20 @@ npx tsx packages/cli/src/index.ts sdd integrate --change <chg-id>
19209
19357
  - **Mission**: Implement atomic tasks from SDD specifications (\`tasks.md\`) with clean, strictly typed code and thorough tests.
19210
19358
  - **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.
19211
19359
 
19212
- ### 7. \`agent-security-auditor\` (Adversarial Code Auditor)
19213
- - **Mission**: Examine Pull Requests for business logic vulnerabilities, injection vectors, secret leaks, and authorization flaws as part of the Pre-Merge Audit Triad.
19214
- - **Directives**: Run \`pnpm run verify:security\`, evaluate CVSS v3.1 severity, and block CRITICAL/HIGH risks.
19215
-
19216
- ### 8. \`agent-compliance-checker\` (Open Source License Compliance Auditor)
19217
- - **Mission**: Audit dependency manifests against \`license-policy.yaml\` as part of the Pre-Merge Audit Triad.
19218
- - **Directives**: Run \`pnpm run verify:licenses\`, blocking viral (\`GPL\`, \`AGPL\`) or unapproved commercial (\`BSL\`, \`SSPL\`) packages.
19219
-
19220
- ### 9. \`agent-expert-user\` (Expert User and Domain Evaluator)
19360
+ ### 7. \`agent-expert-user\` (Expert User and Domain Evaluator)
19221
19361
  - **Mission**: Contrast design and specifications (design phase) and functionally validate finished software against \`UC-*\` and \`FR-*\` (post-development functional validation phase).
19222
19362
 
19223
- ### 10. \`agent-code-reviewer\` (Technical and Architectural Code Reviewer)
19224
- - **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.
19225
- - **Findings classification**: \`[BLOCKING]\`, \`[CLEAN_CODE_SUGGESTION]\`, \`[COMPLIANT]\`.
19226
-
19227
- ### 11. \`agent-devops\` (Automation and Infrastructure Engineer)
19228
- - **Mission**: Maintain, evolve, and audit automated project infrastructure: CI/CD workflows, Docker containers, IaC manifests, and support scripts.
19363
+ ### 8. \`agent-devops\` (Automation and Infrastructure Engineer)
19364
+ - **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\`.
19229
19365
  - **NON-INVASION GUARDRAIL**: STRICTLY FORBIDDEN from modifying application source code (\`src/\`, \`packages/*/src/\`).
19230
19366
 
19231
- ### 12. \`agent-auditor\` (Transversal Quality and Improvement Auditor)
19232
- - **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.
19367
+ ### 9. \`agent-auditor\` (Transversal Quality and Improvement Auditor)
19368
+ - **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\`).
19233
19369
  - **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).
19234
19370
 
19235
- ### 13. \`agent-adversary\` (Transversal Red Team and Chaos Adversary)
19236
- - **Mission**: Actively attempt to break, bypass, or invalidate deliverables from any target specialist agent, providing concrete proofs-of-concept (PoC), counterexamples, and reproduction steps.
19237
- - **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).
19371
+ ### 10. \`agent-adversary\` (Transversal Red Team and Chaos Adversary)
19372
+ - **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.
19373
+ - **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).
19238
19374
 
19239
19375
  ---
19240
19376
 
@@ -19351,7 +19487,7 @@ Non-Negotiable Quality Thresholds (\`quality-policy.yaml\`):
19351
19487
  - **Conditional Activation**:
19352
19488
  * \u{1F7E2} **\`AUTONOMOUS\` Mode** (or PR/CI final supervision): **OMITTED**. Do not interrupt unattended execution.
19353
19489
  * \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**.
19354
- - **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).
19490
+ - **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).
19355
19491
 
19356
19492
  ---
19357
19493
 
@@ -19359,19 +19495,16 @@ Non-Negotiable Quality Thresholds (\`quality-policy.yaml\`):
19359
19495
 
19360
19496
  | Role | Mission (summary) |
19361
19497
  | :--- | :--- |
19362
- | \`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\`. |
19498
+ | \`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\`. |
19363
19499
  | \`agent-threat-modeler\` | STRIDE/OWASP threat triad (\`ACT-THREAT-*\`, \`ABUSE-*\`, \`SEC-REQ-*\`); hands off to \`agent-privacy-officer\`. |
19364
19500
  | \`agent-privacy-officer\` | LINDDUN & GDPR/LOPDGDD privacy triad (\`DATA-ASSET-*\`, \`PRIV-ROPA-*\`, \`PRIV-REQ-*\`) + Pre-Merge \`verify:privacy\`. |
19365
- | \`agent-system-architect\` | Modular arc42 + NAF v4 architecture (\`CMP-*\`, Mermaid diagrams, \`ADR-*\`). |
19501
+ | \`agent-system-architect\` | Modular arc42 + NAF v4 architecture (\`CMP-*\`, \`ARCH-DEP-001\`, Mermaid diagrams, \`ADR-*\`). |
19366
19502
  | \`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. |
19367
19503
  | \`agent-developer\` | Atomic tasks from \`tasks.md\`; autonomy mode must be respected; runs \`pnpm run check:fix\` + \`pnpm run verify:all\`. |
19368
- | \`agent-security-auditor\` | Adversarial PR security audit, SAST, secrets, and CVSS v3.1 evaluation. |
19369
- | \`agent-compliance-checker\` | SPDX license compliance audit against \`license-policy.yaml\`. |
19370
19504
  | \`agent-expert-user\` | Bimodal MVP evaluation (design) and functional validation against \`UC-*\` and \`FR-*\` (pre-PR). |
19371
- | \`agent-code-reviewer\` | PR audit (SOLID, DRY, YAGNI): \`[BLOCKING]\` / \`[CLEAN_CODE_SUGGESTION]\` / \`[COMPLIANT]\`. |
19372
- | \`agent-devops\` | CI/CD, Docker, IaC only \u2014 **FORBIDDEN** to touch \`src/\` or \`packages/*/src/\`. |
19373
- | \`agent-auditor\` | Transversal on-demand constructive auditor; identifies overengineering, blind spots & YAGNI simplifications; returns handoff to audited agent. |
19374
- | \`agent-adversary\` | Transversal on-demand Red Team adversary; breaks deliverables with reproducible PoC & mutation tests; returns handoff to audited agent. |
19505
+ | \`agent-devops\` | CI/CD, Docker, IaC only \u2014 clarifies deployment/CI strategy; **FORBIDDEN** to touch \`src/\` or \`packages/*/src/\`. |
19506
+ | \`agent-auditor\` | Transversal auditor: YAGNI, Clean Code/SOLID/AST thresholds, UI standards, SPDX licenses (\`verify:licenses\`); returns handoff to audited agent. |
19507
+ | \`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. |
19375
19508
 
19376
19509
  ---
19377
19510
 
@@ -23814,23 +23947,8 @@ var TimestampedBackupManagerAdapter = class {
23814
23947
  fs12__namespace.mkdirSync(targetBackupDir, { recursive: true, mode: 448 });
23815
23948
  const manifestEntries = [];
23816
23949
  for (const relPath of filesToBackup) {
23817
- const srcFile = path14__namespace.resolve(resolvedRoot, relPath);
23818
- if (fs12__namespace.existsSync(srcFile)) {
23819
- const destFile = path14__namespace.resolve(targetBackupDir, relPath);
23820
- const destDir = path14__namespace.dirname(destFile);
23821
- if (!fs12__namespace.existsSync(destDir)) {
23822
- fs12__namespace.mkdirSync(destDir, { recursive: true });
23823
- }
23824
- const content = fs12__namespace.readFileSync(srcFile, "utf-8");
23825
- fs12__namespace.writeFileSync(destFile, content, "utf-8");
23826
- const digest = this.diffDetector.computeDigest(content);
23827
- const stats = fs12__namespace.statSync(destFile);
23828
- manifestEntries.push({
23829
- path: relPath,
23830
- sha256: digest,
23831
- bytes: stats.size
23832
- });
23833
- }
23950
+ const entry = this.backupSingleFile(resolvedRoot, targetBackupDir, relPath);
23951
+ if (entry) manifestEntries.push(entry);
23834
23952
  }
23835
23953
  const manifest = {
23836
23954
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -23843,6 +23961,18 @@ var TimestampedBackupManagerAdapter = class {
23843
23961
  );
23844
23962
  return targetBackupDir;
23845
23963
  }
23964
+ backupSingleFile(resolvedRoot, targetBackupDir, relPath) {
23965
+ const srcFile = path14__namespace.resolve(resolvedRoot, relPath);
23966
+ if (!fs12__namespace.existsSync(srcFile)) return null;
23967
+ const destFile = path14__namespace.resolve(targetBackupDir, relPath);
23968
+ const destDir = path14__namespace.dirname(destFile);
23969
+ if (!fs12__namespace.existsSync(destDir)) fs12__namespace.mkdirSync(destDir, { recursive: true });
23970
+ const content = fs12__namespace.readFileSync(srcFile, "utf-8");
23971
+ fs12__namespace.writeFileSync(destFile, content, "utf-8");
23972
+ const digest = this.diffDetector.computeDigest(content);
23973
+ const stats = fs12__namespace.statSync(destFile);
23974
+ return { path: relPath, sha256: digest, bytes: stats.size };
23975
+ }
23846
23976
  async restoreBackup(repoRoot, backupPath) {
23847
23977
  const resolvedRoot = path14__namespace.resolve(repoRoot);
23848
23978
  const manifestPath = path14__namespace.join(backupPath, "manifest.json");
@@ -24494,6 +24624,7 @@ exports.collectAgentFiles = collectAgentFiles;
24494
24624
  exports.collectDashboardMetrics = collectDashboardMetrics;
24495
24625
  exports.collectHistoricalKpis = collectHistoricalKpis;
24496
24626
  exports.compileTestPatterns = compileTestPatterns;
24627
+ exports.computeAgentPerformanceKpis = computeAgentPerformanceKpis;
24497
24628
  exports.computeCanonicalSha256 = computeCanonicalSha256;
24498
24629
  exports.computeLfSha256 = computeLfSha256;
24499
24630
  exports.computeRawSha256 = computeRawSha256;
@@ -24540,6 +24671,7 @@ exports.extractPythonFunctionsPolyglot = extractPythonFunctionsPolyglot;
24540
24671
  exports.extractSemanticContent = extractSemanticContent;
24541
24672
  exports.findChangeWorkspaceDir = findChangeWorkspaceDir;
24542
24673
  exports.findLicenseFile = findLicenseFile;
24674
+ exports.formatAgentKpisMarkdownSection = formatAgentKpisMarkdownSection;
24543
24675
  exports.formatCommitTrailers = formatCommitTrailers;
24544
24676
  exports.formatInspectResultMarkdown = formatInspectResultMarkdown;
24545
24677
  exports.formatPrKpiMarkdown = formatPrKpiMarkdown;