All files report-writer.ts

91.86% Statements 113/123
70.83% Branches 34/48
100% Functions 8/8
93.63% Lines 103/110

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340                          4x   4x 4x 4x 4x 4x                                                         40x     305x     40x                 40x 40x 40x 40x             88x 88x 88x 88x 88x 40x   40x                                   40x                     40x                   13x               13x       12x               12x     40x             40x               5x 5x 5x       2x 2x     40x                                               40x   40x               40x 40x   40x   40x       5x 5x 5x 5x 5x   5x 3x   5x   12x       39x 39x       75x   5x 5x   5x         9x   12x       9x 9x 9x   9x   9x                 9x   9x 9x 9x 9x     9x             5x     3x 3x 3x   3x 9x 9x 9x     3x       3x 3x 3x   3x 6x 6x 6x     3x     5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x     3x 3x 3x   3x   3x                     5x    
import fs from 'node:fs';
import path from 'node:path';
 
import { computeHotFiles } from './architecture.js';
import { computeGraphAnalytics } from './graph-analytics.js';
import { computeReportAnalysisSummary, enrichFileInventoryEntries, enrichFindings } from './report-analysis.js';
import { categoryBreakdown, generateSummaryMd, severityBreakdown } from './summary-md.js';
import { PILLAR_CATEGORIES } from './types.js';
import { renderTreesText } from './utils.js';
 
import type { AnalysisOptions, DependencyState, DependencySummary, DuplicateFlowHint, FileCriticality, FileEntry, Finding, TreeEntry } from './types.js';
 
 
export const REPORT_SCHEMA_VERSION = '1.1.0';
 
export const ARCHITECTURE_CATEGORIES = new Set(PILLAR_CATEGORIES['architecture']);
export const CODE_QUALITY_CATEGORIES = new Set(PILLAR_CATEGORIES['code-quality']);
export const DEAD_CODE_CATEGORIES = new Set(PILLAR_CATEGORIES['dead-code']);
export const SECURITY_CATEGORIES = new Set(PILLAR_CATEGORIES['security']);
export const TEST_QUALITY_CATEGORIES = new Set(PILLAR_CATEGORIES['test-quality']);
 
export interface FullReport {
  generatedAt: string;
  repoRoot: string;
  options: Record<string, unknown>;
  parser: Record<string, unknown>;
  summary: Record<string, unknown>;
  fileInventory: FileEntry[];
  duplicateFlows: Record<string, unknown>;
  dependencyGraph: DependencySummary;
  dependencyFindings: Finding[];
  agentOutput: Record<string, unknown>;
  optimizationOpportunities: DuplicateFlowHint[];
  optimizationFindings: Finding[];
  parseErrors: { file: string; message: string }[];
  astTrees?: TreeEntry[];
  graphAnalytics?: import('./graph-analytics.js').GraphAnalyticsSummary;
  reportAnalysis?: import('./report-analysis.js').ReportAnalysisSummary;
}
 
export function writeMultiFileReport(
  dir: string,
  report: FullReport,
  options: AnalysisOptions,
  dependencyState: DependencyState,
  dependencySummary: DependencySummary,
  fileCriticalityByPath: Map<string, FileCriticality>,
): Record<string, string> {
  fs.mkdirSync(dir, { recursive: true });
 
  const writeJson = (name: string, data: unknown): void => {
    fs.writeFileSync(path.join(dir, name), JSON.stringify(data, null, 2), 'utf8');
  };
 
  const outputFiles: Record<string, string> = {
    summary: 'summary.json',
    architecture: 'architecture.json',
    codeQuality: 'code-quality.json',
    deadCode: 'dead-code.json',
    fileInventory: 'file-inventory.json',
    findings: 'findings.json',
  };
 
  const hotFiles = computeHotFiles(dependencyState, dependencySummary, fileCriticalityByPath);
  const graphAnalytics = report.graphAnalytics ?? computeGraphAnalytics(dependencyState, dependencySummary, fileCriticalityByPath);
  const enrichedFileInventory = enrichFileInventoryEntries(report.fileInventory || [], { flowEnabled: !!options.flow });
  const allFindings = enrichFindings(
    report.optimizationFindings || [],
    enrichedFileInventory,
    hotFiles,
    graphAnalytics,
    { flowEnabled: !!options.flow },
  );
  const architectureFindings = allFindings.filter(f => ARCHITECTURE_CATEGORIES.has(f.category));
  const codeQualityFindings = allFindings.filter(f => CODE_QUALITY_CATEGORIES.has(f.category));
  const deadCodeFindings = allFindings.filter(f => DEAD_CODE_CATEGORIES.has(f.category));
  const securityFindings = allFindings.filter(f => SECURITY_CATEGORIES.has(f.category));
  const testQualityFindings = allFindings.filter(f => TEST_QUALITY_CATEGORIES.has(f.category));
  const reportAnalysis = report.reportAnalysis ?? computeReportAnalysisSummary(allFindings, enrichedFileInventory, hotFiles, graphAnalytics);
 
  writeJson('architecture.json', {
    schemaVersion: REPORT_SCHEMA_VERSION,
    generatedAt: report.generatedAt,
    dependencyGraph: report.dependencyGraph,
    dependencyFindings: report.dependencyFindings,
    findings: architectureFindings,
    findingsCount: architectureFindings.length,
    severityBreakdown: severityBreakdown(architectureFindings),
    categoryBreakdown: categoryBreakdown(architectureFindings),
    hotFiles,
    graphSignals: reportAnalysis.graphSignals,
    chokepoints: graphAnalytics.chokepoints,
    criticalHubCandidates: graphAnalytics.chokepoints.slice(0, 10),
    sccClusters: options.graphAdvanced ? graphAnalytics.sccClusters : [],
    packageGraphSummary: options.graphAdvanced ? graphAnalytics.packageGraphSummary : null,
    packageHotspots: options.graphAdvanced ? graphAnalytics.packageGraphSummary.hotspots : [],
  });
 
  writeJson('code-quality.json', {
    schemaVersion: REPORT_SCHEMA_VERSION,
    generatedAt: report.generatedAt,
    duplicateFlows: report.duplicateFlows,
    optimizationOpportunities: report.optimizationOpportunities,
    findings: codeQualityFindings,
    findingsCount: codeQualityFindings.length,
    severityBreakdown: severityBreakdown(codeQualityFindings),
    categoryBreakdown: categoryBreakdown(codeQualityFindings),
  });
 
  writeJson('dead-code.json', {
    schemaVersion: REPORT_SCHEMA_VERSION,
    generatedAt: report.generatedAt,
    findings: deadCodeFindings,
    findingsCount: deadCodeFindings.length,
    severityBreakdown: severityBreakdown(deadCodeFindings),
    categoryBreakdown: categoryBreakdown(deadCodeFindings),
  });
 
  if (securityFindings.length > 0) {
    writeJson('security.json', {
      schemaVersion: REPORT_SCHEMA_VERSION,
      generatedAt: report.generatedAt,
      findings: securityFindings,
      findingsCount: securityFindings.length,
      severityBreakdown: severityBreakdown(securityFindings),
      categoryBreakdown: categoryBreakdown(securityFindings),
    });
    outputFiles.security = 'security.json';
  }
 
  if (testQualityFindings.length > 0) {
    writeJson('test-quality.json', {
      schemaVersion: REPORT_SCHEMA_VERSION,
      generatedAt: report.generatedAt,
      findings: testQualityFindings,
      findingsCount: testQualityFindings.length,
      severityBreakdown: severityBreakdown(testQualityFindings),
      categoryBreakdown: categoryBreakdown(testQualityFindings),
    });
    outputFiles.testQuality = 'test-quality.json';
  }
 
  writeJson('file-inventory.json', {
    schemaVersion: REPORT_SCHEMA_VERSION,
    generatedAt: report.generatedAt,
    fileInventory: enrichedFileInventory,
    fileCount: enrichedFileInventory.length,
  });
 
  writeJson('findings.json', {
    schemaVersion: REPORT_SCHEMA_VERSION,
    generatedAt: report.generatedAt,
    optimizationFindings: allFindings,
    totalFindings: allFindings.length,
  });
 
  if (options.graph) {
    const graphMd = generateMermaidGraph(dependencyState, dependencySummary, fileCriticalityByPath);
    fs.writeFileSync(path.join(dir, 'graph.md'), graphMd, 'utf8');
    outputFiles.graph = 'graph.md';
  }
 
  if (report.astTrees) {
    fs.writeFileSync(path.join(dir, 'ast-trees.txt'), renderTreesText(report.astTrees, report.generatedAt), 'utf8');
    outputFiles.astTrees = 'ast-trees.txt';
  }
 
  const summaryJsonData = {
    schemaVersion: REPORT_SCHEMA_VERSION,
    generatedAt: report.generatedAt,
    repoRoot: report.repoRoot,
    options: report.options,
    parser: report.parser,
    summary: report.summary,
    agentOutput: report.agentOutput,
    analysisSummary: {
      graphSignals: reportAnalysis.graphSignals,
      astSignals: reportAnalysis.astSignals,
      strongestGraphSignal: reportAnalysis.strongestGraphSignal,
      strongestAstSignal: reportAnalysis.strongestAstSignal,
      combinedSignals: reportAnalysis.combinedSignals,
      recommendedValidation: reportAnalysis.recommendedValidation,
    },
    strongestGraphSignal: reportAnalysis.strongestGraphSignal,
    strongestAstSignal: reportAnalysis.strongestAstSignal,
    combinedSignals: reportAnalysis.combinedSignals,
    recommendedValidation: reportAnalysis.recommendedValidation,
    investigationPrompts: reportAnalysis.investigationPrompts,
    parseErrors: report.parseErrors,
    outputFiles,
  };
  writeJson('summary.json', summaryJsonData);
 
  const summaryMd = generateSummaryMd({
    dir, report, outputFiles,
    architectureFindings, codeQualityFindings, deadCodeFindings,
    hotFiles, activeFeatures: options.features, scope: options.scope,
    root: options.root, scopeSymbols: options.scopeSymbols,
    semanticEnabled: options.semantic, securityFindings, testQualityFindings,
    reportAnalysis,
  });
  fs.writeFileSync(path.join(dir, 'summary.md'), summaryMd, 'utf8');
  outputFiles.summaryMd = 'summary.md';
 
  writeJson('summary.json', { ...summaryJsonData, outputFiles });
 
  return outputFiles;
}
 
export function generateMermaidGraph(dependencyState: DependencyState, dependencySummary: DependencySummary, _fileCriticalityByPath: Map<string, FileCriticality>): string {
  const lines: string[] = [];
  lines.push('# Dependency Graph\n');
  lines.push('## Module Dependency Map\n');
  lines.push('```mermaid');
  lines.push('graph LR');
 
  const criticalFiles = new Set(
    (dependencySummary.criticalModules || []).map((m) => m.file),
  );
  const cycleFiles = new Set<string>();
  for (const cycle of dependencySummary.cycles || []) {
    for (const f of cycle.path) cycleFiles.add(f);
  }
 
  const shorten = (filePath: string): string => {
    const parts = filePath.split('/');
    Eif (parts.length <= 2) return parts.join('/');
    return `${parts[0]}/…/${parts[parts.length - 1]}`;
  };
 
  const sanitize = (id: string): string => id.replace(/[^a-zA-Z0-9]/g, '_');
 
  const renderedNodes = new Set<string>();
  const renderedEdges = new Set<string>();
 
  const topModules = [
    ...(dependencySummary.outgoingTop || []).slice(0, 15),
    ...(dependencySummary.inboundTop || []).slice(0, 15),
    ...(dependencySummary.criticalModules || []).slice(0, 10),
  ];
  const moduleSet = new Set(topModules.map((m) => m.file));
  for (const cycle of (dependencySummary.cycles || []).slice(0, 5)) {
    for (const f of cycle.path) moduleSet.add(f);
  }
 
  for (const file of moduleSet) {
    const id = sanitize(file);
    Iif (renderedNodes.has(id)) continue;
    renderedNodes.add(id);
 
    const label = shorten(file);
    if (cycleFiles.has(file)) {
      lines.push(`  ${id}["🔴 ${label}"]`);
    } else if (criticalFiles.has(file)) {
      lines.push(`  ${id}["⚠️ ${label}"]`);
    } else {
      lines.push(`  ${id}["${label}"]`);
    }
  }
 
  for (const file of moduleSet) {
    const outgoing = dependencyState.outgoing.get(file) || new Set();
    for (const dep of outgoing) {
      Iif (!moduleSet.has(dep)) continue;
      const edgeKey = `${sanitize(file)}-->${sanitize(dep)}`;
      Iif (renderedEdges.has(edgeKey)) continue;
      renderedEdges.add(edgeKey);
 
      if (cycleFiles.has(file) && cycleFiles.has(dep)) {
        lines.push(`  ${sanitize(file)} -. cycle .-> ${sanitize(dep)}`);
      } else {
        lines.push(`  ${sanitize(file)} --> ${sanitize(dep)}`);
      }
    }
  }
 
  lines.push('```\n');
 
  if (dependencySummary.cycles?.length > 0) {
    lines.push('## Dependency Cycles\n');
    lines.push('```mermaid');
    lines.push('graph LR');
    for (const [idx, cycle] of dependencySummary.cycles.slice(0, 10).entries()) {
      for (let i = 0; i < cycle.path.length - 1; i++) {
        const from = sanitize(cycle.path[i]);
        const to = sanitize(cycle.path[i + 1]);
        lines.push(`  ${from}["${shorten(cycle.path[i])}"] -. "cycle ${idx + 1}" .-> ${to}["${shorten(cycle.path[i + 1])}"]`);
      }
    }
    lines.push('```\n');
  }
 
  if (dependencySummary.criticalPaths?.length > 0) {
    lines.push('## Critical Dependency Chains\n');
    lines.push('```mermaid');
    lines.push('graph LR');
    for (const chain of dependencySummary.criticalPaths.slice(0, 8)) {
      for (let i = 0; i < chain.path.length - 1; i++) {
        const from = sanitize(chain.path[i]);
        const to = sanitize(chain.path[i + 1]);
        lines.push(`  ${from}["${shorten(chain.path[i])}"] ==> ${to}["${shorten(chain.path[i + 1])}"]`);
      }
    }
    lines.push('```\n');
  }
 
  lines.push('## Summary\n');
  lines.push(`| Metric | Value |`);
  lines.push(`|--------|-------|`);
  lines.push(`| Total modules | ${dependencySummary.totalModules} |`);
  lines.push(`| Total edges | ${dependencySummary.totalEdges} |`);
  lines.push(`| Root modules | ${dependencySummary.rootsCount} |`);
  lines.push(`| Leaf modules | ${dependencySummary.leavesCount} |`);
  lines.push(`| Cycles | ${dependencySummary.cycles?.length || 0} |`);
  lines.push(`| Critical paths | ${dependencySummary.criticalPaths?.length || 0} |`);
  lines.push(`| Test-only modules | ${dependencySummary.testOnlyModules?.length || 0} |`);
  lines.push(`| Unresolved imports | ${dependencySummary.unresolvedEdgeCount || 0} |`);
  lines.push('');
 
  if (dependencySummary.criticalModules?.length > 0) {
    lines.push('## Critical Modules (Hub Nodes)\n');
    lines.push('| Module | Score | Risk | Inbound | Outbound |');
    lines.push('|--------|-------|------|---------|----------|');
    for (const m of dependencySummary.criticalModules.slice(0, 20)) {
      lines.push(`| \`${m.file}\` | ${m.score} | ${m.riskBand || '-'} | ${m.inboundCount} | ${m.outboundCount} |`);
    }
    lines.push('');
  }
 
  if (dependencySummary.testOnlyModules?.length > 0) {
    lines.push('## Test-Only Modules\n');
    for (const m of dependencySummary.testOnlyModules.slice(0, 20)) {
      lines.push(`- \`${m.file}\``);
    }
    lines.push('');
  }
 
  return lines.join('\n');
}