@aisdlc/core 1.1.1 → 1.3.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
@@ -148,17 +148,31 @@ function calculateLocAndHalstead(fullText, cyclomatic) {
148
148
  const normalizedMI = Math.max(0, Math.min(100, rawMI * 100 / 171));
149
149
  return { loc, mi: Math.round(normalizedMI * 10) / 10 };
150
150
  }
151
- function detectAstCodeSmells(node, loc, nodeText) {
151
+ var TEST_FILE_PATTERN = /(?:^|\/)(?:tests|__tests__|fixtures)\/|\.(?:spec|test)\.[cm]?[jt]sx?$/i;
152
+ var EMPTY_UI_HANDLER_PATTERN = /\bon[A-Z]\w*\s*=\s*\{\s*(?:\([^)]*\)\s*=>\s*\{\s*\}|function\s*\([^)]*\)\s*\{\s*\})\s*\}/;
153
+ var FAKE_WIRING_STUB_PATTERN = /(?:\/\/\s*T[O]DO:\s*(?:connect|wire|integrate)\b|\b(?:m[o]ckData|F[A]KE_DATA)\b)/i;
154
+ function isProductionFile(filePath) {
155
+ return !TEST_FILE_PATTERN.test(filePath.replace(/\\/g, "/"));
156
+ }
157
+ function detectAstCodeSmells(node, loc, fullText, filePath) {
152
158
  const smells = [];
153
159
  if (node.getDescendantsOfKind(tsMorph.SyntaxKind.AnyKeyword).length > 0) {
154
160
  smells.push('Uso prohibido de "any"');
155
161
  }
156
- if (/\/\/\s*@ts-ignore|\/\/\s*eslint-disable/.test(nodeText)) {
162
+ if (/\/\/\s*@ts-ignore|\/\/\s*eslint-disable/.test(fullText)) {
157
163
  smells.push("Supresi\xF3n no autorizada de linter");
158
164
  }
159
165
  if (loc > 40) {
160
166
  smells.push(`Funci\xF3n extensa (${loc} l\xEDneas > l\xEDmite 40)`);
161
167
  }
168
+ if (isProductionFile(filePath)) {
169
+ if (EMPTY_UI_HANDLER_PATTERN.test(fullText)) {
170
+ smells.push("Handler de UI vac\xEDo (fake-wiring detectado)");
171
+ }
172
+ if (FAKE_WIRING_STUB_PATTERN.test(fullText)) {
173
+ smells.push("Datos simulados o conexi\xF3n pendiente en producci\xF3n (fake-wiring)");
174
+ }
175
+ }
162
176
  return smells;
163
177
  }
164
178
  function isDeclarationFunction(node) {
@@ -182,9 +196,8 @@ function buildNodeMetrics(node, filePath) {
182
196
  const cyclomatic = computeCyclomaticFromAst(node);
183
197
  const cognitive = computeCognitiveFromAst(node);
184
198
  const fullText = node.getFullText();
185
- const nodeText = node.getText();
186
199
  const { loc, mi } = calculateLocAndHalstead(fullText, cyclomatic);
187
- const codeSmells = detectAstCodeSmells(node, loc, nodeText);
200
+ const codeSmells = detectAstCodeSmells(node, loc, fullText, filePath);
188
201
  return { functionName, filePath, loc, cyclomatic, cognitive, maintainability: mi, codeSmells };
189
202
  }
190
203
  function buildModuleFallback(content, filePath) {
@@ -513,6 +526,9 @@ function createDefaultQualityPolicy() {
513
526
  max_cognitive: 15,
514
527
  min_maintainability: 50,
515
528
  max_function_lines: 40,
529
+ min_line_coverage: 85,
530
+ min_branch_coverage: 80,
531
+ min_function_coverage: 90,
516
532
  enforce_mode: "STRICT",
517
533
  target_directories: ["src", "lib", "examples", "tests"],
518
534
  supported_extensions: [...DEFAULT_EXTENSIONS],
@@ -536,6 +552,15 @@ function applyDocScope(policy, doc) {
536
552
  }
537
553
  }
538
554
  }
555
+ function applyCoverageThresholds(policy, covRaw) {
556
+ if (!covRaw || typeof covRaw !== "object") return;
557
+ const cov = covRaw;
558
+ if (cov.min_line_coverage_percent !== void 0) policy.min_line_coverage = Number(cov.min_line_coverage_percent);
559
+ if (cov.min_branch_coverage_percent !== void 0) policy.min_branch_coverage = Number(cov.min_branch_coverage_percent);
560
+ if (cov.min_function_coverage_percent !== void 0) {
561
+ policy.min_function_coverage = Number(cov.min_function_coverage_percent);
562
+ }
563
+ }
539
564
  function applyDocThresholds(policy, doc) {
540
565
  const sections = [doc.release_thresholds, doc.thresholds].filter(
541
566
  (s) => Boolean(s && typeof s === "object")
@@ -549,6 +574,7 @@ function applyDocThresholds(policy, doc) {
549
574
  if (cog !== void 0) policy.max_cognitive = Number(cog);
550
575
  if (mi !== void 0) policy.min_maintainability = Number(mi);
551
576
  if (loc !== void 0) policy.max_function_lines = Number(loc);
577
+ applyCoverageThresholds(policy, s.test_coverage);
552
578
  }
553
579
  const codingRules = doc.coding_rules;
554
580
  const rules = codingRules?.rules;
@@ -5815,6 +5841,78 @@ function detectLanguage(filePath) {
5815
5841
  return "Unknown";
5816
5842
  }
5817
5843
  }
5844
+ function parseJsonSummaryFile(filePath, relSource) {
5845
+ try {
5846
+ const raw = JSON.parse(fs6__namespace.readFileSync(filePath, "utf-8"));
5847
+ const total = raw.total;
5848
+ if (!total || typeof total !== "object") return null;
5849
+ const linesPct = Number(total.lines?.pct);
5850
+ const branchesPct = Number(total.branches?.pct);
5851
+ const functionsPct = Number(total.functions?.pct);
5852
+ if (Number.isNaN(linesPct) || Number.isNaN(branchesPct) || Number.isNaN(functionsPct)) return null;
5853
+ const statementsPct = total.statements?.pct !== void 0 ? Number(total.statements.pct) : void 0;
5854
+ return { linesPct, branchesPct, functionsPct, statementsPct, source: relSource };
5855
+ } catch {
5856
+ return null;
5857
+ }
5858
+ }
5859
+ function parseLcovFile(filePath, relSource) {
5860
+ try {
5861
+ const lines = fs6__namespace.readFileSync(filePath, "utf-8").split(/\r?\n/);
5862
+ let lf = 0, lh = 0, brf = 0, brh = 0, fnf = 0, fnh = 0;
5863
+ for (const line of lines) {
5864
+ if (line.startsWith("LF:")) lf += parseInt(line.slice(3), 10) || 0;
5865
+ else if (line.startsWith("LH:")) lh += parseInt(line.slice(3), 10) || 0;
5866
+ else if (line.startsWith("BRF:")) brf += parseInt(line.slice(4), 10) || 0;
5867
+ else if (line.startsWith("BRH:")) brh += parseInt(line.slice(4), 10) || 0;
5868
+ else if (line.startsWith("FNF:")) fnf += parseInt(line.slice(4), 10) || 0;
5869
+ else if (line.startsWith("FNH:")) fnh += parseInt(line.slice(4), 10) || 0;
5870
+ }
5871
+ if (lf === 0 && fnf === 0 && brf === 0) return null;
5872
+ const pct = (hit, found) => found > 0 ? Math.round(hit / found * 1e3) / 10 : 100;
5873
+ return {
5874
+ linesPct: pct(lh, lf),
5875
+ branchesPct: pct(brh, brf),
5876
+ functionsPct: pct(fnh, fnf),
5877
+ source: relSource
5878
+ };
5879
+ } catch {
5880
+ return null;
5881
+ }
5882
+ }
5883
+ function readCodeCoverageSummary(rootDir = process.cwd()) {
5884
+ const jsonCandidates = ["coverage/coverage-summary.json", "reports/coverage-summary.json"];
5885
+ for (const rel of jsonCandidates) {
5886
+ const full = path8__namespace.join(rootDir, rel);
5887
+ if (fs6__namespace.existsSync(full)) {
5888
+ const parsed = parseJsonSummaryFile(full, rel);
5889
+ if (parsed) return parsed;
5890
+ }
5891
+ }
5892
+ const lcovCandidates = ["coverage/lcov.info", "lcov.info", "reports/lcov.info"];
5893
+ for (const rel of lcovCandidates) {
5894
+ const full = path8__namespace.join(rootDir, rel);
5895
+ if (fs6__namespace.existsSync(full)) {
5896
+ const parsed = parseLcovFile(full, rel);
5897
+ if (parsed) return parsed;
5898
+ }
5899
+ }
5900
+ return null;
5901
+ }
5902
+ function formatCoverageRow(label, measured, minThreshold) {
5903
+ if (measured === void 0) {
5904
+ return `| **${label}** | \`N/A (Run test:coverage)\` | $\\ge ${minThreshold}\\%$ | \u2139\uFE0F NOT MEASURED |`;
5905
+ }
5906
+ const status = measured >= minThreshold ? "\u2705 COMPLIANT" : "\u26A0\uFE0F BELOW THRESHOLD";
5907
+ return `| **${label}** | \`${measured}%\` | $\\ge ${minThreshold}\\%$ | ${status} |`;
5908
+ }
5909
+ function buildCoverageRows(coverage, policy) {
5910
+ return [
5911
+ formatCoverageRow("Line Coverage", coverage?.linesPct, policy.min_line_coverage),
5912
+ formatCoverageRow("Branch Coverage", coverage?.branchesPct, policy.min_branch_coverage),
5913
+ formatCoverageRow("Function Coverage", coverage?.functionsPct, policy.min_function_coverage)
5914
+ ];
5915
+ }
5818
5916
  function generateQualityReport(options = {}) {
5819
5917
  const rootDir = options.rootDir || process.cwd();
5820
5918
  const gateResult = verifyQualityGate({
@@ -5822,6 +5920,7 @@ function generateQualityReport(options = {}) {
5822
5920
  policyPath: options.policyPath,
5823
5921
  thresholds: options.thresholds
5824
5922
  });
5923
+ const coverage = readCodeCoverageSummary(rootDir);
5825
5924
  const totalFiles = gateResult.totalFiles;
5826
5925
  const totalFunctions = gateResult.totalFunctions;
5827
5926
  let totalMi = 0;
@@ -5870,6 +5969,7 @@ function generateQualityReport(options = {}) {
5870
5969
  `| **Cyclomatic Complexity (Average)** | \`${avgCyclomatic}\` | $\\le ${gateResult.policy.max_cyclomatic}$ | ${avgCyclomatic <= gateResult.policy.max_cyclomatic ? "\u2705 COMPLIANT" : "\u274C EXCEEDED"} |`,
5871
5970
  `| **Cognitive Complexity (Average)** | \`${avgCognitive}\` | $\\le ${gateResult.policy.max_cognitive}$ | ${avgCognitive <= gateResult.policy.max_cognitive ? "\u2705 COMPLIANT" : "\u274C EXCEEDED"} |`,
5872
5971
  `| **Maintainability Index (SEI MI)** | \`${avgMaintainability} / 100\` | $\\ge ${gateResult.policy.min_maintainability}$ | ${avgMaintainability >= gateResult.policy.min_maintainability ? "\u2705 COMPLIANT" : "\u274C INSUFFICIENT"} |`,
5972
+ ...buildCoverageRows(coverage, gateResult.policy),
5873
5973
  `| **Functions in Violation** | \`${gateResult.failCount}\` | $0$ (Mode ${gateResult.policy.enforce_mode}) | ${gateResult.failCount === 0 ? "\u2705 0 VIOLATIONS" : "\u274C BLOCKED"} |`,
5874
5974
  ``,
5875
5975
  `---`,
@@ -5901,6 +6001,7 @@ function generateQualityReport(options = {}) {
5901
6001
  lines.push("## 4. Evaluation Criteria and Standards");
5902
6002
  lines.push("- **McCabe Cyclomatic Complexity (CC)**: Number of linearly independent paths.");
5903
6003
  lines.push("- **Maintainability Index (SEI MI)**: Normalized formula [0 - 100] combining Halstead Volume, CC, and LOC.");
6004
+ lines.push("- **Automated Test Coverage**: Passively ingested from `coverage/coverage-summary.json` or `lcov.info` when present.");
5904
6005
  lines.push("- **Clean Code Guardrails**: Prohibition of implicit `any` typing, function length limits ($le 40$ lines), and zero unjustified suppressions.");
5905
6006
  const markdown = lines.join("\n");
5906
6007
  const reportsDir = path8__namespace.join(rootDir, "reports");
@@ -5912,7 +6013,8 @@ function generateQualityReport(options = {}) {
5912
6013
  totalFunctions,
5913
6014
  avgMaintainability,
5914
6015
  avgCyclomatic,
5915
- verdict
6016
+ verdict,
6017
+ coverage
5916
6018
  };
5917
6019
  }
5918
6020
 
@@ -7601,10 +7703,12 @@ function collectDashboardMetrics(rootDir) {
7601
7703
  }
7602
7704
  } catch {
7603
7705
  }
7706
+ const codeCoverage = readCodeCoverageSummary(rootDir);
7604
7707
  return {
7605
7708
  gate,
7606
7709
  gov,
7607
7710
  cov,
7711
+ codeCoverage,
7608
7712
  trace,
7609
7713
  history,
7610
7714
  activePrKpi,
@@ -8146,6 +8250,11 @@ function renderDashboardHtml(graphData, metricsData, title = "AI-SDLC: Dashboard
8146
8250
  <span class="value">${metricsData.cov.totalRequirements > 0 ? Math.round(metricsData.cov.passedRequirements / metricsData.cov.totalRequirements * 100) : 100}%</span>
8147
8251
  <span class="subtitle">${metricsData.cov.passedRequirements} / ${metricsData.cov.totalRequirements} verified</span>
8148
8252
  </div>
8253
+ <div class="metric-card">
8254
+ <span class="title">Code Coverage (Lines)</span>
8255
+ <span class="value">${metricsData.codeCoverage ? metricsData.codeCoverage.linesPct + "%" : "N/A"}</span>
8256
+ <span class="subtitle">${metricsData.codeCoverage ? `Branches: ${metricsData.codeCoverage.branchesPct}% | Funcs: ${metricsData.codeCoverage.functionsPct}%` : `Min target: ${metricsData.gate.policy.min_line_coverage}% (Run test:coverage)`}</span>
8257
+ </div>
8149
8258
  </div>
8150
8259
 
8151
8260
  <div class="chart-container">
@@ -9217,6 +9326,7 @@ var SPECIALIZED_AGENT_TEMPLATES = [
9217
9326
 
9218
9327
  ## Operational Directives & Guardrails
9219
9328
  - Decompose the system into building blocks \`CMP-*\` ensuring each component declares which use cases \`UC-*\` it implements and which requirements (\`FR-*\`, \`QR-*\`, \`SEC-REQ-*\`) it fulfills under \`satisfies-requirements\`.
9329
+ - **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.
9220
9330
  - Generate interaction and sequence diagrams in native Mermaid syntax.
9221
9331
  - Document critical technological decisions using immutable \`ADR-*\` records conforming to \`schemas/architecture/adr.schema.json\`.
9222
9332
  - Validate that architectural choices comply with legal constraints in \`license-policy.yaml\`.
@@ -9239,6 +9349,7 @@ var SPECIALIZED_AGENT_TEMPLATES = [
9239
9349
  2. **Boundary Cases** (\`Scenario Outline\` + \`Examples\` table): values at the extremes of the accepted range.
9240
9350
  3. **Out-of-Range / Invalid Cases** (\`Scenario Outline\` + \`Examples\` table): null, empty, wrong types, values exceeding bounds.
9241
9351
  - Apply conditional categories when applicable: Security (\`@security @mitigation\`), Performance (\`@performance\`), Idempotency (\`@idempotence\`), Postconditions, and Interface Contracts.
9352
+ - **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\`).
9242
9353
  - Tag all scenarios with \`@<FR-ID> @automated @regression\`.
9243
9354
  - **STRICTLY FORBIDDEN**: Including production code, suggesting implementation, or anticipating technical solutions.
9244
9355
  - Run \`pnpm run verify:testing\` before emitting handoff.
@@ -9257,6 +9368,9 @@ var SPECIALIZED_AGENT_TEMPLATES = [
9257
9368
  - Respect the autonomy mode assigned to each task in \`tasks.md\` (\`AUTONOMOUS\`, \`HUMAN_REVIEW_PLAN\`, \`AMBIGUOUS\`, \`HIGH_RISK_MANUAL\`).
9258
9369
  - Apply Test-Driven Development (TDD): make failing tests delivered by \`agent-qa-engineer\` pass green without altering tests to accommodate buggy code.
9259
9370
  - Cite implemented \`FR-*\` or \`SEC-REQ-*\` IDs in test header comments to maintain 360\xB0 reverse traceability.
9371
+ - **Zero Fake-Wiring Guardrail**: Strictly forbidden from marking a task \`COMPLETED\` with hardcoded \`mockData\` arrays in production views, \`setTimeout\` simulating network calls, or empty UI event handlers (\`onClick={() => {}}\`, \`onSubmit={() => {}}\`). Frontend components must wire directly to the shared contract and real Backend endpoints.
9372
+ - **Mandatory 4 UI States Matrix**: Every data-driven UI component or screen must explicitly implement all 4 usability states: \`Loading\` (spinner/skeleton + disabled submit), \`Empty\` (clear message + CTA), \`Error\` (visible error recovery banner, never silent failure), and \`Nominal/Success\` (accessible semantic DOM + keyboard navigation).
9373
+ - **Live Runtime Smoke Verification**: For tasks touching UI or UI-to-Backend integration, unit tests alone are insufficient. Before emitting handoff, boot the real Backend and Frontend servers and verify (via Playwright E2E or Chrome DevTools MCP) that browser \`console.error\` and \`pageerror\` counts are \`0\` and API calls return real \`2xx\` responses without CORS or schema mismatches.
9260
9374
  - Before adding any external dependency, verify its SPDX license is permitted in \`license-policy.yaml\`.
9261
9375
  - Respect non-negotiable \`quality-policy.yaml\` thresholds: Cyclomatic Complexity $\\le 10$, Cognitive Complexity $\\le 15$, Maintainability Index $\\ge 50$, Function Length $\\le 40$ lines.
9262
9376
  - Run unified pre-flight with auto-fix (\`pnpm run check:fix\`) and full verification (\`pnpm run verify:all\`).
@@ -9305,9 +9419,9 @@ var SPECIALIZED_AGENT_TEMPLATES = [
9305
9419
  ## Operational Directives & Guardrails
9306
9420
  - Operate under bimodal discipline depending on the lifecycle phase:
9307
9421
  1. **Design Mode (Upstream)**: Adopt the primary actor persona under real-world field conditions (stress, latency, constrained viewports). Separate strict Minimum Viable Product (MVP) core from future roadmap ideas using \`templates/product/user-design-feedback.template.md\`.
9308
- 2. **Functional Validation Mode (Downstream / Pre-PR / Post-Development Functional Validation)**: Inspect \`agent-developer\` deliverables once unit tests pass green. Contrast actual UI, CLI, and API behavior against approved \`UC-*\` and \`FR-*\` criteria.
9422
+ 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, and \`0\` browser \`console.error\` / network failures.
9309
9423
  - Formulate decisive questions under \`open-questions\` for the human Product Owner.
9310
- - Emit handoff block suggesting the Pre-Merge Audit Triad (\`agent-code-reviewer\`, \`agent-security-auditor\`, \`agent-compliance-checker\`) if compliant, or return to \`agent-developer\` on functional drift.`
9424
+ - Emit handoff block suggesting the Pre-Merge Audit Triad (\`agent-code-reviewer\`, \`agent-security-auditor\`, \`agent-compliance-checker\`) if compliant, or return to \`agent-developer\` on functional drift or fake-wiring.`
9311
9425
  },
9312
9426
  {
9313
9427
  id: "agent-code-reviewer",
@@ -9322,6 +9436,7 @@ var SPECIALIZED_AGENT_TEMPLATES = [
9322
9436
  - 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$.
9323
9437
  - Detect improper coupling, code smells, magic numbers, ambiguous identifiers, and encapsulation breaches.
9324
9438
  - Flag premature abstractions and speculative code violating YAGNI.
9439
+ - **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.
9325
9440
  - Coordinate Pre-Merge Audit Triad with \`agent-security-auditor\` and \`agent-compliance-checker\`.
9326
9441
  - Categorize findings into: \`[BLOCKING]\` (quality violation or broken pattern), \`[CLEAN_CODE_SUGGESTION]\` (non-blocking improvement), and \`[COMPLIANT]\`.
9327
9442
  - 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.`
@@ -11558,6 +11673,7 @@ exports.parseSpecCatalogScope = parseSpecCatalogScope;
11558
11673
  exports.parseTasksDoc = parseTasksDoc;
11559
11674
  exports.parseTasksFromContent = parseTasksFromContent;
11560
11675
  exports.processPackageDir = processPackageDir;
11676
+ exports.readCodeCoverageSummary = readCodeCoverageSummary;
11561
11677
  exports.readPackageJson = readPackageJson;
11562
11678
  exports.renderAntigravityAgentFile = renderAntigravityAgentFile;
11563
11679
  exports.renderClaudeAgentFile = renderClaudeAgentFile;